notifications.rs

   1use crate::{MultiWorkspace, SuppressNotification, Toast, Workspace};
   2use anyhow::Context as _;
   3use gpui::{
   4    AnyEntity, AnyView, App, AppContext as _, AsyncApp, AsyncWindowContext, ClickEvent, Context,
   5    DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, PromptLevel, Render, ScrollHandle,
   6    Task, TextStyleRefinement, UnderlineStyle, WeakEntity, svg,
   7};
   8use markdown::{CopyButtonVisibility, Markdown, MarkdownElement, MarkdownStyle};
   9use parking_lot::Mutex;
  10use project::project_settings::ProjectSettings;
  11use settings::Settings;
  12use theme_settings::ThemeSettings;
  13
  14use std::ops::Deref;
  15use std::sync::{Arc, LazyLock};
  16use std::{any::TypeId, time::Duration};
  17use ui::{CopyButton, Tooltip, prelude::*};
  18use util::ResultExt;
  19
  20#[derive(Default)]
  21pub struct Notifications {
  22    notifications: Vec<(NotificationId, AnyView)>,
  23}
  24
  25impl Deref for Notifications {
  26    type Target = Vec<(NotificationId, AnyView)>;
  27
  28    fn deref(&self) -> &Self::Target {
  29        &self.notifications
  30    }
  31}
  32
  33impl std::ops::DerefMut for Notifications {
  34    fn deref_mut(&mut self) -> &mut Self::Target {
  35        &mut self.notifications
  36    }
  37}
  38
  39#[derive(Debug, Eq, PartialEq, Clone, Hash)]
  40pub enum NotificationId {
  41    Unique(TypeId),
  42    Composite(TypeId, ElementId),
  43    Named(SharedString),
  44}
  45
  46impl NotificationId {
  47    /// Returns a unique [`NotificationId`] for the given type.
  48    pub const fn unique<T: 'static>() -> Self {
  49        Self::Unique(TypeId::of::<T>())
  50    }
  51
  52    /// Returns a [`NotificationId`] for the given type that is also identified
  53    /// by the provided ID.
  54    pub fn composite<T: 'static>(id: impl Into<ElementId>) -> Self {
  55        Self::Composite(TypeId::of::<T>(), id.into())
  56    }
  57
  58    /// Builds a `NotificationId` out of the given string.
  59    pub fn named(id: SharedString) -> Self {
  60        Self::Named(id)
  61    }
  62}
  63
  64pub trait Notification:
  65    EventEmitter<DismissEvent> + EventEmitter<SuppressEvent> + Focusable + Render
  66{
  67}
  68
  69pub struct SuppressEvent;
  70
  71impl Workspace {
  72    #[cfg(any(test, feature = "test-support"))]
  73    pub fn notification_ids(&self) -> Vec<NotificationId> {
  74        self.notifications
  75            .iter()
  76            .map(|(id, _)| id)
  77            .cloned()
  78            .collect()
  79    }
  80
  81    pub fn show_notification<V: Notification>(
  82        &mut self,
  83        id: NotificationId,
  84        cx: &mut Context<Self>,
  85        build_notification: impl FnOnce(&mut Context<Self>) -> Entity<V>,
  86    ) {
  87        self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
  88            let notification = build_notification(cx);
  89            cx.subscribe(&notification, {
  90                let id = id.clone();
  91                move |this, _, _: &DismissEvent, cx| {
  92                    this.dismiss_notification(&id, cx);
  93                }
  94            })
  95            .detach();
  96            cx.subscribe(&notification, {
  97                let id = id.clone();
  98                move |workspace: &mut Workspace, _, _: &SuppressEvent, cx| {
  99                    workspace.suppress_notification(&id, cx);
 100                }
 101            })
 102            .detach();
 103
 104            if let Ok(prompt) =
 105                AnyEntity::from(notification.clone()).downcast::<LanguageServerPrompt>()
 106            {
 107                let is_prompt_without_actions = prompt
 108                    .read(cx)
 109                    .request
 110                    .as_ref()
 111                    .is_some_and(|request| request.actions.is_empty());
 112
 113                let dismiss_timeout_ms = ProjectSettings::get_global(cx)
 114                    .global_lsp_settings
 115                    .notifications
 116                    .dismiss_timeout_ms;
 117
 118                if is_prompt_without_actions {
 119                    if let Some(dismiss_duration_ms) = dismiss_timeout_ms.filter(|&ms| ms > 0) {
 120                        let task = cx.spawn({
 121                            let id = id.clone();
 122                            async move |this, cx| {
 123                                cx.background_executor()
 124                                    .timer(Duration::from_millis(dismiss_duration_ms))
 125                                    .await;
 126                                let _ = this.update(cx, |workspace, cx| {
 127                                    workspace.dismiss_notification(&id, cx);
 128                                });
 129                            }
 130                        });
 131                        prompt.update(cx, |prompt, _| {
 132                            prompt.dismiss_task = Some(task);
 133                        });
 134                    }
 135                }
 136            }
 137            notification.into()
 138        });
 139    }
 140
 141    /// Shows a notification in this workspace's window. Caller must handle dismiss.
 142    ///
 143    /// This exists so that the `build_notification` closures stored for app notifications can
 144    /// return `AnyView`. Subscribing to events from an `AnyView` is not supported, so instead that
 145    /// responsibility is pushed to the caller where the `V` type is known.
 146    pub(crate) fn show_notification_without_handling_dismiss_events(
 147        &mut self,
 148        id: &NotificationId,
 149        cx: &mut Context<Self>,
 150        build_notification: impl FnOnce(&mut Context<Self>) -> AnyView,
 151    ) {
 152        if self.suppressed_notifications.contains(id) {
 153            return;
 154        }
 155        self.dismiss_notification(id, cx);
 156        self.notifications
 157            .push((id.clone(), build_notification(cx)));
 158        cx.notify();
 159    }
 160
 161    pub fn show_error<E>(&mut self, err: &E, cx: &mut Context<Self>)
 162    where
 163        E: std::fmt::Debug + std::fmt::Display,
 164    {
 165        self.show_notification(workspace_error_notification_id(), cx, |cx| {
 166            cx.new(|cx| ErrorMessagePrompt::new(format!("Error: {err}"), cx))
 167        });
 168    }
 169
 170    pub fn show_portal_error(&mut self, err: String, cx: &mut Context<Self>) {
 171        struct PortalError;
 172
 173        self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
 174            cx.new(|cx| {
 175                ErrorMessagePrompt::new(err.to_string(), cx).with_link_button(
 176                    "See docs",
 177                    "https://zed.dev/docs/linux#i-cant-open-any-files",
 178                )
 179            })
 180        });
 181    }
 182
 183    pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 184        self.notifications.retain(|(existing_id, _)| {
 185            if existing_id == id {
 186                cx.notify();
 187                false
 188            } else {
 189                true
 190            }
 191        });
 192    }
 193
 194    pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<Self>) {
 195        self.dismiss_notification(&toast.id, cx);
 196        self.show_notification(toast.id.clone(), cx, |cx| {
 197            cx.new(|cx| match toast.on_click.as_ref() {
 198                Some((click_msg, on_click)) => {
 199                    let on_click = on_click.clone();
 200                    simple_message_notification::MessageNotification::new(toast.msg.clone(), cx)
 201                        .primary_message(click_msg.clone())
 202                        .primary_on_click(move |window, cx| on_click(window, cx))
 203                }
 204                None => {
 205                    simple_message_notification::MessageNotification::new(toast.msg.clone(), cx)
 206                }
 207            })
 208        });
 209        if toast.autohide {
 210            cx.spawn(async move |workspace, cx| {
 211                cx.background_executor()
 212                    .timer(Duration::from_millis(5000))
 213                    .await;
 214                workspace
 215                    .update(cx, |workspace, cx| workspace.dismiss_toast(&toast.id, cx))
 216                    .ok();
 217            })
 218            .detach();
 219        }
 220    }
 221
 222    pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 223        self.dismiss_notification(id, cx);
 224    }
 225
 226    pub fn clear_all_notifications(&mut self, cx: &mut Context<Self>) {
 227        self.notifications.clear();
 228        cx.notify();
 229    }
 230
 231    /// Hide all notifications matching the given ID
 232    pub fn suppress_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
 233        self.dismiss_notification(id, cx);
 234        self.suppressed_notifications.insert(id.clone());
 235    }
 236
 237    pub fn is_notification_suppressed(&self, notification_id: NotificationId) -> bool {
 238        self.suppressed_notifications.contains(&notification_id)
 239    }
 240
 241    pub fn unsuppress(&mut self, notification_id: NotificationId) {
 242        self.suppressed_notifications.remove(&notification_id);
 243    }
 244
 245    pub fn show_initial_notifications(&mut self, cx: &mut Context<Self>) {
 246        // Allow absence of the global so that tests don't need to initialize it.
 247        let app_notifications = GLOBAL_APP_NOTIFICATIONS
 248            .lock()
 249            .app_notifications
 250            .iter()
 251            .cloned()
 252            .collect::<Vec<_>>();
 253        for (id, build_notification) in app_notifications {
 254            self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
 255                build_notification(cx)
 256            });
 257        }
 258    }
 259}
 260
 261pub struct LanguageServerPrompt {
 262    focus_handle: FocusHandle,
 263    request: Option<project::LanguageServerPromptRequest>,
 264    scroll_handle: ScrollHandle,
 265    markdown: Entity<Markdown>,
 266    dismiss_task: Option<Task<()>>,
 267}
 268
 269impl Focusable for LanguageServerPrompt {
 270    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
 271        self.focus_handle.clone()
 272    }
 273}
 274
 275impl Notification for LanguageServerPrompt {}
 276
 277impl LanguageServerPrompt {
 278    pub fn new(request: project::LanguageServerPromptRequest, cx: &mut App) -> Self {
 279        let markdown = cx.new(|cx| Markdown::new(request.message.clone().into(), None, None, cx));
 280
 281        Self {
 282            focus_handle: cx.focus_handle(),
 283            request: Some(request),
 284            scroll_handle: ScrollHandle::new(),
 285            markdown,
 286            dismiss_task: None,
 287        }
 288    }
 289
 290    async fn select_option(this: Entity<Self>, ix: usize, cx: &mut AsyncWindowContext) {
 291        util::maybe!(async move {
 292            let potential_future = this.update(cx, |this, _| {
 293                this.request.take().map(|request| request.respond(ix))
 294            });
 295
 296            potential_future
 297                .context("Response already sent")?
 298                .await
 299                .context("Stream already closed")?;
 300
 301            this.update(cx, |this, cx| {
 302                this.dismiss_notification(cx);
 303            });
 304
 305            anyhow::Ok(())
 306        })
 307        .await
 308        .log_err();
 309    }
 310
 311    fn dismiss_notification(&mut self, cx: &mut Context<Self>) {
 312        self.dismiss_task = None;
 313        cx.emit(DismissEvent);
 314    }
 315}
 316
 317impl Render for LanguageServerPrompt {
 318    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 319        let Some(request) = &self.request else {
 320            return div().id("language_server_prompt_notification");
 321        };
 322
 323        let (icon, color) = match request.level {
 324            PromptLevel::Info => (IconName::Info, Color::Muted),
 325            PromptLevel::Warning => (IconName::Warning, Color::Warning),
 326            PromptLevel::Critical => (IconName::XCircle, Color::Error),
 327        };
 328
 329        let suppress = window.modifiers().shift;
 330        let (close_id, close_icon) = if suppress {
 331            ("suppress", IconName::Minimize)
 332        } else {
 333            ("close", IconName::Close)
 334        };
 335
 336        div()
 337            .id("language_server_prompt_notification")
 338            .group("language_server_prompt_notification")
 339            .occlude()
 340            .w_full()
 341            .max_h(vh(0.8, window))
 342            .elevation_3(cx)
 343            .overflow_y_scroll()
 344            .track_scroll(&self.scroll_handle)
 345            .on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
 346            .child(
 347                v_flex()
 348                    .p_3()
 349                    .overflow_hidden()
 350                    .child(
 351                        h_flex()
 352                            .justify_between()
 353                            .child(
 354                                h_flex()
 355                                    .gap_2()
 356                                    .child(Icon::new(icon).color(color).size(IconSize::Small))
 357                                    .child(Label::new(request.lsp_name.clone())),
 358                            )
 359                            .child(
 360                                h_flex()
 361                                    .gap_1()
 362                                    .child(
 363                                        CopyButton::new(
 364                                            "copy-description",
 365                                            request.message.clone(),
 366                                        )
 367                                        .tooltip_label("Copy Description"),
 368                                    )
 369                                    .child(
 370                                        IconButton::new(close_id, close_icon)
 371                                            .tooltip(move |_window, cx| {
 372                                                if suppress {
 373                                                    Tooltip::with_meta(
 374                                                        "Suppress",
 375                                                        Some(&SuppressNotification),
 376                                                        "Click to close",
 377                                                        cx,
 378                                                    )
 379                                                } else {
 380                                                    Tooltip::with_meta(
 381                                                        "Close",
 382                                                        Some(&menu::Cancel),
 383                                                        "Suppress with shift-click",
 384                                                        cx,
 385                                                    )
 386                                                }
 387                                            })
 388                                            .on_click(cx.listener(
 389                                                move |this, _: &ClickEvent, _, cx| {
 390                                                    if suppress {
 391                                                        cx.emit(SuppressEvent);
 392                                                    } else {
 393                                                        this.dismiss_notification(cx);
 394                                                    }
 395                                                },
 396                                            )),
 397                                    ),
 398                            ),
 399                    )
 400                    .child(
 401                        MarkdownElement::new(self.markdown.clone(), markdown_style(window, cx))
 402                            .text_size(TextSize::Small.rems(cx))
 403                            .code_block_renderer(markdown::CodeBlockRenderer::Default {
 404                                copy_button_visibility: CopyButtonVisibility::Hidden,
 405                                border: false,
 406                            })
 407                            .on_url_click(|link, _, cx| cx.open_url(&link)),
 408                    )
 409                    .children(request.actions.iter().enumerate().map(|(ix, action)| {
 410                        let this_handle = cx.entity();
 411                        Button::new(ix, action.title.clone())
 412                            .size(ButtonSize::Large)
 413                            .on_click(move |_, window, cx| {
 414                                let this_handle = this_handle.clone();
 415                                window
 416                                    .spawn(cx, async move |cx| {
 417                                        LanguageServerPrompt::select_option(this_handle, ix, cx)
 418                                            .await
 419                                    })
 420                                    .detach()
 421                            })
 422                    })),
 423            )
 424    }
 425}
 426
 427impl EventEmitter<DismissEvent> for LanguageServerPrompt {}
 428impl EventEmitter<SuppressEvent> for LanguageServerPrompt {}
 429
 430fn workspace_error_notification_id() -> NotificationId {
 431    struct WorkspaceErrorNotification;
 432    NotificationId::unique::<WorkspaceErrorNotification>()
 433}
 434
 435fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
 436    let settings = ThemeSettings::get_global(cx);
 437    let ui_font_family = settings.ui_font.family.clone();
 438    let ui_font_fallbacks = settings.ui_font.fallbacks.clone();
 439    let buffer_font_family = settings.buffer_font.family.clone();
 440    let buffer_font_fallbacks = settings.buffer_font.fallbacks.clone();
 441
 442    let mut base_text_style = window.text_style();
 443    base_text_style.refine(&TextStyleRefinement {
 444        font_family: Some(ui_font_family),
 445        font_fallbacks: ui_font_fallbacks,
 446        color: Some(cx.theme().colors().text),
 447        ..Default::default()
 448    });
 449
 450    MarkdownStyle {
 451        base_text_style,
 452        selection_background_color: cx.theme().colors().element_selection_background,
 453        inline_code: TextStyleRefinement {
 454            background_color: Some(cx.theme().colors().editor_background.opacity(0.5)),
 455            font_family: Some(buffer_font_family),
 456            font_fallbacks: buffer_font_fallbacks,
 457            ..Default::default()
 458        },
 459        link: TextStyleRefinement {
 460            underline: Some(UnderlineStyle {
 461                thickness: px(1.),
 462                color: Some(cx.theme().colors().text_accent),
 463                wavy: false,
 464            }),
 465            ..Default::default()
 466        },
 467        ..Default::default()
 468    }
 469}
 470
 471#[derive(Debug, Clone)]
 472pub struct ErrorMessagePrompt {
 473    message: SharedString,
 474    focus_handle: gpui::FocusHandle,
 475    label_and_url_button: Option<(SharedString, SharedString)>,
 476}
 477
 478impl ErrorMessagePrompt {
 479    pub fn new<S>(message: S, cx: &mut App) -> Self
 480    where
 481        S: Into<SharedString>,
 482    {
 483        Self {
 484            message: message.into(),
 485            focus_handle: cx.focus_handle(),
 486            label_and_url_button: None,
 487        }
 488    }
 489
 490    pub fn with_link_button<S>(mut self, label: S, url: S) -> Self
 491    where
 492        S: Into<SharedString>,
 493    {
 494        self.label_and_url_button = Some((label.into(), url.into()));
 495        self
 496    }
 497}
 498
 499impl Render for ErrorMessagePrompt {
 500    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 501        h_flex()
 502            .id("error_message_prompt_notification")
 503            .occlude()
 504            .elevation_3(cx)
 505            .items_start()
 506            .justify_between()
 507            .p_2()
 508            .gap_2()
 509            .w_full()
 510            .child(
 511                v_flex()
 512                    .w_full()
 513                    .child(
 514                        h_flex()
 515                            .w_full()
 516                            .justify_between()
 517                            .child(
 518                                svg()
 519                                    .size(window.text_style().font_size)
 520                                    .flex_none()
 521                                    .mr_2()
 522                                    .mt(px(-2.0))
 523                                    .map(|icon| {
 524                                        icon.path(IconName::Warning.path())
 525                                            .text_color(Color::Error.color(cx))
 526                                    }),
 527                            )
 528                            .child(
 529                                h_flex()
 530                                    .gap_1()
 531                                    .child(
 532                                        CopyButton::new("copy-error-message", self.message.clone())
 533                                            .tooltip_label("Copy Error Message"),
 534                                    )
 535                                    .child(
 536                                        ui::IconButton::new("close", ui::IconName::Close).on_click(
 537                                            cx.listener(|_, _, _, cx| cx.emit(DismissEvent)),
 538                                        ),
 539                                    ),
 540                            ),
 541                    )
 542                    .child(
 543                        div()
 544                            .id("error_message")
 545                            .max_w_96()
 546                            .max_h_40()
 547                            .overflow_y_scroll()
 548                            .child(Label::new(self.message.clone()).size(LabelSize::Small)),
 549                    )
 550                    .when_some(self.label_and_url_button.clone(), |elm, (label, url)| {
 551                        elm.child(
 552                            div().mt_2().child(
 553                                ui::Button::new("error_message_prompt_notification_button", label)
 554                                    .on_click(move |_, _, cx| cx.open_url(&url)),
 555                            ),
 556                        )
 557                    }),
 558            )
 559    }
 560}
 561
 562impl Focusable for ErrorMessagePrompt {
 563    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
 564        self.focus_handle.clone()
 565    }
 566}
 567
 568impl EventEmitter<DismissEvent> for ErrorMessagePrompt {}
 569impl EventEmitter<SuppressEvent> for ErrorMessagePrompt {}
 570
 571impl Notification for ErrorMessagePrompt {}
 572
 573#[derive(IntoElement, RegisterComponent)]
 574pub struct NotificationFrame {
 575    title: Option<SharedString>,
 576    show_suppress_button: bool,
 577    show_close_button: bool,
 578    close: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
 579    contents: Option<AnyElement>,
 580    suffix: Option<AnyElement>,
 581}
 582
 583impl NotificationFrame {
 584    pub fn new() -> Self {
 585        Self {
 586            title: None,
 587            contents: None,
 588            suffix: None,
 589            show_suppress_button: true,
 590            show_close_button: true,
 591            close: None,
 592        }
 593    }
 594
 595    pub fn with_title(mut self, title: Option<impl Into<SharedString>>) -> Self {
 596        self.title = title.map(Into::into);
 597        self
 598    }
 599
 600    pub fn with_content(self, content: impl IntoElement) -> Self {
 601        Self {
 602            contents: Some(content.into_any_element()),
 603            ..self
 604        }
 605    }
 606
 607    /// Determines whether the given notification ID should be suppressible
 608    /// Suppressed notifications will not be shown anymore
 609    pub fn show_suppress_button(mut self, show: bool) -> Self {
 610        self.show_suppress_button = show;
 611        self
 612    }
 613
 614    pub fn show_close_button(mut self, show: bool) -> Self {
 615        self.show_close_button = show;
 616        self
 617    }
 618
 619    pub fn on_close(self, on_close: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
 620        Self {
 621            close: Some(Box::new(on_close)),
 622            ..self
 623        }
 624    }
 625
 626    pub fn with_suffix(mut self, suffix: impl IntoElement) -> Self {
 627        self.suffix = Some(suffix.into_any_element());
 628        self
 629    }
 630}
 631
 632impl RenderOnce for NotificationFrame {
 633    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
 634        let entity = window.current_view();
 635        let show_suppress_button = self.show_suppress_button;
 636        let suppress = show_suppress_button && window.modifiers().shift;
 637        let (close_id, close_icon) = if suppress {
 638            ("suppress", IconName::Minimize)
 639        } else {
 640            ("close", IconName::Close)
 641        };
 642
 643        v_flex()
 644            .occlude()
 645            .p_3()
 646            .gap_2()
 647            .elevation_3(cx)
 648            .child(
 649                h_flex()
 650                    .gap_4()
 651                    .justify_between()
 652                    .items_start()
 653                    .child(
 654                        v_flex()
 655                            .gap_0p5()
 656                            .when_some(self.title.clone(), |div, title| {
 657                                div.child(Label::new(title))
 658                            })
 659                            .child(div().max_w_96().children(self.contents)),
 660                    )
 661                    .when(self.show_close_button, |this| {
 662                        this.on_modifiers_changed(move |_, _, cx| cx.notify(entity))
 663                            .child(
 664                                IconButton::new(close_id, close_icon)
 665                                    .tooltip(move |_window, cx| {
 666                                        if suppress {
 667                                            Tooltip::with_meta(
 668                                                "Suppress",
 669                                                Some(&SuppressNotification),
 670                                                "Click to Close",
 671                                                cx,
 672                                            )
 673                                        } else if show_suppress_button {
 674                                            Tooltip::with_meta(
 675                                                "Close",
 676                                                Some(&menu::Cancel),
 677                                                "Shift-click to Suppress",
 678                                                cx,
 679                                            )
 680                                        } else {
 681                                            Tooltip::for_action("Close", &menu::Cancel, cx)
 682                                        }
 683                                    })
 684                                    .on_click({
 685                                        let close = self.close.take();
 686                                        move |_, window, cx| {
 687                                            if let Some(close) = &close {
 688                                                close(&suppress, window, cx)
 689                                            }
 690                                        }
 691                                    }),
 692                            )
 693                    }),
 694            )
 695            .children(self.suffix)
 696    }
 697}
 698
 699impl Component for NotificationFrame {}
 700
 701pub mod simple_message_notification {
 702    use std::sync::Arc;
 703
 704    use gpui::{
 705        AnyElement, DismissEvent, EventEmitter, FocusHandle, Focusable, ParentElement, Render,
 706        ScrollHandle, SharedString, Styled,
 707    };
 708    use ui::{WithScrollbar, prelude::*};
 709
 710    use crate::notifications::NotificationFrame;
 711
 712    use super::{Notification, SuppressEvent};
 713
 714    pub struct MessageNotification {
 715        focus_handle: FocusHandle,
 716        build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
 717        primary_message: Option<SharedString>,
 718        primary_icon: Option<IconName>,
 719        primary_icon_color: Option<Color>,
 720        primary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
 721        secondary_message: Option<SharedString>,
 722        secondary_icon: Option<IconName>,
 723        secondary_icon_color: Option<Color>,
 724        secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
 725        more_info_message: Option<SharedString>,
 726        more_info_url: Option<Arc<str>>,
 727        show_close_button: bool,
 728        show_suppress_button: bool,
 729        title: Option<SharedString>,
 730        scroll_handle: ScrollHandle,
 731    }
 732
 733    impl Focusable for MessageNotification {
 734        fn focus_handle(&self, _: &App) -> FocusHandle {
 735            self.focus_handle.clone()
 736        }
 737    }
 738
 739    impl EventEmitter<DismissEvent> for MessageNotification {}
 740    impl EventEmitter<SuppressEvent> for MessageNotification {}
 741
 742    impl Notification for MessageNotification {}
 743
 744    impl MessageNotification {
 745        pub fn new<S>(message: S, cx: &mut App) -> MessageNotification
 746        where
 747            S: Into<SharedString>,
 748        {
 749            let message = message.into();
 750            Self::new_from_builder(cx, move |_, _| {
 751                Label::new(message.clone()).into_any_element()
 752            })
 753        }
 754
 755        pub fn new_from_builder<F>(cx: &mut App, content: F) -> MessageNotification
 756        where
 757            F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
 758        {
 759            Self {
 760                build_content: Box::new(content),
 761                primary_message: None,
 762                primary_icon: None,
 763                primary_icon_color: None,
 764                primary_on_click: None,
 765                secondary_message: None,
 766                secondary_icon: None,
 767                secondary_icon_color: None,
 768                secondary_on_click: None,
 769                more_info_message: None,
 770                more_info_url: None,
 771                show_close_button: true,
 772                show_suppress_button: true,
 773                title: None,
 774                focus_handle: cx.focus_handle(),
 775                scroll_handle: ScrollHandle::new(),
 776            }
 777        }
 778
 779        pub fn primary_message<S>(mut self, message: S) -> Self
 780        where
 781            S: Into<SharedString>,
 782        {
 783            self.primary_message = Some(message.into());
 784            self
 785        }
 786
 787        pub fn primary_icon(mut self, icon: IconName) -> Self {
 788            self.primary_icon = Some(icon);
 789            self
 790        }
 791
 792        pub fn primary_icon_color(mut self, color: Color) -> Self {
 793            self.primary_icon_color = Some(color);
 794            self
 795        }
 796
 797        pub fn primary_on_click<F>(mut self, on_click: F) -> Self
 798        where
 799            F: 'static + Fn(&mut Window, &mut Context<Self>),
 800        {
 801            self.primary_on_click = Some(Arc::new(on_click));
 802            self
 803        }
 804
 805        pub fn primary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
 806        where
 807            F: 'static + Fn(&mut Window, &mut Context<Self>),
 808        {
 809            self.primary_on_click = Some(on_click);
 810            self
 811        }
 812
 813        pub fn secondary_message<S>(mut self, message: S) -> Self
 814        where
 815            S: Into<SharedString>,
 816        {
 817            self.secondary_message = Some(message.into());
 818            self
 819        }
 820
 821        pub fn secondary_icon(mut self, icon: IconName) -> Self {
 822            self.secondary_icon = Some(icon);
 823            self
 824        }
 825
 826        pub fn secondary_icon_color(mut self, color: Color) -> Self {
 827            self.secondary_icon_color = Some(color);
 828            self
 829        }
 830
 831        pub fn secondary_on_click<F>(mut self, on_click: F) -> Self
 832        where
 833            F: 'static + Fn(&mut Window, &mut Context<Self>),
 834        {
 835            self.secondary_on_click = Some(Arc::new(on_click));
 836            self
 837        }
 838
 839        pub fn secondary_on_click_arc<F>(mut self, on_click: Arc<F>) -> Self
 840        where
 841            F: 'static + Fn(&mut Window, &mut Context<Self>),
 842        {
 843            self.secondary_on_click = Some(on_click);
 844            self
 845        }
 846
 847        pub fn more_info_message<S>(mut self, message: S) -> Self
 848        where
 849            S: Into<SharedString>,
 850        {
 851            self.more_info_message = Some(message.into());
 852            self
 853        }
 854
 855        pub fn more_info_url<S>(mut self, url: S) -> Self
 856        where
 857            S: Into<Arc<str>>,
 858        {
 859            self.more_info_url = Some(url.into());
 860            self
 861        }
 862
 863        pub fn dismiss(&mut self, cx: &mut Context<Self>) {
 864            cx.emit(DismissEvent);
 865        }
 866
 867        pub fn show_close_button(mut self, show: bool) -> Self {
 868            self.show_close_button = show;
 869            self
 870        }
 871
 872        /// Determines whether the given notification ID should be suppressible
 873        /// Suppressed notifications will not be shown anymor
 874        pub fn show_suppress_button(mut self, show: bool) -> Self {
 875            self.show_suppress_button = show;
 876            self
 877        }
 878
 879        pub fn with_title<S>(mut self, title: S) -> Self
 880        where
 881            S: Into<SharedString>,
 882        {
 883            self.title = Some(title.into());
 884            self
 885        }
 886    }
 887
 888    impl Render for MessageNotification {
 889        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 890            NotificationFrame::new()
 891                .with_title(self.title.clone())
 892                .with_content(
 893                    div()
 894                        .child(
 895                            div()
 896                                .id("message-notification-content")
 897                                .max_h(vh(0.6, window))
 898                                .overflow_y_scroll()
 899                                .track_scroll(&self.scroll_handle.clone())
 900                                .child((self.build_content)(window, cx)),
 901                        )
 902                        .vertical_scrollbar_for(&self.scroll_handle, window, cx),
 903                )
 904                .show_close_button(self.show_close_button)
 905                .show_suppress_button(self.show_suppress_button)
 906                .on_close(cx.listener(|_, suppress, _, cx| {
 907                    if *suppress {
 908                        cx.emit(SuppressEvent);
 909                    } else {
 910                        cx.emit(DismissEvent);
 911                    }
 912                }))
 913                .with_suffix(
 914                    h_flex()
 915                        .gap_1()
 916                        .children(self.primary_message.iter().map(|message| {
 917                            let mut button = Button::new(message.clone(), message.clone())
 918                                .label_size(LabelSize::Small)
 919                                .on_click(cx.listener(|this, _, window, cx| {
 920                                    if let Some(on_click) = this.primary_on_click.as_ref() {
 921                                        (on_click)(window, cx)
 922                                    };
 923                                    this.dismiss(cx)
 924                                }));
 925
 926                            if let Some(icon) = self.primary_icon {
 927                                button = button.start_icon(
 928                                    Icon::new(icon)
 929                                        .size(IconSize::Small)
 930                                        .color(self.primary_icon_color.unwrap_or(Color::Muted)),
 931                                );
 932                            }
 933
 934                            button
 935                        }))
 936                        .children(self.secondary_message.iter().map(|message| {
 937                            let mut button = Button::new(message.clone(), message.clone())
 938                                .label_size(LabelSize::Small)
 939                                .on_click(cx.listener(|this, _, window, cx| {
 940                                    if let Some(on_click) = this.secondary_on_click.as_ref() {
 941                                        (on_click)(window, cx)
 942                                    };
 943                                    this.dismiss(cx)
 944                                }));
 945
 946                            if let Some(icon) = self.secondary_icon {
 947                                button = button.start_icon(
 948                                    Icon::new(icon)
 949                                        .size(IconSize::Small)
 950                                        .color(self.secondary_icon_color.unwrap_or(Color::Muted)),
 951                                );
 952                            }
 953
 954                            button
 955                        }))
 956                        .child(
 957                            h_flex().w_full().justify_end().children(
 958                                self.more_info_message
 959                                    .iter()
 960                                    .zip(self.more_info_url.iter())
 961                                    .map(|(message, url)| {
 962                                        let url = url.clone();
 963                                        Button::new(message.clone(), message.clone())
 964                                            .label_size(LabelSize::Small)
 965                                            .end_icon(
 966                                                Icon::new(IconName::ArrowUpRight)
 967                                                    .size(IconSize::Indicator)
 968                                                    .color(Color::Muted),
 969                                            )
 970                                            .on_click(cx.listener(move |_, _, _, cx| {
 971                                                cx.open_url(&url);
 972                                            }))
 973                                    }),
 974                            ),
 975                        ),
 976                )
 977        }
 978    }
 979}
 980
 981static GLOBAL_APP_NOTIFICATIONS: LazyLock<Mutex<AppNotifications>> = LazyLock::new(|| {
 982    Mutex::new(AppNotifications {
 983        app_notifications: Vec::new(),
 984    })
 985});
 986
 987/// Stores app notifications so that they can be shown in new workspaces.
 988struct AppNotifications {
 989    app_notifications: Vec<(
 990        NotificationId,
 991        Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
 992    )>,
 993}
 994
 995impl AppNotifications {
 996    pub fn insert(
 997        &mut self,
 998        id: NotificationId,
 999        build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync>,
1000    ) {
1001        self.remove(&id);
1002        self.app_notifications.push((id, build_notification))
1003    }
1004
1005    pub fn remove(&mut self, id: &NotificationId) {
1006        self.app_notifications
1007            .retain(|(existing_id, _)| existing_id != id);
1008    }
1009}
1010
1011/// Shows a notification in all workspaces. New workspaces will also receive the notification - this
1012/// is particularly to handle notifications that occur on initialization before any workspaces
1013/// exist. If the notification is dismissed within any workspace, it will be removed from all.
1014pub fn show_app_notification<V: Notification + 'static>(
1015    id: NotificationId,
1016    cx: &mut App,
1017    build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static + Send + Sync,
1018) {
1019    // Defer notification creation so that windows on the stack can be returned to GPUI
1020    cx.defer(move |cx| {
1021        // Handle dismiss events by removing the notification from all workspaces.
1022        let build_notification: Arc<dyn Fn(&mut Context<Workspace>) -> AnyView + Send + Sync> =
1023            Arc::new({
1024                let id = id.clone();
1025                move |cx| {
1026                    let notification = build_notification(cx);
1027                    cx.subscribe(&notification, {
1028                        let id = id.clone();
1029                        move |_, _, _: &DismissEvent, cx| {
1030                            dismiss_app_notification(&id, cx);
1031                        }
1032                    })
1033                    .detach();
1034                    cx.subscribe(&notification, {
1035                        let id = id.clone();
1036                        move |workspace: &mut Workspace, _, _: &SuppressEvent, cx| {
1037                            workspace.suppress_notification(&id, cx);
1038                        }
1039                    })
1040                    .detach();
1041                    notification.into()
1042                }
1043            });
1044
1045        // Store the notification so that new workspaces also receive it.
1046        GLOBAL_APP_NOTIFICATIONS
1047            .lock()
1048            .insert(id.clone(), build_notification.clone());
1049
1050        for window in cx.windows() {
1051            if let Some(multi_workspace) = window.downcast::<MultiWorkspace>() {
1052                multi_workspace
1053                    .update(cx, |multi_workspace, _window, cx| {
1054                        for workspace in multi_workspace.workspaces() {
1055                            workspace.update(cx, |workspace, cx| {
1056                                workspace.show_notification_without_handling_dismiss_events(
1057                                    &id,
1058                                    cx,
1059                                    |cx| build_notification(cx),
1060                                );
1061                            });
1062                        }
1063                    })
1064                    .ok(); // Doesn't matter if the windows are dropped
1065            }
1066        }
1067    });
1068}
1069
1070pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
1071    let id = id.clone();
1072    // Defer notification dismissal so that windows on the stack can be returned to GPUI
1073    cx.defer(move |cx| {
1074        GLOBAL_APP_NOTIFICATIONS.lock().remove(&id);
1075        for window in cx.windows() {
1076            if let Some(multi_workspace) = window.downcast::<MultiWorkspace>() {
1077                let id = id.clone();
1078                multi_workspace
1079                    .update(cx, |multi_workspace, _window, cx| {
1080                        for workspace in multi_workspace.workspaces() {
1081                            workspace.update(cx, |workspace, cx| {
1082                                workspace.dismiss_notification(&id, cx)
1083                            });
1084                        }
1085                    })
1086                    .ok();
1087            }
1088        }
1089    });
1090}
1091
1092pub trait NotifyResultExt {
1093    type Ok;
1094
1095    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
1096    -> Option<Self::Ok>;
1097
1098    fn notify_workspace_async_err(
1099        self,
1100        workspace: WeakEntity<Workspace>,
1101        cx: &mut AsyncApp,
1102    ) -> Option<Self::Ok>;
1103
1104    /// Notifies the active workspace if there is one, otherwise notifies all workspaces.
1105    fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
1106}
1107
1108impl<T, E> NotifyResultExt for std::result::Result<T, E>
1109where
1110    E: std::fmt::Debug + std::fmt::Display,
1111{
1112    type Ok = T;
1113
1114    fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
1115        match self {
1116            Ok(value) => Some(value),
1117            Err(err) => {
1118                log::error!("Showing error notification in workspace: {err:?}");
1119                workspace.show_error(&err, cx);
1120                None
1121            }
1122        }
1123    }
1124
1125    fn notify_workspace_async_err(
1126        self,
1127        workspace: WeakEntity<Workspace>,
1128        cx: &mut AsyncApp,
1129    ) -> Option<T> {
1130        match self {
1131            Ok(value) => Some(value),
1132            Err(err) => {
1133                log::error!("{err:?}");
1134                workspace
1135                    .update(cx, |workspace, cx| workspace.show_error(&err, cx))
1136                    .ok();
1137                None
1138            }
1139        }
1140    }
1141
1142    fn notify_app_err(self, cx: &mut App) -> Option<T> {
1143        match self {
1144            Ok(value) => Some(value),
1145            Err(err) => {
1146                let message: SharedString = format!("Error: {err}").into();
1147                log::error!("Showing error notification in app: {message}");
1148                show_app_notification(workspace_error_notification_id(), cx, {
1149                    move |cx| {
1150                        cx.new({
1151                            let message = message.clone();
1152                            move |cx| ErrorMessagePrompt::new(message, cx)
1153                        })
1154                    }
1155                });
1156
1157                None
1158            }
1159        }
1160    }
1161}
1162
1163pub trait NotifyTaskExt {
1164    fn detach_and_notify_err(
1165        self,
1166        workspace: WeakEntity<Workspace>,
1167        window: &mut Window,
1168        cx: &mut App,
1169    );
1170}
1171
1172impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
1173where
1174    E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
1175    R: 'static,
1176{
1177    fn detach_and_notify_err(
1178        self,
1179        workspace: WeakEntity<Workspace>,
1180        window: &mut Window,
1181        cx: &mut App,
1182    ) {
1183        window
1184            .spawn(cx, async move |mut cx| {
1185                self.await.notify_workspace_async_err(workspace, &mut cx)
1186            })
1187            .detach();
1188    }
1189}
1190
1191pub trait DetachAndPromptErr<R> {
1192    fn prompt_err(
1193        self,
1194        msg: &str,
1195        window: &Window,
1196        cx: &App,
1197        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1198    ) -> Task<Option<R>>;
1199
1200    fn detach_and_prompt_err(
1201        self,
1202        msg: &str,
1203        window: &Window,
1204        cx: &App,
1205        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1206    );
1207}
1208
1209impl<R> DetachAndPromptErr<R> for Task<anyhow::Result<R>>
1210where
1211    R: 'static,
1212{
1213    fn prompt_err(
1214        self,
1215        msg: &str,
1216        window: &Window,
1217        cx: &App,
1218        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1219    ) -> Task<Option<R>> {
1220        let msg = msg.to_owned();
1221        window.spawn(cx, async move |cx| {
1222            let result = self.await;
1223            if let Err(err) = result.as_ref() {
1224                log::error!("{err:#}");
1225                if let Ok(prompt) = cx.update(|window, cx| {
1226                    let mut display = format!("{err:#}");
1227                    if !display.ends_with('\n') {
1228                        display.push('.');
1229                    }
1230                    let detail = f(err, window, cx).unwrap_or(display);
1231                    window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
1232                }) {
1233                    prompt.await.ok();
1234                }
1235                return None;
1236            }
1237            Some(result.unwrap())
1238        })
1239    }
1240
1241    fn detach_and_prompt_err(
1242        self,
1243        msg: &str,
1244        window: &Window,
1245        cx: &App,
1246        f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
1247    ) {
1248        self.prompt_err(msg, window, cx, f).detach();
1249    }
1250}
1251
1252#[cfg(test)]
1253mod tests {
1254    use fs::FakeFs;
1255    use gpui::TestAppContext;
1256    use project::{LanguageServerPromptRequest, Project};
1257
1258    use crate::tests::init_test;
1259
1260    use super::*;
1261
1262    #[gpui::test]
1263    async fn test_notification_auto_dismiss_with_notifications_from_multiple_language_servers(
1264        cx: &mut TestAppContext,
1265    ) {
1266        init_test(cx);
1267
1268        let fs = FakeFs::new(cx.executor());
1269        let project = Project::test(fs, [], cx).await;
1270
1271        let (workspace, cx) =
1272            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1273
1274        let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1275            workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1276        };
1277
1278        let show_notification = |workspace: &Entity<Workspace>,
1279                                 cx: &mut TestAppContext,
1280                                 lsp_name: &str| {
1281            workspace.update(cx, |workspace, cx| {
1282                let request = LanguageServerPromptRequest::test(
1283                    gpui::PromptLevel::Warning,
1284                    "Test notification".to_string(),
1285                    vec![], // Empty actions triggers auto-dismiss
1286                    lsp_name.to_string(),
1287                );
1288                let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1289                workspace.show_notification(notification_id, cx, |cx| {
1290                    cx.new(|cx| LanguageServerPrompt::new(request, cx))
1291                });
1292            })
1293        };
1294
1295        show_notification(&workspace, cx, "Lsp1");
1296        assert_eq!(count_notifications(&workspace, cx), 1);
1297
1298        cx.executor().advance_clock(Duration::from_millis(1000));
1299
1300        show_notification(&workspace, cx, "Lsp2");
1301        assert_eq!(count_notifications(&workspace, cx), 2);
1302
1303        cx.executor().advance_clock(Duration::from_millis(1000));
1304
1305        show_notification(&workspace, cx, "Lsp3");
1306        assert_eq!(count_notifications(&workspace, cx), 3);
1307
1308        cx.executor().advance_clock(Duration::from_millis(3000));
1309        assert_eq!(count_notifications(&workspace, cx), 2);
1310
1311        cx.executor().advance_clock(Duration::from_millis(1000));
1312        assert_eq!(count_notifications(&workspace, cx), 1);
1313
1314        cx.executor().advance_clock(Duration::from_millis(1000));
1315        assert_eq!(count_notifications(&workspace, cx), 0);
1316    }
1317
1318    #[gpui::test]
1319    async fn test_notification_auto_dismiss_with_multiple_notifications_from_single_language_server(
1320        cx: &mut TestAppContext,
1321    ) {
1322        init_test(cx);
1323
1324        let lsp_name = "server1";
1325
1326        let fs = FakeFs::new(cx.executor());
1327        let project = Project::test(fs, [], cx).await;
1328        let (workspace, cx) =
1329            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1330
1331        let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1332            workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1333        };
1334
1335        let show_notification = |lsp_name: &str,
1336                                 workspace: &Entity<Workspace>,
1337                                 cx: &mut TestAppContext| {
1338            workspace.update(cx, |workspace, cx| {
1339                let lsp_name = lsp_name.to_string();
1340                let request = LanguageServerPromptRequest::test(
1341                    gpui::PromptLevel::Warning,
1342                    "Test notification".to_string(),
1343                    vec![], // Empty actions triggers auto-dismiss
1344                    lsp_name,
1345                );
1346                let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1347
1348                workspace.show_notification(notification_id, cx, |cx| {
1349                    cx.new(|cx| LanguageServerPrompt::new(request, cx))
1350                });
1351            })
1352        };
1353
1354        show_notification(lsp_name, &workspace, cx);
1355        assert_eq!(count_notifications(&workspace, cx), 1);
1356
1357        cx.executor().advance_clock(Duration::from_millis(1000));
1358
1359        show_notification(lsp_name, &workspace, cx);
1360        assert_eq!(count_notifications(&workspace, cx), 2);
1361
1362        cx.executor().advance_clock(Duration::from_millis(4000));
1363        assert_eq!(count_notifications(&workspace, cx), 1);
1364
1365        cx.executor().advance_clock(Duration::from_millis(1000));
1366        assert_eq!(count_notifications(&workspace, cx), 0);
1367    }
1368
1369    #[gpui::test]
1370    async fn test_notification_auto_dismiss_turned_off(cx: &mut TestAppContext) {
1371        init_test(cx);
1372
1373        cx.update(|cx| {
1374            let mut settings = ProjectSettings::get_global(cx).clone();
1375            settings
1376                .global_lsp_settings
1377                .notifications
1378                .dismiss_timeout_ms = Some(0);
1379            ProjectSettings::override_global(settings, cx);
1380        });
1381
1382        let fs = FakeFs::new(cx.executor());
1383        let project = Project::test(fs, [], cx).await;
1384        let (workspace, cx) =
1385            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1386
1387        let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1388            workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1389        };
1390
1391        workspace.update(cx, |workspace, cx| {
1392            let request = LanguageServerPromptRequest::test(
1393                gpui::PromptLevel::Warning,
1394                "Test notification".to_string(),
1395                vec![], // Empty actions would trigger auto-dismiss if enabled
1396                "test_server".to_string(),
1397            );
1398            let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1399            workspace.show_notification(notification_id, cx, |cx| {
1400                cx.new(|cx| LanguageServerPrompt::new(request, cx))
1401            });
1402        });
1403
1404        assert_eq!(count_notifications(&workspace, cx), 1);
1405
1406        // Advance time beyond the default auto-dismiss duration
1407        cx.executor().advance_clock(Duration::from_millis(10000));
1408        assert_eq!(count_notifications(&workspace, cx), 1);
1409    }
1410
1411    #[gpui::test]
1412    async fn test_notification_auto_dismiss_with_custom_duration(cx: &mut TestAppContext) {
1413        init_test(cx);
1414
1415        let custom_duration_ms: u64 = 2000;
1416        cx.update(|cx| {
1417            let mut settings = ProjectSettings::get_global(cx).clone();
1418            settings
1419                .global_lsp_settings
1420                .notifications
1421                .dismiss_timeout_ms = Some(custom_duration_ms);
1422            ProjectSettings::override_global(settings, cx);
1423        });
1424
1425        let fs = FakeFs::new(cx.executor());
1426        let project = Project::test(fs, [], cx).await;
1427        let (workspace, cx) =
1428            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1429
1430        let count_notifications = |workspace: &Entity<Workspace>, cx: &mut TestAppContext| {
1431            workspace.read_with(cx, |workspace, _| workspace.notification_ids().len())
1432        };
1433
1434        workspace.update(cx, |workspace, cx| {
1435            let request = LanguageServerPromptRequest::test(
1436                gpui::PromptLevel::Warning,
1437                "Test notification".to_string(),
1438                vec![], // Empty actions triggers auto-dismiss
1439                "test_server".to_string(),
1440            );
1441            let notification_id = NotificationId::composite::<LanguageServerPrompt>(request.id);
1442            workspace.show_notification(notification_id, cx, |cx| {
1443                cx.new(|cx| LanguageServerPrompt::new(request, cx))
1444            });
1445        });
1446
1447        assert_eq!(count_notifications(&workspace, cx), 1);
1448
1449        // Advance time less than custom duration
1450        cx.executor()
1451            .advance_clock(Duration::from_millis(custom_duration_ms - 500));
1452        assert_eq!(count_notifications(&workspace, cx), 1);
1453
1454        // Advance time past the custom duration
1455        cx.executor().advance_clock(Duration::from_millis(1000));
1456        assert_eq!(count_notifications(&workspace, cx), 0);
1457    }
1458}