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