Update ACP SDK to 5.4.0 and align v2 session behavior (#67155)

Update to published ACP Rust SDK 5.4.0 (schema crate 1.19.0). Follow the
[protocol changes since schema
1.18](https://github.com/agentclientprotocol/agent-client-protocol/compare/v1.18.0...dbff792240171b199b5ad24d01406720ac9e4bd3)
for behavior Zed already implements:

- Use each parent's `replay_complete` marker to distinguish historical
child state and cancel capabilities from current updates. Keep current
child updates that arrive before the resume response, but wait for a
successful response before sending child controls. Detach descendants
when their root closes.
- Reply to agent-cancelled v2 permission requests and elicitations with
`cancelled` or `cancel`, respectively. Leave background requests and
tools alone when cancelling foreground work, and keep accepting agent
status updates.
- Ignore `pattern` in v2 elicitation forms, but keep validating it in v1
forms.

Cursor and fork-at-position UI, retaining history from a failed resume,
and automatic keyed prompt resend are out of scope. This PR uses the
published SDK and does not depend on an unreleased SDK fix.

Release Notes:

- N/A
This commit is contained in:
Ben Brandt
2026-11-18 17:47:54 +00:00
committed by GitHub
parent 264f0b67be
commit 988007a89a
11 changed files with 662 additions and 173 deletions
Generated
+7 -6
View File
@@ -329,9 +329,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol"
version = "5.3.0"
version = "5.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "956559bd2dfddb5c8bc86792b1669bd2611fb4bd2c31865e4b8165ab6ea63109"
checksum = "5480352b071301dfa2ba98d36d02132ad95c336116b469548feca2f45eaf0b3d"
dependencies = [
"agent-client-protocol-derive",
"agent-client-protocol-schema",
@@ -348,9 +348,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol-derive"
version = "5.3.0"
version = "5.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4956a27f160f7ff73b17822066d1cb57d415ef9f442d3bcebb8074d2c8f24ec3"
checksum = "a2ff29b1cc0de7ea56df8971f559741872119ddf8d2245bce264a9fb2f577aaf"
dependencies = [
"quote",
"syn 3.0.3",
@@ -358,9 +358,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol-schema"
version = "1.18.0"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5128cd57704892e3978c85bfce0d532ef3162f585739f44726fa80d464c1782f"
checksum = "5d27fec60e79b5682eae06f9c94e028eb7043dfc972a4a38e7008701b4408d21"
dependencies = [
"anyhow",
"derive_more",
@@ -369,6 +369,7 @@ dependencies = [
"serde_json",
"serde_with",
"strum 0.28.0",
"uuid",
]
[[package]]
+1 -1
View File
@@ -539,7 +539,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] }
accesskit_macos = "0.26.0"
accesskit_unix = "0.22"
accesskit_windows = "0.34"
agent-client-protocol = { version = "=5.3.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
agent-client-protocol = { version = "=5.4.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" }
any_vec = "0.14"
+88 -15
View File
@@ -578,6 +578,7 @@ pub struct ElicitationEntryId(pub Arc<str>);
pub struct Elicitation {
pub id: ElicitationEntryId,
pub request: acp_v2::CreateElicitationRequest,
pub v1_string_patterns: std::collections::BTreeMap<String, String>,
pub status: ElicitationStatus,
}
@@ -638,7 +639,7 @@ impl ElicitationStore {
fn insert_pending_elicitation(
&mut self,
request: acp_v2::CreateElicitationRequest,
request: elicitation::ElicitationRequest,
) -> (
ElicitationEntryId,
oneshot::Receiver<acp_v2::CreateElicitationResponse>,
@@ -647,7 +648,8 @@ impl ElicitationStore {
let id = ElicitationEntryId(Uuid::new_v4().to_string().into());
self.elicitations.push(Elicitation {
id: id.clone(),
request,
request: request.request,
v1_string_patterns: request.v1_string_patterns,
status: ElicitationStatus::Pending { respond_tx },
});
(id, response_rx)
@@ -754,7 +756,7 @@ impl ElicitationStore {
pub fn request_elicitation(
&mut self,
request: acp_v2::CreateElicitationRequest,
request: impl Into<elicitation::ElicitationRequest>,
cx: &mut Context<Self>,
) -> Result<Task<acp_v2::CreateElicitationResponse>, acp_v2::Error> {
self.request_elicitation_with_id(request, cx)
@@ -763,10 +765,11 @@ impl ElicitationStore {
pub fn request_elicitation_with_id(
&mut self,
request: acp_v2::CreateElicitationRequest,
request: impl Into<elicitation::ElicitationRequest>,
cx: &mut Context<Self>,
) -> Result<(ElicitationEntryId, Task<acp_v2::CreateElicitationResponse>), acp_v2::Error> {
Self::validate_request(&request)?;
let request = request.into();
Self::validate_request(&request.request)?;
let (id, response_rx) = self.insert_pending_elicitation(request);
cx.emit(ElicitationStoreEvent::ElicitationRequested(id.clone()));
cx.notify();
@@ -4215,10 +4218,7 @@ impl AcpThread {
Ok(())
}
/// Ends a history replay into this session, after a successful load or resume. The
/// subagents RFD treats the work states and cancel grants that the replay reported for
/// subagents as history, outcomes included: each subagent's work state is unconfirmed,
/// and it cannot be cancelled, until the agent reports current ones after the response.
/// Discards child state and cancel grants after a v1 load or a failed v2 resume.
/// Titles and transcripts stay.
pub fn invalidate_replayed_subagent_state(&mut self, cx: &mut Context<Self>) {
for subagent in self.subagents.values() {
@@ -4681,6 +4681,7 @@ impl AcpThread {
pub fn handle_connection_lost(&mut self, cx: &mut Context<Self>) {
let was_observable = self.activity.ensure_observable().is_ok();
self.activity.close_observation();
self.clear_live_subagent_state(cx);
let changed = self.submissions.disconnect();
if !changed.is_empty() {
for id in changed {
@@ -4731,11 +4732,28 @@ impl AcpThread {
pub fn handle_session_closed(&mut self, cx: &mut Context<Self>) {
// Close confirms stopping without inventing an Idle snapshot or ending receipts.
self.activity.finish_close();
self.clear_live_subagent_state(cx);
self.cancel_generic_permission_requests(cx);
self.cancel_outstanding_elicitations(cx);
for subagent in self.subagents.values() {
subagent.update(cx, |subagent, cx| subagent.handle_session_closed(cx));
}
cx.notify();
}
fn clear_live_subagent_state(&mut self, cx: &mut Context<Self>) {
if matches!(
self.submissions.transport(),
SubmissionTransport::AgentOwned
) && let Some(association) = &mut self.subagent_association
{
association.can_cancel = false;
if self.foreground_activity().is_active() {
self.clear_session_state(cx).log_err();
}
}
}
fn register_submission(
&mut self,
content: Arc<[acp_v2::ContentBlock]>,
@@ -4879,6 +4897,19 @@ impl AcpThread {
}
}
pub fn update_v2_subagent_state(
&mut self,
state: acp_v2::StateUpdate,
cx: &mut Context<Self>,
) -> Result<()> {
// The agent can send the same state on the child's stream and on the
// parent's. A second copy is not another outcome.
if self.foreground_state() == Some(&state) {
return Ok(());
}
self.update_session_state(state, cx)
}
pub fn update_session_state(
&mut self,
state: acp_v2::StateUpdate,
@@ -4946,12 +4977,15 @@ impl AcpThread {
stop_reason: stop_reason.clone(),
});
}
// A subagent's work can stop because Zed cancelled an ancestor. Its requests stay
// answerable until it reports that, and then go as if Zed had cancelled it.
if self.subagent_association.is_some()
&& matches!(stop_reason, Some(acp_v2::StopReason::Cancelled))
{
self.cancel_local_actions(RequestPermissionOutcome::Cancelled, cx);
if self.connection.answers_permission_requests_on_cancel() {
self.cancel_local_actions(RequestPermissionOutcome::Cancelled, cx);
} else if was_in_progress {
// Only the agent knows which requests are still needed by background work.
self.mark_foreground_tool_calls_cancelled(cx);
}
}
}
if previous != self.foreground_activity() {
@@ -7131,7 +7165,7 @@ impl AcpThread {
pub fn request_elicitation(
&mut self,
request: acp_v2::CreateElicitationRequest,
request: impl Into<elicitation::ElicitationRequest>,
cx: &mut Context<Self>,
) -> Result<Task<acp_v2::CreateElicitationResponse>, acp_v2::Error> {
self.request_elicitation_with_id(request, cx)
@@ -7140,10 +7174,11 @@ impl AcpThread {
pub fn request_elicitation_with_id(
&mut self,
request: acp_v2::CreateElicitationRequest,
request: impl Into<elicitation::ElicitationRequest>,
cx: &mut Context<Self>,
) -> Result<(ElicitationEntryId, Task<acp_v2::CreateElicitationResponse>), acp_v2::Error> {
ElicitationStore::validate_request(&request)?;
let request = request.into();
ElicitationStore::validate_request(&request.request)?;
let (id, response_rx) = self.elicitations.insert_pending_elicitation(request);
self.push_entry(AgentThreadEntry::Elicitation(id.clone()), cx);
@@ -7861,6 +7896,11 @@ impl AcpThread {
|| self.has_unsettled_submissions()
{
self.connection.cancel(self.session_id(), cx)?;
if self.activity.in_progress()
&& !self.connection.answers_permission_requests_on_cancel()
{
self.mark_foreground_tool_calls_cancelled(cx);
}
}
if self.connection.answers_permission_requests_on_cancel() {
if self.subagent_association.is_some() {
@@ -7999,6 +8039,39 @@ impl AcpThread {
self.cancel_outstanding_elicitations(cx);
}
fn mark_foreground_tool_calls_cancelled(&mut self, cx: &mut Context<Self>) {
let background = self
.activity
.state()
.and_then(|state| state.background())
.unwrap_or_default();
for (index, entry) in self
.entries
.iter_mut()
.enumerate()
.skip(self.activity.first_entry_index())
{
let AgentThreadEntry::ToolCall(call) = entry else {
continue;
};
if matches!(
call.underlying_status(),
ToolCallStatus::Pending | ToolCallStatus::InProgress | ToolCallStatus::Paused
) && !background.iter().any(|item| match item {
acp_v2::BackgroundWork::ToolCall(item) => item.tool_call_id == call.id,
acp_v2::BackgroundWork::Terminal(item) => call
.terminals()
.any(|terminal| terminal.read(cx).id() == &item.terminal_id),
_ => false,
}) {
// This is a display hint. The next reported status replaces it.
call.set_local_status(ToolCallStatus::Canceled);
cx.emit(AcpThreadEvent::EntryUpdated(index));
cx.notify();
}
}
}
fn mark_pending_entries_as_canceled(
&mut self,
permission_outcome: RequestPermissionOutcome,
+50 -14
View File
@@ -2,13 +2,27 @@ use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use anyhow::{Result, bail};
use std::collections::BTreeMap;
pub fn request_from_v1(
request: v1::CreateElicitationRequest,
) -> Result<v2::CreateElicitationRequest> {
pub struct ElicitationRequest {
pub request: v2::CreateElicitationRequest,
// v2 removed `pattern`, but Zed still validates it for v1 forms.
pub v1_string_patterns: BTreeMap<String, String>,
}
impl From<v2::CreateElicitationRequest> for ElicitationRequest {
fn from(request: v2::CreateElicitationRequest) -> Self {
Self {
request,
v1_string_patterns: BTreeMap::new(),
}
}
}
pub fn request_from_v1(request: v1::CreateElicitationRequest) -> Result<ElicitationRequest> {
let mut v1_string_patterns = BTreeMap::new();
let mode = match request.mode {
v1::ElicitationMode::Form(mode) => v2::ElicitationMode::Form(v2::ElicitationFormMode::new(
scope_from_v1(mode.scope)?,
schema_from_v1(mode.requested_schema)?,
schema_from_v1(mode.requested_schema, &mut v1_string_patterns)?,
)),
v1::ElicitationMode::Url(mode) => v2::ElicitationMode::Url(v2::ElicitationUrlMode::new(
scope_from_v1(mode.scope)?,
@@ -26,7 +40,10 @@ pub fn request_from_v1(
}
_ => bail!("unsupported v1 elicitation mode"),
};
Ok(v2::CreateElicitationRequest::new(mode, request.message).meta(request.meta))
Ok(ElicitationRequest {
request: v2::CreateElicitationRequest::new(mode, request.message).meta(request.meta),
v1_string_patterns,
})
}
pub fn response_to_v1(
@@ -79,7 +96,10 @@ fn request_id_from_v1(id: v1::RequestId) -> Result<v2::RequestId> {
})
}
fn schema_from_v1(schema: v1::ElicitationSchema) -> Result<v2::ElicitationSchema> {
fn schema_from_v1(
schema: v1::ElicitationSchema,
v1_string_patterns: &mut BTreeMap<String, String>,
) -> Result<v2::ElicitationSchema> {
let mut converted = v2::ElicitationSchema::new();
converted.type_ = match schema.type_ {
v1::ElicitationSchemaType::Object => v2::ElicitationSchemaType::Object,
@@ -89,7 +109,14 @@ fn schema_from_v1(schema: v1::ElicitationSchema) -> Result<v2::ElicitationSchema
converted.properties = schema
.properties
.into_iter()
.map(|(name, property)| Ok((name, property_from_v1(property)?)))
.map(|(name, mut property)| {
if let v1::ElicitationPropertySchema::String(property) = &mut property
&& let Some(pattern) = property.pattern.take()
{
v1_string_patterns.insert(name.clone(), pattern);
}
Ok((name, property_from_v1(property)?))
})
.collect::<Result<_>>()?;
converted.required = schema.required;
converted.description = schema.description;
@@ -107,7 +134,6 @@ fn property_from_v1(
converted.description = property.description;
converted.min_length = property.min_length;
converted.max_length = property.max_length;
converted.pattern = property.pattern;
converted.format = property.format.map(string_format_from_v1).transpose()?;
converted.default = property.default;
converted.enum_values = property.enum_values;
@@ -249,7 +275,7 @@ mod tests {
#[test]
fn elicitation_request_adapter_preserves_schema_scopes_and_extensions() -> Result<()> {
let fixture = json!({
let mut fixture = json!({
"mode": "form",
"sessionId": "session-01",
"toolCallId": "tool-01",
@@ -320,8 +346,16 @@ mod tests {
});
let request: v1::CreateElicitationRequest = serde_json::from_value(fixture.clone())?;
let converted = request_from_v1(request)?;
assert_eq!(serde_json::to_value(&converted)?, fixture);
let v2::ElicitationMode::Form(mode) = converted.mode else {
assert_eq!(
converted.v1_string_patterns,
BTreeMap::from([("name".into(), "^[a-z]+$".into())])
);
fixture["requestedSchema"]["properties"]["name"]
.as_object_mut()
.ok_or_else(|| anyhow::anyhow!("expected a string property"))?
.remove("pattern");
assert_eq!(serde_json::to_value(&converted.request)?, fixture);
let v2::ElicitationMode::Form(mode) = converted.request.mode else {
bail!("expected form mode");
};
assert!(matches!(
@@ -342,7 +376,7 @@ mod tests {
}
_ => bail!("expected request scope"),
};
let converted = request_from_v1(request)?;
let converted = request_from_v1(request)?.request;
let v2::ElicitationScope::Request(scope) = converted.scope() else {
bail!("expected request scope");
};
@@ -370,7 +404,7 @@ mod tests {
.clone(),
);
let request: v1::CreateElicitationRequest = serde_json::from_value(fixture.clone())?;
let converted = request_from_v1(request)?;
let converted = request_from_v1(request)?.request;
assert!(matches!(converted.mode, v2::ElicitationMode::Other(_)));
assert_eq!(serde_json::to_value(converted)?, fixture);
}
@@ -380,7 +414,9 @@ mod tests {
"requestedSchema": {"type": "object", "properties": {}, "required": []}
});
assert_eq!(
serde_json::to_value(request_from_v1(serde_json::from_value(fixture.clone())?)?)?,
serde_json::to_value(
request_from_v1(serde_json::from_value(fixture.clone())?)?.request
)?,
fixture
);
Ok(())
+121 -22
View File
@@ -15,7 +15,9 @@ pub use v1::test_support;
pub use v1::{AcpConnection, AcpSessionList, GEMINI_TERMINAL_AUTH_METHOD_ID};
pub use v2::AcpV2Connection;
use acp_thread::{AcpThread, AuthRequired, ElicitationStore, LoadError};
use acp_thread::{
AcpThread, AuthRequired, ElicitationStore, LoadError, elicitation::ElicitationRequest,
};
use action_log::ActionLog;
use agent_client_protocol::{
Agent, Client, HandleDispatchFrom, Handled, JsonRpcMessage, JsonRpcResponse, Protocol,
@@ -23,6 +25,7 @@ use agent_client_protocol::{
v2::{Builder as V2Builder, ConnectionTo as V2ConnectionTo, Responder as V2Responder},
};
use agent_client_protocol::{
schema::MaybeUndefined,
v1::schema::{self as acp, ErrorCode},
v2::schema as acp_v2,
};
@@ -482,10 +485,9 @@ impl acp_thread::AgentSessionConfigOptions for ReadOnlyConfigOptions {
pub struct AcpSession {
thread: WeakEntity<AcpThread>,
/// Whether a parent announced this session as its ACP subagent. This mirrors the
/// thread's subagent association, so the connection can refuse a subagent's
/// mutations even while its thread is being updated.
is_subagent: bool,
/// The root of an announced child session controls when the child is addressable.
subagent_root: Option<acp_v2::SessionId>,
replay: Option<Rc<RefCell<V2Replay>>>,
suppress_abort_err: bool,
session_modes: Option<Rc<RefCell<acp::SessionModeState>>>,
config_options: Option<ConfigOptions>,
@@ -493,6 +495,13 @@ pub struct AcpSession {
_release_subscription: Subscription,
}
#[derive(Default)]
struct V2Replay {
/// Each session, including each child, has its own history boundary.
completed: HashSet<acp_v2::SessionId>,
finished: bool,
}
/// Builds a v2 terminal-notification handler without selecting it for application connections.
/// Other session updates remain unclaimed so later inbound handlers can process them.
pub fn v2_terminal_client_builder(
@@ -795,8 +804,8 @@ fn close_undelivered_session(
/// Applies a `subagent_update` received on `parent`'s stream. The first update for a
/// session announces it: Zed creates its thread, routes the session's traffic on this
/// connection, and hands the thread to the parent. Later updates patch the association.
/// The update's `state` is left to the caller, since only v1 uses it as the subagent's
/// activity.
/// The update's `state` is left to the caller because v2 separates history from live
/// state per session, whereas v1 uses the response as the boundary.
fn apply_subagent_update(
parent: &Entity<AcpThread>,
update: &acp_v2::SubagentUpdate,
@@ -820,6 +829,23 @@ fn apply_subagent_update(
!sessions.borrow().contains_key(&session_id),
"Session {session_id} cannot become a subagent of {parent_session_id}"
);
let (subagent_root, replay) = {
let sessions = sessions.borrow();
let parent = sessions
.get(&parent_session_id)
.context("Parent session was released")?;
(
parent
.subagent_root
.clone()
.unwrap_or_else(|| parent_session_id.clone()),
parent
.replay
.as_ref()
.filter(|replay| !replay.borrow().finished)
.cloned(),
)
};
let (connection, project, parent_action_log) = {
let parent = parent.read(cx);
@@ -873,7 +899,8 @@ fn apply_subagent_update(
session_id,
AcpSession {
thread: subagent.downgrade(),
is_subagent: true,
subagent_root: Some(subagent_root),
replay,
suppress_abort_err: false,
session_modes: None,
config_options: Some(ConfigOptions::new(Rc::new(RefCell::new(Vec::new())))),
@@ -888,12 +915,33 @@ fn apply_subagent_update(
}
fn apply_v2_session_notification(
notification: InboundSessionNotification,
mut notification: InboundSessionNotification,
thread: &WeakEntity<AcpThread>,
sessions: &Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,
cx: &mut AsyncApp,
) -> Result<()> {
if let InboundSessionUpdate::Subagent(update) = &notification.update {
let (is_subagent, replay) = {
let sessions = sessions.borrow();
let session = sessions
.get(&notification.session_id)
.filter(|session| session.thread.entity_id() == thread.entity_id())
.context("Session was released or replaced before applying an update")?;
(session.subagent_root.is_some(), session.replay.clone())
};
if matches!(notification.update, InboundSessionUpdate::ReplayComplete) {
if let Some(replay) = replay {
let mut replay = replay.borrow_mut();
if !replay.finished {
replay.completed.insert(notification.session_id);
}
}
return Ok(());
}
let replaying = replay.is_some_and(|replay| {
let replay = replay.borrow();
!replay.finished && !replay.completed.contains(&notification.session_id)
});
if let InboundSessionUpdate::Subagent(update) = &mut notification.update {
let parent = thread
.upgrade()
.context("Session was released before its subagent was announced")?;
@@ -902,10 +950,30 @@ fn apply_v2_session_notification(
parent_session_id == notification.session_id,
"Subagent update belongs to a different ACP session"
);
// In v2 the subagent's own `state_update` reports its activity; the parent's copy
// only mirrors it.
cx.update(|cx| apply_subagent_update(&parent, update, sessions, cx))?;
return Ok(());
let state = if replaying {
// This is on the parent's stream. Historical grants and work state are
// never effective, even if the child has already finished its own replay.
update.capabilities = Default::default();
Default::default()
} else {
std::mem::take(&mut update.state)
};
return cx.update(|cx| {
let subagent = apply_subagent_update(&parent, update, sessions, cx)?;
subagent.update(cx, |subagent, cx| match state {
MaybeUndefined::Undefined => Ok(()),
MaybeUndefined::Null => subagent.clear_session_state(cx),
MaybeUndefined::Value(state) => subagent.update_v2_subagent_state(state, cx),
})
});
}
if is_subagent && let InboundSessionUpdate::State(state) = notification.update {
// A child only sends current state after its own marker. Older agents
// may send historical snapshots instead, without a marker.
if replaying {
return Ok(());
}
return thread.update(cx, |thread, cx| thread.update_v2_subagent_state(state, cx))?;
}
if let InboundSessionUpdate::ConfigOptions(update) = &notification.update {
let config_options = {
@@ -983,9 +1051,15 @@ fn handle_v2_request_permission(
cx: &mut AsyncApp,
context: &ClientContext,
) {
let cancelled = || {
acp_v2::RequestPermissionResponse::new(acp_v2::RequestPermissionOutcome::Cancelled(
Default::default(),
))
};
let cancellation = responder.cancellation();
if cancellation.is_cancelled() {
return respond_err(responder, agent_client_protocol::Error::request_cancelled());
responder.respond(cancelled()).log_err();
return;
}
let thread = match session_thread(context, &request.session_id) {
Ok(thread) => thread,
@@ -1019,25 +1093,46 @@ fn handle_v2_request_permission(
thread.cancel_permission_request(request_id, cx)
})
.log_err();
responder.respond(cancelled()).log_err();
} else {
respond_err(responder, error);
}
respond_err(responder, error);
}
}
})
.detach();
}
fn handle_v2_create_elicitation<P: Protocol>(
fn handle_v2_create_elicitation(
args: acp_v2::CreateElicitationRequest,
responder: Responder<acp_v2::CreateElicitationResponse, P>,
responder: V2Responder<acp_v2::CreateElicitationResponse>,
cx: &mut AsyncApp,
ctx: &ClientContext,
) {
handle_elicitation(args.into(), responder, true, cx, ctx);
}
fn handle_elicitation<P: Protocol>(
args: ElicitationRequest,
responder: Responder<acp_v2::CreateElicitationResponse, P>,
respond_with_cancel_action: bool,
cx: &mut AsyncApp,
ctx: &ClientContext,
) {
let cancelled = move || {
if respond_with_cancel_action {
Ok(acp_v2::CreateElicitationResponse::new(
acp_v2::ElicitationAction::Cancel,
))
} else {
Err(agent_client_protocol::Error::request_cancelled())
}
};
let cancellation = responder.cancellation();
if cancellation.is_cancelled() {
return respond_err(responder, agent_client_protocol::Error::request_cancelled());
return respond_result(responder, cancelled());
}
match args.scope() {
match args.request.scope() {
acp_v2::ElicitationScope::Session(scope) => {
let thread = match session_thread(ctx, &scope.session_id) {
Ok(t) => t,
@@ -1072,8 +1167,10 @@ fn handle_v2_create_elicitation<P: Protocol>(
thread.cancel_elicitation(&elicitation_id, cx)
})
.log_err();
respond_result(responder, cancelled());
} else {
respond_err(responder, e);
}
respond_err(responder, e);
}
}
})
@@ -1116,8 +1213,10 @@ fn handle_v2_create_elicitation<P: Protocol>(
store.cancel_elicitation(&elicitation_id, cx)
})
.log_err();
respond_result(responder, cancelled());
} else {
respond_err(responder, e);
}
respond_err(responder, e);
}
}
})
@@ -159,6 +159,7 @@ pub struct InboundSessionNotification {
#[derive(Debug)]
pub enum InboundSessionUpdate {
ReplayComplete,
UserMessage(acp_v2::UserMessage),
AgentMessage(acp_v2::AgentMessage),
AgentThought(acp_v2::AgentThought),
@@ -207,6 +208,7 @@ impl TryFrom<acp_v2::UpdateSessionNotification> for InboundSessionNotification {
fn try_from(mut notification: acp_v2::UpdateSessionNotification) -> Result<Self, Self::Error> {
let update = match notification.update {
acp_v2::SessionUpdate::ReplayComplete(_) => InboundSessionUpdate::ReplayComplete,
acp_v2::SessionUpdate::UserMessage(message) => {
InboundSessionUpdate::UserMessage(message)
}
@@ -306,6 +308,7 @@ impl InboundSessionNotification {
);
// Delivery metadata must not patch retained payload fields.
match update {
InboundSessionUpdate::ReplayComplete => Ok(()),
InboundSessionUpdate::UserMessage(message) => thread.upsert_user_message(message, cx),
InboundSessionUpdate::AgentMessage(message) => {
thread.upsert_assistant_message(message, cx)
+18 -16
View File
@@ -2,7 +2,7 @@ use super::{
AcpDebugLog, AcpDebugMessage, AcpSession, ClientContext, ConfigOptions, FlattenAcpResult as _,
ForegroundWork, ReadOnlyConfigOptions, UnsupportedVersion, apply_subagent_update,
drain_foreground_queue, enqueue_notification, enqueue_request, first_class_terminal_auth_task,
handle_v2_complete_elicitation, handle_v2_create_elicitation, map_acp_error,
handle_elicitation, handle_v2_complete_elicitation, map_acp_error,
mcp_configurations_for_project, respond_err, respond_result, runtime, session_thread,
terminal_auth_task_id, transport, with_v2_client_ingress, work_dirs_from_session_info,
};
@@ -838,7 +838,8 @@ impl AcpConnection {
session_id,
AcpSession {
thread: thread.downgrade(),
is_subagent: false,
subagent_root: None,
replay: None,
suppress_abort_err: false,
session_modes,
config_options,
@@ -3224,9 +3225,9 @@ mod tests {
assert_eq!(
v2_response(response, cx, "pre-cancelled permission")
.await
.expect_err("RPC cancellation before registration")
.code,
ErrorCode::RequestCancelled
.expect("RPC cancellation before registration")
.outcome,
acp_v2::RequestPermissionOutcome::Cancelled(Default::default())
);
cx.run_until_parked();
assert_eq!(
@@ -3258,9 +3259,9 @@ mod tests {
assert_eq!(
v2_response(first, cx, "permission RPC cancellation")
.await
.expect_err("RPC cancellation")
.code,
ErrorCode::RequestCancelled
.expect("RPC cancellation")
.outcome,
acp_v2::RequestPermissionOutcome::Cancelled(Default::default())
);
harness.thread.update(cx, |thread, cx| {
assert!(thread.permission_request(first_id).is_none());
@@ -3479,9 +3480,9 @@ mod tests {
assert_eq!(
v2_response(response, cx, "pre-cancelled elicitation")
.await
.expect_err("RPC cancellation before registration")
.code,
ErrorCode::RequestCancelled
.expect("RPC cancellation before registration")
.action,
acp_v2::ElicitationAction::Cancel
);
harness.thread.read_with(cx, |thread, _| {
assert_eq!(thread.entries().len(), entry_count);
@@ -3504,9 +3505,9 @@ mod tests {
assert_eq!(
v2_response(first, cx, "elicitation RPC cancellation")
.await
.expect_err("RPC cancellation")
.code,
ErrorCode::RequestCancelled
.expect("RPC cancellation")
.action,
acp_v2::ElicitationAction::Cancel
);
assert!((&mut second).now_or_never().is_none());
let check = |first_status: &ElicitationStatus, second_status: &ElicitationStatus| {
@@ -8440,7 +8441,8 @@ exit 7
parent_session_id.clone(),
AcpSession {
thread: parent.downgrade(),
is_subagent: false,
subagent_root: None,
replay: None,
suppress_abort_err: false,
session_modes: None,
config_options: None,
@@ -10293,7 +10295,7 @@ fn handle_create_elicitation(
.map_err(agent_client_protocol::Error::from)
})
});
handle_v2_create_elicitation(args, responder, cx, ctx);
handle_elicitation(args, responder, false, cx, ctx);
}
fn handle_complete_elicitation(
+255 -43
View File
@@ -564,6 +564,9 @@ impl AcpV2Connection {
if self.initialize_response.capabilities.session.is_none() {
return Task::ready(Err(anyhow!("Sessions are not advertised by this agent")));
}
if self.is_subagent_session(&request.session_id) {
return Task::ready(Err(anyhow!("Cannot prompt a subagent session")));
}
if let Err(error) = self.validate_prompt_content(&request.prompt) {
return Task::ready(Err(error));
}
@@ -697,7 +700,9 @@ impl AcpV2Connection {
.get(session_id)
.is_some_and(|session| session.thread.entity_id() == thread_id);
if matches {
self.sessions.borrow_mut().remove(session_id);
self.sessions.borrow_mut().retain(|id, session| {
id != session_id && session.subagent_root.as_ref() != Some(session_id)
});
}
let matches = self
.session_owners
@@ -779,7 +784,8 @@ impl AcpV2Connection {
session_id.clone(),
AcpSession {
thread: thread.downgrade(),
is_subagent: false,
subagent_root: None,
replay: None,
suppress_abort_err: false,
session_modes: None,
config_options: Some(ConfigOptions::new(Rc::new(RefCell::new(Vec::new())))),
@@ -965,13 +971,29 @@ impl AcpV2Connection {
})
}
/// The subagents RFD allows no Client-initiated mutation of a subagent session except
/// the `cancel` its parent advertises, which `AcpThread::cancel` checks.
fn is_subagent_session(&self, session_id: &acp::SessionId) -> bool {
self.sessions
.borrow()
.get(session_id)
.is_some_and(|session| session.is_subagent && session.thread.upgrade().is_some())
.is_some_and(|session| {
session.subagent_root.is_some() && session.thread.upgrade().is_some()
})
}
fn ensure_session_active(&self, session_id: &acp::SessionId) -> Result<()> {
anyhow::ensure!(
!is_connection_closed(&self.connection),
"Agent connection is closed"
);
let sessions = self.sessions.borrow();
let session = sessions
.get(session_id)
.filter(|session| session.thread.upgrade().is_some())
.context("Session has been released")?;
let root_id = session.subagent_root.as_ref().unwrap_or(session_id);
let owners = self.session_owners.borrow();
let owner = owners.get(root_id).context("Session has been released")?;
owner.ensure_ready(owner.thread.entity_id(), sessions.get(root_id))
}
fn open_session(
@@ -1063,6 +1085,15 @@ impl AcpV2Connection {
Err(error) => return Task::ready(Err(error)),
};
thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));
let replay = if replay_history {
let replay = Rc::new(RefCell::new(super::V2Replay::default()));
if let Some(session) = self.sessions.borrow_mut().get_mut(&session_id) {
session.replay = Some(replay.clone());
}
Some(replay)
} else {
None
};
let request = self.connection.prepare_request(request);
let request_id = request.id().clone();
let cancellation = request.cancellation_handle();
@@ -1084,12 +1115,13 @@ impl AcpV2Connection {
let this = this.upgrade().context("Connection was released")?;
let thread = thread.upgrade().context("Session was released")?;
cx.update(|cx| {
// Ordered responses apply after the replay and before any update sent
// after the response, so this is the RFD's freshness boundary.
if replay_history {
thread.update(cx, |thread, cx| {
thread.invalidate_replayed_subagent_state(cx)
});
if let Some(replay) = replay {
let mut replay = replay.borrow_mut();
// For older agents that omit a marker, the response still
// certifies their replay. Don't clear current child state that
// arrived after a marker but before the response.
replay.finished = true;
replay.completed.clear();
}
if !thread.read(cx).has_received_session_state() {
log::warn!(
@@ -1115,7 +1147,7 @@ impl AcpV2Connection {
let thread = thread.downgrade();
let session_id = session_id.clone();
let dispatch_tx = self.dispatch_tx.clone();
async move |_cx| {
async move |cx| {
if thread.upgrade().is_none() {
if let Some(this) = this.upgrade() {
this.remove_session(&session_id, thread.entity_id());
@@ -1125,6 +1157,11 @@ impl AcpV2Connection {
let response = response.await;
if response.is_err() {
drain_foreground_queue(&dispatch_tx).await.log_err();
if let Some(thread) = thread.upgrade() {
thread.update(cx, |thread, cx| {
thread.invalidate_replayed_subagent_state(cx)
});
}
}
if let Some(this) = this.upgrade() {
if response.is_ok() && thread.upgrade().is_some() {
@@ -1704,17 +1741,7 @@ impl AgentConnection for AcpV2Connection {
}
fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) -> Result<()> {
anyhow::ensure!(
self.sessions
.borrow()
.get(session_id)
.is_some_and(|session| session.thread.upgrade().is_some()),
"Session has been released"
);
anyhow::ensure!(
!is_connection_closed(&self.connection),
"Agent connection is closed"
);
self.ensure_session_active(session_id)?;
self.connection
.send_notification(acp::CancelSessionNotification::new(session_id.clone()))
.map_err(map_acp_error)
@@ -1726,6 +1753,9 @@ impl AgentConnection for AcpV2Connection {
tool_call_id: &acp::ToolCallId,
cx: &mut App,
) -> Task<Result<()>> {
if let Err(error) = self.ensure_session_active(session_id) {
return Task::ready(Err(error));
}
let response = Self::scoped_request(
&self.connection,
&self.dispatch_tx,
@@ -1743,6 +1773,9 @@ impl AgentConnection for AcpV2Connection {
terminal_id: &acp::TerminalId,
cx: &mut App,
) -> Task<Result<()>> {
if let Err(error) = self.ensure_session_active(session_id) {
return Task::ready(Err(error));
}
let response = Self::scoped_request(
&self.connection,
&self.dispatch_tx,
@@ -1787,6 +1820,7 @@ impl AgentConnection for AcpV2Connection {
Some(Rc::new(V2SessionList {
connection: self.connection.clone(),
dispatch_tx: self.dispatch_tx.clone(),
sessions: self.sessions.clone(),
supports_delete: capabilities.delete.is_some(),
}))
}
@@ -1799,6 +1833,7 @@ impl AgentConnection for AcpV2Connection {
struct V2SessionList {
connection: V2ConnectionTo<Agent>,
dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
supports_delete: bool,
}
@@ -1856,6 +1891,14 @@ impl AgentSessionList for V2SessionList {
if !self.supports_delete() {
return Task::ready(Err(anyhow!("Deleting sessions is not supported")));
}
if self
.sessions
.borrow()
.get(session_id)
.is_some_and(|session| session.subagent_root.is_some())
{
return Task::ready(Err(anyhow!("Cannot delete a subagent session")));
}
let response = AcpV2Connection::scoped_request(
&self.connection,
&self.dispatch_tx,
@@ -2776,6 +2819,131 @@ mod tests {
}
}
#[gpui::test]
async fn v2_resume_uses_each_parents_replay_complete_for_child_state(cx: &mut TestAppContext) {
let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
let loading = harness.reopen(true, cx);
let (_, responder) = bounded(harness.resume_requests.recv(), cx)
.await
.expect("resume");
let complete = |session_id| {
harness.send_update(
session_id,
acp::SessionUpdate::ReplayComplete(acp::ReplayComplete::new()),
);
};
let can_cancel = || {
acp::SubagentSessionCapabilities::new().cancel(acp::SessionCancelCapabilities::new())
};
let running = acp::StateUpdate::Running(acp::RunningStateUpdate::new());
let idle = acp::StateUpdate::Idle(acp::IdleStateUpdate::new());
harness.send_update(
"saved",
acp::SessionUpdate::SubagentUpdate(
acp::SubagentUpdate::new("child")
.capabilities(can_cancel())
.state(idle.clone()),
),
);
harness.send_update(
"child",
acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("worker")),
);
complete("saved");
harness.send_update(
"saved",
acp::SessionUpdate::SubagentUpdate(
acp::SubagentUpdate::new("child").state(running.clone()),
),
);
// The root's marker does not make the child's stream current.
harness.send_update(
"child",
acp::SessionUpdate::SubagentUpdate(
acp::SubagentUpdate::new("worker")
.capabilities(can_cancel())
.state(idle.clone()),
),
);
harness.drain_updates(cx).await;
let thread = |session_id: &str| {
harness
.client
.sessions
.borrow()
.get(&acp::SessionId::new(session_id))
.and_then(|session| session.thread.upgrade())
.expect("announced session")
};
let child = thread("child");
let worker = thread("worker");
child.read_with(cx, |child, _| {
let association = child.subagent_association().expect("association");
assert_eq!(child.foreground_state(), Some(&running));
assert!(!association.can_cancel);
});
worker.read_with(cx, |worker, _| {
let association = worker.subagent_association().expect("association");
assert_eq!(worker.foreground_state(), None);
assert!(!association.can_cancel);
});
complete("child");
complete("worker");
harness.send_update(
"child",
acp::SessionUpdate::SubagentUpdate(
acp::SubagentUpdate::new("worker")
.capabilities(can_cancel())
.state(running.clone()),
),
);
harness.send_update("worker", acp::SessionUpdate::StateUpdate(running.clone()));
harness.resume_state(idle);
harness.drain_updates(cx).await;
let early = worker.update(cx, |worker, cx| worker.cancel(cx));
assert!(
bounded(early, cx)
.await
.expect_err("cancel cannot be sent before resume succeeds")
.to_string()
.contains("still initializing")
);
assert!(harness.cancellations.is_empty());
responder
.respond(acp::ResumeSessionResponse::new())
.expect("resume response");
let _root = bounded(loading, cx).await.expect("resumed root");
worker.read_with(cx, |worker, _| {
let association = worker.subagent_association().expect("association");
assert_eq!(worker.foreground_state(), Some(&running));
assert_eq!(
worker.activity_generation(),
1,
"the mirror is not a second turn"
);
assert!(association.can_cancel);
});
let _cancellation = worker.update(cx, |worker, cx| worker.cancel(cx));
assert_eq!(
bounded(harness.cancellations.recv(), cx)
.await
.expect("worker cancel")
.session_id,
acp::SessionId::new("worker"),
);
bounded(harness.close(cx), cx).await.expect("closed root");
worker.read_with(cx, |worker, _| {
let association = worker.subagent_association().expect("association");
assert!(worker.is_observation_closed());
assert!(!association.can_cancel);
assert_eq!(worker.foreground_state(), None, "close did not report idle");
});
assert!(harness.client.sessions.borrow().is_empty());
}
#[gpui::test]
async fn v2_subagent_directories_inherit_through_nested_subagents(cx: &mut TestAppContext) {
use agent_client_protocol::schema::MaybeUndefined;
@@ -2900,9 +3068,9 @@ mod tests {
);
assert_eq!(child.entries().len(), 1, "child traffic reaches the child");
assert_eq!(
child.status(),
ThreadStatus::Unconfirmed,
"the parent's mirrored state does not report the child's activity"
child.foreground_activity(),
acp_thread::ForegroundActivity::Running,
"a current mirror also reports the child's activity"
);
});
@@ -3417,12 +3585,12 @@ mod tests {
"only the agent knows whether the request belongs to the cancelled work"
);
permission_cancellation.cancel().expect("cancel request");
let error = bounded(permission, cx)
let response = bounded(permission, cx)
.await
.expect_err("cancelled by the agent");
.expect("typed cancellation response");
assert_eq!(
error.code,
agent_client_protocol::ErrorCode::REQUEST_CANCELLED
response.outcome,
acp::RequestPermissionOutcome::Cancelled(Default::default())
);
cx.run_until_parked();
assert_eq!(
@@ -3492,31 +3660,65 @@ mod tests {
);
});
// The agent has no handler for these methods, so the SDK answers -32602 once a
// request reaches it. A local refusal never sends one.
let sent_code = |result: Result<()>| {
// Only requests that reach the agent receive a protocol error. The test doesn't
// depend on which error the SDK uses for unhandled methods.
let rejected_by_agent = |result: Result<()>| {
result
.expect_err("the harness agent rejects cancellation")
.downcast_ref::<agent_client_protocol::Error>()
.map(|error| error.code)
.is::<agent_client_protocol::Error>()
};
let invalid_params = Some(agent_client_protocol::ErrorCode::INVALID_PARAMS);
let stop_watcher = thread.update(cx, |thread, cx| {
thread.cancel_tool_call(&"watcher".into(), cx)
});
assert_eq!(sent_code(bounded(stop_watcher, cx).await), invalid_params);
assert!(rejected_by_agent(bounded(stop_watcher, cx).await));
let stop_fixed = thread.update(cx, |thread, cx| {
thread.cancel_tool_call(&"fixed".into(), cx)
});
assert_eq!(
sent_code(bounded(stop_fixed, cx).await),
None,
assert!(
!rejected_by_agent(bounded(stop_fixed, cx).await),
"an unadvertised tool call is never sent tool_call/cancel"
);
let stop_server = thread.update(cx, |thread, cx| {
thread.cancel_terminal(&"server".into(), cx)
});
assert_eq!(sent_code(bounded(stop_server, cx).await), invalid_params);
assert!(rejected_by_agent(bounded(stop_server, cx).await));
let background = thread.read_with(cx, |thread, _| {
thread.background_work().expect("background list").to_vec()
});
harness.send_update(
&session_id.0,
acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(
acp::RunningStateUpdate::new().background(background),
)),
);
for (id, content) in [
("foreground", vec![]),
(
"server-tool",
vec![acp::ToolCallContent::Terminal(acp::Terminal::new("server"))],
),
] {
harness.send_update(
&session_id.0,
acp::SessionUpdate::ToolCallUpdate(
acp::ToolCallUpdate::new(id)
.status(acp::ToolCallStatus::InProgress)
.content(content),
),
);
}
harness.drain_updates(cx).await;
let cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));
bounded(harness.cancellations.recv(), cx)
.await
.expect("session/cancel");
thread.read_with(cx, |thread, _| {
let status = |id: &str| thread.tool_call(&id.into()).expect("tool call").1.status();
assert_eq!(status("foreground"), ToolCallStatus::Canceled);
assert_eq!(status("watcher"), ToolCallStatus::Paused);
assert_eq!(status("server-tool"), ToolCallStatus::InProgress);
});
harness.send_update(
&session_id.0,
@@ -3530,12 +3732,21 @@ mod tests {
acp::ToolCallUpdate::new("watcher").status(acp::ToolCallStatus::Cancelled),
),
);
harness.send_update(
&session_id.0,
acp::SessionUpdate::ToolCallUpdate(
acp::ToolCallUpdate::new("foreground").status(acp::ToolCallStatus::Completed),
),
);
harness.send_update(
&session_id.0,
acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(acp::IdleStateUpdate::new())),
);
harness.drain_updates(cx).await;
bounded(cancellation, cx).await.expect("observed idle");
thread.read_with(cx, |thread, cx| {
let (_, foreground) = thread.tool_call(&"foreground".into()).expect("foreground");
assert_eq!(foreground.status(), ToolCallStatus::Completed);
assert_eq!(
thread.background_work(),
None,
@@ -3619,10 +3830,11 @@ mod tests {
let (request, responder) = bounded(harness.prompts.recv(), cx).await.expect("prompt");
assert_eq!(request.prompt, content);
assert_eq!(request.session_id, session_id);
let recorded_content = vec![acp::ContentBlock::from("question recorded by agent")];
let echo = acp::UpdateSessionNotification::new(
session_id.clone(),
acp::SessionUpdate::UserMessage(
acp::UserMessage::new("message").content(content.clone()),
acp::UserMessage::new("message").content(recorded_content.clone()),
),
);
if echo_first {
@@ -3649,7 +3861,7 @@ mod tests {
let [AgentThreadEntry::UserMessage(message)] = thread.entries() else {
panic!("one authoritative user message");
};
assert_eq!(message.content.source_blocks(), content.as_slice());
assert_eq!(message.content.source_blocks(), recorded_content.as_slice());
assert!(matches!(
thread.submission(submission_id).expect("echoed").state,
SubmissionState::Accepted { echoed: true, .. }
+9 -4
View File
@@ -2905,7 +2905,10 @@ impl ConversationView {
.map(|elicitation| {
let is_pending = matches!(elicitation.status, ElicitationStatus::Pending { .. });
let schema = match &elicitation.request.mode {
acp_v2::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
acp_v2::ElicitationMode::Form(mode) => Some((
mode.requested_schema.clone(),
elicitation.v1_string_patterns.clone(),
)),
_ => None,
};
(elicitation.id.clone(), is_pending, schema)
@@ -2921,11 +2924,13 @@ impl ConversationView {
for (id, is_pending, schema) in elicitations {
if is_pending
&& let Some(schema) = schema
&& let Some((schema, patterns)) = schema
&& !self.request_elicitation_form_states.contains_key(&id)
{
self.request_elicitation_form_states
.insert(id, ElicitationFormState::new(&schema, window, cx));
self.request_elicitation_form_states.insert(
id,
ElicitationFormState::with_v1_string_patterns(&schema, patterns, window, cx),
);
} else if !is_pending {
self.request_elicitation_form_states.remove(&id);
}
@@ -7,6 +7,7 @@ use futures::channel::oneshot;
use gpui::{AnyElement, App, Div, Empty, Entity, Focusable, Role, SharedString, Window, div};
use std::collections::BTreeMap;
use std::rc::Rc;
use std::sync::Arc;
use ui::{
Button, Checkbox, ChoiceCard, Color, Icon, IconName, IconSize, Label, LabelSize, ToggleState,
prelude::*,
@@ -37,16 +38,27 @@ enum ElicitationFieldValue {
#[derive(PartialEq, Eq)]
pub(crate) struct ElicitationFormSubmission {
fields: HashMap<String, ElicitationFieldValue>,
v1_string_patterns: Arc<BTreeMap<String, String>>,
}
pub(crate) struct ElicitationFormState {
fields: HashMap<String, ElicitationFieldState>,
field_errors: HashMap<String, SharedString>,
is_submitting: bool,
v1_string_patterns: Arc<BTreeMap<String, String>>,
}
impl ElicitationFormState {
pub(crate) fn new(schema: &acp::ElicitationSchema, window: &mut Window, cx: &mut App) -> Self {
fn new(schema: &acp::ElicitationSchema, window: &mut Window, cx: &mut App) -> Self {
Self::with_v1_string_patterns(schema, BTreeMap::new(), window, cx)
}
pub(crate) fn with_v1_string_patterns(
schema: &acp::ElicitationSchema,
v1_string_patterns: BTreeMap<String, String>,
window: &mut Window,
cx: &mut App,
) -> Self {
let required = schema.required.as_deref().unwrap_or_default();
let mut fields = HashMap::default();
@@ -62,8 +74,9 @@ impl ElicitationFormState {
acp::ElicitationPropertySchema::String(schema) => {
let options = single_select_options(schema);
if options.is_empty() {
let pattern = v1_string_patterns.get(name).map(String::as_str);
let default = schema.default.as_ref().filter(|default| {
validate_string_value(title.clone(), schema, default).is_ok()
validate_string_value(title.clone(), schema, pattern, default).is_ok()
});
let editor = cx.new(|cx| {
let mut editor = Editor::single_line(window, cx);
@@ -136,11 +149,13 @@ impl ElicitationFormState {
fields,
field_errors: HashMap::default(),
is_submitting: false,
v1_string_patterns: Arc::new(v1_string_patterns),
}
}
fn snapshot(&self, cx: &App) -> ElicitationFormSubmission {
ElicitationFormSubmission {
v1_string_patterns: self.v1_string_patterns.clone(),
fields: self
.fields
.iter()
@@ -251,6 +266,7 @@ impl ElicitationFormSubmission {
let Some(field) = self.fields.get(name) else {
continue;
};
let pattern = self.v1_string_patterns.get(name).map(String::as_str);
let field_content = match (property, field) {
(
@@ -264,8 +280,13 @@ impl ElicitationFormSubmission {
Ok(None)
}
} else {
validate_string_value(property_title(name, property), schema, value)
.map(|()| Some(value.clone().into()))
validate_string_value(
property_title(name, property),
schema,
pattern,
value,
)
.map(|()| Some(value.clone().into()))
}
}
(
@@ -275,7 +296,12 @@ impl ElicitationFormSubmission {
if let Some(value) = value {
validate_single_select_value(property_title(name, property), schema, value)
.and_then(|()| {
validate_string_value(property_title(name, property), schema, value)
validate_string_value(
property_title(name, property),
schema,
pattern,
value,
)
})
.map(|()| Some(value.clone().into()))
} else if is_required {
@@ -403,6 +429,7 @@ mod tests {
acp::ElicitationFormMode::new(preview_request_scope(0), schema),
"Choose an answer.",
),
v1_string_patterns: BTreeMap::new(),
status: pending_status(),
},
events: Rc::default(),
@@ -736,10 +763,10 @@ mod tests {
fn string_validation_rejects_email_format_mismatch() {
let schema = acp::StringPropertySchema::email();
validate_string_value("Email".into(), &schema, "user@example.com")
validate_string_value("Email".into(), &schema, None, "user@example.com")
.expect("valid email should be accepted");
assert_eq!(
validate_string_value("Email".into(), &schema, "not-an-email")
validate_string_value("Email".into(), &schema, None, "not-an-email")
.expect_err("invalid email should be rejected")
.to_string(),
"Email must be an email address"
@@ -749,14 +776,14 @@ mod tests {
assert_eq!(string_format_json_name(&format), None);
assert_eq!(string_format_label(&format), None);
let schema = acp::StringPropertySchema::new().format(format);
validate_string_value("Email".into(), &schema, "not-an-email")
validate_string_value("Email".into(), &schema, None, "not-an-email")
.expect("unknown formats should be annotations");
let schema = schema.pattern("^prod-[0-9]+$");
validate_string_value("Email".into(), &schema, "prod-42")
let pattern = Some("^prod-[0-9]+$");
validate_string_value("Email".into(), &schema, pattern, "prod-42")
.expect("known constraints should still apply alongside unknown formats");
assert_eq!(
validate_string_value("Email".into(), &schema, "not-an-email")
validate_string_value("Email".into(), &schema, pattern, "not-an-email")
.expect_err("unknown formats should not bypass known constraints")
.to_string(),
"Email does not match the requested pattern"
@@ -764,27 +791,56 @@ mod tests {
}
#[test]
fn string_validation_rejects_pattern_mismatch() {
let schema = acp::StringPropertySchema::new().pattern("^prod-[0-9]+$");
fn string_validation_only_uses_v1_patterns() {
use acp_thread::elicitation::{ElicitationRequest, request_from_v1};
validate_string_value("Environment".into(), &schema, "prod-42")
.expect("matching pattern should be accepted");
assert_eq!(
validate_string_value("Environment".into(), &schema, "dev-42")
.expect_err("pattern mismatch should be rejected")
.to_string(),
"Environment does not match the requested pattern"
let request = serde_json::json!({
"mode": "form",
"sessionId": "session",
"message": "Choose an environment",
"requestedSchema": {
"type": "object",
"properties": {
"environment": { "type": "string", "minLength": 3, "pattern": "^prod-[0-9]+$" }
}
}
});
let legacy = request_from_v1(serde_json::from_value(request.clone()).expect("v1 request"))
.expect("converted v1 request");
let current = ElicitationRequest::from(
serde_json::from_value::<acp::CreateElicitationRequest>(request).expect("v2 request"),
);
for (request, accepts_other_environment) in [(legacy, false), (current, true)] {
let acp::ElicitationMode::Form(mode) = request.request.mode else {
panic!("expected form");
};
let mut submission = ElicitationFormSubmission {
fields: HashMap::default(),
v1_string_patterns: Arc::new(request.v1_string_patterns),
};
for (value, valid) in [
("prod-42", true),
("dev-42", accepts_other_environment),
("x", false),
] {
submission.fields.insert(
"environment".into(),
ElicitationFieldValue::Text(value.into()),
);
assert_eq!(submission.validate(&mode.requested_schema).is_ok(), valid);
}
}
}
#[test]
fn string_validation_supports_bounded_advanced_patterns() {
let schema = acp::StringPropertySchema::new().pattern(r"^prod-(?=[0-9]+$)([0-9])\1$");
let schema = acp::StringPropertySchema::new();
let pattern = Some(r"^prod-(?=[0-9]+$)([0-9])\1$");
validate_string_value("Environment".into(), &schema, "prod-44")
validate_string_value("Environment".into(), &schema, pattern, "prod-44")
.expect("lookahead and backreference should be accepted");
assert_eq!(
validate_string_value("Environment".into(), &schema, "prod-45")
validate_string_value("Environment".into(), &schema, pattern, "prod-45")
.expect_err("backreference mismatch should be rejected")
.to_string(),
"Environment does not match the requested pattern"
@@ -793,19 +849,18 @@ mod tests {
#[test]
fn string_validation_rejects_patterns_outside_resource_limits() {
let oversized_pattern =
acp::StringPropertySchema::new().pattern("a".repeat(MAX_ELICITATION_PATTERN_BYTES + 1));
let schema = acp::StringPropertySchema::new();
let oversized_pattern = "a".repeat(MAX_ELICITATION_PATTERN_BYTES + 1);
assert_eq!(
validate_string_value("Value".into(), &oversized_pattern, "a")
validate_string_value("Value".into(), &schema, Some(&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)
validate_string_value("Value".into(), &schema, Some(".*"), &oversized_value)
.expect_err("oversized pattern input should be rejected")
.to_string(),
"Value is too long to validate safely"
@@ -843,6 +898,7 @@ mod tests {
),
"Review this request.",
),
v1_string_patterns: BTreeMap::new(),
status: pending_status(),
};
assert!(should_render_elicitation(&pending));
@@ -857,6 +913,7 @@ mod tests {
),
"Authorize Zed in your browser.",
),
v1_string_patterns: BTreeMap::new(),
status: ElicitationStatus::Accepted,
};
assert!(should_render_elicitation(&accepted_url));
@@ -870,6 +927,7 @@ mod tests {
),
"Review this request.",
),
v1_string_patterns: BTreeMap::new(),
status: ElicitationStatus::Accepted,
};
assert!(!should_render_elicitation(&accepted_form));
@@ -880,6 +938,7 @@ mod tests {
acp::OtherElicitationMode::new("future", preview_request_scope(3), BTreeMap::new()),
"Use a future input mode.",
),
v1_string_patterns: BTreeMap::new(),
status: pending_status(),
};
assert!(!should_render_elicitation(&pending_unknown));
@@ -1192,7 +1251,7 @@ mod tests {
"properties": {
"when": {"type": "_future"},
"labels": {"type": "array", "items": {"type": "_future"}},
"code": {"type": "string", "pattern": "^[0-9]+$", "default": "abc"},
"code": {"type": "string", "minLength": 4, "default": "abc"},
"count": {"type": "integer", "minimum": 1, "default": 0},
"ratio": {"type": "number", "maximum": 1, "default": 2},
"tags": {
@@ -1465,6 +1524,7 @@ fn render_preview_card(
let elicitation = Elicitation {
id: ElicitationEntryId(format!("preview-elicitation-{entry_ix}").into()),
request,
v1_string_patterns: BTreeMap::new(),
status,
};
@@ -1671,6 +1731,7 @@ fn validate_integer_value(
fn validate_string_value(
title: SharedString,
schema: &acp::StringPropertySchema,
v1_pattern: Option<&str>,
value: &str,
) -> Result<(), SharedString> {
let length = value.chars().count();
@@ -1687,7 +1748,7 @@ fn validate_string_value(
return Err(format!("{title} is too long").into());
}
validate_string_pattern_and_format(title, schema, value)
validate_string_pattern_and_format(title, schema, v1_pattern, value)
}
fn validate_single_select_value(
@@ -1712,25 +1773,17 @@ const ELICITATION_PATTERN_DFA_SIZE_LIMIT: usize = 1024 * 1024;
fn validate_string_pattern_and_format(
title: SharedString,
schema: &acp::StringPropertySchema,
v1_pattern: Option<&str>,
value: &str,
) -> Result<(), SharedString> {
if schema.pattern.is_none()
&& schema
.format
.as_ref()
.and_then(string_format_json_name)
.is_none()
{
let format = schema.format.as_ref().and_then(string_format_json_name);
if v1_pattern.is_none() && format.is_none() {
return Ok(());
}
if schema
.pattern
.as_ref()
.is_some_and(|pattern| pattern.len() > MAX_ELICITATION_PATTERN_BYTES)
{
if v1_pattern.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 {
if v1_pattern.is_some() && value.len() > MAX_ELICITATION_PATTERN_INPUT_BYTES {
return Err(format!("{title} is too long to validate safely").into());
}
@@ -1739,13 +1792,13 @@ fn validate_string_pattern_and_format(
"type".to_string(),
serde_json::Value::String("string".into()),
);
if let Some(pattern) = &schema.pattern {
if let Some(pattern) = v1_pattern {
validation_schema.insert(
"pattern".to_string(),
serde_json::Value::String(pattern.clone()),
serde_json::Value::String(pattern.into()),
);
}
if let Some(format) = schema.format.as_ref().and_then(string_format_json_name) {
if let Some(format) = format {
validation_schema.insert(
"format".to_string(),
serde_json::Value::String(format.into()),
@@ -1763,7 +1816,7 @@ fn validate_string_pattern_and_format(
)
.build(&validation_schema)
.map_err(|_| {
if schema.pattern.is_some() {
if v1_pattern.is_some() {
format!("{title} has an invalid validation pattern")
} else {
format!("{title} has an invalid validation format")
@@ -1782,7 +1835,7 @@ fn validate_string_pattern_and_format(
}
match (
schema.pattern.is_some(),
v1_pattern.is_some(),
schema.format.as_ref().and_then(string_format_label),
) {
(true, Some(_)) => Err(format!("{title} does not match the requested constraints").into()),
@@ -3529,7 +3529,10 @@ impl ThreadView {
elicitation_id.clone(),
matches!(elicitation.status, ElicitationStatus::Pending { .. }),
match &elicitation.request.mode {
acp_v2::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
acp_v2::ElicitationMode::Form(mode) => Some((
mode.requested_schema.clone(),
elicitation.v1_string_patterns.clone(),
)),
_ => None,
},
)
@@ -3540,11 +3543,13 @@ impl ThreadView {
};
if is_pending
&& let Some(schema) = schema
&& let Some((schema, patterns)) = schema
&& !self.elicitation_form_states.contains_key(&id)
{
self.elicitation_form_states
.insert(id, ElicitationFormState::new(&schema, window, cx));
self.elicitation_form_states.insert(
id,
ElicitationFormState::with_v1_string_patterns(&schema, patterns, window, cx),
);
} else if !is_pending {
self.elicitation_form_states.remove(&id);
}