BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / center.rs

center.rs

center.rs 60.4 KiB Download Raw
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
3use std::time::{Duration, Instant};
4
5use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use store::Sidebar;
8use teams_core::{ForcedAvailability, ForcedKind};
9
10use super::badge::{Badge, badge_for};
11use super::incoming::IncomingTracker;
12use super::layout::{self, MEETING_HEIGHT, Slot, ring_height};
13use super::meeting_view::MeetingToastView;
14use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
15use super::ring_view::RingView;
16use super::rules::{
17 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
18 decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,
19 shows_preview,
20};
21use super::settings;
22use super::sound_cache::{self, SoundHandle};
23use super::sounds::{CallTone, Ringtone};
24use super::stack::{
25 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
26 ToastModel, ToastStack,
27};
28use super::taskbar::taskbar_badge_count;
29use super::text::describe;
30use super::toast::{PillView, ToastView};
31use super::urgent_repeat::UrgentRepeats;
32use crate::active_appearance::{self, ActiveAppearance};
33use crate::active_locale::ActiveLocale;
34use crate::activity::ActivityCenter;
35use crate::agent_api::{self, pending::PendingProposal};
36use crate::agents::{AgentRun, AgentRunsEvent, RunState};
37use crate::app_state::{AppEvent, AppState, selection_for};
38use crate::appearance::AppIcon;
39use crate::autostart::{self, StartupSettings};
40use crate::call::DemoScene;
41use crate::data::{self, Directory, PresenceKind};
42use crate::runtime;
43use crate::settings_section::SettingsSection;
44use crate::single_instance;
45
46const TICK: Duration = Duration::from_millis(33);
47const SLIDE_DURATION: Duration = Duration::from_millis(180);
48const SLIDE_DISTANCE: f32 = 48.;
49const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
50const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
51const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
52const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
53const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
54const AGENT_BODY_LINES: usize = 2;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57enum CallToast {
58 Ring(u64),
59 Meeting(u64),
60}
61
62struct OpenWindow {
63 handle: AnyWindowHandle,
64 native: Option<NativeHandle>,
65 opened: Instant,
66 placed: Cell<Option<(i32, i32, i32, i32)>>,
67}
68
69impl OpenWindow {
70 fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) {
71 let rect = (x, slot.y, slot.width, slot.height);
72 match self.placed.replace(Some(rect)) {
73 Some(previous) if previous == rect => return,
74 Some(_) => platform::place_rect(native, x, slot.y, slot.width, slot.height),
75 None => platform::place(native, x, slot.y, slot.width, slot.height),
76 }
77 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
78 self.handle
79 .update(cx, |_, window, cx| window.bounds_changed(cx))
80 .ok();
81 }
82}
83
84pub struct NotificationCenter {
85 app: Entity<AppState>,
86 activity: Entity<ActivityCenter>,
87 main_window: AnyWindowHandle,
88 main_native: Option<NativeHandle>,
89 settings: Settings,
90 startup: StartupSettings,
91 stack: ToastStack,
92 tracker: IncomingTracker,
93 throttle: SoundThrottle,
94 urgent_repeats: UrgentRepeats,
95 windows: HashMap<u64, OpenWindow>,
96 opening: HashSet<u64>,
97 call_windows: HashMap<CallToast, OpenWindow>,
98 call_opening: HashSet<CallToast>,
99 ring_tone: Option<SoundHandle>,
100 ringback: Option<SoundHandle>,
101 reconnecting: Option<SoundHandle>,
102 preview: Option<SoundHandle>,
103 demo_mode: bool,
104 pill: Option<OpenWindow>,
105 pill_opening: bool,
106 hover_hold: bool,
107 unread_mentions: HashSet<String>,
108 tray: Option<Tray>,
109 tray_do_not_disturb: bool,
110 app_icon: AppIcon,
111 shown_badge: Option<Badge>,
112 shown_mention_dot: bool,
113 animations: bool,
114 _subscription: Subscription,
115 _activity_observation: Subscription,
116 _appearance_observation: Subscription,
117 _locale_observation: Subscription,
118 _agent_subscription: Option<Subscription>,
119 started_at: DateTime<Utc>,
120 known_proposals: HashSet<String>,
121 _proposal_observation: Option<Subscription>,
122}
123
124impl NotificationCenter {
125 pub fn new(
126 app: Entity<AppState>,
127 activity: Entity<ActivityCenter>,
128 window: &mut Window,
129 cx: &mut Context<Self>,
130 ) -> Self {
131 let mut settings = settings::load(&app.read(cx).store);
132 settings.account = app.read(cx).account_chat_settings().notifications;
133 let app_icon = active_appearance::current(cx).app_icon;
134 let tray_do_not_disturb = own_do_not_disturb(app.read(cx));
135 let tray = if app.read(cx).mode.demo {
136 None
137 } else {
138 Tray::new(
139 settings.sounds.notification_sound,
140 tray_do_not_disturb,
141 app_icon.png(),
142 )
143 };
144 platform::set_window_icon(window, app_icon.png());
145 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
146 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
147 });
148 let locale_observation = cx.observe_global::<ActiveLocale>(|this, _| {
149 this.relocalize_tray();
150 });
151 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
152 this.on_app_event(event, cx);
153 });
154 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
155 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
156 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
157 if let AgentRunsEvent::Finished(run_id) = event
158 && let Some(run) = runs.read(cx).get(*run_id).cloned()
159 {
160 this.present_agent_run(&run, cx);
161 }
162 })
163 });
164 let proposal_observation =
165 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
166 let center = NotificationCenter {
167 started_at: Utc::now(),
168 known_proposals: HashSet::new(),
169 _proposal_observation: proposal_observation,
170 main_window: window.window_handle(),
171 main_native: platform::native_handle(window),
172 settings,
173 startup: StartupSettings::load(&app.read(cx).store, !app.read(cx).mode.demo),
174 stack: ToastStack::default(),
175 tracker: IncomingTracker::new(Utc::now()),
176 throttle: SoundThrottle::default(),
177 urgent_repeats: UrgentRepeats::default(),
178 windows: HashMap::new(),
179 opening: HashSet::new(),
180 call_windows: HashMap::new(),
181 call_opening: HashSet::new(),
182 ring_tone: None,
183 ringback: None,
184 reconnecting: None,
185 preview: None,
186 demo_mode: app.read(cx).mode.demo,
187 pill: None,
188 pill_opening: false,
189 hover_hold: false,
190 unread_mentions: HashSet::new(),
191 tray,
192 tray_do_not_disturb,
193 app_icon,
194 shown_badge: None,
195 shown_mention_dot: false,
196 animations: platform::animations_enabled(),
197 app,
198 activity,
199 _subscription: subscription,
200 _activity_observation: activity_observation,
201 _appearance_observation: appearance_observation,
202 _locale_observation: locale_observation,
203 _agent_subscription: agent_subscription,
204 };
205 cx.spawn(async move |this, cx| {
206 loop {
207 cx.background_executor().timer(TICK).await;
208 if this.update(cx, |center, cx| center.tick(cx)).is_err() {
209 break;
210 }
211 }
212 })
213 .detach();
214 if !center.demo_mode {
215 center.prefetch_sounds(cx);
216 }
217 if center.app.read(cx).mode.demo {
218 if demo_scene().is_none() {
219 cx.spawn(async move |this, cx| {
220 cx.background_executor().timer(DEMO_SPEC_DELAY).await;
221 this.update(cx, |center, cx| center.show_demo_toasts(cx))
222 .ok();
223 })
224 .detach();
225 }
226 if let Some(delay) = demo_ring_delay() {
227 let app = center.app.clone();
228 let video =
229 std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
230 cx.spawn(async move |_, cx| {
231 cx.background_executor().timer(delay).await;
232 app.update(cx, |state, cx| {
233 if video {
234 state.demo_incoming_video_ring(cx)
235 } else {
236 state.demo_incoming_ring(cx)
237 }
238 });
239 })
240 .detach();
241 }
242 if let Some(scene) = demo_scene() {
243 let app = center.app.clone();
244 cx.spawn(async move |_, cx| {
245 cx.background_executor().timer(DEMO_SCENE_DELAY).await;
246 app.update(cx, |state, cx| state.start_demo_scene(scene, cx));
247 })
248 .detach();
249 }
250 }
251 center
252 }
253
254 pub fn app(&self) -> &Entity<AppState> {
255 &self.app
256 }
257
258 pub fn settings(&self) -> &Settings {
259 &self.settings
260 }
261
262 pub fn model(&self, id: u64) -> Option<&ToastModel> {
263 self.stack.get(id)
264 }
265
266 pub fn queued_count(&self) -> usize {
267 self.stack.queued_count()
268 }
269
270 pub fn stack_opacity(&self) -> f32 {
271 let now = Instant::now();
272 self.stack
273 .visible()
274 .iter()
275 .map(|toast| toast.opacity(now))
276 .fold(0., f32::max)
277 }
278
279 fn animated(&self, duration: Duration) -> Duration {
280 if self.animations {
281 duration
282 } else {
283 Duration::ZERO
284 }
285 }
286
287 pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
288 &self.app.read(cx).directory
289 }
290
291 pub fn reply_text(&self, id: u64) -> Option<String> {
292 self.stack.get(id).map(|toast| toast.reply_text.clone())
293 }
294
295 pub fn startup(&self) -> StartupSettings {
296 self.startup
297 }
298
299 pub fn set_auto_start(&mut self, enabled: bool, cx: &mut Context<Self>) {
300 if !self.demo_mode
301 && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled)
302 {
303 self.app.update(cx, |state, cx| {
304 state.raise_notice(
305 format!("Auto-start could not be changed: {error}"),
306 None,
307 cx,
308 )
309 });
310 return;
311 }
312 self.startup.auto_start = enabled;
313 cx.notify();
314 }
315
316 pub fn set_open_in_background(&mut self, enabled: bool, cx: &mut Context<Self>) {
317 self.startup.open_in_background = enabled;
318 self.startup.save_background(&self.app.read(cx).store);
319 cx.notify();
320 }
321
322 /// Points at a main window reopened from the tray.
323 pub fn attach_main_window(&mut self, window: &mut Window) {
324 self.main_window = window.window_handle();
325 self.main_native = platform::native_handle(window);
326 platform::set_window_icon(window, self.app_icon.png());
327 }
328
329 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
330 match (&self.tray, self.main_native) {
331 (Some(_), Some(native)) => platform::hide_window(native),
332 #[cfg(target_os = "linux")]
333 (Some(_), None) => crate::main_window::hide(cx),
334 _ => window.minimize_window(),
335 }
336 let _ = cx;
337 }
338
339 /// True when the close is handled here (window hidden natively). On Linux the
340 /// window closes for real and the app stays in the tray.
341 pub fn intercept_close(&self, cx: &mut App) -> bool {
342 match (self.settings.close_to_tray, &self.tray, self.main_native) {
343 (true, Some(_), Some(native)) => {
344 platform::hide_window(native);
345 true
346 }
347 #[cfg(target_os = "linux")]
348 (true, Some(_), None) => {
349 crate::main_window::mark_hiding(cx);
350 false
351 }
352 _ => {
353 let _ = cx;
354 false
355 }
356 }
357 }
358
359 pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
360 let previous = self.settings.sounds.clone();
361 change(&mut self.settings);
362 settings::save(&self.app.read(cx).store, &self.settings);
363 self.sync_tray(cx);
364 if self.settings.sounds != previous {
365 let updated = self.settings.sounds.clone();
366 self.app.update(cx, |state, cx| {
367 state.save_sound_settings(previous, updated, cx)
368 });
369 self.prefetch_sounds(cx);
370 }
371 cx.notify();
372 }
373
374 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
375 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
376 cx.notify();
377 }
378
379 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
380 let Some(account) = self.app.read(cx).account_sounds.clone() else {
381 return;
382 };
383 if account == self.settings.sounds {
384 return;
385 }
386 self.settings.sounds = account;
387 settings::save(&self.app.read(cx).store, &self.settings);
388 self.sync_tray(cx);
389 if !self.demo_mode {
390 self.prefetch_sounds(cx);
391 }
392 cx.notify();
393 }
394
395 fn prefetch_sounds(&self, cx: &App) {
396 let sounds = &self.settings.sounds;
397 let chosen = [
398 sounds.notification_sound_type.file_name(),
399 sounds.urgent_sound_type.file_name(),
400 sounds.ringtones.regular.file_name(),
401 Ringtone::Beep.file_name(),
402 ];
403 let call_tones = CallTone::ALL.map(CallTone::file_name);
404 sound_cache::prefetch(&chosen, cx);
405 sound_cache::prefetch(&call_tones, cx);
406 }
407
408 pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context<Self>) {
409 self.preview = Some(sound_cache::start(file_name, false, cx));
410 }
411
412 fn play_notification_sound(&self, cx: &App) {
413 let file_name = self.settings.sounds.notification_sound_type.file_name();
414 sound_cache::play_or(file_name, platform::play_sound, cx);
415 }
416
417 fn play_urgent_sound(&self, cx: &App) {
418 let file_name = self.settings.sounds.urgent_sound_type.file_name();
419 sound_cache::play_or(file_name, platform::play_sound, cx);
420 }
421
422 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
423 match event {
424 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
425 AppEvent::Selection => self.on_selection(cx),
426 AppEvent::Sidebar => self.refresh_badge(cx),
427 AppEvent::Directory => self.sync_tray_presence(cx),
428 AppEvent::Ring => self.on_rings_changed(cx),
429 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
430 AppEvent::MeetingChime => self.on_meeting_chime(cx),
431 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
432 AppEvent::Call => self.sync_call_sounds(cx),
433 AppEvent::SoundSettings => self.on_account_sounds(cx),
434 AppEvent::ChatSettings => self.on_account_notifications(cx),
435 AppEvent::FollowedStatus { user_id, text } => {
436 self.present_status_change(user_id, text, cx)
437 }
438 _ => {}
439 }
440 }
441
442 fn on_selection(&mut self, cx: &mut Context<Self>) {
443 let selected = self
444 .app
445 .read(cx)
446 .selection
447 .as_ref()
448 .map(|selection| selection.conversation_id().to_owned());
449 if let Some(conversation_id) = selected {
450 self.unread_mentions.remove(&conversation_id);
451 self.stack.remove_conversation(&conversation_id);
452 self.urgent_repeats.stop_conversation(&conversation_id);
453 }
454 self.refresh_badge(cx);
455 }
456
457 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
458 let state = self.app.read(cx);
459 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
460 let found = self.tracker.collect(
461 &state.store,
462 &state.sidebar,
463 my_user_id.as_deref(),
464 &state.late_arrivals,
465 conversation_id,
466 );
467 for incoming in found {
468 self.handle_incoming(incoming, cx);
469 }
470 self.refresh_badge(cx);
471 }
472
473 fn environment(&self, conversation_id: &str, cx: &mut Context<Self>) -> Environment {
474 let state = self.app.read(cx);
475 let selected = state
476 .selection
477 .as_ref()
478 .is_some_and(|selection| selection.conversation_id() == conversation_id);
479 let own_do_not_disturb = own_do_not_disturb(state);
480 let own_busy = own_presence(state) == PresenceKind::Busy;
481 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
482 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
483 _ => false,
484 };
485 let in_call = in_call(server_in_call, state.call.as_ref().map(|call| &call.model));
486 let paused = state.notifications_paused(chrono::Utc::now());
487 Environment {
488 chat_in_foreground: selected && self.main_window_active(cx),
489 system_quiet: platform::system_quiet(),
490 own_do_not_disturb,
491 paused,
492 own_busy,
493 in_call,
494 }
495 }
496
497 fn main_window_active(&self, cx: &mut Context<Self>) -> bool {
498 self.main_window
499 .update(cx, |_, window, _| window.is_window_active())
500 .unwrap_or(false)
501 }
502
503 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
504 incoming.chat.desktop = self
505 .app
506 .read(cx)
507 .chat_desktop_notifications(&incoming.conversation_id);
508 let bubble_text = match &incoming.preview {
509 Preview::Text(text) => text.replace('\n', " "),
510 Preview::Image => "Sent a picture".to_owned(),
511 };
512 self.app.update(cx, |state, cx| {
513 state.note_call_chat_message(
514 &incoming.conversation_id,
515 &incoming.message_id,
516 incoming.sender_id.clone(),
517 &incoming.sender_name,
518 &bubble_text,
519 cx,
520 )
521 });
522 let environment = self.environment(&incoming.conversation_id, cx);
523 if !environment.chat_in_foreground && incoming.mentions_me {
524 self.unread_mentions
525 .insert(incoming.conversation_id.clone());
526 }
527 let decision = decide(&self.settings, &incoming, environment);
528 self.present(&incoming, decision, cx);
529 if !environment.chat_in_foreground {
530 self.urgent_repeats.track(&incoming, Utc::now());
531 }
532 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
533 && let Some(native) = self.main_native
534 {
535 platform::flash(native);
536 }
537 }
538
539 fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) {
540 if !decision.toast {
541 return;
542 }
543 let now = Instant::now();
544 let outcome = self.stack.push(incoming, now);
545 if let Some(model) = self.stack.get_mut(outcome.id) {
546 model.time = chrono::Local::now()
547 .format(crate::format::clock_format())
548 .to_string();
549 }
550 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
551 let audible =
552 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
553 if decision.sound && audible && !self.app.read(cx).mode.demo {
554 if decision.urgent_sound {
555 self.play_urgent_sound(cx);
556 } else {
557 self.play_notification_sound(cx);
558 }
559 }
560 if let Some(user_id) = incoming.sender_id.clone() {
561 self.app
562 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
563 }
564 self.sync_windows(cx);
565 }
566
567 fn own_feature_decision(&self, cx: &mut Context<Self>) -> Decision {
568 let environment = self.environment("", cx);
569 decide_proposal(
570 &self.settings,
571 teams_core::DesktopNotifications::MatchAllChats,
572 environment,
573 )
574 }
575
576 fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
577 if !self.own_feature_decision(cx).toast {
578 return;
579 }
580 let (name, conversation_id) = {
581 let state = self.app.read(cx);
582 let name = state
583 .followed_presence
584 .iter()
585 .find(|person| person.user_id == user_id)
586 .map(|person| person.name.clone())
587 .unwrap_or_default();
588 (
589 name,
590 state.one_on_one_chat_with(user_id).unwrap_or_default(),
591 )
592 };
593 let id =
594 self.stack
595 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
596 if let Some(model) = self.stack.get_mut(id) {
597 model.time = chrono::Local::now()
598 .format(crate::format::clock_format())
599 .to_string();
600 }
601 let user_id = user_id.to_owned();
602 self.app
603 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
604 self.sync_windows(cx);
605 }
606
607 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
608 let decision = self.own_feature_decision(cx);
609 if !decision.toast {
610 return;
611 }
612 let failed = matches!(run.state, RunState::Failed { .. });
613 let verb = if failed { "failed" } else { "finished" };
614 let body = if failed {
615 run.current_step.clone()
616 } else {
617 first_lines(&run.final_text, AGENT_BODY_LINES)
618 };
619 let toast = AgentToast {
620 kind: AgentToastKind::Run {
621 run_id: run.id,
622 session_id: run.session_id.clone(),
623 failed,
624 },
625 header: format!(
626 "{} - {} - {}",
627 run.action_label,
628 run.agent_name,
629 run.elapsed_text()
630 ),
631 title: format!(
632 "{} {verb}: {} for {}",
633 run.agent_name, run.action_label, run.sender_name
634 ),
635 body: if body.is_empty() {
636 "Done".to_owned()
637 } else {
638 body
639 },
640 };
641 let now = Instant::now();
642 let id = self
643 .stack
644 .push_agent(toast, &run.conversation_id, &run.message_id, now);
645 if let Some(model) = self.stack.get_mut(id) {
646 model.time = chrono::Local::now()
647 .format(crate::format::clock_format())
648 .to_string();
649 }
650 if decision.sound && !self.app.read(cx).mode.demo {
651 self.play_notification_sound(cx);
652 }
653 self.sync_windows(cx);
654 }
655
656 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
657 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
658 return;
659 };
660 self.drop_toast(id, cx);
661 match agent.kind {
662 AgentToastKind::Run {
663 run_id,
664 failed: true,
665 ..
666 } => crate::agents::retry_run(run_id, cx),
667 AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),
668 AgentToastKind::Proposal { .. } => {}
669 }
670 }
671
672 fn on_proposals(&mut self, cx: &mut Context<Self>) {
673 let pending = agent_api::pending_proposals(cx);
674 let unseen: HashSet<&str> = pending
675 .iter()
676 .filter(|proposal| !proposal.seen)
677 .map(|proposal| proposal.id.as_str())
678 .collect();
679 let resolved: Vec<u64> = self
680 .stack
681 .ids()
682 .into_iter()
683 .filter(|id| {
684 self.stack
685 .get(*id)
686 .and_then(|toast| toast.agent.as_ref()?.proposal_id())
687 .is_some_and(|proposal_id| !unseen.contains(proposal_id))
688 })
689 .collect();
690 for id in resolved {
691 self.drop_toast(id, cx);
692 }
693 let arrived: Vec<PendingProposal> = pending
694 .iter()
695 .filter(|proposal| {
696 !self.known_proposals.contains(&proposal.id)
697 && !proposal.seen
698 && proposal.created_at >= self.started_at
699 })
700 .cloned()
701 .collect();
702 self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();
703 for proposal in arrived {
704 self.present_proposal(&proposal, cx);
705 }
706 self.refresh_badge(cx);
707 }
708
709 fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {
710 let state = self.app.read(cx);
711 let desktop = state.chat_desktop_notifications(&proposal.conversation_id);
712 let conversation =
713 agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);
714 let environment = self.environment(&proposal.conversation_id, cx);
715 let decision = decide_proposal(&self.settings, desktop, environment);
716 if !decision.toast {
717 return;
718 }
719 let toast = AgentToast {
720 kind: AgentToastKind::Proposal {
721 proposal_id: proposal.id.clone(),
722 },
723 header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),
724 title: proposal.title(),
725 body: proposal.detail(),
726 };
727 let id = self.stack.push_agent(
728 toast,
729 &proposal.conversation_id,
730 proposal.jump_message_id(),
731 Instant::now(),
732 );
733 if let Some(model) = self.stack.get_mut(id) {
734 model.time = chrono::Local::now()
735 .format(crate::format::clock_format())
736 .to_string();
737 }
738 if decision.sound && !self.demo_mode {
739 self.play_notification_sound(cx);
740 }
741 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
742 && let Some(native) = self.main_native
743 {
744 platform::flash(native);
745 }
746 self.sync_windows(cx);
747 }
748
749 fn visible_ids(&self) -> Vec<u64> {
750 self.stack.visible().iter().map(|toast| toast.id).collect()
751 }
752
753 fn work_area(&self, cx: &App) -> WorkArea {
754 if let Some(area) = self.main_native.and_then(platform::work_area) {
755 return area;
756 }
757 let bounds = cx
758 .primary_display()
759 .map(|display| display.bounds())
760 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.))));
761 WorkArea {
762 left: f32::from(bounds.origin.x) as i32,
763 top: f32::from(bounds.origin.y) as i32,
764 right: f32::from(bounds.origin.x + bounds.size.width) as i32,
765 bottom: f32::from(bounds.origin.y + bounds.size.height) as i32,
766 scale: 1.,
767 }
768 }
769
770 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
771 let state = self.app.read(cx);
772 let in_call = state.call.is_some();
773 let rings = state
774 .rings
775 .ringing()
776 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
777 let meetings = state
778 .meeting_toasts
779 .entries()
780 .iter()
781 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
782 rings.chain(meetings).collect()
783 }
784
785 fn sync_windows(&mut self, cx: &mut Context<Self>) {
786 let visible = self.visible_ids();
787 let stale: Vec<u64> = self
788 .windows
789 .keys()
790 .filter(|id| !visible.contains(id))
791 .copied()
792 .collect();
793 for id in stale {
794 self.close_window(id, cx);
795 }
796 let call_toasts = self.call_toasts(cx);
797 let stale_call_toasts: Vec<CallToast> = self
798 .call_windows
799 .keys()
800 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
801 .copied()
802 .collect();
803 for key in stale_call_toasts {
804 self.close_call_window(key, cx);
805 }
806 let area = self.work_area(cx);
807 let mut heights: Vec<f32> = self
808 .stack
809 .visible()
810 .iter()
811 .map(|toast| {
812 let lines = match &toast.agent {
813 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
814 None => {
815 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
816 }
817 };
818 layout::toast_height(toast, lines)
819 })
820 .collect();
821 heights.extend(call_toasts.iter().map(|(_, height)| *height));
822 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
823 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
824 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
825 self.place_toast(*id, *slot, area, cx);
826 }
827 for ((key, _), slot) in call_toasts
828 .iter()
829 .zip(slots.toasts.iter().skip(visible.len()))
830 {
831 self.place_call_toast(*key, *slot, area, cx);
832 }
833 self.sync_pill(slots.pill, area, cx);
834 }
835
836 fn place_call_toast(
837 &mut self,
838 key: CallToast,
839 slot: Slot,
840 area: WorkArea,
841 cx: &mut Context<Self>,
842 ) {
843 let Some(window) = self.call_windows.get(&key) else {
844 self.open_call_window(key, slot, area, cx);
845 return;
846 };
847 if let Some(native) = window.native {
848 let offset = self.slide_offset(window.opened, area);
849 window.place(native, slot, slot.x + offset, cx);
850 }
851 }
852
853 fn open_call_window(
854 &mut self,
855 key: CallToast,
856 slot: Slot,
857 area: WorkArea,
858 cx: &mut Context<Self>,
859 ) {
860 if !self.call_opening.insert(key) {
861 return;
862 }
863 open_popup(
864 popup_options(slot, area),
865 cx,
866 move |center, _, cx| match key {
867 CallToast::Ring(ring_id) => {
868 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
869 }
870 CallToast::Meeting(toast_id) => {
871 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
872 }
873 },
874 move |this, window| {
875 this.call_opening.remove(&key);
876 if let Some(window) = window {
877 this.call_windows.insert(key, window);
878 }
879 },
880 );
881 }
882
883 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
884 let closed = self.call_windows.get(&key).is_some_and(|window| {
885 window
886 .handle
887 .update(cx, |_, window, _| window.remove_window())
888 .is_ok()
889 || !window_is_open(window.handle.window_id(), cx)
890 });
891 if closed {
892 self.call_windows.remove(&key);
893 }
894 }
895
896 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
897 if !self.app.read(cx).meeting_toasts.is_empty()
898 && !self.main_window_active(cx)
899 && let Some(native) = self.main_native
900 {
901 platform::flash(native);
902 }
903 self.sync_windows(cx);
904 cx.notify();
905 }
906
907 fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {
908 let busy = self.environment("", cx).busy();
909 if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode
910 {
911 sound_cache::play(CallTone::MeetingReminder.file_name(), cx);
912 }
913 }
914
915 fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context<Self>) {
916 if !self.demo_mode {
917 sound_cache::play(tone.file_name(), cx);
918 }
919 }
920
921 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
922 self.raise_main_window(cx);
923 self.app
924 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
925 }
926
927 fn reminders_quiet(&self, cx: &App) -> bool {
928 platform::system_quiet() || own_do_not_disturb(self.app.read(cx))
929 }
930
931 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
932 let ringing = self.app.read(cx).rings.is_ringing();
933 if ringing
934 && !self.main_window_active(cx)
935 && let Some(native) = self.main_native
936 {
937 platform::flash(native);
938 }
939 self.sync_windows(cx);
940 self.sync_ring_tone(ringing, cx);
941 cx.notify();
942 }
943
944 fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context<Self>) {
945 if !ringing || self.demo_mode {
946 self.ring_tone = None;
947 return;
948 }
949 if self.ring_tone.is_some() {
950 return;
951 }
952 let environment = self.environment("", cx);
953 let native_call = self.app.read(cx).call.is_some();
954 if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) {
955 self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx));
956 }
957 }
958
959 fn sync_call_sounds(&mut self, cx: &Context<Self>) {
960 let model = self.app.read(cx).call.as_ref().map(|call| &call.model);
961 let ringback = should_ringback(model) && !self.demo_mode;
962 let reconnecting =
963 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
964 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
965 sync_loop(
966 &mut self.reconnecting,
967 reconnecting,
968 CallTone::Reconnecting,
969 cx,
970 );
971 }
972
973 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
974 if !self.animations {
975 return 0;
976 }
977 let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.);
978 let eased = 1. - (1. - progress).powi(3);
979 let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32;
980 if self.settings.corner.is_right() {
981 distance
982 } else {
983 -distance
984 }
985 }
986
987 fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
988 if !self.windows.contains_key(&id) {
989 self.open_toast_window(id, slot, area, cx);
990 return;
991 }
992 let offset = self
993 .windows
994 .get(&id)
995 .map(|window| self.slide_offset(window.opened, area))
996 .unwrap_or(0);
997 if let Some(window) = self.windows.get(&id)
998 && let Some(native) = window.native
999 {
1000 window.place(native, slot, slot.x + offset, cx);
1001 }
1002 }
1003
1004 fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
1005 if !self.opening.insert(id) {
1006 return;
1007 }
1008 open_popup(
1009 popup_options(slot, area),
1010 cx,
1011 move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)),
1012 move |this, window| {
1013 this.opening.remove(&id);
1014 if let Some(window) = window {
1015 this.windows.insert(id, window);
1016 }
1017 },
1018 );
1019 }
1020
1021 fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {
1022 let Some(slot) = slot else {
1023 if let Some(pill) = self.pill.take() {
1024 pill.handle
1025 .update(cx, |_, window, _| window.remove_window())
1026 .ok();
1027 }
1028 return;
1029 };
1030 if self.pill.is_none() && !self.pill_opening {
1031 self.pill_opening = true;
1032 open_popup(
1033 popup_options(slot, area),
1034 cx,
1035 |center, _, cx| cx.new(|cx| PillView::new(center, cx)),
1036 |this, window| {
1037 this.pill_opening = false;
1038 this.pill = window;
1039 },
1040 );
1041 }
1042 if let Some(pill) = self.pill.as_ref()
1043 && let Some(native) = pill.native
1044 {
1045 pill.place(native, slot, slot.x, cx);
1046 }
1047 }
1048
1049 fn close_window(&mut self, id: u64, cx: &mut Context<Self>) {
1050 let closed = self.windows.get(&id).is_some_and(|window| {
1051 window
1052 .handle
1053 .update(cx, |_, window, _| window.remove_window())
1054 .is_ok()
1055 || !window_is_open(window.handle.window_id(), cx)
1056 });
1057 if closed {
1058 self.windows.remove(&id);
1059 }
1060 }
1061
1062 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1063 let fast = self.animated(FAST_FADE);
1064 self.stack.dismiss(id, Instant::now(), fast);
1065 cx.notify();
1066 }
1067
1068 pub fn hide_all(&mut self, cx: &mut Context<Self>) {
1069 for id in self.stack.ids() {
1070 self.drop_toast(id, cx);
1071 }
1072 }
1073
1074 fn sync_hover_hold(&mut self, now: Instant) {
1075 let any_hovered = self.stack.any_hovered();
1076 if !any_hovered && !self.hover_hold {
1077 return;
1078 }
1079 if any_hovered {
1080 let fast = self.animated(FAST_FADE);
1081 self.stack.restore(now, fast);
1082 }
1083 for id in self.stack.ids() {
1084 if let Some(toast) = self.stack.get_mut(id)
1085 && !toast.queued
1086 {
1087 if any_hovered {
1088 toast.timer.pause(now);
1089 } else if !toast.holds_open() {
1090 toast.timer.resume(now);
1091 }
1092 }
1093 }
1094 self.hover_hold = any_hovered;
1095 }
1096
1097 fn is_dismissed(&self, id: u64) -> bool {
1098 self.stack.get(id).is_none_or(|toast| toast.dismissed)
1099 }
1100
1101 fn tick(&mut self, cx: &mut Context<Self>) {
1102 let now = Instant::now();
1103 let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE));
1104 for id in self.stack.expired(now) {
1105 self.stack.fade_out(id, now, slow);
1106 }
1107 for id in self.stack.gone(now) {
1108 self.stack.remove(id);
1109 }
1110 self.stack.promote(now, fade_in);
1111 self.sync_hover_hold(now);
1112 if !self.urgent_repeats.is_empty() {
1113 self.repeat_urgent(cx);
1114 }
1115 if !self.app.read(cx).rings.is_empty() {
1116 self.app.update(cx, |state, cx| state.tick_rings(cx));
1117 }
1118 if self
1119 .app
1120 .read(cx)
1121 .meeting_toasts
1122 .is_due_for_check(Utc::now())
1123 {
1124 let show = !self.reminders_quiet(cx);
1125 self.app
1126 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
1127 }
1128 if !self.stack.is_empty()
1129 || !self.windows.is_empty()
1130 || self.pill.is_some()
1131 || !self.call_windows.is_empty()
1132 {
1133 self.sync_windows(cx);
1134 cx.notify();
1135 }
1136 self.poll_tray(cx);
1137 if single_instance::take_activation() {
1138 self.raise_main_window(cx);
1139 }
1140 for command in single_instance::take_commands() {
1141 self.app
1142 .update(cx, |state, cx| state.run_remote_command(&command, cx));
1143 }
1144 }
1145
1146 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
1147 let sidebar = &self.app.read(cx).sidebar;
1148 self.urgent_repeats.stop_read(|conversation_id| {
1149 sidebar
1150 .chats
1151 .iter()
1152 .find(|chat| chat.id == conversation_id)
1153 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
1154 });
1155 for incoming in self.urgent_repeats.due(Utc::now()) {
1156 let environment = self.environment(&incoming.conversation_id, cx);
1157 if environment.chat_in_foreground {
1158 self.urgent_repeats
1159 .stop_conversation(&incoming.conversation_id);
1160 continue;
1161 }
1162 self.stack.remove_conversation(&incoming.conversation_id);
1163 let decision = decide(&self.settings, &incoming, environment);
1164 self.present(&incoming, decision, cx);
1165 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
1166 && let Some(native) = self.main_native
1167 {
1168 platform::flash(native);
1169 }
1170 }
1171 }
1172
1173 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1174 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1175 for command in commands {
1176 match command {
1177 TrayCommand::Toggle => self.toggle_main_window(cx),
1178 TrayCommand::Open => self.raise_main_window(cx),
1179 TrayCommand::ToggleSound => self.update_settings(cx, |settings| {
1180 settings.sounds.notification_sound = !settings.sounds.notification_sound
1181 }),
1182 TrayCommand::ToggleDoNotDisturb => self.toggle_own_do_not_disturb(cx),
1183 TrayCommand::Settings => {
1184 self.raise_main_window(cx);
1185 self.app.update(cx, |state, cx| {
1186 state.open_settings(SettingsSection::Notifications, cx)
1187 });
1188 }
1189 TrayCommand::Quit => cx.quit(),
1190 }
1191 }
1192 }
1193
1194 fn toggle_own_do_not_disturb(&mut self, cx: &mut Context<Self>) {
1195 let forced = (!own_do_not_disturb(self.app.read(cx))).then_some(ForcedAvailability {
1196 kind: ForcedKind::DoNotDisturb,
1197 expires_at: None,
1198 });
1199 self.app
1200 .update(cx, |state, cx| state.set_own_availability(forced, cx));
1201 self.sync_tray(cx);
1202 }
1203
1204 fn sync_tray_presence(&mut self, cx: &App) {
1205 if self.tray_do_not_disturb != own_do_not_disturb(self.app.read(cx)) {
1206 self.sync_tray(cx);
1207 }
1208 }
1209
1210 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
1211 if self.main_window_active(cx) {
1212 if let Some(native) = self.main_native {
1213 platform::hide_window(native);
1214 } else {
1215 #[cfg(target_os = "linux")]
1216 crate::main_window::hide(cx);
1217 }
1218 } else {
1219 self.raise_main_window(cx);
1220 }
1221 }
1222
1223 pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context<Self>) {
1224 self.raise_main_window(cx);
1225 self.app
1226 .update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1227 }
1228
1229 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1230 #[cfg(target_os = "linux")]
1231 if crate::main_window::is_hidden(cx) {
1232 crate::main_window::show(cx);
1233 return;
1234 }
1235 if let Some(native) = self.main_native {
1236 platform::restore_and_raise(native);
1237 }
1238 self.main_window
1239 .update(cx, |_, window, _| window.activate_window())
1240 .ok();
1241 }
1242
1243 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1244 if icon != self.app_icon {
1245 self.show_app_icon(icon, cx);
1246 }
1247 }
1248
1249 fn show_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1250 self.app_icon = icon;
1251 let mention = !self.unread_mentions.is_empty();
1252 if let Some(tray) = &mut self.tray {
1253 tray.set_app_icon(icon.png(), mention);
1254 }
1255 let _ = self.main_window.update(cx, |_, window, _| {
1256 platform::set_window_icon(window, icon.png())
1257 });
1258 }
1259
1260 fn relocalize_tray(&self) {
1261 if let Some(tray) = &self.tray {
1262 tray.relocalize();
1263 }
1264 }
1265
1266 fn sync_tray(&mut self, cx: &App) {
1267 self.tray_do_not_disturb = own_do_not_disturb(self.app.read(cx));
1268 if let Some(tray) = &self.tray {
1269 tray.sync(
1270 self.settings.sounds.notification_sound,
1271 self.tray_do_not_disturb,
1272 !self.unread_mentions.is_empty(),
1273 );
1274 }
1275 }
1276
1277 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
1278 let state = self.app.read(cx);
1279 let count = taskbar_badge_count(
1280 &state.sidebar,
1281 self.activity.read(cx).feed(),
1282 state.directory.section_settings.adaptive_rail(),
1283 ) + crate::agent_api::unseen_proposal_count(cx);
1284 let still_unread = unread_conversation_ids(&state.sidebar);
1285 self.unread_mentions
1286 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1287 let badge = badge_for(count);
1288 let mention_dot = !self.unread_mentions.is_empty();
1289 if badge == self.shown_badge && mention_dot == self.shown_mention_dot {
1290 return;
1291 }
1292 self.shown_mention_dot = mention_dot;
1293 if badge != self.shown_badge
1294 && let Some(native) = self.main_native
1295 {
1296 platform::set_badge(native, badge.as_ref());
1297 if badge.is_none() && self.shown_badge.is_some() {
1298 platform::stop_flash(native);
1299 }
1300 }
1301 self.shown_badge = badge;
1302 self.sync_tray(cx);
1303 }
1304
1305 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
1306 let now = Instant::now();
1307 let Some(toast) = self.stack.get_mut(id) else {
1308 return;
1309 };
1310 if toast.hovered == hovered {
1311 return;
1312 }
1313 toast.hovered = hovered;
1314 self.sync_hover_hold(now);
1315 cx.notify();
1316 }
1317
1318 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
1319 self.drop_toast(id, cx);
1320 }
1321
1322 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
1323 let now = Instant::now();
1324 let toast = self.stack.get_mut(id)?;
1325 toast.reply = ReplyState::Open;
1326 toast.timer.pause(now);
1327 let draft = toast.reply_text.clone();
1328 cx.notify();
1329 Some(draft)
1330 }
1331
1332 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
1333 if let Some(toast) = self.stack.get_mut(id) {
1334 toast.reply = ReplyState::Closed;
1335 toast.reply_text.clear();
1336 toast.hovered = false;
1337 }
1338 cx.notify();
1339 }
1340
1341 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
1342 let Some(toast) = self.stack.get_mut(id) else {
1343 return;
1344 };
1345 toast.reply_text = text.clone();
1346 let conversation_id = toast.conversation_id.clone();
1347 let message_id = toast.message_id.clone();
1348 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
1349 let state = self.app.read(cx);
1350 let (mode, engine) = (state.mode, state.engine.clone());
1351 let outcome: Result<(), ()> = if mode.demo {
1352 Ok(())
1353 } else if mode.read_only {
1354 Err(())
1355 } else if let Some(engine) = engine {
1356 let receiver = runtime::spawn(async move {
1357 if is_channel {
1358 engine.reply_to(&conversation_id, &message_id, &text).await
1359 } else {
1360 engine.send_message(&conversation_id, &text, None).await
1361 }
1362 .map(|_| ())
1363 });
1364 cx.spawn(async move |this, cx| {
1365 let sent = matches!(receiver.await, Ok(Ok(())));
1366 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
1367 .ok();
1368 })
1369 .detach();
1370 return;
1371 } else {
1372 Err(())
1373 };
1374 self.finish_reply(id, outcome.is_ok(), cx);
1375 }
1376
1377 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
1378 let Some(toast) = self.stack.get_mut(id) else {
1379 return;
1380 };
1381 toast.reply = if sent {
1382 ReplyState::Sent
1383 } else {
1384 ReplyState::Failed
1385 };
1386 let conversation_id = toast.conversation_id.clone();
1387 cx.notify();
1388 if sent {
1389 cx.spawn(async move |this, cx| {
1390 cx.background_executor().timer(SENT_DURATION).await;
1391 this.update(cx, |center, cx| {
1392 center.mark_conversation_read(&conversation_id, cx);
1393 center.drop_toast(id, cx);
1394 })
1395 .ok();
1396 })
1397 .detach();
1398 }
1399 }
1400
1401 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1402 self.unread_mentions.remove(conversation_id);
1403 let conversation_id = conversation_id.to_owned();
1404 self.app
1405 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
1406 self.refresh_badge(cx);
1407 }
1408
1409 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
1410 if self.is_dismissed(id) {
1411 return;
1412 }
1413 let Some(conversation_id) = self
1414 .stack
1415 .get(id)
1416 .map(|toast| toast.conversation_id.clone())
1417 else {
1418 return;
1419 };
1420 self.mark_conversation_read(&conversation_id, cx);
1421 self.drop_toast(id, cx);
1422 }
1423
1424 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
1425 if self.is_dismissed(id) {
1426 return;
1427 }
1428 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1429 (
1430 toast.conversation_id.clone(),
1431 toast.message_id.clone(),
1432 toast
1433 .agent
1434 .as_ref()
1435 .and_then(|agent| agent.proposal_id().map(str::to_owned)),
1436 )
1437 }) else {
1438 return;
1439 };
1440 self.drop_toast(id, cx);
1441 if let Some(proposal_id) = proposal_id {
1442 agent_api::mark_proposal_seen(&proposal_id, cx);
1443 }
1444 self.raise_main_window(cx);
1445 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1446 if let Some(selection) = selection {
1447 self.app.update(cx, |state, cx| {
1448 if message_id.is_empty() {
1449 state.select(selection, cx)
1450 } else {
1451 state.jump_to_message(selection, message_id, cx)
1452 }
1453 });
1454 }
1455 }
1456
1457 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
1458 let incoming = Incoming {
1459 conversation_id: "test-notification".to_owned(),
1460 message_id: "test".to_owned(),
1461 kind: ChatKind::Direct,
1462 chat_title: "Mara Lindqvist".to_owned(),
1463 sender_id: None,
1464 sender_name: "Mara Lindqvist".to_owned(),
1465 preview: Preview::Text("This is a test notification.".to_owned()),
1466 mentions_me: false,
1467 muted: false,
1468 signals: Default::default(),
1469 chat: Default::default(),
1470 created_at: Utc::now(),
1471 importance: Default::default(),
1472 };
1473 let decision = Decision {
1474 toast: true,
1475 sound: self.settings.sounds.notification_sound,
1476 urgent_sound: false,
1477 };
1478 self.throttle = SoundThrottle::default();
1479 self.present(&incoming, decision, cx);
1480 }
1481
1482 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
1483 for incoming in demo_incoming() {
1484 let decision = Decision {
1485 toast: true,
1486 sound: false,
1487 urgent_sound: false,
1488 };
1489 self.present(&incoming, decision, cx);
1490 }
1491 }
1492}
1493
1494/// Opens a window outside the current update: `open_window` draws right away, and every
1495/// notification view reads the center while rendering.
1496fn open_popup<V: Into<AnyView>>(
1497 options: WindowOptions,
1498 cx: &mut Context<NotificationCenter>,
1499 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1500 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1501) {
1502 let center = cx.entity();
1503 cx.defer(move |cx| {
1504 let view_center = center.clone();
1505 let Ok(handle) = cx.open_window(options, move |window, cx| {
1506 let view = build(view_center, window, cx);
1507 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
1508 }) else {
1509 center.update(cx, |this, _| opened(this, None));
1510 return;
1511 };
1512 let handle = AnyWindowHandle::from(handle);
1513 let native = handle
1514 .update(cx, |_, window, _| platform::native_handle(window))
1515 .ok()
1516 .flatten();
1517 if let Some(native) = native {
1518 platform::prepare_toast_window(native);
1519 }
1520 let window = OpenWindow {
1521 handle,
1522 native,
1523 opened: Instant::now(),
1524 placed: Cell::new(None),
1525 };
1526 center.update(cx, |this, _| opened(this, Some(window)));
1527 });
1528}
1529
1530fn window_is_open(window_id: WindowId, cx: &App) -> bool {
1531 cx.windows()
1532 .iter()
1533 .any(|window| window.window_id() == window_id)
1534}
1535
1536fn own_presence(state: &AppState) -> PresenceKind {
1537 state
1538 .directory
1539 .me
1540 .as_ref()
1541 .map_or(PresenceKind::Unknown, |me| {
1542 state.directory.presence_of(&me.user_id).kind()
1543 })
1544}
1545
1546fn own_do_not_disturb(state: &AppState) -> bool {
1547 own_presence(state) == PresenceKind::DoNotDisturb
1548}
1549
1550fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1551 match (audible, handle.is_some()) {
1552 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
1553 (false, true) => *handle = None,
1554 _ => {}
1555 }
1556}
1557
1558fn demo_scene() -> Option<DemoScene> {
1559 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1560}
1561
1562/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
1563fn demo_ring_delay() -> Option<Duration> {
1564 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
1565 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
1566}
1567
1568fn first_lines(text: &str, count: usize) -> String {
1569 text.lines()
1570 .map(str::trim)
1571 .filter(|line| !line.is_empty())
1572 .take(count)
1573 .collect::<Vec<_>>()
1574 .join("\n")
1575}
1576
1577fn preview_lines(text: &str, cx: &App) -> usize {
1578 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
1579}
1580
1581fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
1582 let mut wrapper = cx
1583 .text_system()
1584 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
1585 text.split('\n')
1586 .map(|line| {
1587 let fragments = [LineFragment::text(line)];
1588 wrapper
1589 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
1590 .count()
1591 + 1
1592 })
1593 .sum()
1594}
1595
1596fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1597 let scale = area.scale;
1598 let bounds = Bounds::new(
1599 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
1600 size(
1601 px(slot.width as f32 / scale),
1602 px(slot.height as f32 / scale),
1603 ),
1604 );
1605 WindowOptions {
1606 window_bounds: Some(WindowBounds::Windowed(bounds)),
1607 titlebar: None,
1608 focus: false,
1609 show: true,
1610 kind: WindowKind::PopUp,
1611 is_movable: false,
1612 is_resizable: false,
1613 is_minimizable: false,
1614 window_background: WindowBackgroundAppearance::Transparent,
1615 ..Default::default()
1616 }
1617}
1618
1619pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1620 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1621 let channels = sidebar
1622 .teams
1623 .iter()
1624 .flat_map(|team| team.channels.iter())
1625 .filter(|channel| channel.unread);
1626 chats
1627 .map(|chat| chat.id.as_str())
1628 .chain(channels.map(|channel| channel.id.as_str()))
1629 .collect()
1630}
1631
1632fn demo_incoming() -> Vec<Incoming> {
1633 let item = |conversation: &str,
1634 kind: ChatKind,
1635 title: &str,
1636 sender: &str,
1637 text: &str,
1638 mention: bool| Incoming {
1639 conversation_id: conversation.to_owned(),
1640 message_id: format!("{conversation}-message"),
1641 kind,
1642 chat_title: title.to_owned(),
1643 sender_id: None,
1644 sender_name: sender.to_owned(),
1645 preview: Preview::Text(text.to_owned()),
1646 mentions_me: mention,
1647 muted: false,
1648 signals: Default::default(),
1649 chat: Default::default(),
1650 created_at: Utc::now(),
1651 importance: Default::default(),
1652 };
1653 vec![
1654 item(
1655 "demo-toast-direct",
1656 ChatKind::Direct,
1657 "Tobias Klein",
1658 "Tobias Klein",
1659 "Sounds good, I will look at it tomorrow.",
1660 false,
1661 ),
1662 item(
1663 "demo-toast-group",
1664 ChatKind::Group { member_count: 5 },
1665 "Retro-Team",
1666 "Priya Nair",
1667 "Please add topics by 5 pm.",
1668 false,
1669 ),
1670 item(
1671 "demo-toast-mention",
1672 ChatKind::Channel {
1673 team: "Platform".to_owned(),
1674 channel: "Releases".to_owned(),
1675 },
1676 "Releases",
1677 "Mara Lindqvist",
1678 "@Jonas can you approve the merge? The pipeline is waiting.",
1679 true,
1680 ),
1681 item(
1682 "demo-toast-lea",
1683 ChatKind::Direct,
1684 "Lea Schneider",
1685 "Lea Schneider",
1686 "Lunch at 12?",
1687 false,
1688 ),
1689 item(
1690 "demo-toast-jonas",
1691 ChatKind::Direct,
1692 "Jonas Ortega",
1693 "Jonas Ortega",
1694 "Deploy window moved to Thursday 6 pm.",
1695 false,
1696 ),
1697 ]
1698}
1699
1700#[cfg(test)]
1701mod tests {
1702 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
1703
1704 use std::collections::HashSet;
1705
1706 use gpui_kit::{WindowBackgroundAppearance, WindowKind};
1707
1708 use super::{Slot, WorkArea, popup_options, preview_lines, unread_conversation_ids};
1709 use store::Sidebar;
1710
1711 #[test]
1712 fn toast_windows_ask_for_a_transparent_background() {
1713 let slot = Slot {
1714 x: 0,
1715 y: 0,
1716 width: 360,
1717 height: 120,
1718 };
1719 let area = WorkArea {
1720 left: 0,
1721 top: 0,
1722 right: 1920,
1723 bottom: 1080,
1724 scale: 1.,
1725 };
1726 let options = popup_options(slot, area);
1727 assert_eq!(
1728 options.window_background,
1729 WindowBackgroundAppearance::Transparent
1730 );
1731 assert_eq!(options.kind, WindowKind::PopUp);
1732 }
1733
1734 fn sidebar() -> Sidebar {
1735 Sidebar {
1736 chats: vec![
1737 ChatRecord {
1738 id: "a".into(),
1739 unread: true,
1740 ..Default::default()
1741 },
1742 ChatRecord {
1743 id: "b".into(),
1744 unread: false,
1745 ..Default::default()
1746 },
1747 ],
1748 teams: vec![SidebarTeam {
1749 rights: Default::default(),
1750 team: TeamRecord {
1751 id: "t".into(),
1752 name: "Team".into(),
1753 },
1754 channels: vec![ChannelRecord {
1755 id: "ch".into(),
1756 team_id: "t".into(),
1757 name: "General".into(),
1758 membership_type: None,
1759 last_message_at: None,
1760 unread: true,
1761 }],
1762 hidden: false,
1763 hidden_channel_ids: Vec::new(),
1764 notifications: Default::default(),
1765 mentions: Default::default(),
1766 }],
1767 }
1768 }
1769
1770 #[test]
1771 fn unread_conversation_ids_hold_chats_and_channels() {
1772 let sidebar = sidebar();
1773 assert_eq!(
1774 unread_conversation_ids(&sidebar),
1775 HashSet::from(["a", "ch"])
1776 );
1777 }
1778
1779 #[gpui_kit::test]
1780 fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) {
1781 cx.update(|cx| {
1782 assert_eq!(preview_lines("ok", cx), 1);
1783 assert_eq!(preview_lines("a\nb", cx), 2);
1784 let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3);
1785 assert!(preview_lines(&long, cx) >= 2);
1786 });
1787 }
1788}