Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Fix selection loss while an agent thread is loading (#64252)

Dom Poradaf8c2cc844057
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 8b50b5e74ca..c45f1f77a3b 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -658,12 +658,25 @@ pub fn init(cx: &mut App) {
agent_panel.update(cx, |panel, cx| {
panel.last_context_source = Some(source);
- cx.defer_in(window, move |panel, window, cx| {
- if let Some(conversation_view) = panel.active_conversation_view() {
- conversation_view.update(cx, |conversation_view, cx| {
+ if let Some(conversation_view) = panel.active_conversation_view() {
+ conversation_view.update(cx, |conversation_view, cx| {
+ if conversation_view.active_thread().is_some() {
+ cx.defer_in(
+ window,
+ move |conversation_view, window, cx| {
+ conversation_view
+ .insert_selection(selection, window, cx);
+ },
+ );
+ } else {
conversation_view.insert_selection(selection, window, cx);
- });
- } else if let Some(terminal_id) = panel.active_terminal_id()
+ }
+ });
+ return;
+ }
+
+ cx.defer_in(window, move |panel, window, cx| {
+ if let Some(terminal_id) = panel.active_terminal_id()
&& let Some(agent_terminal) = panel.terminals.get(&terminal_id)
{
// Resolve mentions against the cwd: live cwd, else spawn dir.
@@ -1812,6 +1825,9 @@ impl AgentPanel {
fn draft_has_content(&self, draft: &Entity<ConversationView>, cx: &App) -> bool {
let cv = draft.read(cx);
+ if cv.has_pending_selections() {
+ return true;
+ }
if let Some(thread_view) = cv.active_thread() {
let text = thread_view.read(cx).message_editor.read(cx).text(cx);
if !text.trim().is_empty() {
@@ -3015,7 +3031,11 @@ impl AgentPanel {
if conversation_view.entity_id() == draft_entity
);
- if agent_matches || has_editor_content || !draft_is_active {
+ if agent_matches
+ || has_editor_content
+ || draft.read(cx).has_pending_selections()
+ || !draft_is_active
+ {
return draft.clone();
}
@@ -3322,10 +3342,11 @@ impl AgentPanel {
}
if self.active_thread_id(cx) == Some(id) {
+ // Activating another view must not retain the thread that was explicitly removed
+ self.base_view = BaseView::Uninitialized;
if activate_draft_after_remove {
self.activate_draft(false, AgentThreadSource::AgentPanel, window, cx);
} else {
- self.base_view = BaseView::Uninitialized;
self.refresh_base_view_subscriptions(window, cx);
}
self.serialize(cx);
@@ -4264,7 +4285,11 @@ impl AgentPanel {
.retained_threads
.iter()
.filter(|(_id, view)| {
- let Some(thread_view) = view.read(cx).root_thread_view() else {
+ let view = view.read(cx);
+ if view.has_pending_selections() {
+ return false;
+ }
+ let Some(thread_view) = view.root_thread_view() else {
return true;
};
let thread = thread_view.read(cx).thread.read(cx);
@@ -9296,6 +9321,264 @@ mod tests {
});
}
+ struct DelayedSelectionAgentServer {
+ ready: async_channel::Receiver<()>,
+ }
+
+ impl AgentServer for DelayedSelectionAgentServer {
+ fn logo(&self) -> IconName {
+ IconName::ZedAgent
+ }
+
+ fn agent_id(&self) -> AgentId {
+ AgentId::new("delayed-selection")
+ }
+
+ fn connect(
+ &self,
+ _delegate: agent_servers::AgentServerDelegate,
+ _project: Entity<Project>,
+ cx: &mut App,
+ ) -> Task<Result<Rc<dyn AgentConnection>>> {
+ let ready = self.ready.clone();
+ cx.spawn(async move |_| {
+ ready.recv().await?;
+ Ok(Rc::new(StubAgentConnection::new()) as Rc<dyn AgentConnection>)
+ })
+ }
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ #[gpui::test]
+ async fn test_add_selection_to_loading_thread(cx: &mut TestAppContext) {
+ let (panel, mut cx) = setup_visible_panel(cx).await;
+ open_thread_with_connection(&panel, StubAgentConnection::new(), &mut cx);
+ let (workspace, project, previous) = panel.read_with(&cx, |panel, _cx| {
+ (
+ panel.workspace.upgrade().expect("workspace must exist"),
+ panel.project.clone(),
+ panel
+ .active_conversation_view()
+ .cloned()
+ .expect("previous conversation must exist"),
+ )
+ });
+ let previous_editor = previous.read_with(&cx, |view, cx| {
+ view.active_thread()
+ .expect("previous thread must be ready")
+ .read(cx)
+ .message_editor
+ .clone()
+ });
+ previous_editor.update_in(&mut cx, |editor, window, cx| {
+ editor.set_text("Keep this draft", window, cx);
+ });
+ let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
+ let buffer = project.update(cx, |project, cx| {
+ project.create_local_buffer("first selection\nsecond selection\n", None, false, cx)
+ });
+ let editor = cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
+ workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
+ editor
+ });
+ editor.update_in(&mut cx, |editor, window, cx| {
+ editor.change_selections(Default::default(), window, cx, |selections| {
+ selections.select_ranges([text::Point::new(0, 0)..text::Point::new(0, 15)]);
+ });
+ });
+
+ let (release, ready) = async_channel::bounded(1);
+ panel.update(&mut cx, |panel, cx| {
+ let server = Rc::new(DelayedSelectionAgentServer { ready });
+ let agent = Agent::Custom {
+ id: server.agent_id(),
+ };
+ install_custom_agent(server.agent_id().0.as_ref(), cx);
+ panel.connection_store.update(cx, |store, cx| {
+ store.request_connection(agent.clone(), server, cx);
+ });
+ panel.set_selected_agent_and_persist(agent, cx);
+ panel.set_last_created_entry_kind_from_user_action(AgentPanelEntryKind::Thread, cx);
+ });
+ cx.update(|_, cx| {
+ cx.bind_keys([gpui::KeyBinding::new(
+ "ctrl-alt-q",
+ settings::ActionSequence(vec![
+ ToggleFocus.boxed_clone(),
+ NewThread.boxed_clone(),
+ ToggleFocus.boxed_clone(),
+ AddSelectionToThread.boxed_clone(),
+ ]),
+ Some("Workspace"),
+ )]);
+ });
+ cx.focus(&editor);
+ cx.simulate_keystrokes("ctrl-alt-q");
+ cx.run_until_parked();
+
+ let conversation = panel.read_with(&cx, |panel, _| {
+ panel
+ .active_conversation_view()
+ .cloned()
+ .expect("new conversation must exist")
+ });
+ assert_ne!(conversation.entity_id(), previous.entity_id());
+ assert!(conversation.read_with(&cx, |view, _| view.active_thread().is_none()));
+
+ editor.update_in(&mut cx, |editor, window, cx| {
+ editor.change_selections(Default::default(), window, cx, |selections| {
+ selections.select_ranges([text::Point::new(1, 0)..text::Point::new(1, 16)]);
+ });
+ });
+ cx.focus(&editor);
+ workspace.update_in(&mut cx, |_, window, cx| {
+ window.dispatch_action(AddSelectionToThread.boxed_clone(), cx);
+ });
+ cx.run_until_parked();
+ editor.update_in(&mut cx, |editor, window, cx| {
+ editor.change_selections(Default::default(), window, cx, |selections| {
+ selections.select_ranges([text::Point::new(2, 0)..text::Point::new(2, 0)]);
+ });
+ });
+ cx.focus(&editor);
+ release.try_send(()).expect("startup gate must remain open");
+ cx.run_until_parked();
+
+ let message_editor = conversation.read_with(&cx, |view, cx| {
+ let thread = view
+ .active_thread()
+ .expect("thread must finish loading")
+ .read(cx);
+ assert!(thread.thread.read(cx).entries().is_empty());
+ thread.message_editor.clone()
+ });
+ let (contents, _) = message_editor
+ .update(&mut cx, |editor, cx| editor.contents(true, cx))
+ .await
+ .expect("selections must resolve");
+ let selections = contents
+ .iter()
+ .filter_map(|block| match block {
+ acp::ContentBlock::Resource(resource) => match &resource.resource {
+ acp::EmbeddedResourceResource::TextResourceContents(content) => {
+ Some(content.text.as_str())
+ }
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(selections, ["first selection", "second selection"]);
+ assert_eq!(
+ previous_editor.read_with(&cx, |editor, cx| editor.text(cx)),
+ "Keep this draft"
+ );
+ cx.update(|window, cx| {
+ assert!(editor.focus_handle(cx).is_focused(window));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_loading_selection_survives_draft_retention(cx: &mut TestAppContext) {
+ assert_loading_selection_removal(cx, false).await;
+ }
+
+ #[gpui::test]
+ async fn test_loading_selection_is_discarded_with_active_draft(cx: &mut TestAppContext) {
+ assert_loading_selection_removal(cx, true).await;
+ }
+
+ async fn assert_loading_selection_removal(cx: &mut TestAppContext, remove_active: bool) {
+ let (panel, mut cx) = setup_visible_panel(cx).await;
+ let (release, ready) = async_channel::bounded(1);
+ let conversation = panel.update_in(&mut cx, |panel, window, cx| {
+ panel.open_draft_with_server(
+ Rc::new(DelayedSelectionAgentServer { ready }),
+ window,
+ cx,
+ );
+ let conversation = panel
+ .active_conversation_view()
+ .cloned()
+ .expect("draft must exist");
+ conversation.update(cx, |view, cx| {
+ view.insert_selection(
+ AgentContextSelection::Terminal(vec!["pending context".into()]),
+ window,
+ cx,
+ );
+ });
+ panel.selected_agent = Agent::Stub;
+ let draft = panel.ensure_draft(AgentThreadSource::AgentPanel, window, cx);
+ assert_eq!(draft.entity_id(), conversation.entity_id());
+ assert!(panel.draft_has_content(&conversation, cx));
+ AgentSettings::override_global(
+ AgentSettings {
+ max_idle_retained_threads: 0,
+ ..AgentSettings::get_global(cx).clone()
+ },
+ cx,
+ );
+ panel.new_thread(&NewThread, window, cx);
+ panel.cleanup_retained_threads(cx);
+ assert!(
+ panel
+ .retained_threads
+ .contains_key(&conversation.read(cx).thread_id)
+ );
+ conversation
+ });
+ cx.run_until_parked();
+ let current = panel.read_with(&cx, |panel, _| {
+ panel
+ .active_conversation_view()
+ .cloned()
+ .expect("replacement draft must exist")
+ });
+ assert_ne!(conversation.entity_id(), current.entity_id());
+ if remove_active {
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel.set_base_view(
+ BaseView::AgentThread {
+ conversation_view: conversation.clone(),
+ },
+ false,
+ window,
+ cx,
+ );
+ });
+ }
+ let workspace = panel.read_with(&cx, |panel, _| {
+ panel.workspace.upgrade().expect("workspace must exist")
+ });
+ cx.focus(&workspace);
+ let focused = cx.update(|window, cx| window.focused(cx));
+ let thread_id = conversation.read_with(&cx, |view, _| view.thread_id);
+ let removed = conversation.downgrade();
+ drop(conversation);
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel.remove_thread(thread_id, window, cx);
+ });
+ cx.run_until_parked();
+ assert!(removed.upgrade().is_none());
+ release
+ .try_send(())
+ .expect("connection store must retain the startup gate");
+ cx.run_until_parked();
+ current.read_with(&cx, |view, cx| {
+ let thread = view
+ .active_thread()
+ .expect("replacement must be ready")
+ .read(cx);
+ assert!(thread.message_editor.read(cx).text(cx).is_empty());
+ assert!(thread.thread.read(cx).entries().is_empty());
+ });
+ assert_eq!(cx.update(|window, cx| window.focused(cx)), focused);
+ }
+
#[gpui::test]
async fn test_add_selection_to_terminal_thread_pastes_mention(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index ce890d8fa90..ee223fdd877 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -644,6 +644,7 @@ pub struct ConversationView {
pub(crate) thread_id: ThreadId,
pub(crate) root_session_id: Option<acp_v1::SessionId>,
server_state: ServerState,
+ pending_selections: Vec<AgentContextSelection>,
focus_handle: FocusHandle,
notifications: Vec<WindowHandle<AgentNotification>>,
notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
@@ -926,6 +927,7 @@ impl ConversationView {
window,
cx,
),
+ pending_selections: Vec::new(),
notifications: Vec::new(),
notification_subscriptions: HashMap::default(),
auth_task: None,
@@ -1235,6 +1237,16 @@ impl ConversationView {
cx,
);
+ if this.has_pending_selections() {
+ current.update(cx, |thread, cx| {
+ thread.message_editor.update(cx, |editor, cx| {
+ for selection in std::mem::take(&mut this.pending_selections) {
+ editor.insert_selections(selection, window, cx);
+ }
+ });
+ });
+ }
+
if this.focus_handle.contains_focused(window, cx) {
current
.read(cx)
@@ -3313,10 +3325,14 @@ impl ConversationView {
}
}
+ pub(crate) fn has_pending_selections(&self) -> bool {
+ !self.pending_selections.is_empty()
+ }
+
/// Inserts the selected text into the message editor or the message being
- /// edited, if any.
+ /// edited, if any. Queues the selection until an editor is available.
pub(crate) fn insert_selection(
- &self,
+ &mut self,
selection: AgentContextSelection,
window: &mut Window,
cx: &mut Context<Self>,
@@ -3327,6 +3343,9 @@ impl ConversationView {
editor.insert_selections(selection, window, cx);
})
});
+ } else {
+ self.pending_selections.push(selection);
+ cx.notify();
}
}
@@ -5714,6 +5733,81 @@ pub(crate) mod tests {
});
}
+ #[gpui::test]
+ async fn test_pending_selections_survive_connection_retry(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let connection = StubAgentConnection::new().with_supports_load_session(true);
+ let (server, fail) = FlakyAgentServer::new(connection);
+ let (conversation_view, cx) = setup_conversation_view(server, cx).await;
+
+ conversation_view.update_in(cx, |view, window, cx| {
+ assert!(matches!(view.server_state, ServerState::LoadError { .. }));
+ assert!(!view.has_pending_selections());
+ view.insert_selection(
+ AgentContextSelection::Terminal(vec!["first selection".into()]),
+ window,
+ cx,
+ );
+ view.retry_connection(window, cx);
+ assert!(matches!(view.server_state, ServerState::Loading { .. }));
+ view.insert_selection(
+ AgentContextSelection::Terminal(vec!["second selection".into()]),
+ window,
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ conversation_view.read_with(cx, |view, _cx| {
+ assert!(matches!(view.server_state, ServerState::LoadError { .. }));
+ assert!(view.active_thread().is_none());
+ assert!(view.has_pending_selections());
+ });
+
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+
+ conversation_view.read_with(cx, |view, cx| {
+ assert!(!view.has_pending_selections());
+ let active = view.active_thread().expect("expected a thread after retry");
+ assert!(active.read(cx).thread.read(cx).entries().is_empty());
+ });
+ let editor = message_editor(&conversation_view, cx);
+ let (contents, _) = editor
+ .update(cx, |editor, cx| editor.contents(true, cx))
+ .await
+ .expect("pending selections must resolve after retry");
+ let [
+ acp_v1::ContentBlock::Resource(first),
+ acp_v1::ContentBlock::Text(separator),
+ acp_v1::ContentBlock::Resource(second),
+ ] = contents.as_slice()
+ else {
+ panic!("expected exactly two resolved selections, got {contents:?}");
+ };
+ assert_eq!(separator.text, " ");
+ for (selection, expected) in [(first, "first selection"), (second, "second selection")] {
+ let acp_v1::EmbeddedResourceResource::TextResourceContents(selection) =
+ &selection.resource
+ else {
+ panic!("expected selected text");
+ };
+ assert_eq!(selection.text, expected);
+ }
+
+ editor.update_in(cx, |editor, window, cx| editor.clear(window, cx));
+ conversation_view.update_in(cx, |view, window, cx| view.retry_connection(window, cx));
+ cx.run_until_parked();
+
+ let (contents, _) = message_editor(&conversation_view, cx)
+ .update(cx, |editor, cx| editor.contents(true, cx))
+ .await
+ .expect("message contents must resolve after another retry");
+ assert!(contents.is_empty(), "delivered selections must not replay");
+ }
+
#[gpui::test]
async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) {
init_test(cx);
@@ -5757,6 +5851,26 @@ pub(crate) mod tests {
);
});
+ let selection_text = "selected before authentication";
+ conversation_view.update_in(cx, |view, window, cx| {
+ assert!(!view.has_pending_selections());
+ let buffer = view.project.update(cx, |project, cx| {
+ project.create_local_buffer(selection_text, None, false, cx)
+ });
+ let range = buffer.read(cx).anchor_before(0)
+ ..buffer.read(cx).anchor_after(selection_text.len());
+ view.insert_selection(
+ AgentContextSelection::Editor(vec![(buffer, range)]),
+ window,
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ conversation_view.read_with(cx, |view, _cx| {
+ assert!(view.active_thread().is_none());
+ assert!(view.has_pending_selections());
+ });
+
// Authenticate using the real authenticate flow on ConnectionView.
// This calls connection.authenticate(), which flips the internal flag,
// then on success triggers reset() -> new_session() which now succeeds.
@@ -5800,8 +5914,23 @@ pub(crate) mod tests {
active.read(cx).thread_error.is_none(),
"The new thread should have no errors"
);
+ assert!(!view.has_pending_selections());
+ assert!(active.read(cx).thread.read(cx).entries().is_empty());
});
+ let (contents, _) = message_editor(&conversation_view, cx)
+ .update(cx, |editor, cx| editor.contents(true, cx))
+ .await
+ .expect("pending selection must resolve after authentication");
+ let [acp_v1::ContentBlock::Resource(selection)] = contents.as_slice() else {
+ panic!("expected one resolved selection, got {contents:?}");
+ };
+ let acp_v1::EmbeddedResourceResource::TextResourceContents(selection) = &selection.resource
+ else {
+ panic!("expected selected text");
+ };
+ assert_eq!(selection.text, selection_text);
+
conversation_view.update_in(cx, |view, window, cx| view.logout(window, cx));
cx.run_until_parked();