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.

agent_ui: Scroll to AskUserQuestion Other answers (#64007)

Seth Woodc3ab5564f83e
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index ef1bb58dc2b..8443bcb8e01 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -3833,6 +3833,30 @@ impl AcpThread {
}
}
+ /// Form elicitations stop rendering after accept, so the associated tool
+ /// call is the scroll target for the user's answer.
+ pub fn is_user_authored_scroll_target(&self, entry: &AgentThreadEntry) -> bool {
+ match entry {
+ AgentThreadEntry::UserMessage(_) => true,
+ AgentThreadEntry::ToolCall(call) => self.tool_call_has_accepted_user_answer(&call.id),
+ _ => false,
+ }
+ }
+
+ fn tool_call_has_accepted_user_answer(&self, tool_call_id: &acp_v1::ToolCallId) -> bool {
+ self.elicitations.elicitations().iter().any(|elicitation| {
+ matches!(elicitation.status, ElicitationStatus::Accepted)
+ // Accepting a URL elicitation only consents to opening a link,
+ // so it isn't an answer.
+ && matches!(elicitation.request.mode, acp_v2::ElicitationMode::Form(_))
+ && matches!(
+ elicitation.request.scope(),
+ acp_v2::ElicitationScope::Session(scope)
+ if scope.tool_call_id.as_ref().is_some_and(|id| id.0 == tool_call_id.0)
+ )
+ })
+ }
+
pub fn is_compacting(&self) -> bool {
self.entries.iter().rev().any(|entry| {
matches!(
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index ae883e3baae..ecc09f0aac1 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -1,7 +1,7 @@
use super::*;
use acp_thread::{
- AgentConnection, AgentModelGroupName, AgentModelId, AgentModelList, ClientUserMessageId,
- PermissionOptions, ThreadStatus,
+ AgentConnection, AgentModelGroupName, AgentModelId, AgentModelList, AgentThreadEntry,
+ ClientUserMessageId, PermissionOptions, ThreadStatus,
};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
@@ -5794,6 +5794,148 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
}
}
+#[gpui::test]
+async fn test_ask_user_elicitation_references_scoped_tool_call_id(cx: &mut TestAppContext) {
+ let fake = init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store
+ .set_user_settings(
+ &json!({
+ "agent": {
+ "profiles": {
+ "ask-user": {
+ "name": "Ask User",
+ "tools": { AskUserTool::NAME: true }
+ }
+ }
+ }
+ })
+ .to_string(),
+ cx,
+ )
+ .result()
+ .expect("test settings should parse");
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree("/", json!({ "a": {} })).await;
+ let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
+ let thread_store = cx.new(|cx| ThreadStore::new(cx));
+ let agent =
+ cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
+ let connection = Rc::new(NativeAgentConnection(agent.clone()));
+
+ let acp_thread = cx
+ .update(|cx| {
+ connection
+ .clone()
+ .new_session(project.clone(), PathList::new(&[Path::new("")]), cx)
+ })
+ .await
+ .unwrap();
+ let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let thread = agent.read_with(cx, |agent, _| {
+ agent.sessions.get(&session_id).unwrap().thread.clone()
+ });
+ let model = fake.model("thread");
+ thread.update(cx, |thread, cx| {
+ thread.set_model(model.clone(), cx);
+ thread.set_profile(AgentProfileId("ask-user".into()), cx);
+ });
+ cx.run_until_parked();
+
+ let send = acp_thread.update(cx, |thread, cx| thread.send_raw("Prompt", cx));
+ cx.run_until_parked();
+ let ask_user_input = AskUserToolInput {
+ question: "Which directory should we explore?".to_string(),
+ options: Vec::new(),
+ allow_free_text: true,
+ };
+ fake.send_last_event(
+ &model,
+ LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
+ id: "call_1".into(),
+ name: AskUserTool::NAME.into(),
+ raw_input: serde_json::to_string(&ask_user_input).unwrap(),
+ input: language_model::LanguageModelToolUseInput::Json(
+ serde_json::to_value(&ask_user_input).unwrap(),
+ ),
+ is_input_complete: true,
+ thought_signature: None,
+ }),
+ );
+ fake.end_last(&model);
+ cx.run_until_parked();
+
+ let (tool_call_id, elicitation_id) = acp_thread.read_with(cx, |thread, _| {
+ let tool_call_id = thread
+ .entries()
+ .iter()
+ .find_map(|entry| match entry {
+ AgentThreadEntry::ToolCall(tool_call) => Some(tool_call.id.clone()),
+ _ => None,
+ })
+ .expect("ask_user tool call should be rendered");
+ let elicitation_id = thread
+ .entries()
+ .iter()
+ .find_map(|entry| match entry {
+ AgentThreadEntry::Elicitation(id) => Some(id.clone()),
+ _ => None,
+ })
+ .expect("ask_user elicitation should be rendered");
+ let (_, elicitation) = thread
+ .elicitation(&elicitation_id)
+ .expect("elicitation should be stored");
+ let acp_v2::ElicitationScope::Session(scope) = elicitation.request.scope() else {
+ panic!("ask_user elicitation should be session-scoped");
+ };
+ assert_ne!(tool_call_id, acp::ToolCallId::new("call_1"));
+ assert_eq!(
+ scope.tool_call_id.as_ref().map(|id| &id.0),
+ Some(&tool_call_id.0),
+ "the elicitation must reference the tool card's scoped id"
+ );
+ (tool_call_id, elicitation_id)
+ });
+
+ acp_thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp_v2::CreateElicitationResponse::new(acp_v2::ElicitationAction::Accept(
+ acp_v2::ElicitationAcceptAction::new().content(std::collections::BTreeMap::from([
+ (
+ "other".to_string(),
+ acp_v2::ElicitationContentValue::from("delve into src"),
+ ),
+ ])),
+ )),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ acp_thread.read_with(cx, |thread, _| {
+ let tool_call_entry = thread
+ .entries()
+ .iter()
+ .find(|entry| {
+ matches!(entry, AgentThreadEntry::ToolCall(tool_call) if tool_call.id == tool_call_id)
+ })
+ .expect("ask_user tool call should still be present");
+ assert!(
+ thread.is_user_authored_scroll_target(tool_call_entry),
+ "the answered ask_user tool call should be a scroll-to-user-message target"
+ );
+ });
+
+ fake.send_last_text(&model, "Exploring src");
+ fake.end_last(&model);
+ send.await.unwrap();
+}
+
#[gpui::test]
async fn test_spawn_agent_tool_forwards_explicit_model(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 336ce607c1a..5ac8971aa86 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -9290,6 +9290,238 @@ pub(crate) mod tests {
});
}
+ #[gpui::test]
+ async fn test_scroll_to_user_message_lands_on_ask_user_elicitation_answer(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+
+ let tool_call_id = acp_v1::ToolCallId::new("ask-user-1");
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Which directory should we explore?")
+ .kind(acp_v1::ToolKind::Other)
+ .status(acp_v1::ToolCallStatus::InProgress)
+ .meta(acp_thread::meta_with_tool_name("ask_user")),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread = conversation_view
+ .read_with(cx, |view, cx| {
+ view.active_thread().map(|r| r.read(cx).thread.clone())
+ })
+ .unwrap();
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.send_raw("List the top directories, then ask which to explore", cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp_v2::CreateElicitationRequest::new(
+ acp_v2::ElicitationFormMode::new(
+ acp_v2::ElicitationSessionScope::new(acp_v2::SessionId::new(
+ session_id.0.clone(),
+ ))
+ .tool_call_id(acp_v2::ToolCallId::new(tool_call_id.0.clone())),
+ acp_v2::ElicitationSchema::new().string("other", true),
+ ),
+ "Which directory should we explore?",
+ ),
+ cx,
+ )
+ .expect("ask_user elicitation should be accepted")
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ thread.entries().iter().find_map(|entry| {
+ if let AgentThreadEntry::Elicitation(id) = entry {
+ Some(id.clone())
+ } else {
+ None
+ }
+ })
+ });
+ let elicitation_id = elicitation_id.expect("elicitation entry should exist");
+
+ let other_answer = std::collections::BTreeMap::from([(
+ "other".to_string(),
+ acp_v2::ElicitationContentValue::from("delve into src"),
+ )]);
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp_v2::CreateElicitationResponse::new(acp_v2::ElicitationAction::Accept(
+ acp_v2::ElicitationAcceptAction::new().content(other_answer),
+ )),
+ cx,
+ );
+ });
+ response_task.await;
+ cx.run_until_parked();
+
+ thread.update(cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
+ tool_call_id.clone(),
+ acp_v1::ToolCallUpdateFields::new()
+ .title("Answered: delve into src")
+ .status(acp_v1::ToolCallStatus::Completed),
+ )),
+ cx,
+ )
+ .expect("ask_user tool call should update");
+ thread
+ .handle_session_update(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ "I'll explore src in depth.".into(),
+ )),
+ cx,
+ )
+ .expect("follow-up assistant message should apply");
+ });
+ cx.run_until_parked();
+
+ thread.read_with(cx, |thread, _| {
+ let entries = thread.entries();
+ assert_eq!(entries.len(), 4);
+ assert!(matches!(entries[0], AgentThreadEntry::UserMessage(_)));
+ assert!(matches!(entries[1], AgentThreadEntry::ToolCall(_)));
+ assert!(matches!(entries[2], AgentThreadEntry::Elicitation(_)));
+ assert!(matches!(entries[3], AgentThreadEntry::AssistantMessage(_)));
+ });
+
+ active_thread(&conversation_view, cx).update(cx, |view, cx| {
+ view.scroll_to_top(cx);
+ view.scroll_to_user_message_index(None, cx);
+ let scroll_top = view.list_state.logical_scroll_top();
+ assert_eq!(
+ scroll_top.item_ix, 1,
+ "scroll should land on the ask_user tool call that holds the Other answer, not the original prompt"
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_scroll_to_user_message_skips_accepted_url_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let tool_call_id = acp_v1::ToolCallId::new("sign-in-1");
+ let connection = StubAgentConnection::new();
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Sign in to continue")
+ .kind(acp_v1::ToolKind::Other)
+ .status(acp_v1::ToolCallStatus::InProgress),
+ )]);
+
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+
+ let thread = conversation_view
+ .read_with(cx, |view, cx| {
+ view.active_thread().map(|r| r.read(cx).thread.clone())
+ })
+ .unwrap();
+
+ thread
+ .update(cx, |thread, cx| {
+ thread.send_raw("Fetch my private repos", cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp_v2::CreateElicitationRequest::new(
+ acp_v2::ElicitationUrlMode::new(
+ acp_v2::ElicitationSessionScope::new(acp_v2::SessionId::new(
+ session_id.0.clone(),
+ ))
+ .tool_call_id(acp_v2::ToolCallId::new(tool_call_id.0.clone())),
+ acp_v2::ElicitationId::new("sign-in-url-1"),
+ "https://example.com/sign-in",
+ ),
+ "Continue in the browser",
+ ),
+ cx,
+ )
+ .expect("URL elicitation should be accepted")
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ thread.entries().iter().find_map(|entry| {
+ if let AgentThreadEntry::Elicitation(id) = entry {
+ Some(id.clone())
+ } else {
+ None
+ }
+ })
+ });
+ let elicitation_id = elicitation_id.expect("elicitation entry should exist");
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp_v2::CreateElicitationResponse::new(acp_v2::ElicitationAction::Accept(
+ acp_v2::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ response_task.await;
+ cx.run_until_parked();
+
+ thread.update(cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ "Waiting for sign-in to finish.".into(),
+ )),
+ cx,
+ )
+ .expect("follow-up assistant message should apply");
+ });
+ cx.run_until_parked();
+
+ thread.read_with(cx, |thread, _| {
+ let entries = thread.entries();
+ assert_eq!(entries.len(), 4);
+ assert!(matches!(entries[0], AgentThreadEntry::UserMessage(_)));
+ assert!(matches!(entries[1], AgentThreadEntry::ToolCall(_)));
+ assert!(matches!(entries[2], AgentThreadEntry::Elicitation(_)));
+ assert!(matches!(entries[3], AgentThreadEntry::AssistantMessage(_)));
+ let (_, elicitation) = thread
+ .elicitation(&elicitation_id)
+ .expect("elicitation should be stored");
+ assert!(matches!(
+ elicitation.status,
+ acp_thread::ElicitationStatus::Accepted
+ ));
+ });
+
+ active_thread(&conversation_view, cx).update(cx, |view, cx| {
+ view.scroll_to_top(cx);
+ view.scroll_to_user_message_index(None, cx);
+ let scroll_top = view.list_state.logical_scroll_top();
+ assert_eq!(
+ scroll_top.item_ix, 0,
+ "consenting to open a URL is not a user answer, so scroll should land on the prompt"
+ );
+ });
+ }
+
#[gpui::test]
async fn test_thread_search_finds_matches_across_entries(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 5ad381bf402..8b0e7334e9b 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -7157,12 +7157,14 @@ impl ThreadView {
.unwrap_or(!is_generating);
let primary = if is_turn_end && !assistant_message_is_blank {
- let user_message_index = thread
- .read(cx)
- .entries()
- .iter()
- .take(entry_ix)
- .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)));
+ let user_message_index = {
+ let thread = thread.read(cx);
+ thread
+ .entries()
+ .iter()
+ .take(entry_ix)
+ .rposition(|entry| thread.is_user_authored_scroll_target(entry))
+ };
v_flex()
.w_full()
@@ -7627,7 +7629,8 @@ impl ThreadView {
user_message_index: Option<usize>,
cx: &mut Context<Self>,
) {
- let entries = self.thread.read(cx).entries();
+ let thread = self.thread.read(cx);
+ let entries = thread.entries();
if entries.is_empty() {
return;
}
@@ -7637,7 +7640,7 @@ impl ThreadView {
if let Some(ix) = user_message_index.or_else(|| {
entries
.iter()
- .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
+ .rposition(|entry| thread.is_user_authored_scroll_target(entry))
}) {
self.list_state.scroll_to(ListOffset {
item_ix: ix,
@@ -7742,12 +7745,14 @@ impl ThreadView {
_window: &mut Window,
cx: &mut Context<Self>,
) {
- let entries = self.thread.read(cx).entries();
+ let thread = self.thread.read(cx);
+ let entries = thread.entries();
let current_ix = self.list_state.logical_scroll_top().item_ix;
- if let Some(target_ix) = (0..current_ix)
- .rev()
- .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
- {
+ if let Some(target_ix) = (0..current_ix).rev().find(|&i| {
+ entries
+ .get(i)
+ .is_some_and(|entry| thread.is_user_authored_scroll_target(entry))
+ }) {
self.list_state.scroll_to(ListOffset {
item_ix: target_ix,
offset_in_item: px(0.),
@@ -7762,11 +7767,14 @@ impl ThreadView {
_window: &mut Window,
cx: &mut Context<Self>,
) {
- let entries = self.thread.read(cx).entries();
+ let thread = self.thread.read(cx);
+ let entries = thread.entries();
let current_ix = self.list_state.logical_scroll_top().item_ix;
- if let Some(target_ix) = (current_ix + 1..entries.len())
- .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
- {
+ if let Some(target_ix) = (current_ix + 1..entries.len()).find(|&i| {
+ entries
+ .get(i)
+ .is_some_and(|entry| thread.is_user_authored_scroll_target(entry))
+ }) {
self.list_state.scroll_to(ListOffset {
item_ix: target_ix,
offset_in_item: px(0.),