A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(gui): bring up the pane or thread a notification came from
RoversX8a445c29623c
diff --git a/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rsindex 9b524471..70bc261e 100644--- a/wezterm-font/src/lib.rs+++ b/wezterm-font/src/lib.rs@@ -543,6 +543,7 @@ impl FallbackResolveInfo {fallback_str.escape_unicode()),url: Some(url.to_string()),+ target: None,timeout: Some(Duration::from_secs(15)),}.show();diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex e841a9cc..648f8be1 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -330,37 +330,39 @@ impl GuiFrontEnd {MuxNotification::PaneExited { .. } => {}MuxNotification::Alert {pane_id,- alert:- Alert::ToastNotification {- title,- body,- focus: _,- },+ alert: Alert::ToastNotification { title, body, focus },} => {let mux = Mux::get();if let Some((_domain, window_id, tab_id)) = mux.resolve_pane_id(pane_id) {let config = config::configuration();+ // Nothing focused yet, as in a window not clicked+ // since it opened, suppresses nothing.+ let focused = mux.resolve_focused_pane(&client_id);+ let show = match config.notification_handling {+ NotificationHandling::NeverShow => false,+ NotificationHandling::AlwaysShow => true,+ NotificationHandling::SuppressFromFocusedPane => {+ focused.map_or(true, |(_, _, _, f_pane)| f_pane != pane_id)+ }+ NotificationHandling::SuppressFromFocusedTab => {+ focused.map_or(true, |(_, _, f_tab, _)| f_tab != tab_id)+ }+ NotificationHandling::SuppressFromFocusedWindow => {+ focused.map_or(true, |(_, f_window, _, _)| f_window != window_id)+ }+ };- if let Some((_fdomain, f_window, f_tab, f_pane)) =- mux.resolve_focused_pane(&client_id)- {- let show = match config.notification_handling {- NotificationHandling::NeverShow => false,- NotificationHandling::AlwaysShow => true,- NotificationHandling::SuppressFromFocusedPane => f_pane != pane_id,- NotificationHandling::SuppressFromFocusedTab => f_tab != tab_id,- NotificationHandling::SuppressFromFocusedWindow => {- f_window != window_id- }- };-- if show {- let message = if title.is_none() { "" } else { &body };- let title = title.as_ref().unwrap_or(&body);- // FIXME: if notification.focus is true, we should do- // something here to arrange to focus pane_id when the- // notification is clicked+ if show {+ let message = if title.is_none() { "" } else { &body };+ let title = title.as_ref().unwrap_or(&body);+ if focus {+ // A click brings the pane up.+ let target =+ crate::notification_click::NotificationTarget::Pane(pane_id)+ .encode();+ persistent_toast_notification_with_target(title, message, &target);+ } else {persistent_toast_notification(title, message);}}@@ -1206,6 +1208,7 @@ fn spawn_malloc_pressure_relief_thread() {}pub fn try_new() -> Result<Rc<GuiFrontEnd>, Error> {let front_end = GuiFrontEnd::try_new()?;FRONT_END.with(|f| *f.borrow_mut() = Some(Rc::clone(&front_end)));+ crate::notification_click::install();let config_subscription = config::subscribe_to_config_reload({move || {diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 8811c734..31a55b4d 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -54,6 +54,7 @@ mod markdown_editor;mod local_sessions;mod native_paths;mod native_settings;+mod notification_click;mod overlay;mod perf;mod plugins;diff --git a/wezterm-gui/src/notification_click.rs b/wezterm-gui/src/notification_click.rsnew file mode 100644index 00000000..8e7f5256--- /dev/null+++ b/wezterm-gui/src/notification_click.rs@@ -0,0 +1,197 @@+//! A clicked system notification brings up what it was about: the pane+//! whose program sent it, or the thread that finished or wants input.++use crate::scripting::guiwin::GuiWin;+use crate::termwindow::TermWindowNotif;+use mux::pane::PaneId;+use mux::Mux;+use std::sync::OnceLock;+use std::time::{SystemTime, UNIX_EPOCH};+use wezterm_toast_notification::NotificationClick;+use window::WindowOps;++/// What a notification is about, in the form its click hands back.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum NotificationTarget {+ Pane(PaneId),+ /// A thread, by its workspace.+ Thread(String),+}++impl NotificationTarget {+ pub fn encode(&self) -> String {+ match self {+ Self::Pane(pane_id) => format!("pane:{}:{pane_id}", this_run()),+ Self::Thread(workspace) => format!("thread:{workspace}"),+ }+ }++ /// `run` is this run's: a pane target from another one is no target.+ fn decode(text: &str, run: &str) -> Option<Self> {+ match text.split_once(':')? {+ ("pane", rest) => {+ let (from, pane_id) = rest.split_once(':')?;+ if from != run {+ log::debug!("a notification from an earlier run was clicked");+ return None;+ }+ pane_id.parse().ok().map(Self::Pane)+ }+ ("thread", workspace) if !workspace.is_empty() => {+ Some(Self::Thread(workspace.to_string()))+ }+ _ => None,+ }+ }+}++/// This run of ThinkTerm. Pane ids start over with every run, and the system+/// keeps notifications listed across them: one from before must not bring+/// up whichever pane has its id now. Threads keep their names.+fn this_run() -> &'static str {+ static RUN: OnceLock<String> = OnceLock::new();+ RUN.get_or_init(|| {+ let started = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|since| since.as_millis())+ .unwrap_or_default();+ format!("{}-{started}", std::process::id())+ })+}++/// Have clicks on ThinkTerm's notifications bring up their targets.+pub fn install() {+ wezterm_toast_notification::set_click_handler(|click| {+ // The system reports the click on a thread of its own.+ promise::spawn::spawn_into_main_thread(async move { reveal(click) }).detach();+ });+ // The click handler is otherwise set up with this run's first+ // notification, and a click on one still listed from before is lost.+ // Not for someone who turned notifications off: setting it up is what+ // lists ThinkTerm in the system's notification settings.+ #[cfg(target_os = "macos")]+ if crate::native_settings::system_notifications_enabled() {+ wezterm_toast_notification::macos_initialize();+ }+}++fn reveal(click: NotificationClick) {+ let Some(target) = NotificationTarget::decode(&click.target, this_run()) else {+ return;+ };+ log::debug!("bringing up {target:?} for a clicked notification");+ let Some(front_end) = crate::frontend::try_front_end() else {+ return;+ };+ let mux = Mux::get();+ let windows = front_end.gui_windows();+ let token = click.activation_token;+ match target {+ NotificationTarget::Pane(pane_id) => {+ // Closed since; the click has still brought ThinkTerm up.+ let Some((_domain, window_id, _tab_id)) = mux.resolve_pane_id(pane_id) else {+ return;+ };+ if let Some(showing) = windows.iter().find(|gui| gui.mux_window_id == window_id) {+ let window = showing.window.clone();+ showing+ .window+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ // From over a page such as Remote Hosts, too.+ term_window.bring_terminal_forward();+ term_window.reveal_pane(pane_id);+ window.invalidate();+ window.focus_with_activation_token(token.as_deref());+ })));+ } else if let Some(start) = last_used(&windows) {+ let window = start.window.clone();+ start+ .window+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ // Activating puts pages behind the terminal, but+ // Live Overview has to close.+ term_window.close_live_overview();+ if term_window.reveal_pane_elsewhere(pane_id, &window, token.clone()) {+ window.focus_with_activation_token(token.as_deref());+ }+ })));+ }+ }+ NotificationTarget::Thread(workspace) => {+ let showing = windows.iter().find(|gui| {+ mux.get_window(gui.mux_window_id)+ .is_some_and(|window| window.get_workspace() == workspace)+ });+ if let Some(showing) = showing {+ let window = showing.window.clone();+ showing+ .window+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.bring_terminal_forward();+ window.invalidate();+ window.focus_with_activation_token(token.as_deref());+ })));+ } else if let Some(start) = last_used(&windows) {+ let window = start.window.clone();+ start+ .window+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.close_live_overview();+ if term_window.reveal_thread(&workspace, &window, token.clone()) {+ window.focus_with_activation_token(token.as_deref());+ }+ })));+ }+ }+ }+}++/// The window last in use, which the paths to other threads and Spaces+/// start from.+fn last_used(windows: &[GuiWin]) -> Option<&GuiWin> {+ let mux = Mux::get();+ let focused = mux+ .active_identity()+ .and_then(|client| mux.resolve_focused_pane(&client))+ .map(|(_domain, window_id, _tab_id, _pane_id)| window_id);+ windows+ .iter()+ .find(|gui| Some(gui.mux_window_id) == focused)+ .or_else(|| windows.first())+}++#[cfg(test)]+mod tests {+ use super::{this_run, NotificationTarget};++ #[test]+ fn a_target_comes_back_from_the_system_as_it_went() {+ for target in [+ NotificationTarget::Pane(42),+ NotificationTarget::Thread("project:p1:thread-1".to_string()),+ ] {+ assert_eq!(+ NotificationTarget::decode(&target.encode(), this_run()),+ Some(target)+ );+ }+ assert_eq!(NotificationTarget::decode("pane:", this_run()), None);+ assert_eq!(NotificationTarget::decode("thread:", this_run()), None);+ assert_eq!(+ NotificationTarget::decode("https://example.com", this_run()),+ None+ );+ }++ #[test]+ fn a_pane_from_an_earlier_run_is_not_brought_up() {+ let earlier = NotificationTarget::Pane(3).encode();+ assert_eq!(NotificationTarget::decode(&earlier, "1-0"), None);+ // A thread is the same thread in the next run.+ let thread = NotificationTarget::Thread("project:p1:thread-1".to_string());+ assert_eq!(+ NotificationTarget::decode(&thread.encode(), "1-0"),+ Some(thread)+ );+ }+}diff --git a/wezterm-gui/src/scripting/guiwin.rs b/wezterm-gui/src/scripting/guiwin.rsindex 6a0cea73..414c06ef 100644--- a/wezterm-gui/src/scripting/guiwin.rs+++ b/wezterm-gui/src/scripting/guiwin.rs@@ -88,6 +88,7 @@ impl UserData for GuiWin {title,message,url,+ target: None,timeout: timeout.map(std::time::Duration::from_millis)});Ok(())diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 82ff63c7..88d9c346 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -8286,6 +8286,36 @@ impl TermWindow {}}+ /// Show this window's terminal for something about to be brought up in+ /// it, as a clicked notification's pane: a page over the terminal goes+ /// behind it, Live Overview closes, and a thread activation still under+ /// way no longer takes the window over when it lands.+ pub(crate) fn bring_terminal_forward(&mut self) {+ self.close_live_overview();+ self.set_content_view_active(false);+ self.next_local_thread_activation_generation = self+ .next_local_thread_activation_generation+ .saturating_add(1)+ .max(1);+ self.local_thread_activation = None;+ self.workspace_sidebar_pending_thread_selection = None;+ }++ /// Close Live Overview, when it is open. It covers the whole window and+ /// keeps a recording of it: put behind the terminal instead, it would+ /// linger stale, holding that recording.+ pub(crate) fn close_live_overview(&mut self) {+ let key = crate::termwindow::live_overview::LIVE_OVERVIEW_CONTENT_VIEW_KEY;+ let overview = self+ .content_views+ .iter()+ .find(|tab| tab.key.as_deref() == Some(key))+ .map(|tab| tab.id);+ if let Some(id) = overview {+ self.close_content_view_by_id(id);+ }+ }+pub(crate) fn activate_content_view(&mut self, id: ContentViewId) {if self.content_viewsdiff --git a/wezterm-gui/src/termwindow/ui/agent_panel.rs b/wezterm-gui/src/termwindow/ui/agent_panel.rsindex 19850b26..3a2e63aa 100644--- a/wezterm-gui/src/termwindow/ui/agent_panel.rs+++ b/wezterm-gui/src/termwindow/ui/agent_panel.rs@@ -1112,10 +1112,10 @@ impl TermWindow {crate::settings_window::show_from(self.mux_window_id, &self.active_space_id);}AgentPanelAction::Reveal(pane_id) => {- self.reveal_agent_pane(pane_id);+ self.reveal_pane(pane_id);}AgentPanelAction::RevealElsewhere(pane_id) => {- self.reveal_agent_pane_elsewhere(pane_id, context);+ self.reveal_pane_elsewhere(pane_id, context, None);}AgentPanelAction::ToggleSubtasks(pane_id) => {if !self.right_sidebar_agents_open_subtasks.remove(&pane_id) {@@ -1339,15 +1339,20 @@ impl TermWindow {}}- /// The agent lives in another window: deep-focus its tab and pane in- /// the owning mux window first, then activate the backing thread —- /// the same path a left-sidebar thread click takes, which switches- /// the workspace and brings the right window forward. The activated- /// window then comes up already pointing at the agent.- fn reveal_agent_pane_elsewhere(&mut self, pane_id: PaneId, context: &dyn WindowOps) {+ /// The pane lives in a mux window this one does not show: deep-focus+ /// its tab and pane in the owning mux window first, then open the+ /// backing thread with [`Self::reveal_thread`]. The window that shows+ /// it then comes up already pointing at the pane. Says whether that is+ /// this window.+ pub(crate) fn reveal_pane_elsewhere(+ &mut self,+ pane_id: PaneId,+ context: &dyn WindowOps,+ activation_token: Option<String>,+ ) -> bool {let mux = Mux::get();let Some((_domain, window_id, tab_id)) = mux.resolve_pane_id(pane_id) else {- return;+ return false;};let tab_idx = mux.get_window(window_id).and_then(|window| {(0..window.len()).find(|idx| {@@ -1369,66 +1374,99 @@ impl TermWindow {.get_window(window_id).map(|window| window.get_workspace().to_string())else {- return;+ return false;};- if let Some(thread_id) = crate::workspace_threads::thread_id_for_workspace_any(&workspace) {- // Only a thread of this Space (or one it references) can be- // activated here; activate_workspace_thread's guard silently- // drops anything else, which used to make these clicks no-ops.- let home_space = crate::workspace_threads::thread_space_id(&thread_id);- let in_this_space = home_space.as_deref() == Some(self.active_space_id.as_str());- let referenced = !in_this_space- && crate::workspace_threads::thread_ref_exists(&self.active_space_id, &thread_id);- if in_this_space || referenced {- self.activate_workspace_thread(thread_id, context);- return;- }- let Some(home_space) = home_space else {- return;+ self.reveal_thread(&workspace, context, activation_token)+ }++ /// Activate the thread backing `workspace` -- the same path a+ /// left-sidebar thread click takes, which switches the workspace and+ /// brings the right window forward. Says whether this window now shows+ /// it: a thread of a Space another window owns goes to that window,+ /// which comes forward itself, with `activation_token` when one came.+ pub(crate) fn reveal_thread(+ &mut self,+ workspace: &str,+ context: &dyn WindowOps,+ activation_token: Option<String>,+ ) -> bool {+ let Some(thread_id) = crate::workspace_threads::thread_id_for_workspace_any(workspace)+ else {+ return false;+ };+ // Only a thread of this Space (or one it references) can be+ // activated here; activate_workspace_thread's guard silently+ // drops anything else, which used to make these clicks no-ops.+ let home_space = crate::workspace_threads::thread_space_id(&thread_id);+ let in_this_space = home_space.as_deref() == Some(self.active_space_id.as_str());+ let referenced = !in_this_space+ && crate::workspace_threads::thread_ref_exists(&self.active_space_id, &thread_id);+ if in_this_space || referenced {+ // Activating hands the thread to a window already showing it,+ // which comes forward itself; otherwise the thread opens here,+ // at once or once its panes are up.+ let handed_off = self.workspace_shown_elsewhere(workspace);+ self.activate_workspace_thread(thread_id, context);+ return !handed_off;+ }+ let Some(home_space) = home_space else {+ return false;+ };+ // The thread belongs to another Space. Hand the activation to+ // the window owning that Space, inside that window's own event+ // loop -- the mux-window lookup would only find a window that+ // is already displaying this very thread, which is exactly the+ // case that cannot happen here. Same shape as live_overview's+ // open_thread_response.+ if let Some(target_owner_id) = crate::workspace_threads::window_owner_for_space(&home_space)+ {+ let Some(target) = crate::frontend::front_end()+ .gui_window_for_recovery_slot(FrontendRecoverySlot::Window(target_owner_id))+ else {+ return false;};- // The thread belongs to another Space. Hand the activation to- // the window owning that Space, inside that window's own event- // loop -- the mux-window lookup would only find a window that- // is already displaying this very thread, which is exactly the- // case that cannot happen here. Same shape as live_overview's- // open_thread_response.- if let Some(target_owner_id) =- crate::workspace_threads::window_owner_for_space(&home_space)- {- let Some(target) = crate::frontend::front_end()- .gui_window_for_recovery_slot(FrontendRecoverySlot::Window(target_owner_id))- else {- return;- };- let target_window = target.window.clone();- target.window.notify(TermWindowNotif::Apply(Box::new(- move |target_term_window| {- // Ownership can change between the click and this- // callback; do not steal a Space on a stale lookup.- if crate::workspace_threads::window_owner_for_space(&home_space)- != Some(target_owner_id)- || target_term_window.frontend_recovery_slot()- != FrontendRecoverySlot::Window(target_owner_id)- {- return;- }- target_term_window.activate_workspace_thread(thread_id, &target_window);- target_window.focus();- },- )));- return;- }- // No window owns that Space: navigate this one there, exactly- // as opening a windowless Space's thread does elsewhere.- if let Some(window) = self.window.clone() {- self.switch_space_to_thread(home_space, Some(thread_id), &window);- }+ let target_window = target.window.clone();+ target.window.notify(TermWindowNotif::Apply(Box::new(+ move |target_term_window| {+ // Ownership can change between the click and this+ // callback; do not steal a Space on a stale lookup.+ if crate::workspace_threads::window_owner_for_space(&home_space)+ != Some(target_owner_id)+ || target_term_window.frontend_recovery_slot()+ != FrontendRecoverySlot::Window(target_owner_id)+ {+ return;+ }+ // Activating puts pages behind the terminal; Live+ // Overview has to close, or it lingers stale.+ target_term_window.close_live_overview();+ target_term_window.activate_workspace_thread(thread_id, &target_window);+ target_window.focus_with_activation_token(activation_token.as_deref());+ },+ )));+ return false;}+ // No window owns that Space: navigate this one there, exactly+ // as opening a windowless Space's thread does elsewhere.+ if let Some(window) = self.window.clone() {+ return self.switch_space_to_thread(home_space, Some(thread_id), &window);+ }+ false+ }++ /// Whether activating `workspace`'s thread here would hand it to another+ /// window already showing it: the check `activate_workspace_thread` makes.+ fn workspace_shown_elsewhere(&self, workspace: &str) -> bool {+ crate::workspace_threads::window_to_show_in_workspace(workspace).is_some_and(|target| {+ target != self.mux_window_id+ && crate::frontend::front_end()+ .gui_window_for_mux_window(target)+ .is_some()+ })}- /// Focus the tab and pane hosting this agent, when it lives in this- /// window.- fn reveal_agent_pane(&mut self, pane_id: PaneId) {+ /// Focus the tab and pane `pane_id` is in, when it lives in this window.+ pub(crate) fn reveal_pane(&mut self, pane_id: PaneId) {let mux = Mux::get();let Some((_domain, window_id, tab_id)) = mux.resolve_pane_id(pane_id) else {return;diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 2c4671fd..02e58fc9 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -3025,7 +3025,14 @@ fn notify_system(workspace: &str, announcement: WorkAnnouncement, finished_after});let thread = thread_display_name_for_workspace(workspace).unwrap_or_else(|| workspace.to_string());let reason = crate::agent_status::workspace_reason(workspace).unwrap_or_default();- wezterm_toast_notification::persistent_toast_notification(&format!("{thread} · {state}"), &reason);+ // A click brings the thread up.+ let target =+ crate::notification_click::NotificationTarget::Thread(workspace.to_string()).encode();+ wezterm_toast_notification::persistent_toast_notification_with_target(+ &format!("{thread} · {state}"),+ &reason,+ &target,+ );}pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {diff --git a/wezterm-toast-notification/src/dbus.rs b/wezterm-toast-notification/src/dbus.rsindex b6669412..ca479ca0 100644--- a/wezterm-toast-notification/src/dbus.rs+++ b/wezterm-toast-notification/src/dbus.rs@@ -2,7 +2,7 @@//! See <https://developer.gnome.org/notification-spec/>use crate::ToastNotification;-use futures_util::stream::{abortable, StreamExt};+use futures_util::stream::StreamExt;use serde::{Deserialize, Serialize};use std::collections::HashMap;use zbus::proxy;@@ -58,6 +58,11 @@ trait Notifications {#[zbus(signal)]fn notification_closed(&self, nid: u32, reason: u32) -> zbus::Result<()>;++ /// Sent just before `ActionInvoked`, by servers that implement version+ /// 1.2 of the spec: the token that lets the app take focus for it.+ #[zbus(signal)]+ fn activation_token(&self, nid: u32, activation_token: String) -> zbus::Result<()>;}/// Timeout/expiration was reached@@ -100,8 +105,21 @@ async fn show_notif_impl(notif: ToastNotification) -> Result<(), Box<dyn std::erreturn Ok(());}+ // Every signal of the service, in the order the server sent them, and+ // from before the notification exists: the token comes just before the+ // click it belongs to, and a stream per signal lost that order.+ let mut signals = proxy.inner().receive_all_signals().await?;+let mut hints = HashMap::new();hints.insert("urgency", Value::U8(2 /* Critical */));+ let mut actions = vec![];+ if notif.url.is_some() {+ actions.extend(["show", "Show"]);+ }+ if notif.target.is_some() {+ // The action of a click on the notification itself.+ actions.extend(["default", "Show"]);+ }let notification = proxy.notify("ThinkTerm",@@ -109,45 +127,49 @@ async fn show_notif_impl(notif: ToastNotification) -> Result<(), Box<dyn std::er"com.roversx.thinkterm",¬if.title,¬if.message,- if notif.url.is_some() {- &["show", "Show"]- } else {- &[]- },+ &actions,&hints,notif.timeout.map(|d| d.as_millis() as _).unwrap_or(0),).await?;- let (mut invoked_stream, abort_invoked) = abortable(proxy.receive_action_invoked().await?);- let (mut closed_stream, abort_closed) = abortable(proxy.receive_notification_closed().await?);-- futures_util::try_join!(- async {- while let Some(signal) = invoked_stream.next().await {- let args = signal.args()?;- if args.nid == notification {- if let Some(url) = notif.url.as_ref() {- wezterm_open_url::open_url(url);- abort_closed.abort();- break;+ let mut activation_token = None;+ while let Some(signal) = signals.next().await {+ let header = signal.header();+ let Some(member) = header.member() else {+ continue;+ };+ match member.as_str() {+ "ActivationToken" => {+ let (nid, token): (u32, String) = signal.body().deserialize()?;+ if nid == notification {+ activation_token = Some(token);+ }+ }+ "ActionInvoked" => {+ let (nid, action_key): (u32, String) = signal.body().deserialize()?;+ if nid != notification {+ continue;+ }+ match (action_key.as_str(), ¬if.url, ¬if.target) {+ ("default", _, Some(target)) => {+ crate::clicked(target.clone(), activation_token.take())}+ (_, Some(url), _) => wezterm_open_url::open_url(url),+ _ => continue,}+ break;}- Ok::<(), zbus::Error>(())- },- async {- while let Some(signal) = closed_stream.next().await {- let args = signal.args()?;- let _reason = Reason::new(args.reason);- if args.nid == notification {- abort_invoked.abort();+ "NotificationClosed" => {+ let (nid, reason): (u32, u32) = signal.body().deserialize()?;+ if nid == notification {+ let _reason = Reason::new(reason);break;}}- Ok(())+ _ => {}}- )?;+ }Ok(())}diff --git a/wezterm-toast-notification/src/lib.rs b/wezterm-toast-notification/src/lib.rsindex ba97d9c5..851f17c5 100644--- a/wezterm-toast-notification/src/lib.rs+++ b/wezterm-toast-notification/src/lib.rs@@ -2,11 +2,16 @@ mod dbus;mod macos;mod windows;+use std::sync::OnceLock;+#[derive(Debug, Clone)]pub struct ToastNotification {pub title: String,pub message: String,pub url: Option<String>,+ /// What a click on the notification brings up: opaque here, and handed+ /// to the handler given to [`set_click_handler`].+ pub target: Option<String>,pub timeout: Option<std::time::Duration>,}@@ -16,6 +21,37 @@ impl ToastNotification {}}+/// A click on a notification that had a target.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NotificationClick {+ pub target: String,+ /// The token a Linux notification server hands over with the click,+ /// without which Wayland does not let a window take focus.+ pub activation_token: Option<String>,+}++static CLICK_HANDLER: OnceLock<Box<dyn Fn(NotificationClick) + Send + Sync>> = OnceLock::new();++/// Set what a click on a notification with a target does. It runs on+/// whichever thread the system reports the click on; only the first+/// handler set is kept.+pub fn set_click_handler(handler: impl Fn(NotificationClick) + Send + Sync + 'static) {+ if CLICK_HANDLER.set(Box::new(handler)).is_err() {+ log::warn!("a notification click handler was already set");+ }+}++#[allow(dead_code)]+fn clicked(target: String, activation_token: Option<String>) {+ match CLICK_HANDLER.get() {+ Some(handler) => handler(NotificationClick {+ target,+ activation_token,+ }),+ None => log::debug!("notification for {target} clicked, with no handler"),+ }+}+#[cfg(windows)]use crate::windows as backend;#[cfg(all(not(target_os = "macos"), not(windows)))]@@ -43,6 +79,18 @@ pub fn persistent_toast_notification_with_click_to_open_url(title: &str, messagetitle: title.to_string(),message: message.to_string(),url: Some(url.to_string()),+ target: None,+ timeout: None,+ });+}++/// A notification that, clicked, hands `target` to the click handler.+pub fn persistent_toast_notification_with_target(title: &str, message: &str, target: &str) {+ show(ToastNotification {+ title: title.to_string(),+ message: message.to_string(),+ url: None,+ target: Some(target.to_string()),timeout: None,});}@@ -52,9 +100,37 @@ pub fn persistent_toast_notification(title: &str, message: &str) {title: title.to_string(),message: message.to_string(),url: None,+ target: None,timeout: None,});}#[cfg(target_os = "macos")]pub use macos::initialize as macos_initialize;++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Mutex;++ #[test]+ fn a_click_reaches_the_handler_with_its_token() {+ static CLICKS: Mutex<Vec<NotificationClick>> = Mutex::new(vec![]);+ set_click_handler(|click| CLICKS.lock().unwrap().push(click));+ clicked("pane:7".to_string(), Some("token".to_string()));+ clicked("thread:t1".to_string(), None);+ assert_eq!(+ *CLICKS.lock().unwrap(),+ vec![+ NotificationClick {+ target: "pane:7".to_string(),+ activation_token: Some("token".to_string()),+ },+ NotificationClick {+ target: "thread:t1".to_string(),+ activation_token: None,+ },+ ]+ );+ }+}diff --git a/wezterm-toast-notification/src/macos.rs b/wezterm-toast-notification/src/macos.rsindex 3ee6442f..8d535fbd 100644--- a/wezterm-toast-notification/src/macos.rs+++ b/wezterm-toast-notification/src/macos.rs@@ -8,14 +8,21 @@ use objc2_foundation::{ns_string, NSArray, NSDictionary, NSError, NSSet, NSStrinuse objc2_user_notifications::{UNAuthorizationOptions, UNMutableNotificationContent, UNNotification, UNNotificationAction,UNNotificationActionOptions, UNNotificationCategory, UNNotificationCategoryOptions,- UNNotificationPresentationOptions, UNNotificationRequest, UNNotificationResponse,- UNUserNotificationCenter, UNUserNotificationCenterDelegate,+ UNNotificationDefaultActionIdentifier, UNNotificationPresentationOptions,+ UNNotificationRequest, UNNotificationResponse, UNUserNotificationCenter,+ UNUserNotificationCenterDelegate,};use std::sync::{LazyLock, Once};const NEEDS_SIGN: &str = "Note that the application must be code-signed \for UNUserNotificationCenter to work";+/// UNUserNotificationCenter throws, taking the whole process down, unless+/// it runs from an app bundle; a development build is a bare binary.+fn in_app_bundle() -> bool {+ std::env::current_exe().is_ok_and(|exe| exe.to_string_lossy().contains(".app/Contents/MacOS/"))+}+fn ns_error_to_string(err: *mut NSError) -> String {if err.is_null() {"null error".to_string()@@ -73,6 +80,14 @@ define_class!(}}+ // The notification itself was clicked, not one of its buttons.+ if action.isEqualToString(UNNotificationDefaultActionIdentifier) {+ let target = user_info.valueForKey(ns_string!("target"));+ if let Some(Ok(target)) = target.map(|t| t.downcast::<NSString>()) {+ crate::clicked(target.to_string(), None);+ }+ }+completion_handler.call(());}}@@ -97,6 +112,9 @@ const CENTER: LazyLock<Retained<UNUserNotificationCenter>> =LazyLock::new(UNUserNotificationCenter::currentNotificationCenter);pub fn initialize() {+ if !in_app_bundle() {+ return;+ }static INIT: Once = Once::new();INIT.call_once(|| {CENTER.requestAuthorizationWithOptions_completionHandler(@@ -148,6 +166,9 @@ pub fn initialize() {}pub fn show_notif(toast: ToastNotification) -> Result<(), Box<dyn std::error::Error>> {+ if !in_app_bundle() {+ return Err("notifications need ThinkTerm.app; this is a bare binary".into());+ }initialize();unsafe {log::debug!("show_notif center.delegate is {:?}", CENTER.delegate());@@ -156,14 +177,24 @@ pub fn show_notif(toast: ToastNotification) -> Result<(), Box<dyn std::error::Ernotif.setTitle(&NSString::from_str(&toast.title));notif.setBody(&NSString::from_str(&toast.message));+ let mut keys = vec![];+ let mut values = vec![];if let Some(url) = &toast.url {- let info =- NSDictionary::from_slices(&[ns_string!("url")], &[&*NSString::from_str(&url)]);+ keys.push(ns_string!("url"));+ values.push(NSString::from_str(url));+ notif.setCategoryIdentifier(ns_string!("SHOW_URL_ACTION"));+ }+ if let Some(target) = &toast.target {+ keys.push(ns_string!("target"));+ values.push(NSString::from_str(target));+ }+ if !keys.is_empty() {+ let values: Vec<&NSString> = values.iter().map(|value| &**value).collect();+ let info = NSDictionary::from_slices(&keys, &values);notif.setUserInfo(info.downcast_ref::<NSDictionary>().expect("is NSDictionary"),);- notif.setCategoryIdentifier(ns_string!("SHOW_URL_ACTION"));}let identifier = uuid::Uuid::new_v4().to_string();diff --git a/wezterm-toast-notification/src/windows.rs b/wezterm-toast-notification/src/windows.rsindex ef204490..b7fb614b 100644--- a/wezterm-toast-notification/src/windows.rs+++ b/wezterm-toast-notification/src/windows.rs@@ -1,7 +1,7 @@#![cfg(windows)]use crate::ToastNotification as TN;-use xml::escape::escape_str_pcdata;+use xml::escape::{escape_str_attribute, escape_str_pcdata};use windows::core::{Error as WinError, IInspectable, Interface, HSTRING};use windows::Data::Xml::Dom::XmlDocument;@@ -31,8 +31,14 @@ fn show_notif_impl(toast: TN) -> Result<(), Box<dyn std::error::Error>> {""};+ // A click on the toast itself activates it with these arguments.+ let launch = match &toast.target {+ Some(target) => format!(r#" launch="{}""#, escape_str_attribute(target)),+ None => String::new(),+ };+xml.LoadXml(HSTRING::from(format!(- r#"<toast duration="long">+ r#"<toast duration="long"{}><visual><binding template="ToastGeneric"><text>{}</text>@@ -41,6 +47,7 @@ fn show_notif_impl(toast: TN) -> Result<(), Box<dyn std::error::Error>> {</visual>{}</toast>"#,+ launch,escape_str_pcdata(&toast.title),escape_str_pcdata(&toast.message),url_actions@@ -59,6 +66,10 @@ fn show_notif_impl(toast: TN) -> Result<(), Box<dyn std::error::Error>> {if let Some(url) = toast.url.as_ref() {wezterm_open_url::open_url(url);}+ } else if let Some(target) = toast.target.as_ref() {+ if args.to_string_lossy() == *target {+ crate::clicked(target.clone(), None);+ }}Ok(())diff --git a/window/src/lib.rs b/window/src/lib.rsindex 830d37d5..4eca9e0f 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -951,6 +951,14 @@ pub trait WindowOps {fn restore(&self) {}fn focus(&self) {}+ /// Bring the window forward for something another program handed on,+ /// such as a clicked notification. Wayland lets a window take focus only+ /// with the activation token that came with it; elsewhere this is+ /// `focus`.+ fn focus_with_activation_token(&self, _token: Option<&str>) {+ self.focus()+ }+fn toggle_fullscreen(&self) {}fn config_did_change(&self, _config: &config::ConfigHandle) {}diff --git a/window/src/os/wayland/state.rs b/window/src/os/wayland/state.rsindex fcbda535..55609560 100644--- a/window/src/os/wayland/state.rs+++ b/window/src/os/wayland/state.rs@@ -3,6 +3,7 @@ use std::collections::HashMap;use std::rc::Rc;use std::sync::{Arc, Mutex};+use smithay_client_toolkit::activation::{ActivationHandler, ActivationState, RequestData};use smithay_client_toolkit::compositor::{CompositorState, SurfaceData};use smithay_client_toolkit::data_device_manager::data_device::DataDevice;use smithay_client_toolkit::data_device_manager::data_source::CopyPasteSource;@@ -23,7 +24,7 @@ use smithay_client_toolkit::shm::slot::SlotPool;use smithay_client_toolkit::shm::{Shm, ShmHandler};use smithay_client_toolkit::subcompositor::SubcompositorState;use smithay_client_toolkit::{- delegate_compositor, delegate_data_device, delegate_output, delegate_pointer, delegate_primary_selection, delegate_registry, delegate_seat, delegate_shm, delegate_subcompositor, delegate_xdg_shell, delegate_xdg_window, registry_handlers+ delegate_activation, delegate_compositor, delegate_data_device, delegate_output, delegate_pointer, delegate_primary_selection, delegate_registry, delegate_seat, delegate_shm, delegate_subcompositor, delegate_xdg_shell, delegate_xdg_window, registry_handlers};use wayland_client::backend::ObjectId;use wayland_client::globals::GlobalList;@@ -74,6 +75,9 @@ pub(super) struct WaylandState {pub(super) shm: Shm,pub(super) mem_pool: RefCell<SlotPool>,pub(super) kde_blur_manager: Option<OrgKdeKwinBlurManager>,+ /// xdg-activation, when the compositor offers it: how a window comes+ /// forward with a token another program handed on.+ pub(super) activation: Option<ActivationState>,}impl WaylandState {@@ -119,6 +123,7 @@ impl WaylandState {shm,mem_pool: RefCell::new(mem_pool),kde_blur_manager: blur_manager,+ activation: ActivationState::bind(globals, qh).ok(),};Ok(wayland_state)}@@ -175,6 +180,15 @@ delegate_xdg_window!(WaylandState);delegate_primary_selection!(WaylandState);+// Tokens only come from elsewhere; none are asked for.+impl ActivationHandler for WaylandState {+ type RequestData = RequestData;++ fn new_token(&mut self, _token: String, _data: &RequestData) {}+}++delegate_activation!(WaylandState);+delegate_dispatch!(WaylandState: [ZwpTextInputManagerV3: GlobalData] => TextInputState);delegate_dispatch!(WaylandState: [ZwpTextInputV3: TextInputData] => TextInputState);diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rsindex 03aabad0..ab90b946 100644--- a/window/src/os/wayland/window.rs+++ b/window/src/os/wayland/window.rs@@ -490,6 +490,17 @@ impl WindowOps for WaylandWindow {});}+ fn focus_with_activation_token(&self, token: Option<&str>) {+ // Without a token the compositor would refuse: nothing to ask for.+ let Some(token) = token.map(str::to_string) else {+ return;+ };+ WaylandConnection::with_window_inner(self.0, move |inner| {+ inner.activate(token);+ Ok(())+ });+ }+fn close(&self) {WaylandConnection::with_window_inner(self.0, |inner| {inner.close();@@ -812,6 +823,18 @@ impl WaylandWindowInner {.remove(&self.window_id);}+ fn activate(&mut self, token: String) {+ let Some(window) = self.window.as_ref() else {+ return;+ };+ let conn = Connection::get().unwrap().wayland();+ let state = conn.wayland_state.borrow();+ match state.activation.as_ref() {+ Some(activation) => activation.activate::<WaylandState>(window.wl_surface(), token),+ None => log::debug!("the compositor has no xdg-activation to come forward with"),+ }+ }+fn show(&mut self) {log::trace!("WaylandWindowInner show: {:?}", self.window);if self.window.is_none() {diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex f02a114d..ef64cd8e 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -1017,6 +1017,9 @@ enum ShowWindowCommand {Normal,Minimize,Maximize,+ /// Back from the taskbar to what it was -- maximized, if it was -- and+ /// nothing for a window that is not minimized.+ RestoreIfMinimized,}fn schedule_show_window(hwnd: HWindow, show: ShowWindowCommand) {@@ -1026,14 +1029,17 @@ fn schedule_show_window(hwnd: HWindow, show: ShowWindowCommand) {promise::spawn::spawn(async move {unsafe {log::trace!("applying ShowWindowCommand {show:?}");- ShowWindow(- hwnd.0,- match show {- ShowWindowCommand::Normal => SW_NORMAL,- ShowWindowCommand::Minimize => SW_MINIMIZE,- ShowWindowCommand::Maximize => SW_MAXIMIZE,- },- );+ let command = match show {+ ShowWindowCommand::Normal => Some(SW_NORMAL),+ ShowWindowCommand::Minimize => Some(SW_MINIMIZE),+ ShowWindowCommand::Maximize => Some(SW_MAXIMIZE),+ ShowWindowCommand::RestoreIfMinimized => {+ (IsIconic(hwnd.0) != winapi::shared::minwindef::FALSE).then_some(SW_RESTORE)+ }+ };+ if let Some(command) = command {+ ShowWindow(hwnd.0, command);+ }}}).detach();@@ -1272,6 +1278,13 @@ impl WindowOps for Window {.detach();}+ fn focus_with_activation_token(&self, _token: Option<&str>) {+ // Brought forward while minimized, a window stays minimized: restore+ // it first. Both are scheduled, in this order.+ schedule_show_window(self.0, ShowWindowCommand::RestoreIfMinimized);+ self.focus();+ }+fn set_frame_rect(&self, rect: ScreenRect) {let hwnd = self.0;// Scheduled rather than immediate for the same reason the other windowdiff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rsindex 785805d3..6aefe4c5 100644--- a/window/src/os/x_and_wayland.rs+++ b/window/src/os/x_and_wayland.rs@@ -345,6 +345,17 @@ impl WindowOps for Window {}}+ fn focus_with_activation_token(&self, token: Option<&str>) {+ match self {+ Self::X11(x) => {+ let _ = token;+ x.focus()+ }+ #[cfg(feature = "wayland")]+ Self::Wayland(w) => w.focus_with_activation_token(token),+ }+ }+fn toggle_fullscreen(&self) {match self {Self::X11(x) => x.toggle_fullscreen(),