BlueGit

ict rusty-teams

Files

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

center.rs

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