BlueGit

ict rusty-teams

Files

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

center.rs

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