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
macos: lossless window notifications; gui: presented-output watchdog
RoversXfd8034441400
diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 27287f9a..754a565d 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -415,6 +415,7 @@ pub struct Mux {client_registrations: RwLock<HashMap<ClientId, ClientRegistrationId>>,frontend_lease: Mutex<FrontendLeaseState>,tab_resize_notifications: Mutex<TabResizeNotificationState>,+ pane_output_generations: Mutex<PaneOutputGenerationState>,#[cfg(test)]frontend_geometry_failures: Mutex<std::collections::VecDeque<bool>>,palette_advisories: Mutex<PaletteAdvisoryState>,@@ -431,6 +432,27 @@ struct TabResizeNotificationState {aborted: HashSet<TabId>,}+#[derive(Default)]+struct PaneOutputGenerationState {+ generations: HashMap<PaneId, u64>,+}++impl PaneOutputGenerationState {+ fn note_output(&mut self, pane_id: PaneId) -> u64 {+ let generation = self.generations.entry(pane_id).or_default();+ *generation = generation.wrapping_add(1).max(1);+ *generation+ }++ fn generation(&self, pane_id: PaneId) -> u64 {+ self.generations.get(&pane_id).copied().unwrap_or(0)+ }++ fn remove(&mut self, pane_id: PaneId) {+ self.generations.remove(&pane_id);+ }+}+impl TabResizeNotificationState {fn begin(&mut self, tab_id: TabId) {if self.depth.get(&tab_id).copied().unwrap_or_default() == 0 {@@ -850,6 +872,7 @@ impl Mux {client_registrations: RwLock::new(HashMap::new()),frontend_lease: Mutex::new(FrontendLeaseState::default()),tab_resize_notifications: Mutex::new(TabResizeNotificationState::default()),+ pane_output_generations: Mutex::new(PaneOutputGenerationState::default()),#[cfg(test)]frontend_geometry_failures: Mutex::new(std::collections::VecDeque::new()),palette_advisories: Mutex::new(PaletteAdvisoryState::default()),@@ -2059,6 +2082,17 @@ impl Mux {}pub fn notify(&self, notification: MuxNotification) {+ let removed_pane = match ¬ification {+ MuxNotification::PaneRemoved(pane_id) => Some(*pane_id),+ _ => None,+ };+ if let MuxNotification::PaneOutput(pane_id) = ¬ification {+ // Record the durable fact before invoking subscribers. A native+ // window can temporarily be unable to accept its notification,+ // but it can later compare this generation with the last frame it+ // successfully presented and recover the missing repaint.+ self.pane_output_generations.lock().note_output(*pane_id);+ }match notification {MuxNotification::TabResized(tab_id) => {if self.tab_resize_notifications.lock().defer(tab_id) {@@ -2068,6 +2102,16 @@ impl Mux {}other => self.notify_immediate(other),}+ if let Some(pane_id) = removed_pane {+ self.pane_output_generations.lock().remove(pane_id);+ }+ }++ /// The latest PaneOutput generation published for this pane. Each GUI+ /// window acknowledges generations independently after a successful+ /// frame presentation.+ pub fn pane_output_generation(&self, pane_id: PaneId) -> u64 {+ self.pane_output_generations.lock().generation(pane_id)}fn notify_immediate(&self, notification: MuxNotification) {@@ -3194,6 +3238,40 @@ impl wezterm_term::DownloadHandler for MuxDownloader {mod tests {use super::*;+ #[test]+ fn pane_output_generation_is_visible_before_subscribers_run() {+ let mux = Arc::new(Mux::new(None));+ let observed = Arc::new(Mutex::new(Vec::new()));+ let subscriber_mux = Arc::clone(&mux);+ let subscriber_observed = Arc::clone(&observed);+ mux.subscribe(move |notification| {+ if let MuxNotification::PaneOutput(pane_id) = notification {+ subscriber_observed+ .lock()+ .push(subscriber_mux.pane_output_generation(pane_id));+ }+ true+ });++ mux.notify(MuxNotification::PaneOutput(7));+ mux.notify(MuxNotification::PaneOutput(7));+ mux.notify(MuxNotification::PaneOutput(8));+ assert_eq!(&*observed.lock(), &[1, 2, 1]);+ assert_eq!(mux.pane_output_generation(7), 2);+ assert_eq!(mux.pane_output_generation(8), 1);++ mux.notify(MuxNotification::PaneRemoved(7));+ assert_eq!(mux.pane_output_generation(7), 0);+ assert_eq!(mux.pane_output_generation(8), 1);+ }++ #[test]+ fn pane_output_generation_wraps_without_using_zero() {+ let mut state = PaneOutputGenerationState::default();+ state.generations.insert(9, u64::MAX);+ assert_eq!(state.note_output(9), 1);+ }+#[test]fn tab_geometry_transaction_coalesces_and_is_tab_scoped() {let mut state = TabResizeNotificationState::default();diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex c924d725..a97d1e50 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -1431,6 +1431,71 @@ pub struct PaneState {bell_start: Option<Instant>,pub mouse_terminal_coords: Option<(ClickPosition, StableRowIndex)>,pub font_scale: Option<f64>,+ /// Latest durable Mux PaneOutput generation included in a frame this+ /// native window successfully presented.+ presented_output_generation: u64,+}++fn pane_output_needs_repaint(current: u64, presented: u64) -> bool {+ current != presented+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) struct PaintOutcome {+ draw_submitted: bool,+ frame_complete: bool,+}++fn frame_can_acknowledge_output(outcome: PaintOutcome, presented: bool) -> bool {+ presented && outcome.draw_submitted && outcome.frame_complete+}++#[cfg(test)]+mod pane_output_watchdog_tests {+ use super::{frame_can_acknowledge_output, pane_output_needs_repaint, PaintOutcome};++ #[test]+ fn a_later_output_remains_unpresented_after_an_older_frame_commits() {+ let captured = 4;+ let current_after_paint = 5;+ assert!(frame_can_acknowledge_output(+ PaintOutcome {+ draw_submitted: true,+ frame_complete: true,+ },+ true,+ ));+ assert!(pane_output_needs_repaint(+ current_after_paint,+ captured+ ));+ assert!(!pane_output_needs_repaint(captured, captured));+ }++ #[test]+ fn incomplete_failed_or_skipped_frames_never_acknowledge_output() {+ assert!(!frame_can_acknowledge_output(+ PaintOutcome {+ draw_submitted: true,+ frame_complete: false,+ },+ true,+ ));+ assert!(!frame_can_acknowledge_output(+ PaintOutcome {+ draw_submitted: false,+ frame_complete: true,+ },+ true,+ ));+ assert!(!frame_can_acknowledge_output(+ PaintOutcome {+ draw_submitted: true,+ frame_complete: true,+ },+ false,+ ));+ }}#[derive(Clone)]@@ -1765,6 +1830,11 @@ pub struct TermWindow {tab_state: RefCell<HashMap<TabId, TabState>>,pane_state: RefCell<HashMap<PaneId, PaneState>>,+ /// Generations read before the terminal lines used by the current paint+ /// pass. Retried or abandoned passes replace this map; only a successful+ /// GPU present commits it into `PaneState`.+ frame_pane_output_generations: HashMap<PaneId, u64>,+ track_pane_output_generations_for_frame: bool,pane_font_cache: RefCell<HashMap<PaneFontKey, PaneFontEntry>>,pane_font_cache_tick: Cell<u64>,/// One recorded thumbnail per card, kept across frames so an unchanged@@ -2818,6 +2888,8 @@ impl TermWindow {last_scroll_info: RenderableDimensions::default(),tab_state: RefCell::new(HashMap::new()),pane_state: RefCell::new(HashMap::new()),+ frame_pane_output_generations: HashMap::new(),+ track_pane_output_generations_for_frame: false,pane_font_cache: RefCell::new(HashMap::new()),pane_font_cache_tick: Cell::new(0),preview_quad_cache: RefCell::new(HashMap::new()),@@ -3576,8 +3648,25 @@ impl TermWindow {self.dimensions.pixel_height as u32,),);- self.paint_impl(&mut RenderFrame::Glium(&mut frame));- window.finish_frame(frame).is_ok()+ let outcome = match self.paint_impl(&mut RenderFrame::Glium(&mut frame)) {+ Ok(outcome) => outcome,+ Err(err) => {+ log::error!("failed to draw OpenGL frame: {err:#}");+ self.discard_unpresented_pane_output();+ return false;+ }+ };+ if !outcome.draw_submitted {+ self.discard_unpresented_pane_output();+ return false;+ }+ let presented = window.finish_frame(frame).is_ok();+ if frame_can_acknowledge_output(outcome, presented) {+ self.acknowledge_presented_pane_output();+ } else {+ self.discard_unpresented_pane_output();+ }+ presented}fn do_paint_webgpu(&mut self) -> anyhow::Result<bool> {@@ -3585,6 +3674,7 @@ impl TermWindow {match self.do_paint_webgpu_impl() {Ok(ok) => Ok(ok),Err(err) => {+ self.discard_unpresented_pane_output();match err.downcast_ref::<wgpu::SurfaceError>() {Some(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {self.webgpu.as_mut().unwrap().resize(self.dimensions);@@ -3598,8 +3688,13 @@ impl TermWindow {}fn do_paint_webgpu_impl(&mut self) -> anyhow::Result<bool> {- self.paint_impl(&mut RenderFrame::WebGpu);- Ok(true)+ let outcome = self.paint_impl(&mut RenderFrame::WebGpu)?;+ if frame_can_acknowledge_output(outcome, outcome.draw_submitted) {+ self.acknowledge_presented_pane_output();+ } else {+ self.discard_unpresented_pane_output();+ }+ Ok(outcome.draw_submitted)}fn dispatch_notif(&mut self, notif: TermWindowNotif, window: &Window) -> anyhow::Result<()> {@@ -3924,8 +4019,15 @@ impl TermWindow {MuxNotification::Empty => {}},TermWindowNotif::EmitStatusUpdate => {+ // Re-arm before doing any work: this tick drives the render+ // watchdog, and a panic below (swallowed by the spawn queue)+ // must not end the heartbeat for the window's lifetime. The+ // later re-arm from the title path dedupes via+ // last_status_call.+ self.schedule_next_status_update();self.emit_status_event();self.refresh_all_thread_work();+ self.terminal_render_watchdog();}TermWindowNotif::OpenProjectPath(path) => {let path = path.to_string_lossy();@@ -6056,6 +6158,109 @@ impl TermWindow {self.schedule_next_status_update();}+ fn active_terminal_has_overlay(&self, tab: &Arc<Tab>) -> bool {+ if self+ .tab_state+ .borrow()+ .get(&tab.tab_id())+ .is_some_and(|state| state.overlay.is_some())+ {+ return true;+ }+ let pane_state = self.pane_state.borrow();+ tab.iter_panes().into_iter().any(|pos| {+ pane_state+ .get(&pos.pane.pane_id())+ .is_some_and(|state| state.overlay.is_some())+ })+ }++ fn can_track_presented_terminal_output(&self, tab: &Arc<Tab>) -> bool {+ !self.content_view_foreground()+ && self.content_view_fade.is_none()+ && !self.frontend_surface_blocked()+ && !self.active_terminal_has_overlay(tab)+ }++ fn acknowledge_presented_pane_output(&mut self) {+ let presented = std::mem::take(&mut self.frame_pane_output_generations);+ let mut pane_state = self.pane_state.borrow_mut();+ for (pane_id, generation) in presented {+ pane_state+ .entry(pane_id)+ .or_default()+ .presented_output_generation = generation;+ }+ }++ fn discard_unpresented_pane_output(&mut self) {+ self.frame_pane_output_generations.clear();+ }++ /// PaneOutput is durable in the Mux, while delivery into a native window+ /// is asynchronous. Compare that durable generation with this window's+ /// last successful present so a lost last repaint is observable for every+ /// pane type. ClientPane gets an additional state watchdog for work that+ /// has not yet become a renderable line.+ fn terminal_render_watchdog(&mut self) {+ let mux = Mux::get();+ let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) else {+ return;+ };+ // These surfaces replace or deliberately hide terminal pixels. They+ // cannot acknowledge a terminal generation, so retrying underneath+ // them would latch the watchdog at one repaint per status tick.+ if !self.can_track_presented_terminal_output(&tab) {+ return;+ }+ for pos in tab.iter_panes() {+ if self+ .collapsed_pane_layouts+ .contains_key(&pos.pane_stack_id)+ {+ continue;+ }+ let pane_id = pos.pane.pane_id();+ let current = mux.pane_output_generation(pane_id);+ let presented = self+ .pane_state+ .borrow()+ .get(&pane_id)+ .map(|state| state.presented_output_generation)+ .unwrap_or(0);+ if pane_output_needs_repaint(current, presented) {+ log::debug!(+ "terminal render watchdog: window={} pane={pane_id} output generation \+ {current} has not been presented (last={presented}); repainting",+ self.mux_window_id,+ );+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ return;+ }+ if let Some(client_pane) = pos+ .pane+ .downcast_ref::<wezterm_client::pane::ClientPane>()+ {+ // Pass the viewport the renderer will actually paint —+ // scrolled back, that is not the live screen, and judging+ // the live rows would latch the watchdog on Stale rows a+ // repaint never touches.+ let viewport_top = self.get_viewport(pane_id);+ if client_pane.render_looks_stalled(viewport_top) {+ log::debug!(+ "terminal render watchdog: pane {pane_id} has undelivered content; repainting"+ );+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ return;+ }+ }+ }+ }+fn schedule_next_status_update(&mut self) {if let Some(window) = self.window.as_ref() {let now = Instant::now();diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 45c3d9e0..d3edeb95 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -3,7 +3,7 @@ use crate::quad::{};use crate::termwindow::content_view::{ContentViewTypography, TerminalPreviewRequest};use crate::termwindow::render::{LineToEleShapeCacheKey, RenderScreenLineParams};-use crate::termwindow::{RenderFrame, TermWindowNotif, UIItem, UIItemType};+use crate::termwindow::{PaintOutcome, RenderFrame, TermWindowNotif, UIItem, UIItemType};use crate::ui::{DrawContext, UiPalette};use ::window::bitmaps::atlas::OutOfTextureSpace;use ::window::color::LinearRgba;@@ -642,7 +642,10 @@ impl crate::TermWindow {}}- pub fn paint_impl(&mut self, frame: &mut RenderFrame) {+ pub(crate) fn paint_impl(+ &mut self,+ frame: &mut RenderFrame,+ ) -> anyhow::Result<PaintOutcome> {self.num_frames += 1;// If nothing on screen needs animating, then we can avoid// invalidating as frequently@@ -692,8 +695,11 @@ impl crate::TermWindow {// and will be swapped regardless, so an unpainted frame there would// present undefined content, which is worse than a partial one.let mut present_frame = true;+ let mut frame_complete = false;'pass: for pass in 0.. {+ self.frame_pane_output_generations.clear();+ self.track_pane_output_generations_for_frame = false;match self.paint_pass() {Ok(_) => match self.render_state.as_mut().unwrap().allocated_more_quads() {Ok(allocated) => {@@ -702,6 +708,7 @@ impl crate::TermWindow {// so the counter can be read as a distribution// rather than as "something went wrong once".crate::perf::log_counter("paint_passes", pass + 1);+ frame_complete = true;break 'pass;}// Each retry repaints the *whole* window, thumbnails@@ -827,9 +834,11 @@ impl crate::TermWindow {}log::debug!("paint_impl before call_draw elapsed={:?}", start.elapsed());- if present_frame || !matches!(frame, RenderFrame::WebGpu) {- self.call_draw(frame).ok();- }+ let draw_result = if present_frame || !matches!(frame, RenderFrame::WebGpu) {+ self.call_draw(frame).map(|_| true)+ } else {+ Ok(false)+ };self.publish_ui_shape_cache_diagnostics_throttled();self.last_frame_duration = start.elapsed();log::debug!(@@ -881,7 +890,10 @@ impl crate::TermWindow {if let Some(window) = self.window.as_ref() {window.invalidate();}- return;+ return draw_result.map(|draw_submitted| PaintOutcome {+ draw_submitted,+ frame_complete,+ });}let prior = self.scheduled_animation.borrow_mut().take();match prior {@@ -914,6 +926,10 @@ impl crate::TermWindow {}}}+ draw_result.map(|draw_submitted| PaintOutcome {+ draw_submitted,+ frame_complete,+ })}/// Paint the active content view into the content area (right of the@@ -3479,6 +3495,11 @@ impl crate::TermWindow {let frontend_blocked = !content_view_active && self.frontend_surface_blocked();+ self.track_pane_output_generations_for_frame = !recording_flight+ && mux::Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .is_some_and(|tab| self.can_track_presented_terminal_output(&tab));+// Everything the terminal registers during a transition sits under a// view that is on its way in or out. Leaving those targets live would// let a click land on a pane the user is looking at through adiff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rsindex 4fd42d62..3f0e41f8 100644--- a/wezterm-gui/src/termwindow/render/pane.rs+++ b/wezterm-gui/src/termwindow/render/pane.rs@@ -1059,11 +1059,20 @@ impl crate::TermWindow {}fn paint_pane_box_model(&mut self, pos: &PositionedPane) -> anyhow::Result<()> {+ let pane_id = pos.pane.pane_id();+ let output_generation = self+ .track_pane_output_generations_for_frame+ .then(|| mux::Mux::get().pane_output_generation(pane_id));let computed = self.build_pane(pos)?;let mut ui_items = computed.ui_items();self.ui_items.append(&mut ui_items);let gl_state = self.render_state.as_ref().unwrap();- self.render_element(&computed, gl_state, None)+ self.render_element(&computed, gl_state, None)?;+ if let Some(generation) = output_generation {+ self.frame_pane_output_generations+ .insert(pane_id, generation);+ }+ Ok(())}pub fn paint_pane(@@ -1670,10 +1679,20 @@ impl crate::TermWindow {}}+ let output_generation = render+ .term_window+ .track_pane_output_generations_for_frame+ .then(|| mux::Mux::get().pane_output_generation(pane_id));pos.pane.with_lines_mut(stable_range.clone(), &mut render);if let Some(error) = render.error.take() {return Err(error).context("error while calling with_lines_mut");}+ if let Some(generation) = output_generation {+ render+ .term_window+ .frame_pane_output_generations+ .insert(pane_id, generation);+ }}/*diff --git a/window/examples/async.rs b/window/examples/async.rsindex d375fe32..3fe34805 100644--- a/window/examples/async.rs+++ b/window/examples/async.rs@@ -93,6 +93,7 @@ impl MyWindow {| WindowEvent::ContextMenuDismissed| WindowEvent::NativeTextInputReplace { .. }| WindowEvent::ToggleWorkspaceSidebar+ | WindowEvent::WorkspaceSidebarButtonHover(_)| WindowEvent::MouseLeave| WindowEvent::SetInnerSizeCompleted => {}}diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rsindex 54585605..ea24d596 100644--- a/window/src/os/macos/window.rs+++ b/window/src/os/macos/window.rs@@ -50,6 +50,7 @@ use raw_window_handle::{};use std::any::Any;use std::cell::{Cell, RefCell};+use std::collections::VecDeque;use std::ffi::{c_void, CStr};use std::hash::{DefaultHasher, Hash, Hasher};use std::path::{Path, PathBuf};@@ -82,6 +83,118 @@ const NS_DRAG_OPERATION_COPY: NSUInteger = 1;static THINKTERM_PERF_ENABLED: OnceLock<bool> = OnceLock::new();+type PendingWindowNotification = Box<dyn Any + Send + Sync>;++struct PendingNotificationQueue<T> {+ pending: VecDeque<T>,+ draining: bool,+ drain_scheduled: bool,+}++impl<T> Default for PendingNotificationQueue<T> {+ fn default() -> Self {+ Self {+ pending: VecDeque::new(),+ draining: false,+ drain_scheduled: false,+ }+ }+}++impl<T> PendingNotificationQueue<T> {+ fn enqueue(&mut self, item: T) {+ self.pending.push_back(item);+ }++ fn begin_scheduled_drain(&mut self) {+ self.drain_scheduled = false;+ }+}++/// Drain without holding the queue borrow across `dispatch`. That is what+/// lets a notification handler enqueue another notification without either+/// re-entering the window state or overtaking work that was already queued.+/// Returns true when the caller must schedule one future drain attempt.+fn drain_pending_notifications<T>(+ queue: &RefCell<PendingNotificationQueue<T>>,+ mut dispatch: impl FnMut(T) -> Result<(), T>,+) -> bool {+ {+ let mut queue = queue.borrow_mut();+ if queue.draining {+ return false;+ }+ queue.draining = true;+ }++ let mut schedule_retry = false;+ loop {+ let Some(item) = queue.borrow_mut().pending.pop_front() else {+ break;+ };+ if let Err(item) = dispatch(item) {+ let mut queue = queue.borrow_mut();+ queue.pending.push_front(item);+ if !queue.drain_scheduled {+ queue.drain_scheduled = true;+ schedule_retry = true;+ }+ break;+ }+ }+ queue.borrow_mut().draining = false;+ schedule_retry+}++#[cfg(test)]+mod pending_notification_tests {+ use super::{drain_pending_notifications, PendingNotificationQueue};+ use std::cell::RefCell;++ #[test]+ fn busy_notifications_retry_once_and_keep_fifo_order() {+ let queue = RefCell::new(PendingNotificationQueue::default());+ queue.borrow_mut().enqueue(1);+ queue.borrow_mut().enqueue(2);++ assert!(drain_pending_notifications(&queue, Err));+ assert_eq!(queue.borrow().pending.iter().copied().collect::<Vec<_>>(), [1, 2]);+ assert!(queue.borrow().drain_scheduled);++ queue.borrow_mut().enqueue(3);+ assert!(+ !drain_pending_notifications(&queue, Err),+ "an already scheduled retry must not be duplicated"+ );++ queue.borrow_mut().begin_scheduled_drain();+ let mut delivered = Vec::new();+ assert!(!drain_pending_notifications(&queue, |item| {+ delivered.push(item);+ Ok(())+ }));+ assert_eq!(delivered, [1, 2, 3]);+ assert!(queue.borrow().pending.is_empty());+ }++ #[test]+ fn reentrant_notifications_append_after_the_existing_backlog() {+ let queue = RefCell::new(PendingNotificationQueue::default());+ queue.borrow_mut().enqueue(1);+ queue.borrow_mut().enqueue(2);++ let mut delivered = Vec::new();+ assert!(!drain_pending_notifications(&queue, |item| {+ delivered.push(item);+ if item == 1 {+ queue.borrow_mut().enqueue(3);+ }+ Ok(())+ }));+ assert_eq!(delivered, [1, 2, 3]);+ }+}+fn thinkterm_perf_enabled() -> bool {*THINKTERM_PERF_ENABLED.get_or_init(|| {std::env::var_os("THINKTERM_PERF")@@ -997,13 +1110,7 @@ impl WindowOps for Window {{Connection::with_window_inner(self.id, move |inner| {if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {- if let Ok(mut inner) = window_view.inner.try_borrow_mut() {- inner- .events- .dispatch(WindowEvent::Notification(Box::new(t)));- } else {- log::trace!("skipping notification while window is busy");- }+ window_view.enqueue_notification(Box::new(t), *inner.view);}Ok(())});@@ -2812,6 +2919,11 @@ fn code_to_cursor(code: i64) -> Option<MouseCursor> {struct WindowView {inner: Rc<RefCell<Inner>>,+ // Notifications must live outside `inner`: AppKit can run nested event+ // loops while an event handler holds that RefCell. Dropping work on a+ // failed try_borrow loses PaneOutput repaints and even the timer tick that+ // would otherwise recover them.+ pending_notifications: RefCell<PendingNotificationQueue<PendingWindowNotification>>,// Repaint scheduling flags live outside the RefCell: they are touched// from paths that can run while `inner` is borrowed (reentrant drawRect,// the frame throttle timer, invalidate()), and losing an update here is@@ -4637,6 +4749,48 @@ impl WindowView {}}+ fn enqueue_notification(&self, notification: PendingWindowNotification, view: id) {+ self.pending_notifications+ .borrow_mut()+ .enqueue(notification);+ self.try_drain_notifications(view);+ }++ fn try_drain_notifications(&self, view: id) {+ let schedule_retry =+ drain_pending_notifications(&self.pending_notifications, |notification| {+ let Ok(mut inner) = self.inner.try_borrow_mut() else {+ return Err(notification);+ };+ inner+ .events+ .dispatch(WindowEvent::Notification(notification));+ Ok(())+ });+ if schedule_retry {+ let pending = self.pending_notifications.borrow().pending.len();+ log::trace!(+ "window is busy; queued {pending} notification(s) for the next runloop turn"+ );+ unsafe {+ let () = msg_send![view, performSelector: sel!(thinktermDrainNotifications)+ withObject: nil+ afterDelay: 0.0];+ }+ }+ }++ extern "C" fn drain_notifications(this: &mut Object, _sel: Sel) {+ let view: id = this as *mut Object;+ if let Some(window_view) = Self::get_this(this) {+ window_view+ .pending_notifications+ .borrow_mut()+ .begin_scheduled_drain();+ window_view.try_drain_notifications(view);+ }+ }+fn init_with_frame(inner: &Rc<RefCell<Inner>>, rect: NSRect) -> anyhow::Result<StrongPtr> {let cls = Self::get_class();@@ -4646,6 +4800,7 @@ impl WindowView {let view = Box::into_raw(Box::new(Self {inner: Rc::clone(&inner),+ pending_notifications: RefCell::new(PendingNotificationQueue::default()),paint_throttled: Cell::new(false),paint_throttled_since: Cell::new(None),invalidated: Cell::new(true),@@ -4694,6 +4849,10 @@ impl WindowView {sel!(thinktermRearmNeedsDisplay),Self::rearm_needs_display as extern "C" fn(&mut Object, Sel),);+ cls.add_method(+ sel!(thinktermDrainNotifications),+ Self::drain_notifications as extern "C" fn(&mut Object, Sel),+ );cls.add_method(sel!(windowWillClose:),Self::window_will_close as extern "C" fn(&mut Object, Sel, id),