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_thread: Share v2 configuration options (#65093)

Ben Brandt57af58b3adb9
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 2c22d9e4f37..afed1c65bef 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -1,3 +1,4 @@
+pub mod config_options;
mod connection;
pub mod content;
mod diff;
@@ -3527,7 +3528,7 @@ pub enum AcpThreadEvent {
Refusal,
AvailableCommandsUpdated(Vec<acp_v1::AvailableCommand>),
ModeUpdated(acp_v1::SessionModeId),
- ConfigOptionsUpdated(Vec<acp_v1::SessionConfigOption>),
+ ConfigOptionsUpdated(Vec<acp_v2::SessionConfigOption>),
WorkingDirectoriesUpdated,
}
@@ -4298,7 +4299,9 @@ impl AcpThread {
acp_v1::SessionUpdate::ConfigOptionUpdate(acp_v1::ConfigOptionUpdate {
config_options,
..
- }) => cx.emit(AcpThreadEvent::ConfigOptionsUpdated(config_options)),
+ }) => cx.emit(AcpThreadEvent::ConfigOptionsUpdated(
+ config_options::from_v1(config_options).map_err(acp_v1::Error::from)?,
+ )),
acp_v1::SessionUpdate::UsageUpdate(update) => {
let usage = self.token_usage.get_or_insert_with(Default::default);
usage.max_tokens = update.size;
diff --git a/crates/acp_thread/src/config_options.rs b/crates/acp_thread/src/config_options.rs
new file mode 100644
index 00000000000..d8abd7c9b3e
--- /dev/null
+++ b/crates/acp_thread/src/config_options.rs
@@ -0,0 +1,199 @@
+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
+use anyhow::{Result, bail};
+
+pub fn from_v1(
+ options: Vec<acp_v1::SessionConfigOption>,
+) -> Result<Vec<acp_v2::SessionConfigOption>> {
+ options.into_iter().map(option_from_v1).collect()
+}
+
+fn option_from_v1(option: acp_v1::SessionConfigOption) -> Result<acp_v2::SessionConfigOption> {
+ let kind = match option.kind {
+ acp_v1::SessionConfigKind::Select(select) => {
+ let options = match select.options {
+ acp_v1::SessionConfigSelectOptions::Ungrouped(options) => {
+ acp_v2::SessionConfigSelectOptions::Ungrouped(
+ options.into_iter().map(select_option_from_v1).collect(),
+ )
+ }
+ acp_v1::SessionConfigSelectOptions::Grouped(groups) => {
+ acp_v2::SessionConfigSelectOptions::Grouped(
+ groups
+ .into_iter()
+ .map(|group| {
+ acp_v2::SessionConfigSelectGroup::new(
+ acp_v2::SessionConfigGroupId::new(group.group.0),
+ group.name,
+ group
+ .options
+ .into_iter()
+ .map(select_option_from_v1)
+ .collect(),
+ )
+ .meta(group.meta)
+ })
+ .collect(),
+ )
+ }
+ _ => bail!("Unsupported legacy configuration choices"),
+ };
+ acp_v2::SessionConfigKind::Select(acp_v2::SessionConfigSelect::new(
+ acp_v2::SessionConfigValueId::new(select.current_value.0),
+ options,
+ ))
+ }
+ acp_v1::SessionConfigKind::Boolean(boolean) => acp_v2::SessionConfigKind::Boolean(
+ acp_v2::SessionConfigBoolean::new(boolean.current_value),
+ ),
+ _ => bail!("Unsupported legacy configuration option"),
+ };
+ let category = option
+ .category
+ .map(|category| {
+ Ok(match category {
+ acp_v1::SessionConfigOptionCategory::Mode => {
+ acp_v2::SessionConfigOptionCategory::Mode
+ }
+ acp_v1::SessionConfigOptionCategory::Model => {
+ acp_v2::SessionConfigOptionCategory::Model
+ }
+ acp_v1::SessionConfigOptionCategory::ModelConfig => {
+ acp_v2::SessionConfigOptionCategory::ModelConfig
+ }
+ acp_v1::SessionConfigOptionCategory::ThoughtLevel => {
+ acp_v2::SessionConfigOptionCategory::ThoughtLevel
+ }
+ acp_v1::SessionConfigOptionCategory::Other(category) => {
+ acp_v2::SessionConfigOptionCategory::Other(category)
+ }
+ _ => bail!("Unsupported legacy configuration category"),
+ })
+ })
+ .transpose()?;
+ Ok(acp_v2::SessionConfigOption::new(
+ acp_v2::SessionConfigId::new(option.id.0),
+ option.name,
+ kind,
+ )
+ .description(option.description)
+ .category(category)
+ .meta(option.meta))
+}
+
+fn select_option_from_v1(
+ option: acp_v1::SessionConfigSelectOption,
+) -> acp_v2::SessionConfigSelectOption {
+ acp_v2::SessionConfigSelectOption::new(
+ acp_v2::SessionConfigValueId::new(option.value.0),
+ option.name,
+ )
+ .description(option.description)
+ .meta(option.meta)
+}
+
+pub fn value_to_v1(
+ value: acp_v2::SessionConfigOptionValue,
+) -> Result<acp_v1::SessionConfigOptionValue> {
+ match value {
+ acp_v2::SessionConfigOptionValue::Id { value } => Ok(
+ acp_v1::SessionConfigOptionValue::value_id(acp_v1::SessionConfigValueId::new(value.0)),
+ ),
+ acp_v2::SessionConfigOptionValue::Boolean { value } => {
+ Ok(acp_v1::SessionConfigOptionValue::boolean(value))
+ }
+ _ => bail!("This configuration value is not supported by ACP v1"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn legacy_options_preserve_fields_in_v2() -> Result<()> {
+ let options = vec![
+ acp_v1::SessionConfigOption::boolean("enabled", "Enabled", false)
+ .meta(acp_v1::Meta::new()),
+ acp_v1::SessionConfigOption::select(
+ "mode",
+ "Mode",
+ "fast",
+ vec![
+ acp_v1::SessionConfigSelectOption::new("fast", "Fast")
+ .description("")
+ .meta(acp_v1::Meta::new()),
+ ],
+ )
+ .description("")
+ .category(acp_v1::SessionConfigOptionCategory::Other("_custom".into()))
+ .meta(acp_v1::Meta::from_iter([(
+ "nested".into(),
+ json!([1, true]),
+ )])),
+ acp_v1::SessionConfigOption::select(
+ "model",
+ "Model",
+ "large",
+ vec![
+ acp_v1::SessionConfigSelectGroup::new(
+ "provider",
+ "Provider",
+ vec![acp_v1::SessionConfigSelectOption::new("large", "Large")],
+ )
+ .meta(acp_v1::Meta::from_iter([(
+ "group".into(),
+ json!("metadata"),
+ )])),
+ ],
+ )
+ .category(acp_v1::SessionConfigOptionCategory::Model),
+ ];
+ assert_eq!(
+ serde_json::to_value(from_v1(options)?)?,
+ json!([
+ {
+ "configId": "enabled", "name": "Enabled",
+ "type": "boolean", "currentValue": false, "_meta": {}
+ },
+ {
+ "configId": "mode", "name": "Mode", "description": "",
+ "category": "_custom", "type": "select", "currentValue": "fast",
+ "options": [{"value": "fast", "name": "Fast", "description": "", "_meta": {}}],
+ "_meta": {"nested": [1, true]}
+ },
+ {
+ "configId": "model", "name": "Model", "category": "model",
+ "type": "select", "currentValue": "large",
+ "options": [{
+ "groupId": "provider", "name": "Provider",
+ "options": [{"value": "large", "name": "Large"}],
+ "_meta": {"group": "metadata"}
+ }]
+ }
+ ])
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn legacy_values_convert_known_shapes_and_reject_unknown_payloads() -> Result<()> {
+ assert_eq!(
+ value_to_v1(acp_v2::SessionConfigOptionValue::id("opaque-id"))?,
+ acp_v1::SessionConfigOptionValue::value_id("opaque-id")
+ );
+ assert_eq!(
+ value_to_v1(acp_v2::SessionConfigOptionValue::boolean(false))?,
+ acp_v1::SessionConfigOptionValue::boolean(false)
+ );
+ let value =
+ acp_v2::SessionConfigOptionValue::Other(acp_v2::OtherSessionConfigOptionValue::new(
+ "_custom",
+ json!("private-value"),
+ Default::default(),
+ ));
+ let error = value_to_v1(value).expect_err("unknown value must not lose its type");
+ assert!(!error.to_string().contains("private-value"));
+ Ok(())
+ }
+}
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 21f81b72948..8c727059319 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -338,16 +338,16 @@ pub trait AgentSessionModes {
pub trait AgentSessionConfigOptions {
/// Get all current config options with their state
- fn config_options(&self) -> Vec<acp_v1::SessionConfigOption>;
+ fn config_options(&self) -> Vec<acp_v2::SessionConfigOption>;
/// Set a config option value
/// Returns the full updated list of config options
fn set_config_option(
&self,
- config_id: acp_v1::SessionConfigId,
- value: acp_v1::SessionConfigOptionValue,
+ config_id: acp_v2::SessionConfigId,
+ value: acp_v2::SessionConfigOptionValue,
cx: &mut App,
- ) -> Task<Result<Vec<acp_v1::SessionConfigOption>>>;
+ ) -> Task<Result<Vec<acp_v2::SessionConfigOption>>>;
/// Whenever the config options are updated the receiver will be notified.
/// Optional for agents that don't update their config options dynamically.
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 8b3dd83ac19..1b912ebbea9 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -377,13 +377,13 @@ struct SessionConfigResponse {
#[derive(Clone)]
struct ConfigOptions {
- config_options: Rc<RefCell<Vec<acp::SessionConfigOption>>>,
+ config_options: Rc<RefCell<Vec<acp_v2::SessionConfigOption>>>,
tx: Rc<RefCell<watch::Sender<()>>>,
rx: watch::Receiver<()>,
}
impl ConfigOptions {
- fn new(config_options: Rc<RefCell<Vec<acp::SessionConfigOption>>>) -> Self {
+ fn new(config_options: Rc<RefCell<Vec<acp_v2::SessionConfigOption>>>) -> Self {
let (tx, rx) = watch::channel(());
Self {
config_options,
@@ -1226,8 +1226,10 @@ impl AcpConnection {
let Some(connection_state) = this.upgrade() else {
return Ok(());
};
- let response = match response {
- Ok(response) => response,
+ let (modes, config_options) = match response
+ .and_then(|response| config_state(response.modes, response.config_options))
+ {
+ Ok(state) => state,
Err(error) => {
connection_state.remove_session(&session_id, thread.entity_id());
connection_state
@@ -1237,8 +1239,6 @@ impl AcpConnection {
};
if let Some(_thread) = thread.upgrade() {
- let (modes, config_options) =
- config_state(response.modes, response.config_options);
{
let mut sessions = connection_state.sessions.borrow_mut();
let Some(session) = sessions
@@ -1299,7 +1299,7 @@ impl AcpConnection {
fn apply_default_config_options(
&self,
session_id: &acp::SessionId,
- config_options: &Rc<RefCell<Vec<acp::SessionConfigOption>>>,
+ config_options: &Rc<RefCell<Vec<acp_v2::SessionConfigOption>>>,
cx: &mut AsyncApp,
) {
let id = self.id.clone();
@@ -1308,58 +1308,58 @@ impl AcpConnection {
config_opts_ref
.iter()
.filter_map(|config_option| {
- let default_value = self.defaults.config_option(config_option.id.0.as_ref())?;
+ let default_value = self
+ .defaults
+ .config_option(config_option.config_id.0.as_ref())?;
let value_to_apply = match &config_option.kind {
- acp::SessionConfigKind::Select(select) => {
+ acp_v2::SessionConfigKind::Select(select) => {
let value_id = default_value.as_value_id()?;
match &select.options {
- acp::SessionConfigSelectOptions::Ungrouped(options) => options
+ acp_v2::SessionConfigSelectOptions::Ungrouped(options) => options
.iter()
.any(|opt| &*opt.value.0 == value_id)
.then(|| {
- acp::SessionConfigOptionValue::value_id(
- value_id.to_string(),
- )
+ acp_v2::SessionConfigOptionValue::id(value_id.to_string())
}),
- acp::SessionConfigSelectOptions::Grouped(groups) => groups
+ acp_v2::SessionConfigSelectOptions::Grouped(groups) => groups
.iter()
.any(|group| {
group.options.iter().any(|opt| &*opt.value.0 == value_id)
})
.then(|| {
- acp::SessionConfigOptionValue::value_id(
- value_id.to_string(),
- )
+ acp_v2::SessionConfigOptionValue::id(value_id.to_string())
}),
_ => None,
}
}
- acp::SessionConfigKind::Boolean(_) => default_value
+ acp_v2::SessionConfigKind::Boolean(_) => default_value
.as_bool()
- .map(acp::SessionConfigOptionValue::boolean),
+ .map(acp_v2::SessionConfigOptionValue::boolean),
_ => None,
};
if let Some(value_to_apply) = value_to_apply {
let initial_value = match &config_option.kind {
- acp::SessionConfigKind::Select(select) => {
- acp::SessionConfigOptionValue::value_id(
- select.current_value.clone(),
- )
+ acp_v2::SessionConfigKind::Select(select) => {
+ acp_v2::SessionConfigOptionValue::id(select.current_value.clone())
}
- acp::SessionConfigKind::Boolean(boolean) => {
- acp::SessionConfigOptionValue::boolean(boolean.current_value)
+ acp_v2::SessionConfigKind::Boolean(boolean) => {
+ acp_v2::SessionConfigOptionValue::boolean(boolean.current_value)
}
_ => return None,
};
- Some((config_option.id.clone(), value_to_apply, initial_value))
+ Some((
+ config_option.config_id.clone(),
+ value_to_apply,
+ initial_value,
+ ))
} else {
log::warn!(
"`{}` is not a valid value for config option `{}` in {}",
default_value,
- config_option.id.0,
+ config_option.config_id.0,
id
);
None
@@ -1369,8 +1369,12 @@ impl AcpConnection {
};
for (config_id, default_value, initial_value) in defaults_to_apply {
+ let Some(wire_value) =
+ acp_thread::config_options::value_to_v1(default_value.clone()).log_err()
+ else {
+ continue;
+ };
cx.spawn({
- let default_value_for_request = default_value.clone();
let session_id = session_id.clone();
let config_id_clone = config_id.clone();
let config_opts = config_options.clone();
@@ -1379,8 +1383,8 @@ impl AcpConnection {
let result = conn
.send_request(acp::SetSessionConfigOptionRequest::new(
session_id,
- config_id_clone.clone(),
- default_value_for_request,
+ acp::SessionConfigId::new(config_id_clone.0.clone()),
+ wire_value,
))
.block_task()
.await
@@ -1388,17 +1392,20 @@ impl AcpConnection {
if result.is_none() {
let mut opts = config_opts.borrow_mut();
- if let Some(opt) = opts.iter_mut().find(|o| o.id == config_id_clone) {
+ if let Some(opt) = opts
+ .iter_mut()
+ .find(|option| option.config_id == config_id_clone)
+ {
match (&mut opt.kind, &initial_value) {
(
- acp::SessionConfigKind::Select(select),
- acp::SessionConfigOptionValue::ValueId { value },
+ acp_v2::SessionConfigKind::Select(select),
+ acp_v2::SessionConfigOptionValue::Id { value },
) => {
select.current_value = value.clone();
}
(
- acp::SessionConfigKind::Boolean(boolean),
- acp::SessionConfigOptionValue::Boolean { value },
+ acp_v2::SessionConfigKind::Boolean(boolean),
+ acp_v2::SessionConfigOptionValue::Boolean { value },
) => {
boolean.current_value = *value;
}
@@ -1411,17 +1418,17 @@ impl AcpConnection {
.detach();
let mut opts = config_options.borrow_mut();
- if let Some(opt) = opts.iter_mut().find(|o| o.id == config_id) {
+ if let Some(opt) = opts.iter_mut().find(|option| option.config_id == config_id) {
match (&mut opt.kind, &default_value) {
(
- acp::SessionConfigKind::Select(select),
- acp::SessionConfigOptionValue::ValueId { value },
+ acp_v2::SessionConfigKind::Select(select),
+ acp_v2::SessionConfigOptionValue::Id { value },
) => {
select.current_value = value.clone();
}
(
- acp::SessionConfigKind::Boolean(boolean),
- acp::SessionConfigOptionValue::Boolean { value },
+ acp_v2::SessionConfigKind::Boolean(boolean),
+ acp_v2::SessionConfigOptionValue::Boolean { value },
) => {
boolean.current_value = *value;
}
@@ -1610,7 +1617,7 @@ impl AgentConnection for AcpConnection {
.await
.map_err(map_acp_error)?;
- let (modes, config_options) = config_state(response.modes, response.config_options);
+ let (modes, config_options) = config_state(response.modes, response.config_options)?;
let default_mode = self.defaults.mode();
if let Some(default_mode) = default_mode {
@@ -4078,7 +4085,7 @@ mod tests {
AgentConfigOptionValue::Boolean(true),
)]),
);
- let config_options = Rc::new(RefCell::new(vec![acp::SessionConfigOption::boolean(
+ let config_options = Rc::new(RefCell::new(vec![acp_v2::SessionConfigOption::boolean(
"web_search",
"Web Search",
false,
@@ -4096,46 +4103,113 @@ mod tests {
let requests = set_config_requests
.lock()
.expect("set config requests mutex poisoned");
- assert_eq!(requests.len(), 1);
assert_eq!(
- requests[0].config_id,
- acp::SessionConfigId::new("web_search")
- );
- assert_eq!(
- requests[0].value,
- acp::SessionConfigOptionValue::boolean(true)
+ requests.as_slice(),
+ &[serde_json::json!({
+ "sessionId": "session-config-defaults", "configId": "web_search",
+ "type": "boolean", "value": true
+ })]
);
let options = config_options.borrow();
assert!(
- matches!(&options[0].kind, acp::SessionConfigKind::Boolean(boolean) if boolean.current_value)
+ matches!(&options[0].kind, acp_v2::SessionConfigKind::Boolean(boolean) if boolean.current_value)
+ );
+ }
+
+ #[gpui::test]
+ async fn shared_config_values_use_v1_wire_shapes(cx: &mut gpui::TestAppContext) {
+ use acp_thread::AgentSessionConfigOptions;
+
+ let (connection, requests) = connect_config_defaults_test_agent(cx).await;
+ let config = ConfigOptions::new(Rc::new(RefCell::new(vec![
+ acp_v2::SessionConfigOption::boolean("config", "Config", false),
+ ])));
+ let options = AcpSessionConfigOptions {
+ session_id: acp::SessionId::new("session"),
+ connection: connection.connection.clone(),
+ state: config.config_options,
+ watch_tx: config.tx,
+ watch_rx: config.rx,
+ };
+ let original = options.config_options();
+ let unknown =
+ acp_v2::SessionConfigOptionValue::Other(acp_v2::OtherSessionConfigOptionValue::new(
+ "_custom",
+ serde_json::json!("private-value"),
+ Default::default(),
+ ));
+ assert!(
+ cx.update(|cx| options.set_config_option("config".into(), unknown, cx))
+ .await
+ .is_err()
+ );
+ assert_eq!(options.config_options(), original);
+ assert!(requests.lock().expect("requests").is_empty());
+
+ for value in [
+ acp_v2::SessionConfigOptionValue::id("choice"),
+ acp_v2::SessionConfigOptionValue::boolean(true),
+ ] {
+ let updated = cx
+ .update(|cx| options.set_config_option("config".into(), value, cx))
+ .await
+ .expect("supported v1 value");
+ assert!(updated.is_empty());
+ assert_eq!(options.config_options(), updated);
+ }
+ assert_eq!(
+ requests.lock().expect("requests").as_slice(),
+ &[
+ serde_json::json!({"sessionId": "session", "configId": "config", "value": "choice"}),
+ serde_json::json!({
+ "sessionId": "session", "configId": "config", "type": "boolean", "value": true
+ })
+ ]
);
}
async fn connect_config_defaults_test_agent(
cx: &mut gpui::TestAppContext,
- ) -> (
- AcpConnection,
- Arc<Mutex<Vec<acp::SetSessionConfigOptionRequest>>>,
- ) {
+ ) -> (AcpConnection, Arc<Mutex<Vec<serde_json::Value>>>) {
let set_config_requests = Arc::new(Mutex::new(Vec::new()));
- let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
+ let (client_transport, client_inspection) = agent_client_protocol::Channel::duplex();
+ let (agent_inspection, agent_transport) = agent_client_protocol::Channel::duplex();
+ cx.background_spawn({
+ let set_config_requests = set_config_requests.clone();
+ async move {
+ agent_client_protocol::Channel::bridge_with_inspection(
+ client_inspection,
+ agent_inspection,
+ move |message| {
+ if let agent_client_protocol::RawJsonRpcMessage::Request(request) = message
+ && request.method.as_ref() == "session/set_config_option"
+ {
+ set_config_requests
+ .lock()
+ .expect("set config requests mutex poisoned")
+ .push(
+ serde_json::to_value(&request.params)
+ .expect("raw config request parameters"),
+ );
+ }
+ Ok(())
+ },
+ |_| Ok(()),
+ )
+ .await
+ .log_err();
+ }
+ })
+ .detach();
cx.background_spawn(
Agent
.builder()
.name("config-defaults-test-agent")
.on_receive_request(
- {
- let set_config_requests = set_config_requests.clone();
- async move |req: acp::SetSessionConfigOptionRequest, responder, _cx| {
- set_config_requests
- .lock()
- .expect("set config requests mutex poisoned")
- .push(req);
-
- responder.respond(acp::SetSessionConfigOptionResponse::new(Vec::new()))
- }
+ async move |_request: acp::SetSessionConfigOptionRequest, responder, _cx| {
+ responder.respond(acp::SetSessionConfigOptionResponse::new(Vec::new()))
},
agent_client_protocol::on_receive_request!(),
)
@@ -5189,7 +5263,10 @@ exit 7
let session = sessions.get(&session_id).expect("loaded session");
assert_eq!(session.thread.entity_id(), thread.entity_id());
let options = session.config_options.as_ref().expect("loaded config");
- assert_eq!(*options.config_options.borrow(), updated_options);
+ assert_eq!(
+ *options.config_options.borrow(),
+ acp_thread::config_options::from_v1(updated_options).expect("shared config options")
+ );
}
#[gpui::test]
@@ -5739,16 +5816,17 @@ fn mcp_servers_for_project(project: &Entity<Project>, cx: &App) -> Vec<acp::McpS
fn config_state(
modes: Option<acp::SessionModeState>,
config_options: Option<Vec<acp::SessionConfigOption>>,
-) -> (
+) -> Result<(
Option<Rc<RefCell<acp::SessionModeState>>>,
- Option<Rc<RefCell<Vec<acp::SessionConfigOption>>>>,
-) {
+ Option<Rc<RefCell<Vec<acp_v2::SessionConfigOption>>>>,
+)> {
if let Some(opts) = config_options {
- return (None, Some(Rc::new(RefCell::new(opts))));
+ let opts = acp_thread::config_options::from_v1(opts)?;
+ return Ok((None, Some(Rc::new(RefCell::new(opts)))));
}
let modes = modes.map(|modes| Rc::new(RefCell::new(modes)));
- (modes, None)
+ Ok((modes, None))
}
struct AcpSessionModes {
@@ -5796,22 +5874,27 @@ impl acp_thread::AgentSessionModes for AcpSessionModes {
struct AcpSessionConfigOptions {
session_id: acp::SessionId,
connection: ConnectionTo<Agent>,
- state: Rc<RefCell<Vec<acp::SessionConfigOption>>>,
+ state: Rc<RefCell<Vec<acp_v2::SessionConfigOption>>>,
watch_tx: Rc<RefCell<watch::Sender<()>>>,
watch_rx: watch::Receiver<()>,
}
impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions {
- fn config_options(&self) -> Vec<acp::SessionConfigOption> {
+ fn config_options(&self) -> Vec<acp_v2::SessionConfigOption> {
self.state.borrow().clone()
}
fn set_config_option(
&self,
- config_id: acp::SessionConfigId,
- value: acp::SessionConfigOptionValue,
+ config_id: acp_v2::SessionConfigId,
+ value: acp_v2::SessionConfigOptionValue,
cx: &mut App,
- ) -> Task<Result<Vec<acp::SessionConfigOption>>> {
+ ) -> Task<Result<Vec<acp_v2::SessionConfigOption>>> {
+ let value = match acp_thread::config_options::value_to_v1(value) {
+ Ok(value) => value,
+ Err(error) => return Task::ready(Err(error)),
+ };
+ let config_id = acp::SessionConfigId::new(config_id.0);
let connection = self.connection.clone();
let session_id = self.session_id.clone();
let state = self.state.clone();
@@ -5826,9 +5909,10 @@ impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions {
.block_task()
.await?;
- *state.borrow_mut() = response.config_options.clone();
+ let config_options = acp_thread::config_options::from_v1(response.config_options)?;
+ *state.borrow_mut() = config_options.clone();
watch_tx.borrow_mut().send(()).ok();
- Ok(response.config_options)
+ Ok(config_options)
})
}
@@ -6148,7 +6232,12 @@ fn handle_session_notification(
}) = &notification.update
{
if let Some((config_opts_cell, tx_cell)) = &config_opts_data {
- *config_opts_cell.borrow_mut() = config_options.clone();
+ let Some(config_options) =
+ acp_thread::config_options::from_v1(config_options.clone()).log_err()
+ else {
+ return;
+ };
+ *config_opts_cell.borrow_mut() = config_options;
tx_cell.borrow_mut().send(()).ok();
}
}
diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs
index 1b36ff8b537..e4ed27c4613 100644
--- a/crates/agent_servers/src/agent_servers.rs
+++ b/crates/agent_servers/src/agent_servers.rs
@@ -13,6 +13,7 @@ use project::{AgentId, Project, agent_server_store::AgentServerStore};
use acp_thread::AgentConnection;
use agent_client_protocol::schema::v1 as acp_schema;
+use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::Result;
use gpui::{App, AppContext, Entity, Task};
use settings::{AgentConfigOptionValue, SettingsStore};
@@ -87,16 +88,16 @@ pub trait AgentServer: Send {
fn favorite_config_option_value_ids(
&self,
- _config_id: &acp_schema::SessionConfigId,
+ _config_id: &acp_v2::SessionConfigId,
_cx: &mut App,
- ) -> HashSet<acp_schema::SessionConfigValueId> {
+ ) -> HashSet<acp_v2::SessionConfigValueId> {
HashSet::default()
}
fn toggle_favorite_config_option_value(
&self,
- _config_id: acp_schema::SessionConfigId,
- _value_id: acp_schema::SessionConfigValueId,
+ _config_id: acp_v2::SessionConfigId,
+ _value_id: acp_v2::SessionConfigValueId,
_should_be_favorite: bool,
_fs: Arc<dyn Fs>,
_cx: &App,
diff --git a/crates/agent_servers/src/custom.rs b/crates/agent_servers/src/custom.rs
index 9d682fdcbc9..e3c6c6b73ed 100644
--- a/crates/agent_servers/src/custom.rs
+++ b/crates/agent_servers/src/custom.rs
@@ -1,6 +1,7 @@
use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::{Context as _, Result};
use collections::HashSet;
use fs::Fs;
@@ -54,9 +55,9 @@ impl AgentServer for CustomAgentServer {
fn favorite_config_option_value_ids(
&self,
- config_id: &acp::SessionConfigId,
+ config_id: &acp_v2::SessionConfigId,
cx: &mut App,
- ) -> HashSet<acp::SessionConfigValueId> {
+ ) -> HashSet<acp_v2::SessionConfigValueId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
@@ -71,7 +72,7 @@ impl AgentServer for CustomAgentServer {
values
.iter()
.cloned()
- .map(acp::SessionConfigValueId::new)
+ .map(acp_v2::SessionConfigValueId::new)
.collect()
})
.unwrap_or_default()
@@ -79,8 +80,8 @@ impl AgentServer for CustomAgentServer {
fn toggle_favorite_config_option_value(
&self,
- config_id: acp::SessionConfigId,
- value_id: acp::SessionConfigValueId,
+ config_id: acp_v2::SessionConfigId,
+ value_id: acp_v2::SessionConfigValueId,
should_be_favorite: bool,
fs: Arc<dyn Fs>,
cx: &App,
diff --git a/crates/agent_ui/src/config_options.rs b/crates/agent_ui/src/config_options.rs
index cbefa713c2b..fc6ce2d04dd 100644
--- a/crates/agent_ui/src/config_options.rs
+++ b/crates/agent_ui/src/config_options.rs
@@ -1,7 +1,7 @@
use std::{cmp::Reverse, rc::Rc, sync::Arc};
use acp_thread::AgentSessionConfigOptions;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_servers::AgentServer;
use collections::HashSet;
@@ -139,7 +139,7 @@ impl ConfigOptionsView {
.config_options()
.into_iter()
.find(|option| option.category.as_ref() == Some(&category) && predicate(option))
- .map(|option| option.id)
+ .map(|option| option.config_id)
}
fn can_cycle_config_option(option: &acp::SessionConfigOption, favorites_only: bool) -> bool {
@@ -171,7 +171,7 @@ impl ConfigOptionsView {
.config_options
.config_options()
.into_iter()
- .find(|option| &option.id == config_id)?;
+ .find(|option| &option.config_id == config_id)?;
match &option.kind {
acp::SessionConfigKind::Select(_) => {
@@ -202,7 +202,7 @@ impl ConfigOptionsView {
(current_index + 1) % options.len()
};
- Some(acp::SessionConfigOptionValue::value_id(
+ Some(acp::SessionConfigOptionValue::id(
options[next_index].value.clone(),
))
}
@@ -225,7 +225,7 @@ impl ConfigOptionsView {
config_options
.config_options()
.into_iter()
- .map(|option| option.id)
+ .map(|option| option.config_id)
.collect()
}
@@ -253,6 +253,12 @@ impl ConfigOptionsView {
config_options
.config_options()
.into_iter()
+ .filter(|option| {
+ matches!(
+ &option.kind,
+ acp::SessionConfigKind::Select(_) | acp::SessionConfigKind::Boolean(_)
+ )
+ })
.map(|option| {
let config_options = config_options.clone();
let agent_server = agent_server.clone();
@@ -260,7 +266,7 @@ impl ConfigOptionsView {
cx.new(|cx| {
ConfigOptionSelector::new(
config_options,
- option.id.clone(),
+ option.config_id,
agent_server,
fs,
window,
@@ -309,7 +315,7 @@ impl ConfigOptionSelector {
let current_option = config_options
.config_options()
.into_iter()
- .find(|opt| opt.id == config_id);
+ .find(|opt| opt.config_id == config_id);
let option_count = current_option
.as_ref()
.map(count_config_options)
@@ -363,7 +369,7 @@ impl ConfigOptionSelector {
self.config_options
.config_options()
.into_iter()
- .find(|opt| opt.id == self.config_id)
+ .find(|opt| opt.config_id == self.config_id)
}
fn config_id(&self) -> &acp::SessionConfigId {
@@ -371,6 +377,13 @@ impl ConfigOptionSelector {
}
fn toggle_picker(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
+ if !self
+ .current_option()
+ .is_some_and(|option| matches!(option.kind, acp::SessionConfigKind::Select(_)))
+ {
+ return false;
+ }
+
if let Some(picker_handle) = &self.picker_handle {
picker_handle.toggle(window, cx);
true
@@ -401,7 +414,7 @@ impl ConfigOptionSelector {
option.category.as_ref() == Some(category)
&& matches!(&option.kind, acp::SessionConfigKind::Select(_))
})
- .is_some_and(|option| option.id == self.config_id)
+ .is_some_and(|option| option.config_id == self.config_id)
}
fn render_trigger_button(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Button {
@@ -432,7 +445,7 @@ impl ConfigOptionSelector {
};
Button::new(
- ElementId::Name(format!("config-option-{}", option.id.0).into()),
+ ElementId::Name(format!("config-option-{}", option.config_id.0).into()),
display_name,
)
.label_size(LabelSize::Small)
@@ -541,7 +554,7 @@ impl Render for ConfigOptionSelector {
.into_any_element()
}
acp::SessionConfigKind::Boolean(boolean) => {
- let option_id = option.id.clone();
+ let option_id = option.config_id.clone();
let option_name: SharedString = option.name.clone().into();
let option_description: Option<SharedString> =
option.description.clone().map(Into::into);
@@ -586,6 +599,13 @@ impl Render for ConfigOptionSelector {
.label_color(Color::Muted)
.disabled(self.setting_value)
.on_click(move |state, _window, cx| {
+ if !config_options.config_options().iter().any(|option| {
+ option.config_id == config_id
+ && matches!(&option.kind, acp::SessionConfigKind::Boolean(_))
+ }) {
+ return;
+ }
+
let next_value = matches!(state, ToggleState::Selected);
agent_server.set_default_config_option(
config_id.0.as_ref(),
@@ -720,7 +740,11 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
fn can_select(&self, ix: usize, _window: &mut Window, _cx: &mut Context<Picker<Self>>) -> bool {
match self.filtered_entries.get(ix) {
- Some(ConfigOptionPickerEntry::Option(_)) => true,
+ Some(ConfigOptionPickerEntry::Option(option)) => {
+ extract_options(&self.config_options, &self.config_id)
+ .iter()
+ .any(|current| current.value == option.value)
+ }
Some(ConfigOptionPickerEntry::Separator(_)) | None => false,
}
}
@@ -777,6 +801,14 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
if let Some(ConfigOptionPickerEntry::Option(option)) =
self.filtered_entries.get(self.selected_index)
{
+ // A deployed picker may outlive the option kind or choices that created it.
+ if !extract_options(&self.config_options, &self.config_id)
+ .iter()
+ .any(|current| current.value == option.value)
+ {
+ return;
+ }
+
self.agent_server.set_default_config_option(
self.config_id.0.as_ref(),
Some(AgentConfigOptionValue::ValueId(option.value.0.to_string())),
@@ -785,7 +817,7 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
);
let task = self.config_options.set_config_option(
self.config_id.clone(),
- acp::SessionConfigOptionValue::value_id(option.value.clone()),
+ acp::SessionConfigOptionValue::id(option.value.clone()),
cx,
);
@@ -871,6 +903,7 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
let value_id = option.value.clone();
let agent_server = self.agent_server.clone();
let fs = self.fs.clone();
+ let config_options = self.config_options.clone();
IconButton::new(("toggle-favorite-config-option", ix), icon)
.layer(ElevationIndex::ElevatedSurface)
@@ -878,6 +911,13 @@ impl PickerDelegate for ConfigOptionPickerDelegate {
.icon_size(IconSize::Small)
.tooltip(Tooltip::text(tooltip))
.on_click(move |_, _, cx| {
+ if !extract_options(&config_options, &config_id)
+ .iter()
+ .any(|current| current.value == value_id)
+ {
+ return;
+ }
+
agent_server.toggle_favorite_config_option_value(
config_id.clone(),
value_id.clone(),
@@ -923,7 +963,7 @@ fn extract_options(
let Some(option) = config_options
.config_options()
.into_iter()
- .find(|opt| &opt.id == config_id)
+ .find(|opt| &opt.config_id == config_id)
else {
return Vec::new();
};
@@ -963,7 +1003,7 @@ fn get_current_select_value(
config_options
.config_options()
.into_iter()
- .find(|opt| &opt.id == config_id)
+ .find(|opt| &opt.config_id == config_id)
.and_then(|opt| match &opt.kind {
acp::SessionConfigKind::Select(select) => Some(select.current_value.clone()),
_ => None,
@@ -974,7 +1014,7 @@ fn setting_value_for_config_option_value(
value: &acp::SessionConfigOptionValue,
) -> Option<AgentConfigOptionValue> {
match value {
- acp::SessionConfigOptionValue::ValueId { value } => {
+ acp::SessionConfigOptionValue::Id { value } => {
Some(AgentConfigOptionValue::ValueId(value.0.to_string()))
}
acp::SessionConfigOptionValue::Boolean { value } => {
@@ -1151,7 +1191,7 @@ mod tests {
config_options.set_values.borrow().as_slice(),
&[(
"mode".to_string(),
- acp::SessionConfigOptionValue::value_id("manual")
+ acp::SessionConfigOptionValue::id("manual")
)]
);
}
@@ -1278,6 +1318,103 @@ mod tests {
assert!(!handled);
}
+ #[gpui::test]
+ fn unknown_config_options_survive_live_selector_updates(cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ let settings_store = SettingsStore::test(cx);
+ cx.set_global(settings_store);
+ theme_settings::init(theme::LoadThemes::JustBase, cx);
+ editor::init(cx);
+ });
+ let category = acp::SessionConfigOptionCategory::Mode;
+ let unknown = acp::SessionConfigOption::new(
+ "mode",
+ "Mode",
+ acp::SessionConfigKind::Other(acp::OtherSessionConfigKind::new(
+ "_future",
+ std::collections::BTreeMap::from([(
+ "currentValue".to_string(),
+ serde_json::json!({"opaque": [1, true]}),
+ )]),
+ )),
+ )
+ .category(category.clone());
+ let config_options = Rc::new(TestSessionConfigOptions::new(vec![unknown.clone()]));
+ let agent_server = Rc::new(TestAgentServer::default());
+ let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
+ let cx = cx.add_empty_window();
+ let view = cx.update(|window, cx| {
+ let config_options: Rc<dyn AgentSessionConfigOptions> = config_options.clone();
+ let agent_server: Rc<dyn AgentServer> = agent_server.clone();
+ cx.new(|cx| ConfigOptionsView::new(config_options, agent_server, fs, window, cx))
+ });
+ cx.update(|window, cx| {
+ view.update(cx, |view, cx| {
+ assert!(view.selectors.is_empty());
+ assert_eq!(
+ view.config_option_ids,
+ vec![acp::SessionConfigId::new("mode")]
+ );
+ assert!(!view.toggle_category_picker(category.clone(), window, cx));
+ assert!(!view.cycle_category_option(category.clone(), false, cx));
+ });
+ });
+ assert_eq!(config_options.config_options(), vec![unknown.clone()]);
+
+ config_options.replace_options(vec![
+ acp::SessionConfigOption::select(
+ "mode",
+ "Mode",
+ "auto",
+ vec![
+ acp::SessionConfigSelectOption::new("auto", "Auto"),
+ acp::SessionConfigSelectOption::new("manual", "Manual"),
+ ],
+ )
+ .category(category.clone()),
+ ]);
+ cx.run_until_parked();
+ let selector = cx.update(|window, cx| {
+ view.update(cx, |view, cx| {
+ assert_eq!(view.selectors.len(), 1);
+ assert!(view.toggle_category_picker(category.clone(), window, cx));
+ assert!(view.cycle_category_option(category.clone(), false, cx));
+ view.selectors.first().expect("select control").clone()
+ })
+ });
+ let picker = cx.update(|_, cx| selector.read(cx).picker.clone().expect("select picker"));
+
+ config_options.replace_options(vec![unknown.clone()]);
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ view.update(cx, |view, cx| {
+ assert!(view.selectors.is_empty());
+ assert!(!view.toggle_category_picker(category.clone(), window, cx));
+ assert!(!view.cycle_category_option(category.clone(), false, cx));
+ });
+ assert!(!selector.update(cx, |selector, cx| selector.toggle_picker(window, cx)));
+ picker.update(cx, |picker, cx| {
+ assert!(!picker.delegate.can_select(0, window, cx));
+ picker.delegate.confirm(false, window, cx);
+ });
+ });
+ assert_eq!(config_options.config_options(), vec![unknown]);
+ assert_eq!(
+ config_options.set_values.borrow().as_slice(),
+ &[(
+ "mode".to_string(),
+ acp::SessionConfigOptionValue::id("manual")
+ )]
+ );
+ assert_eq!(
+ agent_server.saved_defaults.lock().as_slice(),
+ &[(
+ "mode".to_string(),
+ Some(AgentConfigOptionValue::ValueId("manual".to_string()))
+ )]
+ );
+ }
+
#[derive(Default)]
struct TestAgentServer {
saved_defaults: Arc<Mutex<Vec<(String, Option<AgentConfigOptionValue>)>>>,
@@ -1321,6 +1458,7 @@ mod tests {
struct TestSessionConfigOptions {
options: RefCell<Vec<acp::SessionConfigOption>>,
set_values: RefCell<Vec<(String, acp::SessionConfigOptionValue)>>,
+ updates: RefCell<watch::Sender<()>>,
}
impl TestSessionConfigOptions {
@@ -1328,8 +1466,14 @@ mod tests {
Self {
options: RefCell::new(options),
set_values: RefCell::new(Vec::new()),
+ updates: RefCell::new(watch::channel(()).0),
}
}
+
+ fn replace_options(&self, options: Vec<acp::SessionConfigOption>) {
+ *self.options.borrow_mut() = options;
+ self.updates.borrow_mut().send(()).expect("config watcher");
+ }
}
impl AgentSessionConfigOptions for TestSessionConfigOptions {
@@ -1349,11 +1493,14 @@ mod tests {
let options = {
let mut options = self.options.borrow_mut();
- if let Some(option) = options.iter_mut().find(|option| option.id == config_id) {
+ if let Some(option) = options
+ .iter_mut()
+ .find(|option| option.config_id == config_id)
+ {
match (&mut option.kind, value) {
(
acp::SessionConfigKind::Select(select),
- acp::SessionConfigOptionValue::ValueId { value },
+ acp::SessionConfigOptionValue::Id { value },
) => {
select.current_value = value;
}
@@ -1371,5 +1518,9 @@ mod tests {
Task::ready(Ok(options))
}
+
+ fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
+ Some(self.updates.borrow().receiver())
+ }
}
}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 0aaf8d85b97..5327b227c93 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -12982,7 +12982,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp_v1::SessionConfigOptionCategory::ThoughtLevel,
+ acp_v2::SessionConfigOptionCategory::ThoughtLevel,
false,
cx,
)
@@ -13001,7 +13001,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp_v1::SessionConfigOptionCategory::ThoughtLevel,
+ acp_v2::SessionConfigOptionCategory::ThoughtLevel,
window,
cx,
)
@@ -13049,7 +13049,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp_v1::SessionConfigOptionCategory::Mode,
+ acp_v2::SessionConfigOptionCategory::Mode,
window,
cx,
)
@@ -13072,7 +13072,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp_v1::SessionConfigOptionCategory::Mode,
+ acp_v2::SessionConfigOptionCategory::Mode,
false,
cx,
)
@@ -13099,7 +13099,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp_v1::SessionConfigOptionCategory::Model,
+ acp_v2::SessionConfigOptionCategory::Model,
window,
cx,
)
@@ -13121,7 +13121,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp_v1::SessionConfigOptionCategory::Model,
+ acp_v2::SessionConfigOptionCategory::Model,
true,
cx,
)