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.

acp: Validate and surface more elicitation warnings (#61708)

Ben Brandt33e2058302b8
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index c2b2fe35d4d..d76511bd590 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -436,9 +436,19 @@ impl ElicitationStore {
}
fn validate_request(request: &acp::CreateElicitationRequest) -> Result<(), acp::Error> {
- if let acp::ElicitationMode::Url(mode) = &request.mode {
- url::Url::parse(&mode.url)
- .map_err(|_| acp::Error::invalid_params().data("invalid elicitation URL"))?;
+ match &request.mode {
+ acp::ElicitationMode::Form(_) => {}
+ acp::ElicitationMode::Url(mode) => {
+ let url = url::Url::parse(&mode.url)
+ .map_err(|_| acp::Error::invalid_params().data("invalid elicitation URL"))?;
+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
+ return Err(acp::Error::invalid_params()
+ .data("elicitation URL must use HTTP or HTTPS and include a host"));
+ }
+ }
+ _ => {
+ return Err(acp::Error::invalid_params().data("unsupported elicitation mode"));
+ }
}
Ok(())
@@ -500,17 +510,11 @@ impl ElicitationStore {
fn complete_url_elicitation_entry(elicitation: &mut Elicitation) -> bool {
let previous_status = mem::replace(&mut elicitation.status, ElicitationStatus::Completed);
match previous_status {
- ElicitationStatus::Pending { respond_tx } => {
- respond_tx
- .send(acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
- ))
- .ok();
- true
- }
ElicitationStatus::Accepted => true,
- ElicitationStatus::Completed => false,
- previous_status @ (ElicitationStatus::Declined | ElicitationStatus::Canceled) => {
+ previous_status @ (ElicitationStatus::Pending { .. }
+ | ElicitationStatus::Declined
+ | ElicitationStatus::Canceled
+ | ElicitationStatus::Completed) => {
elicitation.status = previous_status;
false
}
@@ -7537,17 +7541,31 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.complete_url_elicitation(&url_elicitation_id, cx);
});
- assert!(matches!(
- response_task.await.action,
- acp::ElicitationAction::Accept(_)
- ));
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(
+ elicitation.status,
+ ElicitationStatus::Pending { .. }
+ ));
+ });
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
cx,
);
});
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_elicitation_id, cx);
+ });
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
panic!("missing elicitation entry");
@@ -8380,18 +8398,31 @@ mod tests {
store.update(cx, |store, cx| {
store.complete_url_elicitation(&url_elicitation_id, cx);
});
-
- assert!(matches!(
- response_task.await.action,
- acp::ElicitationAction::Accept(_)
- ));
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(
+ elicitation.status,
+ ElicitationStatus::Pending { .. }
+ ));
+ });
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
cx,
);
});
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ store.update(cx, |store, cx| {
+ store.complete_url_elicitation(&url_elicitation_id, cx);
+ });
store.read_with(cx, |store, _| {
let Some((_, elicitation)) = store.elicitation(&entry_id) else {
panic!("missing elicitation entry");
@@ -8568,30 +8599,94 @@ mod tests {
}
#[gpui::test]
- async fn test_url_elicitation_rejects_invalid_url(cx: &mut TestAppContext) {
+ async fn test_url_elicitation_rejects_non_browser_urls(cx: &mut TestAppContext) {
init_test(cx);
enable_acp_beta(cx);
let thread = new_test_thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ for invalid_url in [
+ "not a url",
+ "file:///tmp/authorize",
+ "data:text/plain,authorize",
+ "mailto:[email protected]",
+ "zed://settings",
+ ] {
+ let result = thread.update(cx, |thread, cx| {
+ thread.request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id.clone()),
+ "url-1",
+ invalid_url,
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ });
+
+ let Err(error) = result else {
+ panic!("{invalid_url} should not be accepted for URL elicitation");
+ };
+ assert_eq!(error.code, acp::ErrorCode::InvalidParams);
+ }
+ thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
+ }
+
+ #[gpui::test]
+ async fn test_elicitation_rejects_unadvertised_mode(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
let result = thread.update(cx, |thread, cx| {
thread.request_elicitation(
acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
+ acp::OtherElicitationMode::new(
+ "future",
acp::ElicitationSessionScope::new(session_id),
- "url-1",
- "not a url",
+ std::collections::BTreeMap::new(),
),
- "Complete this in the browser",
+ "Use a future input mode",
),
cx,
)
});
- assert!(result.is_err());
+ let Err(error) = result else {
+ panic!("unadvertised elicitation mode should be rejected");
+ };
+ assert_eq!(error.code, acp::ErrorCode::InvalidParams);
thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
}
+ #[gpui::test]
+ async fn test_request_elicitation_store_rejects_unadvertised_mode(cx: &mut TestAppContext) {
+ init_test(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let result = store.update(cx, |store, cx| {
+ store.request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::OtherElicitationMode::new(
+ "future",
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ std::collections::BTreeMap::new(),
+ ),
+ "Use a future input mode",
+ ),
+ cx,
+ )
+ });
+
+ let Err(error) = result else {
+ panic!("unadvertised elicitation mode should be rejected");
+ };
+ assert_eq!(error.code, acp::ErrorCode::InvalidParams);
+ store.read_with(cx, |store, _| assert!(store.elicitations().is_empty()));
+ }
+
async fn run_until_first_tool_call(
thread: &Entity<AcpThread>,
cx: &mut TestAppContext,
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 2c77dfc16fc..f3bf1ba82b5 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -2801,7 +2801,7 @@ mod tests {
}
#[gpui::test]
- async fn request_scoped_url_elicitation_completion_after_create_is_observed(
+ async fn request_scoped_url_elicitation_completion_before_consent_is_ignored(
cx: &mut gpui::TestAppContext,
) {
init_feature_flags_test(cx);
@@ -2835,19 +2835,18 @@ mod tests {
cx.update(|cx| connection.authenticate(acp::AuthMethodId::new("login"), cx));
cx.run_until_parked();
- let response = response_rx
- .recv()
- .await
- .expect("fake auth flow should receive elicitation response");
- assert_eq!(
- response.action,
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new())
+ assert!(
+ matches!(
+ response_rx.try_recv(),
+ Err(async_channel::TryRecvError::Empty)
+ ),
+ "completion before consent must not answer the elicitation request"
);
let store = connection
.request_elicitations()
.expect("ACP connections expose request-scoped elicitations");
- store.read_with(cx, |store, _| {
+ let entry_id = store.read_with(cx, |store, _| {
let [elicitation] = store.elicitations() else {
panic!(
"expected one request-scoped elicitation, got {:?}",
@@ -2860,7 +2859,35 @@ mod tests {
assert_eq!(scope.request_id, request_id);
assert!(matches!(
elicitation.status,
- acp_thread::ElicitationStatus::Completed
+ acp_thread::ElicitationStatus::Pending { .. }
+ ));
+ elicitation.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ let response = response_rx
+ .recv()
+ .await
+ .expect("fake auth flow should receive elicitation response");
+ assert_eq!(
+ response.action,
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new())
+ );
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&entry_id) else {
+ panic!("missing request-scoped elicitation");
+ };
+ assert!(matches!(
+ elicitation.status,
+ acp_thread::ElicitationStatus::Accepted
));
});
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index d65e83e45a2..35f0e70b095 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -2388,6 +2388,11 @@ impl ConversationView {
};
let handlers = Self::request_elicitation_card_handlers(view);
+ let agent_display_name = self
+ .agent_server_store
+ .read(cx)
+ .agent_display_name(&self.agent.agent_id())
+ .unwrap_or_else(|| self.agent.agent_id().0);
store
.read(cx)
@@ -2399,6 +2404,7 @@ impl ConversationView {
ElicitationCard::new(
ix,
elicitation,
+ agent_display_name.clone(),
self.request_elicitation_form_states.get(&elicitation.id),
handlers.clone(),
)
@@ -2439,14 +2445,14 @@ impl ConversationView {
},
{
let view = view.clone();
- move |elicitation_id, url, window, cx| {
- cx.open_url(&url);
+ move |elicitation_id, _window, cx| {
view.update(cx, |this, cx| {
- this.submit_request_elicitation(elicitation_id, window, cx);
+ this.dismiss_request_url_elicitation(elicitation_id, cx);
})
.log_err();
}
},
+ move |_elicitation_id, url, _window, cx| cx.open_url(&url),
{
let view = view.clone();
move |elicitation_id, field_name, value, cx| {
@@ -2523,34 +2529,72 @@ impl ConversationView {
return;
};
- let response = match mode {
+ match mode {
acp::ElicitationMode::Form(mode) => {
- let Some(state) = self.request_elicitation_form_states.get(&elicitation_id) else {
+ let Some(state) = self
+ .request_elicitation_form_states
+ .get_mut(&elicitation_id)
+ else {
return;
};
- match state.collect(&mode.requested_schema, cx) {
- Ok(content) => {
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(content),
- ))
- }
- Err(errors) => {
- self.update_request_elicitation_form_state(
- &elicitation_id,
- |state| state.set_errors(errors),
- cx,
- );
- return;
- }
- }
+ let Some(submission) = state.begin_submission(cx) else {
+ return;
+ };
+ let schema = mode.requested_schema;
+ let validation_task = cx.background_spawn(async move {
+ let result = submission.validate(&schema);
+ (submission, result)
+ });
+ self.notify_request_elicitation_renderers(cx);
+ cx.spawn(async move |this, cx| {
+ let (submission, result) = validation_task.await;
+ this.update(cx, |this, cx| {
+ let is_current = this
+ .request_elicitation_form_states
+ .get_mut(&elicitation_id)
+ .is_some_and(|state| {
+ state.validation_matches_current_values(&submission, cx)
+ });
+ if !is_current {
+ this.notify_request_elicitation_renderers(cx);
+ return;
+ }
+ match result {
+ Ok(content) => {
+ this.respond_to_request_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(content),
+ ),
+ ),
+ cx,
+ );
+ }
+ Err(errors) => {
+ this.update_request_elicitation_form_state(
+ &elicitation_id,
+ |state| state.set_errors(errors),
+ cx,
+ );
+ }
+ }
+ })
+ .log_err();
+ })
+ .detach();
}
- acp::ElicitationMode::Url(_) => acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
- ),
- _ => return,
- };
-
- self.respond_to_request_elicitation(elicitation_id, response, cx);
+ acp::ElicitationMode::Url(_) => {
+ self.respond_to_request_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ }
+ _ => {}
+ }
}
fn decline_request_elicitation(
@@ -2579,6 +2623,20 @@ impl ConversationView {
);
}
+ fn dismiss_request_url_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ cx: &mut Context<Self>,
+ ) {
+ self.request_elicitation_form_states.remove(&elicitation_id);
+ if let Some(store) = self.request_elicitation_store() {
+ store.update(cx, |store, cx| {
+ store.cancel_elicitation(&elicitation_id, cx);
+ });
+ }
+ self.notify_request_elicitation_renderers(cx);
+ }
+
fn respond_to_request_elicitation(
&mut self,
elicitation_id: ElicitationEntryId,
diff --git a/crates/agent_ui/src/conversation_view/elicitation.rs b/crates/agent_ui/src/conversation_view/elicitation.rs
index 3eaaa0652bd..94e0477ebca 100644
--- a/crates/agent_ui/src/conversation_view/elicitation.rs
+++ b/crates/agent_ui/src/conversation_view/elicitation.rs
@@ -26,9 +26,23 @@ enum ElicitationFieldState {
MultiSelect(HashSet<String>),
}
+#[derive(PartialEq, Eq)]
+enum ElicitationFieldValue {
+ Text(String),
+ Boolean(bool),
+ SingleSelect { value: Option<String> },
+ MultiSelect(HashSet<String>),
+}
+
+#[derive(PartialEq, Eq)]
+pub(crate) struct ElicitationFormSubmission {
+ fields: HashMap<String, ElicitationFieldValue>,
+}
+
pub(crate) struct ElicitationFormState {
fields: HashMap<String, ElicitationFieldState>,
field_errors: HashMap<String, SharedString>,
+ is_submitting: bool,
}
impl ElicitationFormState {
@@ -100,13 +114,112 @@ impl ElicitationFormState {
Self {
fields,
field_errors: HashMap::default(),
+ is_submitting: false,
}
}
+ fn snapshot(&self, cx: &App) -> ElicitationFormSubmission {
+ ElicitationFormSubmission {
+ fields: self
+ .fields
+ .iter()
+ .map(|(name, field)| {
+ let value = match field {
+ ElicitationFieldState::Text(editor) => {
+ ElicitationFieldValue::Text(editor.read(cx).text(cx))
+ }
+ ElicitationFieldState::Boolean(value) => {
+ ElicitationFieldValue::Boolean(*value)
+ }
+ ElicitationFieldState::SingleSelect { value } => {
+ ElicitationFieldValue::SingleSelect {
+ value: value.clone(),
+ }
+ }
+ ElicitationFieldState::MultiSelect(values) => {
+ ElicitationFieldValue::MultiSelect(values.clone())
+ }
+ };
+ (name.clone(), value)
+ })
+ .collect(),
+ }
+ }
+
+ pub(crate) fn begin_submission(&mut self, cx: &App) -> Option<ElicitationFormSubmission> {
+ if self.is_submitting {
+ return None;
+ }
+ self.is_submitting = true;
+ Some(self.snapshot(cx))
+ }
+
+ pub(crate) fn validation_matches_current_values(
+ &mut self,
+ submission: &ElicitationFormSubmission,
+ cx: &App,
+ ) -> bool {
+ let is_current = self.snapshot(cx) == *submission;
+ if !is_current {
+ self.is_submitting = false;
+ }
+ is_current
+ }
+
+ #[cfg(test)]
pub(crate) fn collect(
&self,
schema: &acp::ElicitationSchema,
cx: &App,
+ ) -> Result<BTreeMap<String, acp::ElicitationContentValue>, HashMap<String, SharedString>> {
+ self.snapshot(cx).validate(schema)
+ }
+
+ pub(crate) fn set_errors(&mut self, errors: HashMap<String, SharedString>) {
+ self.field_errors = errors;
+ self.is_submitting = false;
+ }
+
+ pub(crate) fn set_field_error(
+ &mut self,
+ field_name: impl Into<String>,
+ error: impl Into<SharedString>,
+ ) {
+ self.field_errors.insert(field_name.into(), error.into());
+ }
+
+ pub(crate) fn set_boolean(&mut self, field_name: &str, value: bool) {
+ if let Some(ElicitationFieldState::Boolean(field)) = self.fields.get_mut(field_name) {
+ *field = value;
+ self.field_errors.remove(field_name);
+ }
+ }
+
+ pub(crate) fn set_single_select(&mut self, field_name: &str, value: String) {
+ if let Some(ElicitationFieldState::SingleSelect { value: selected }) =
+ self.fields.get_mut(field_name)
+ {
+ *selected = Some(value);
+ self.field_errors.remove(field_name);
+ }
+ }
+
+ pub(crate) fn set_multi_select(&mut self, field_name: &str, value: String, selected: bool) {
+ if let Some(ElicitationFieldState::MultiSelect(values)) = self.fields.get_mut(field_name) {
+ if selected {
+ values.insert(value);
+ } else {
+ values.remove(&value);
+ }
+ self.field_errors.remove(field_name);
+ }
+ }
+}
+
+impl ElicitationFormSubmission {
+ pub(crate) fn validate(
+ &self,
+ schema: &acp::ElicitationSchema,
) -> Result<BTreeMap<String, acp::ElicitationContentValue>, HashMap<String, SharedString>> {
let required = schema.required.as_deref().unwrap_or_default();
let mut content = BTreeMap::new();
@@ -121,9 +234,8 @@ impl ElicitationFormState {
let field_content = match (property, field) {
(
acp::ElicitationPropertySchema::String(schema),
- ElicitationFieldState::Text(editor),
+ ElicitationFieldValue::Text(value),
) => {
- let value = editor.read(cx).text(cx).to_string();
if value.is_empty() {
if is_required {
Err(format!("{} is required", property_title(name, property)).into())
@@ -131,13 +243,13 @@ impl ElicitationFormState {
Ok(None)
}
} else {
- validate_string_value(property_title(name, property), schema, &value)
- .map(|()| Some(value.into()))
+ validate_string_value(property_title(name, property), schema, value)
+ .map(|()| Some(value.clone().into()))
}
}
(
acp::ElicitationPropertySchema::String(schema),
- ElicitationFieldState::SingleSelect { value },
+ ElicitationFieldValue::SingleSelect { value },
) => {
if let Some(value) = value {
validate_single_select_value(property_title(name, property), schema, value)
@@ -153,9 +265,9 @@ impl ElicitationFormState {
}
(
acp::ElicitationPropertySchema::Number(schema),
- ElicitationFieldState::Text(editor),
+ ElicitationFieldValue::Text(value),
) => {
- let value = editor.read(cx).text(cx).trim().to_string();
+ let value = value.trim();
if value.is_empty() {
if is_required {
Err(format!("{} is required", property_title(name, property)).into())
@@ -163,15 +275,15 @@ impl ElicitationFormState {
Ok(None)
}
} else {
- validate_number_value(property_title(name, property), schema, &value)
+ validate_number_value(property_title(name, property), schema, value)
.map(|parsed| Some(parsed.into()))
}
}
(
acp::ElicitationPropertySchema::Integer(schema),
- ElicitationFieldState::Text(editor),
+ ElicitationFieldValue::Text(value),
) => {
- let value = editor.read(cx).text(cx).trim().to_string();
+ let value = value.trim();
if value.is_empty() {
if is_required {
Err(format!("{} is required", property_title(name, property)).into())
@@ -179,13 +291,13 @@ impl ElicitationFormState {
Ok(None)
}
} else {
- validate_integer_value(property_title(name, property), schema, &value)
+ validate_integer_value(property_title(name, property), schema, value)
.map(|parsed| Some(parsed.into()))
}
}
(
acp::ElicitationPropertySchema::Boolean(schema),
- ElicitationFieldState::Boolean(value),
+ ElicitationFieldValue::Boolean(value),
) => {
if is_required || *value || schema.default.is_some() {
Ok(Some((*value).into()))
@@ -195,7 +307,7 @@ impl ElicitationFormState {
}
(
acp::ElicitationPropertySchema::Array(schema),
- ElicitationFieldState::MultiSelect(selected),
+ ElicitationFieldValue::MultiSelect(selected),
) => {
let mut values = multi_select_options(schema)
.into_iter()
@@ -246,45 +358,6 @@ impl ElicitationFormState {
Err(errors)
}
}
-
- pub(crate) fn set_errors(&mut self, errors: HashMap<String, SharedString>) {
- self.field_errors = errors;
- }
-
- pub(crate) fn set_field_error(
- &mut self,
- field_name: impl Into<String>,
- error: impl Into<SharedString>,
- ) {
- self.field_errors.insert(field_name.into(), error.into());
- }
-
- pub(crate) fn set_boolean(&mut self, field_name: &str, value: bool) {
- if let Some(ElicitationFieldState::Boolean(field)) = self.fields.get_mut(field_name) {
- *field = value;
- self.field_errors.remove(field_name);
- }
- }
-
- pub(crate) fn set_single_select(&mut self, field_name: &str, value: String) {
- if let Some(ElicitationFieldState::SingleSelect { value: selected }) =
- self.fields.get_mut(field_name)
- {
- *selected = Some(value);
- self.field_errors.remove(field_name);
- }
- }
-
- pub(crate) fn set_multi_select(&mut self, field_name: &str, value: String, selected: bool) {
- if let Some(ElicitationFieldState::MultiSelect(values)) = self.fields.get_mut(field_name) {
- if selected {
- values.insert(value);
- } else {
- values.remove(&value);
- }
- self.field_errors.remove(field_name);
- }
- }
}
#[cfg(test)]
@@ -320,6 +393,41 @@ mod tests {
);
}
+ #[test]
+ fn string_validation_supports_bounded_advanced_patterns() {
+ let schema = acp::StringPropertySchema::new().pattern(r"^prod-(?=[0-9]+$)([0-9])\1$");
+
+ validate_string_value("Environment".into(), &schema, "prod-44")
+ .expect("lookahead and backreference should be accepted");
+ assert_eq!(
+ validate_string_value("Environment".into(), &schema, "prod-45")
+ .expect_err("backreference mismatch should be rejected")
+ .to_string(),
+ "Environment does not match the requested pattern"
+ );
+ }
+
+ #[test]
+ fn string_validation_rejects_patterns_outside_resource_limits() {
+ let oversized_pattern =
+ acp::StringPropertySchema::new().pattern("a".repeat(MAX_ELICITATION_PATTERN_BYTES + 1));
+ assert_eq!(
+ validate_string_value("Value".into(), &oversized_pattern, "a")
+ .expect_err("oversized pattern should be rejected")
+ .to_string(),
+ "Value has an invalid validation pattern"
+ );
+
+ let schema = acp::StringPropertySchema::new().pattern(".*");
+ let oversized_value = "a".repeat(MAX_ELICITATION_PATTERN_INPUT_BYTES + 1);
+ assert_eq!(
+ validate_string_value("Value".into(), &schema, &oversized_value)
+ .expect_err("oversized pattern input should be rejected")
+ .to_string(),
+ "Value is too long to validate safely"
+ );
+ }
+
#[test]
fn number_validation_rejects_non_finite_values() {
let schema = acp::NumberPropertySchema::new();
@@ -381,6 +489,34 @@ mod tests {
status: ElicitationStatus::Accepted,
};
assert!(!should_render_elicitation(&accepted_form));
+
+ let pending_unknown = Elicitation {
+ id: ElicitationEntryId("pending-unknown".into()),
+ request: acp::CreateElicitationRequest::new(
+ acp::OtherElicitationMode::new("future", preview_request_scope(3), BTreeMap::new()),
+ "Use a future input mode.",
+ ),
+ status: pending_status(),
+ };
+ assert!(!should_render_elicitation(&pending_unknown));
+ }
+
+ #[test]
+ fn url_host_presentation_highlights_destination_and_suspicious_idn() {
+ assert_eq!(
+ url_host_presentation("https://auth.example.com/device"),
+ Some(UrlHostPresentation {
+ host: "auth.example.com".to_string(),
+ suspicious_decoded_host: None,
+ })
+ );
+ assert_eq!(
+ url_host_presentation("https://xn--pple-43d.com/device"),
+ Some(UrlHostPresentation {
+ host: "xn--pple-43d.com".to_string(),
+ suspicious_decoded_host: Some("\u{0430}pple.com".to_string()),
+ })
+ );
}
#[test]
@@ -503,6 +639,52 @@ mod tests {
});
}
+ #[gpui::test]
+ fn form_state_prevents_duplicate_submissions(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().string("name", true);
+ let mut form_state = ElicitationFormState::new(&schema, window, cx);
+
+ assert!(form_state.begin_submission(cx).is_some());
+ assert!(form_state.begin_submission(cx).is_none());
+
+ form_state.set_errors(HashMap::default());
+ assert!(form_state.begin_submission(cx).is_some());
+
+ Editor::single_line(window, cx)
+ });
+ }
+
+ #[gpui::test]
+ fn form_state_discards_validation_for_stale_values(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().property(
+ "name",
+ acp::StringPropertySchema::new().default_value("before"),
+ true,
+ );
+ let mut form_state = ElicitationFormState::new(&schema, window, cx);
+ let submission = form_state
+ .begin_submission(cx)
+ .expect("first submission should start");
+ let editor = match form_state.fields.get("name") {
+ Some(ElicitationFieldState::Text(editor)) => editor.clone(),
+ _ => panic!("expected a text field"),
+ };
+
+ editor.update(cx, |editor, cx| editor.set_text("after", window, cx));
+
+ assert!(!form_state.validation_matches_current_values(&submission, cx));
+ assert!(form_state.begin_submission(cx).is_some());
+
+ Editor::single_line(window, cx)
+ });
+ }
+
#[gpui::test]
fn form_state_discards_invalid_optional_single_select_default(cx: &mut TestAppContext) {
crate::conversation_view::tests::init_test(cx);
@@ -786,6 +968,7 @@ fn render_preview_card(
ElicitationCard::new(
entry_ix,
&elicitation,
+ "Example Agent".into(),
form_state,
ElicitationCardHandlers::noop(),
)
@@ -999,6 +1182,12 @@ fn validate_single_select_value(
}
}
+const MAX_ELICITATION_PATTERN_BYTES: usize = 16 * 1024;
+const MAX_ELICITATION_PATTERN_INPUT_BYTES: usize = 1024 * 1024;
+const ELICITATION_PATTERN_BACKTRACK_LIMIT: usize = 10_000;
+const ELICITATION_PATTERN_COMPILED_SIZE_LIMIT: usize = 1024 * 1024;
+const ELICITATION_PATTERN_DFA_SIZE_LIMIT: usize = 1024 * 1024;
+
fn validate_string_pattern_and_format(
title: SharedString,
schema: &acp::StringPropertySchema,
@@ -1007,6 +1196,16 @@ fn validate_string_pattern_and_format(
if schema.pattern.is_none() && schema.format.and_then(string_format_json_name).is_none() {
return Ok(());
}
+ if schema
+ .pattern
+ .as_ref()
+ .is_some_and(|pattern| pattern.len() > MAX_ELICITATION_PATTERN_BYTES)
+ {
+ return Err(format!("{title} has an invalid validation pattern").into());
+ }
+ if schema.pattern.is_some() && value.len() > MAX_ELICITATION_PATTERN_INPUT_BYTES {
+ return Err(format!("{title} is too long to validate safely").into());
+ }
let mut validation_schema = serde_json::Map::new();
validation_schema.insert(
@@ -1029,6 +1228,12 @@ fn validate_string_pattern_and_format(
let validation_schema = serde_json::Value::Object(validation_schema);
let validator = jsonschema::options()
.should_validate_formats(true)
+ .with_pattern_options(
+ jsonschema::PatternOptions::fancy_regex()
+ .backtrack_limit(ELICITATION_PATTERN_BACKTRACK_LIMIT)
+ .size_limit(ELICITATION_PATTERN_COMPILED_SIZE_LIMIT)
+ .dfa_size_limit(ELICITATION_PATTERN_DFA_SIZE_LIMIT),
+ )
.build(&validation_schema)
.map_err(|_| {
if schema.pattern.is_some() {
@@ -1037,7 +1242,15 @@ fn validate_string_pattern_and_format(
format!("{title} has an invalid validation format")
}
})?;
- if validator.is_valid(&serde_json::Value::String(value.to_string())) {
+ let value = serde_json::Value::String(value.to_string());
+ if let Err(error) = validator.validate(&value) {
+ if matches!(
+ error.kind(),
+ jsonschema::error::ValidationErrorKind::BacktrackLimitExceeded { .. }
+ ) {
+ return Err(format!("{title} has a validation pattern that is too complex").into());
+ }
+ } else {
return Ok(());
}
@@ -1107,6 +1320,7 @@ pub(crate) struct ElicitationCardHandlers {
on_submit: RespondHandler,
on_decline: RespondHandler,
on_cancel: RespondHandler,
+ on_dismiss_url: RespondHandler,
on_open_url: OpenUrlHandler,
on_boolean_change: BooleanHandler,
on_single_select_change: SelectHandler,
@@ -1118,6 +1332,7 @@ impl ElicitationCardHandlers {
on_submit: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
on_decline: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
on_cancel: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
+ on_dismiss_url: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
on_open_url: impl Fn(ElicitationEntryId, String, &mut Window, &mut App) + 'static,
on_boolean_change: impl Fn(ElicitationEntryId, String, bool, &mut App) + 'static,
on_single_select_change: impl Fn(ElicitationEntryId, String, String, &mut App) + 'static,
@@ -1127,6 +1342,7 @@ impl ElicitationCardHandlers {
on_submit: Rc::new(on_submit),
on_decline: Rc::new(on_decline),
on_cancel: Rc::new(on_cancel),
+ on_dismiss_url: Rc::new(on_dismiss_url),
on_open_url: Rc::new(on_open_url),
on_boolean_change: Rc::new(on_boolean_change),
on_single_select_change: Rc::new(on_single_select_change),
@@ -1139,6 +1355,7 @@ impl ElicitationCardHandlers {
|_, _, _| {},
|_, _, _| {},
|_, _, _| {},
+ |_, _, _| {},
|_, _, _, _| {},
|_, _, _, _| {},
|_, _, _, _| {},
@@ -1150,14 +1367,33 @@ impl ElicitationCardHandlers {
pub(crate) fn should_render_elicitation(elicitation: &Elicitation) -> bool {
matches!(
(&elicitation.status, &elicitation.request.mode),
- (ElicitationStatus::Pending { .. }, _)
- | (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
+ (
+ ElicitationStatus::Pending { .. },
+ acp::ElicitationMode::Form(_) | acp::ElicitationMode::Url(_)
+ ) | (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
)
}
const MIN_URL_DISPLAY_SEGMENT_CHARS: usize = 16;
const MAX_URL_DISPLAY_SEGMENT_CHARS: usize = 64;
+#[derive(Debug, PartialEq, Eq)]
+struct UrlHostPresentation {
+ host: String,
+ suspicious_decoded_host: Option<String>,
+}
+
+fn url_host_presentation(url: &str) -> Option<UrlHostPresentation> {
+ let url = url::Url::parse(url).ok()?;
+ let host = url.host_str()?.to_string();
+ let (decoded_host, suspicious_characters) = crate::unicode_confusables::scan_host(&host);
+
+ Some(UrlHostPresentation {
+ host,
+ suspicious_decoded_host: (!suspicious_characters.is_empty()).then_some(decoded_host),
+ })
+}
+
fn display_url_segments(url: &str) -> Vec<SharedString> {
let mut segments = Vec::new();
let mut segment = String::new();
@@ -1192,6 +1428,7 @@ fn is_url_display_segment_boundary(character: char) -> bool {
pub(crate) struct ElicitationCard<'a> {
entry_ix: usize,
elicitation: &'a Elicitation,
+ requester_name: SharedString,
form_state: Option<&'a ElicitationFormState>,
handlers: ElicitationCardHandlers,
}
@@ -1200,12 +1437,14 @@ impl<'a> ElicitationCard<'a> {
pub(crate) fn new(
entry_ix: usize,
elicitation: &'a Elicitation,
+ requester_name: SharedString,
form_state: Option<&'a ElicitationFormState>,
handlers: ElicitationCardHandlers,
) -> Self {
Self {
entry_ix,
elicitation,
+ requester_name,
form_state,
handlers,
}
@@ -1274,7 +1513,7 @@ impl<'a> ElicitationCard<'a> {
.color(status_color),
)
.child(
- Label::new("Input Requested")
+ Label::new(format!("Input Requested by {}", self.requester_name))
.size(LabelSize::Custom(tool_name_font_size))
.truncate(),
),
@@ -1286,7 +1525,9 @@ impl<'a> ElicitationCard<'a> {
),
)
.child(body)
- .when(is_pending, |this| this.child(self.render_actions(cx)))
+ .when(is_pending || is_accepted_url, |this| {
+ this.child(self.render_actions(cx))
+ })
}
fn render_form(&self, mode: &acp::ElicitationFormMode, cx: &App) -> AnyElement {
@@ -1296,6 +1537,19 @@ impl<'a> ElicitationCard<'a> {
v_flex()
.gap_2()
+ .when_some(mode.requested_schema.title.clone(), |this, title| {
+ this.child(Label::new(title).size(LabelSize::Small))
+ })
+ .when_some(
+ mode.requested_schema.description.clone(),
+ |this, description| {
+ this.child(
+ Label::new(description)
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ },
+ )
.children(mode.requested_schema.properties.iter().filter_map(
|(field_name, property)| {
let field = state.fields.get(field_name)?;
@@ -1622,6 +1876,44 @@ impl<'a> ElicitationCard<'a> {
fn render_url_elicitation(&self, mode: &acp::ElicitationUrlMode) -> AnyElement {
v_flex()
.gap_2()
+ .when_some(url_host_presentation(&mode.url), |this, presentation| {
+ this.child(
+ v_flex()
+ .gap_1()
+ .child(
+ h_flex()
+ .gap_1()
+ .child(
+ Label::new("Destination")
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ .child(Label::new(presentation.host).size(LabelSize::Small)),
+ )
+ .when_some(
+ presentation.suspicious_decoded_host,
+ |this, decoded_host| {
+ this.child(
+ h_flex()
+ .items_start()
+ .gap_1()
+ .child(
+ Icon::new(IconName::Warning)
+ .size(IconSize::XSmall)
+ .color(Color::Warning),
+ )
+ .child(
+ Label::new(format!(
+ "This internationalized address displays as {decoded_host}. Verify it carefully."
+ ))
+ .size(LabelSize::Small)
+ .color(Color::Warning),
+ ),
+ )
+ },
+ ),
+ )
+ })
.child(Self::render_url_summary(&mode.url))
.into_any_element()
}
@@ -1654,7 +1946,12 @@ impl<'a> ElicitationCard<'a> {
acp::ElicitationMode::Url(mode) => Some(mode.url.clone()),
_ => None,
};
- let (accept_label, accept_icon, accept_icon_color) = if open_url.is_some() {
+ let is_accepted_url =
+ open_url.is_some() && matches!(self.elicitation.status, ElicitationStatus::Accepted);
+ let is_submitting = self.form_state.is_some_and(|state| state.is_submitting);
+ let (accept_label, accept_icon, accept_icon_color) = if is_accepted_url {
+ ("Open Again", IconName::ArrowUpRight, Color::Muted)
+ } else if open_url.is_some() {
("Open", IconName::ArrowUpRight, Color::Muted)
} else {
("Submit", IconName::Check, Color::Success)
@@ -1664,9 +1961,11 @@ impl<'a> ElicitationCard<'a> {
let on_open_url = self.handlers.on_open_url.clone();
let on_decline = self.handlers.on_decline.clone();
let on_cancel = self.handlers.on_cancel.clone();
+ let on_dismiss_url = self.handlers.on_dismiss_url.clone();
let submit_id = self.elicitation.id.clone();
let decline_id = self.elicitation.id.clone();
let cancel_id = self.elicitation.id.clone();
+ let dismiss_id = self.elicitation.id.clone();
h_flex()
.w_full()
@@ -1683,33 +1982,48 @@ impl<'a> ElicitationCard<'a> {
.color(accept_icon_color),
)
.label_size(LabelSize::Small)
+ .disabled(is_submitting)
.on_click(move |_, window, cx| {
if let Some(url) = &open_url {
on_open_url(submit_id.clone(), url.clone(), window, cx);
+ if !is_accepted_url {
+ on_submit(submit_id.clone(), window, cx);
+ }
} else {
on_submit(submit_id.clone(), window, cx);
}
}),
)
- .child(
- Button::new(("elicitation-decline", self.entry_ix), "Decline")
- .start_icon(
- Icon::new(IconName::Close)
- .size(IconSize::XSmall)
- .color(Color::Error),
- )
- .label_size(LabelSize::Small)
- .on_click(move |_, window, cx| {
- on_decline(decline_id.clone(), window, cx);
- }),
- )
- .child(
- Button::new(("elicitation-cancel", self.entry_ix), "Cancel")
- .label_size(LabelSize::Small)
- .on_click(move |_, window, cx| {
- on_cancel(cancel_id.clone(), window, cx);
- }),
- )
+ .when(!is_accepted_url, |this| {
+ this.child(
+ Button::new(("elicitation-decline", self.entry_ix), "Decline")
+ .start_icon(
+ Icon::new(IconName::Close)
+ .size(IconSize::XSmall)
+ .color(Color::Error),
+ )
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ on_decline(decline_id.clone(), window, cx);
+ }),
+ )
+ .child(
+ Button::new(("elicitation-cancel", self.entry_ix), "Cancel")
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ on_cancel(cancel_id.clone(), window, cx);
+ }),
+ )
+ })
+ .when(is_accepted_url, |this| {
+ this.child(
+ Button::new(("elicitation-dismiss-url", self.entry_ix), "Cancel")
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ on_dismiss_url(dismiss_id.clone(), window, cx);
+ }),
+ )
+ })
.into_any_element()
}
}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 718513a9ccc..469e88a5300 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -573,6 +573,7 @@ pub struct ThreadView {
pub agent_icon: IconName,
pub agent_icon_from_external_svg: Option<SharedString>,
pub agent_id: AgentId,
+ pub agent_display_name: SharedString,
pub focus_handle: FocusHandle,
pub workspace: WeakEntity<Workspace>,
pub entry_view_state: Entity<EntryViewState>,
@@ -983,6 +984,7 @@ impl ThreadView {
agent_icon,
agent_icon_from_external_svg,
agent_id,
+ agent_display_name,
workspace,
entry_view_state,
title_editor,
@@ -2638,33 +2640,70 @@ impl ThreadView {
return;
};
- let response = match mode {
+ match mode {
acp::ElicitationMode::Form(mode) => {
- let Some(state) = self.elicitation_form_states.get(&elicitation_id) else {
+ let Some(state) = self.elicitation_form_states.get_mut(&elicitation_id) else {
return;
};
- match state.collect(&mode.requested_schema, cx) {
- Ok(content) => {
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(content),
- ))
- }
- Err(errors) => {
- if let Some(state) = self.elicitation_form_states.get_mut(&elicitation_id) {
- state.set_errors(errors);
+ let Some(submission) = state.begin_submission(cx) else {
+ return;
+ };
+ let schema = mode.requested_schema;
+ let validation_task = cx.background_spawn(async move {
+ let result = submission.validate(&schema);
+ (submission, result)
+ });
+ cx.notify();
+ cx.spawn(async move |this, cx| {
+ let (submission, result) = validation_task.await;
+ this.update(cx, |this, cx| {
+ let is_current = this
+ .elicitation_form_states
+ .get_mut(&elicitation_id)
+ .is_some_and(|state| {
+ state.validation_matches_current_values(&submission, cx)
+ });
+ if !is_current {
+ cx.notify();
+ return;
}
- cx.notify();
- return;
- }
- }
+ match result {
+ Ok(content) => {
+ this.respond_to_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(content),
+ ),
+ ),
+ cx,
+ );
+ }
+ Err(errors) => {
+ if let Some(state) =
+ this.elicitation_form_states.get_mut(&elicitation_id)
+ {
+ state.set_errors(errors);
+ }
+ cx.notify();
+ }
+ }
+ })
+ .log_err();
+ })
+ .detach();
}
- acp::ElicitationMode::Url(_) => acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
- ),
- _ => return,
- };
-
- self.respond_to_elicitation(elicitation_id, response, cx);
+ acp::ElicitationMode::Url(_) => {
+ self.respond_to_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ }
+ _ => {}
+ }
}
fn decline_elicitation(
@@ -2693,6 +2732,19 @@ impl ThreadView {
);
}
+ fn dismiss_url_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.elicitation_form_states.remove(&elicitation_id);
+ self.thread.update(cx, |thread, cx| {
+ thread.cancel_elicitation(&elicitation_id, cx);
+ });
+ cx.notify();
+ }
+
fn respond_to_elicitation(
&mut self,
elicitation_id: ElicitationEntryId,
@@ -6544,6 +6596,7 @@ impl ThreadView {
ElicitationCard::new(
entry_ix,
elicitation,
+ self.agent_display_name.clone(),
self.elicitation_form_states.get(&elicitation.id),
self.elicitation_card_handlers(cx),
)
@@ -6583,14 +6636,14 @@ impl ThreadView {
},
{
let view = view.clone();
- move |elicitation_id, url, window, cx| {
- cx.open_url(&url);
+ move |elicitation_id, window, cx| {
view.update(cx, |this, cx| {
- this.submit_elicitation(elicitation_id, window, cx);
+ this.dismiss_url_elicitation(elicitation_id, window, cx);
})
.log_err();
}
},
+ move |_elicitation_id, url, _window, cx| cx.open_url(&url),
{
let view = view.clone();
move |elicitation_id, field_name, value, cx| {