Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix focus cleanup stalls during conversation restoration (#65177)
Kirill Bulatove463c5ab74e0
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 71aa2703c89..a4ee3234869 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -2408,13 +2408,14 @@ impl ConversationView {cx.spawn_in(window, async move |this, cx| {let subagent_thread = subagent_thread_task.await?;this.update_in(cx, |this, window, cx| {- let Some(conversation) = this- .as_connected()- .map(|connected| connected.conversation.clone())- else {+ let Some(connected) = this.as_connected() else {return;};let subagent_session_id = subagent_thread.read(cx).session_id().clone();+ if connected.threads.contains_key(&subagent_session_id) {+ return;+ }+ let conversation = connected.conversation.clone();conversation.update(cx, |conversation, cx| {conversation.register_thread(subagent_thread.clone(), cx);});@@ -4040,6 +4041,7 @@ pub(crate) mod tests {use serde_json::json;use settings::SettingsStore;use std::any::Any;+ use std::cell::RefCell;use std::path::{Path, PathBuf};use std::rc::Rc;use std::sync::Arc;@@ -5800,6 +5802,56 @@ pub(crate) mod tests {});}+ #[gpui::test]+ async fn test_concurrent_subagent_loads_create_one_thread_view(cx: &mut TestAppContext) {+ init_test(cx);++ let (conversation_view, cx) = setup_conversation_view(FakeAcpAgentServer::new(), cx).await;+ let root_session_id =+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.session_id.clone());+ let subagent_session_id = acp_v2::SessionId::new("subagent");+ let created_views = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|_, cx| {+ cx.observe_new::<ThreadView>({+ let created_views = created_views.clone();+ let subagent_session_id = subagent_session_id.clone();+ move |view, _, cx| {+ if view.session_id == subagent_session_id {+ created_views.borrow_mut().push(cx.entity_id());+ }+ }+ })+ });++ conversation_view.update_in(cx, |view, window, cx| {+ for _ in 0..2 {+ view.load_subagent_session(+ subagent_session_id.clone(),+ root_session_id.clone(),+ window,+ cx,+ );+ }+ assert_eq!(view.as_connected().expect("connected").threads.len(), 1);+ });+ cx.run_until_parked();++ let restored_view = conversation_view.read_with(cx, |view, cx| {+ let connected = view.as_connected().expect("connected");+ assert_eq!(connected.threads.len(), 2);+ assert_eq!(connected.conversation.read(cx).subscriptions.len(), 2);+ connected+ .threads+ .get(&subagent_session_id)+ .expect("restored subagent")+ .clone()+ });+ assert_eq!(+ created_views.borrow().as_slice(),+ &[restored_view.entity_id()]+ );+ }+#[gpui::test]async fn test_session_notices_stay_with_background_session_without_metadata_updates(cx: &mut TestAppContext,diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.tomlindex 4d978071f5e..f6616c8c743 100644--- a/crates/gpui/Cargo.toml+++ b/crates/gpui/Cargo.toml@@ -11,6 +11,7 @@ homepage = "https://gpui.rs"readme = "README.md"keywords = ["desktop", "gui", "immediate"]categories = ["gui"]+autobenches = false[lints]@@ -189,7 +190,7 @@ ignored = ["objc2","objc2-metal",]-ignored-paths = ["src/_ownership_and_data_flow.rs"]+ignored-paths = ["src/_ownership_and_data_flow.rs", "benches/focus_cleanup.rs"][[example]]name = "hello_world"diff --git a/crates/gpui/benches/focus_cleanup.rs b/crates/gpui/benches/focus_cleanup.rsnew file mode 100644index 00000000000..8d143e84cd0--- /dev/null+++ b/crates/gpui/benches/focus_cleanup.rs@@ -0,0 +1,141 @@+use std::{cell::RefCell, rc::Rc, time::Duration};++use gpui::{AppContext as _, BenchAppContext, Entity, EntityId, FocusHandle, WeakFocusHandle};++const ENTITY_COUNT: usize = 10_000;++#[gpui::bench(+ inputs = [0, 100, 1_000, 10_000],+ input_name = "handles",+ group = "focus_cleanup_no_drops_10000_effects",+ fps = 120+)]+fn no_drops(handle_count: &usize, cx: &mut BenchAppContext) {+ measure(*handle_count, false, 0, cx);+}++#[gpui::bench(+ inputs = [10_000],+ input_name = "handles",+ group = "focus_cleanup_final_drops_10000_effects",+ fps = 120+)]+fn final_drops(handle_count: &usize, cx: &mut BenchAppContext) {+ measure(*handle_count, true, 0, cx);+}++#[gpui::bench(+ inputs = [1, 10],+ input_name = "windows",+ group = "focus_cleanup_final_drops_with_windows_10000_handles_10000_effects",+ fps = 120+)]+fn final_drops_with_windows(window_count: &usize, cx: &mut BenchAppContext) {+ measure(10_000, true, *window_count, cx);+}++fn measure(handle_count: usize, final_drops: bool, window_count: usize, cx: &mut BenchAppContext) {+ assert!(!cfg!(debug_assertions), "use --profile release-fast");+ assert!(window_count <= handle_count);+ let windows = (0..window_count)+ .map(|_| cx.add_empty_window().window_handle())+ .collect::<Vec<_>>();+ let observed = Rc::new(RefCell::new(Vec::with_capacity(ENTITY_COUNT)));+ let _subscription = cx.update(|cx| {+ cx.observe_new::<CreatedEntity>({+ let observed = observed.clone();+ move |_, _, cx| observed.borrow_mut().push(cx.entity_id())+ })+ });+ let prepare = |cx: &mut BenchAppContext| {+ cx.update(|cx| {+ let handles = (0..handle_count)+ .map(|_| cx.focus_handle())+ .collect::<Vec<_>>();+ for (window, handle) in windows.iter().zip(&handles) {+ window+ .update(cx, |_, window, cx| {+ window.focus(handle, cx);+ assert_eq!(window.focused(cx).as_ref(), Some(handle));+ })+ .expect("benchmark window missing during focus setup");+ }+ handles+ })+ };+ let run = |handles: Vec<FocusHandle>, cx: &mut BenchAppContext| {+ let observed = observed.clone();+ cx.read(|cx| {+ cx.spawn(async move |cx| {+ let dropped = handles.iter().map(FocusHandle::downgrade).collect();+ let entities = cx.update(|cx| {+ drop(handles);+ (0..ENTITY_COUNT)+ .map(|_| cx.new(|_| CreatedEntity))+ .collect::<Vec<_>>()+ });+ CompletedBatch {+ entities,+ observed,+ dropped,+ }+ })+ })+ };+ if final_drops {+ cx.bench_batched_task(prepare, |handles, cx| run(std::mem::take(handles), cx));++ for window in windows {+ window+ .update(cx, |_, window, cx| assert_eq!(window.focused(cx), None))+ .expect("benchmark window missing after focus cleanup");+ }+ } else {+ let handles = prepare(cx);+ cx.bench_task(|cx| run(Vec::new(), cx));++ for handle in &handles {+ assert_eq!(handle.downgrade().upgrade().as_ref(), Some(handle));+ }+ }+}++struct CreatedEntity;++struct CompletedBatch {+ entities: Vec<Entity<CreatedEntity>>,+ observed: Rc<RefCell<Vec<EntityId>>>,+ dropped: Vec<WeakFocusHandle>,+}++impl Drop for CompletedBatch {+ fn drop(&mut self) {+ assert_eq!(self.entities.len(), ENTITY_COUNT);+ assert_eq!(+ *self.observed.borrow(),+ self.entities+ .iter()+ .map(Entity::entity_id)+ .collect::<Vec<_>>()+ );+ self.observed.borrow_mut().clear();+ assert_eq!(+ self.dropped+ .iter()+ .filter(|handle| handle.upgrade().is_some())+ .count(),+ 0+ );+ }+}++gpui::bench_group! {+ name = benches;+ config = criterion::Criterion::default()+ .sample_size(10)+ .warm_up_time(Duration::from_secs(1))+ .measurement_time(Duration::from_secs(3))+ .without_plots();+ targets = no_drops, final_drops, final_drops_with_windows+}+gpui::bench_main!(benches);diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rsindex 33456df65e4..d26e92f4e3d 100644--- a/crates/gpui/src/app.rs+++ b/crates/gpui/src/app.rs@@ -8,7 +8,7 @@ use std::{ops::{Deref, DerefMut},path::{Path, PathBuf},rc::{Rc, Weak},- sync::{Arc, atomic::Ordering::SeqCst},+ sync::Arc,time::Duration,};@@ -832,7 +832,7 @@ pub struct App {pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,- pub(crate) focus_handles: Arc<FocusMap>,+ pub(crate) focus_handles: Arc<RwLock<FocusMap>>,pub(crate) keymap: Rc<RefCell<Keymap>>,pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,@@ -970,7 +970,7 @@ impl App {windows: SlotMap::with_key(),window_update_stack: Vec::new(),window_handles: FxHashMap::default(),- focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),+ focus_handles: Arc::new(RwLock::new(FocusMap::default())),keymap: Rc::new(RefCell::new(Keymap::default())),keyboard_layout,keyboard_mapper,@@ -2154,25 +2154,36 @@ impl App {/// Repeatedly called during `flush_effects` to handle a focused handle being dropped.fn release_dropped_focus_handles(&mut self) {- self.focus_handles- .clone()- .write()- .retain(|handle_id, focus| {- if focus.ref_count.load(SeqCst) == 0 {- for window_handle in self.windows() {- window_handle- .update(self, |_, window, cx| {- if window.focus == Some(handle_id) {- window.blur(cx);- }- })- .unwrap();- }- false- } else {- true- }- });+ let focus_handles = self.focus_handles.clone();+ let mut focus_handles = focus_handles.write();+ let FocusMap {+ handles,+ dropped_handles,+ } = &mut *focus_handles;+ if dropped_handles.is_empty() {+ return;+ }++ let windows = self+ .windows+ .values()+ .filter_map(|window| {+ let window = window.as_ref()?;+ dropped_handles+ .contains(&window.focus?)+ .then_some(window.handle)+ })+ .collect::<SmallVec<[_; 1]>>();+ for handle_id in dropped_handles.drain(..) {+ handles.remove(handle_id);+ }+ drop(focus_handles);++ for window_handle in windows {+ window_handle+ .update(self, |_, window, cx| window.blur(cx))+ .ok();+ }}fn apply_notify_effect(&mut self, emitter: EntityId) {diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rsindex 0670f88b4a7..bc0cf6f5a79 100644--- a/crates/gpui/src/key_dispatch.rs+++ b/crates/gpui/src/key_dispatch.rs@@ -1375,6 +1375,18 @@ mod tests {assert!(*pending_input_changed_count.borrow() > count_before_blur);});+ let temporary_focus = cx.update(|window, cx| {+ let handle = cx.focus_handle();+ window.focus(&handle, cx);+ handle+ });+ cx.simulate_keystrokes("ctrl-d");+ cx.update(|window, _| assert!(window.has_pending_keystrokes()));+ let count_before_drop = *pending_input_changed_count.borrow();+ cx.update(|_, _| drop(temporary_focus));+ cx.update(|window, _| assert!(window.pending_input_is_none()));+ assert_eq!(*pending_input_changed_count.borrow(), count_before_drop + 1);+cx.update(|window, cx| window.disable_focus(cx));cx.simulate_keystrokes("ctrl-d");diff --git a/crates/gpui/src/tab_stop.rs b/crates/gpui/src/tab_stop.rsindex bde651ae5c4..9e529d8c3de 100644--- a/crates/gpui/src/tab_stop.rs+++ b/crates/gpui/src/tab_stop.rs@@ -315,13 +315,14 @@ mod sum_tree_impl {#[cfg(test)]mod tests {use itertools::Itertools as _;+ use parking_lot::RwLock;use crate::{FocusHandle, FocusId, FocusMap, TabStopMap};use std::sync::Arc;#[test]fn test_tab_handles() {- let focus_map = Arc::new(FocusMap::default());+ let focus_map = Arc::new(RwLock::new(FocusMap::default()));let mut tab_index_map = TabStopMap::default();let focus_handles = [@@ -410,7 +411,7 @@ mod tests {#[test]fn test_tab_non_stop_filtering() {- let focus_map = Arc::new(FocusMap::default());+ let focus_map = Arc::new(RwLock::new(FocusMap::default()));let mut tab_index_map = TabStopMap::default();// Check that we can query next from a non-stop tab@@ -433,7 +434,7 @@ mod tests {#[must_use]struct TabStopMapTest {tab_map: TabStopMap,- focus_map: Arc<FocusMap>,+ focus_map: Arc<RwLock<FocusMap>>,expected: Vec<(usize, FocusId)>,}@@ -442,7 +443,7 @@ mod tests {fn new() -> Self {Self {tab_map: TabStopMap::default(),- focus_map: Arc::new(FocusMap::default()),+ focus_map: Arc::new(RwLock::new(FocusMap::default())),expected: Vec::default(),}}diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex 27c8a3e5b2c..33fa14bfea6 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -39,7 +39,7 @@ use itertools::Itertools;use objc2_core_foundation::CFRetained;#[cfg(any(target_os = "macos", target_os = "ios"))]use objc2_core_video::CVPixelBuffer;-use parking_lot::RwLock;+use parking_lot::{RwLock, RwLockUpgradableReadGuard};use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};use refineable::Refineable;use scheduler::Instant;@@ -497,7 +497,12 @@ impl ArenaClearNeeded {}}-pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;+#[derive(Default)]+pub(crate) struct FocusMap {+ pub(crate) handles: SlotMap<FocusId, FocusRef>,+ pub(crate) dropped_handles: Vec<FocusId>,+}+pub(crate) struct FocusRef {pub(crate) ref_count: AtomicUsize,pub(crate) tab_index: isize,@@ -537,7 +542,7 @@ impl FocusId {/// A handle which can be used to track and manipulate the focused element in a window.pub struct FocusHandle {pub(crate) id: FocusId,- handles: Arc<FocusMap>,+ handles: Arc<RwLock<FocusMap>>,/// The index of this element in the tab order.pub tab_index: isize,/// Whether this element can be focused by tab navigation.@@ -551,8 +556,8 @@ impl std::fmt::Debug for FocusHandle {}impl FocusHandle {- pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {- let id = handles.write().insert(FocusRef {+ pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {+ let id = handles.write().handles.insert(FocusRef {ref_count: AtomicUsize::new(1),tab_index: 0,tab_stop: false,@@ -566,9 +571,9 @@ impl FocusHandle {}}- pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {+ pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {let lock = handles.read();- let focus = lock.get(id)?;+ let focus = lock.handles.get(id)?;if atomic_incr_if_not_zero(&focus.ref_count) == 0 {return None;}@@ -583,7 +588,7 @@ impl FocusHandle {/// Sets the tab index of the element associated with this handle.pub fn tab_index(mut self, index: isize) -> Self {self.tab_index = index;- if let Some(focus) = self.handles.write().get_mut(self.id) {+ if let Some(focus) = self.handles.write().handles.get_mut(self.id) {focus.tab_index = index;}self@@ -594,7 +599,7 @@ impl FocusHandle {/// When `false`, the element will not be included in the tab order.pub fn tab_stop(mut self, tab_stop: bool) -> Self {self.tab_stop = tab_stop;- if let Some(focus) = self.handles.write().get_mut(self.id) {+ if let Some(focus) = self.handles.write().handles.get_mut(self.id) {focus.tab_stop = tab_stop;}self@@ -663,12 +668,15 @@ impl Eq for FocusHandle {}impl Drop for FocusHandle {fn drop(&mut self) {- self.handles- .read()- .get(self.id)- .unwrap()- .ref_count- .fetch_sub(1, SeqCst);+ let handles = self.handles.upgradable_read();+ let focus = handles.handles.get(self.id).expect("focus handle missing");+ let previous_count = focus.ref_count.fetch_sub(1, SeqCst);+ assert_ne!(previous_count, 0, "over-released focus handle");+ if previous_count == 1 {+ RwLockUpgradableReadGuard::upgrade(handles)+ .dropped_handles+ .push(self.id);+ }}}@@ -676,7 +684,7 @@ impl Drop for FocusHandle {#[derive(Clone, Debug)]pub struct WeakFocusHandle {pub(crate) id: FocusId,- pub(crate) handles: Weak<FocusMap>,+ pub(crate) handles: Weak<RwLock<FocusMap>>,}impl WeakFocusHandle {@@ -7917,6 +7925,95 @@ mod tests {canvas, div, hsla, point, px, size,};+ #[gpui::test]+ async fn test_focus_handle_release(cx: &mut TestAppContext) {+ let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));+ let handle_id = handle.id;+ let weak_handle = handle.downgrade();+ let retained = handle.clone();+ drop(handle);++ cx.update(|_| {});+ cx.read(|cx| {+ let handles = cx.focus_handles.read();+ assert_eq!(handles.handles.len(), 2);+ assert!(handles.dropped_handles.is_empty());+ });+ assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));++ cx.background_spawn(async move { drop(retained) }).await;+ assert_eq!(weak_handle.upgrade(), None);+ cx.read(|cx| {+ assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);+ });+ cx.update(|_| {});+ cx.read(|cx| {+ let handles = cx.focus_handles.read();+ assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);+ assert!(handles.dropped_handles.is_empty());+ });++ let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);+ assert_eq!(weak_handle.upgrade(), None);+ cx.update(|cx| {+ drop(replacements);+ cx.defer(move |_| drop(survivor));+ });+ cx.read(|cx| {+ let handles = cx.focus_handles.read();+ assert_eq!(handles.handles.len(), 0);+ assert!(handles.dropped_handles.is_empty());+ });+ }++ #[gpui::test]+ fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {+ let windows = [+ cx.add_window(|_, _| EmptyView),+ cx.add_window(|_, _| EmptyView),+ cx.add_window(|_, _| EmptyView),+ cx.add_window(|_, _| EmptyView),+ cx.add_window(|_, _| EmptyView),+ ];+ let (handle, other_handle, survivor) =+ cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));+ for window in &windows[..2] {+ window+ .update(cx, |_, window, cx| window.focus(&handle, cx))+ .expect("window exists");+ }+ windows[2]+ .update(cx, |_, window, cx| window.focus(&other_handle, cx))+ .expect("window exists");+ windows[3]+ .update(cx, |_, window, cx| window.focus(&survivor, cx))+ .expect("window exists");++ cx.update(|cx| {+ for _ in 0..1_000 {+ drop(cx.focus_handle());+ }+ drop((handle, other_handle));+ });+ for window in &windows[..3] {+ window+ .update(cx, |_, window, _| assert_eq!(window.focus, None))+ .expect("window exists");+ }+ windows[3]+ .update(cx, |_, window, cx| {+ assert_eq!(window.focused(cx).as_ref(), Some(&survivor));+ assert_eq!(window.focus_generation, 1);+ })+ .expect("window exists");+ windows[4]+ .update(cx, |_, window, _| {+ assert_eq!(window.focus, None);+ assert_eq!(window.focus_generation, 0);+ })+ .expect("window exists");+ }+#[cfg(feature = "profiler")]#[gpui::test]fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {diff --git a/crates/gpui_platform/Cargo.toml b/crates/gpui_platform/Cargo.tomlindex 0d95d3e6a7f..ace83f52cde 100644--- a/crates/gpui_platform/Cargo.toml+++ b/crates/gpui_platform/Cargo.toml@@ -26,6 +26,12 @@ runtime_shaders = ["gpui_macos/runtime_shaders", "gpui_ios/runtime_shaders"]wayland = ["gpui_linux/wayland"]x11 = ["gpui_linux/x11"]+[[bench]]+name = "focus_cleanup"+path = "../gpui/benches/focus_cleanup.rs"+harness = false+required-features = ["bench-support"]+[[bench]]name = "inspector_render"harness = false