BlueGit

ict rusty-teams

Files

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

center.rs

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