Skip to content

armgit / zed

Public Imported from GitHub
0

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

agent: Use config values for modes and defaults (#65520)

Ben Brandt10644801ad60
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 20ef8bc094a..b026eeac46f 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -3578,7 +3578,7 @@ pub enum AcpThreadEvent {
PromptCapabilitiesUpdated,
Refusal,
AvailableCommandsUpdated(Vec<acp_v2::AvailableCommand>),
- ModeUpdated(acp_v1::SessionModeId),
+ ModeUpdated(acp_v2::SessionConfigValueId),
ConfigOptionsUpdated(Vec<acp_v2::SessionConfigOption>),
WorkingDirectoriesUpdated,
}
@@ -4444,7 +4444,9 @@ impl AcpThread {
acp_v1::SessionUpdate::CurrentModeUpdate(acp_v1::CurrentModeUpdate {
current_mode_id,
..
- }) => cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id)),
+ }) => cx.emit(AcpThreadEvent::ModeUpdated(
+ acp_v2::SessionConfigValueId::new(current_mode_id.0),
+ )),
acp_v1::SessionUpdate::ConfigOptionUpdate(acp_v1::ConfigOptionUpdate {
config_options,
..
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index dbba02bb1ca..672b3697fe1 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -351,11 +351,11 @@ pub trait AgentTelemetry {
}
pub trait AgentSessionModes {
- fn current_mode(&self) -> acp_v1::SessionModeId;
+ fn current_mode(&self) -> acp_v2::SessionConfigValueId;
- fn all_modes(&self) -> Vec<acp_v1::SessionMode>;
+ fn all_modes(&self) -> Vec<acp_v2::SessionConfigSelectOption>;
- fn set_mode(&self, mode: acp_v1::SessionModeId, cx: &mut App) -> Task<Result<()>>;
+ fn set_mode(&self, mode: acp_v2::SessionConfigValueId, cx: &mut App) -> Task<Result<()>>;
}
pub trait AgentSessionConfigOptions {
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index d43a76860a8..666d3807202 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -339,13 +339,13 @@ pub struct AcpConnection {
#[derive(Clone, Default)]
struct AcpConnectionDefaults {
- mode: Rc<RefCell<Option<acp::SessionModeId>>>,
+ mode: Rc<RefCell<Option<acp_v2::SessionConfigValueId>>>,
config_options: Rc<RefCell<HashMap<String, AgentConfigOptionValue>>>,
}
impl AcpConnectionDefaults {
fn new(
- mode: Option<acp::SessionModeId>,
+ mode: Option<acp_v2::SessionConfigValueId>,
config_options: HashMap<String, AgentConfigOptionValue>,
) -> Self {
Self {
@@ -354,7 +354,7 @@ impl AcpConnectionDefaults {
}
}
- fn mode(&self) -> Option<acp::SessionModeId> {
+ fn mode(&self) -> Option<acp_v2::SessionConfigValueId> {
self.mode.borrow().clone()
}
@@ -364,7 +364,7 @@ impl AcpConnectionDefaults {
fn set(
&self,
- mode: Option<acp::SessionModeId>,
+ mode: Option<acp_v2::SessionConfigValueId>,
config_options: HashMap<String, AgentConfigOptionValue>,
) {
*self.mode.borrow_mut() = mode;
@@ -393,7 +393,9 @@ impl AcpConnectionDefaults {
} => default_config_options.clone(),
};
self.set(
- agent_settings.default_mode().map(acp::SessionModeId::new),
+ agent_settings
+ .default_mode()
+ .map(acp_v2::SessionConfigValueId::new),
default_config_options,
);
}
@@ -591,7 +593,7 @@ pub async fn connect(
project: Entity<Project>,
command: AgentServerCommand,
agent_server_store: WeakEntity<AgentServerStore>,
- default_mode: Option<acp::SessionModeId>,
+ default_mode: Option<acp_v2::SessionConfigValueId>,
default_config_options: HashMap<String, AgentConfigOptionValue>,
cx: &mut AsyncApp,
) -> Result<Rc<dyn AgentConnection>> {
@@ -809,7 +811,7 @@ impl AcpConnection {
project: Entity<Project>,
command: AgentServerCommand,
agent_server_store: WeakEntity<AgentServerStore>,
- default_mode: Option<acp::SessionModeId>,
+ default_mode: Option<acp_v2::SessionConfigValueId>,
default_config_options: HashMap<String, AgentConfigOptionValue>,
cx: &mut AsyncApp,
) -> Result<Self> {
@@ -1708,6 +1710,7 @@ impl AgentConnection for AcpConnection {
let default_mode = self.defaults.mode();
if let Some(default_mode) = default_mode {
+ let default_mode = acp::SessionModeId::new(default_mode.0);
if let Some(modes) = modes.as_ref() {
let mut modes_ref = modes.borrow_mut();
let has_mode = modes_ref
@@ -2754,6 +2757,40 @@ mod tests {
use super::*;
use settings::Settings as _;
+ #[test]
+ fn test_legacy_modes_use_config_choices_without_overriding_config_options() {
+ let id = acp::SessionModeId::new("opaque/手動");
+ let meta =
+ acp::Meta::from_iter([("custom".into(), serde_json::json!({"keep": [null, 7]}))]);
+ let mode = acp::SessionMode::new(id.clone(), "Manual label")
+ .description("Mode description")
+ .meta(meta.clone());
+ let choice = mode_from_v1(&mode);
+ assert!(Arc::ptr_eq(&choice.value.0, &id.0));
+ assert_eq!(choice.name, mode.name);
+ assert_eq!(choice.description, mode.description);
+ assert_eq!(choice.meta, Some(meta));
+
+ let modes =
+ acp::SessionModeState::new(id, vec![mode, acp::SessionMode::new("auto", "Auto")]);
+ let (legacy, config) = config_state(Some(modes.clone()), None).expect("legacy modes");
+ assert!(config.is_none());
+ let choices = legacy
+ .expect("legacy fallback")
+ .borrow()
+ .available_modes
+ .iter()
+ .map(mode_from_v1)
+ .map(|choice| choice.value.to_string())
+ .collect::<Vec<_>>();
+ assert_eq!(choices, ["opaque/手動", "auto"]);
+
+ let (legacy, config) =
+ config_state(Some(modes), Some(Vec::new())).expect("config options take precedence");
+ assert!(legacy.is_none());
+ assert!(config.is_some());
+ }
+
#[test]
fn test_process_terminal_responses_preserve_v1_payloads() {
use acp_thread::ProcessOutput;
@@ -4355,6 +4392,77 @@ mod tests {
.expect("failed to receive ACP connection")
}
+ #[gpui::test]
+ async fn legacy_mode_set_preserves_wire_ids_and_rolls_back_on_failure(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ use acp_thread::AgentSessionModes as _;
+
+ let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ cx.background_spawn(
+ Agent
+ .builder()
+ .on_receive_request(
+ {
+ let requests = requests.clone();
+ async move |request: acp::SetSessionModeRequest, responder, _cx| {
+ let rejected = request.mode_id.0.as_ref() == "reject";
+ requests.lock().expect("mode requests").push(request);
+ if rejected {
+ responder.respond_with_error(acp::Error::invalid_params())
+ } else {
+ responder.respond(acp::SetSessionModeResponse::default())
+ }
+ }
+ },
+ agent_client_protocol::on_receive_request!(),
+ )
+ .connect_to(agent_transport),
+ )
+ .detach();
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ cx.background_spawn(Client.builder().connect_with(
+ client_transport,
+ move |connection: ConnectionTo<Agent>| async move {
+ sender.send(connection).expect("client connection");
+ futures::future::pending::<Result<(), acp::Error>>().await
+ },
+ ))
+ .detach();
+ let modes = AcpSessionModes {
+ session_id: acp_v2::SessionId::new("mode-session"),
+ connection: receiver.await.expect("client connected"),
+ state: Rc::new(RefCell::new(acp::SessionModeState::new(
+ "auto",
+ vec![
+ acp::SessionMode::new("auto", "Auto"),
+ acp::SessionMode::new("opaque/手動", "Manual"),
+ ],
+ ))),
+ };
+ let selected = acp_v2::SessionConfigValueId::new("opaque/手動");
+ let change = cx.update(|cx| modes.set_mode(selected.clone(), cx));
+ assert_eq!(modes.current_mode(), selected);
+ change.await.expect("mode changed");
+ let rejected = acp_v2::SessionConfigValueId::new("reject");
+ let change = cx.update(|cx| modes.set_mode(rejected.clone(), cx));
+ assert_eq!(modes.current_mode(), rejected);
+ change.await.expect_err("peer rejected mode change");
+ assert_eq!(modes.current_mode(), selected);
+ let requests = requests.lock().expect("mode requests");
+ assert_eq!(
+ requests
+ .iter()
+ .map(|request| (request.session_id.to_string(), request.mode_id.to_string()))
+ .collect::<Vec<_>>(),
+ [
+ ("mode-session".into(), "opaque/手動".into()),
+ ("mode-session".into(), "reject".into())
+ ],
+ );
+ }
+
#[gpui::test]
async fn settings_changes_refresh_active_connection_defaults(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
@@ -4378,7 +4486,7 @@ mod tests {
default_mode: Some("manual".to_string()),
default_config_options: HashMap::from_iter([(
"mode".to_string(),
- AgentConfigOptionValue::from("manual"),
+ AgentConfigOptionValue::from("config-value"),
)]),
favorite_config_option_values: HashMap::default(),
}
@@ -4391,7 +4499,7 @@ mod tests {
assert_eq!(
harness.connection.defaults.mode(),
- Some(acp::SessionModeId::new("manual"))
+ Some(acp_v2::SessionConfigValueId::new("manual"))
);
assert_eq!(
harness
@@ -4400,7 +4508,7 @@ mod tests {
.config_option("mode")
.as_ref()
.and_then(AgentConfigOptionValue::as_value_id),
- Some("manual"),
+ Some("config-value"),
);
cx.update(|cx| {
@@ -7306,16 +7414,31 @@ struct AcpSessionModes {
state: Rc<RefCell<acp::SessionModeState>>,
}
+fn mode_from_v1(mode: &acp::SessionMode) -> acp_v2::SessionConfigSelectOption {
+ acp_v2::SessionConfigSelectOption::new(
+ acp_v2::SessionConfigValueId::new(mode.id.0.clone()),
+ mode.name.clone(),
+ )
+ .description(mode.description.clone())
+ .meta(mode.meta.clone())
+}
+
impl acp_thread::AgentSessionModes for AcpSessionModes {
- fn current_mode(&self) -> acp::SessionModeId {
- self.state.borrow().current_mode_id.clone()
+ fn current_mode(&self) -> acp_v2::SessionConfigValueId {
+ acp_v2::SessionConfigValueId::new(self.state.borrow().current_mode_id.0.clone())
}
- fn all_modes(&self) -> Vec<acp::SessionMode> {
- self.state.borrow().available_modes.clone()
+ fn all_modes(&self) -> Vec<acp_v2::SessionConfigSelectOption> {
+ self.state
+ .borrow()
+ .available_modes
+ .iter()
+ .map(mode_from_v1)
+ .collect()
}
- fn set_mode(&self, mode_id: acp::SessionModeId, cx: &mut App) -> Task<Result<()>> {
+ fn set_mode(&self, mode_id: acp_v2::SessionConfigValueId, cx: &mut App) -> Task<Result<()>> {
+ let mode_id = acp::SessionModeId::new(mode_id.0);
let connection = self.connection.clone();
let session_id = acp::SessionId::new(self.session_id.0.clone());
let old_mode_id;
diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs
index e4ed27c4613..0bc7394d5b4 100644
--- a/crates/agent_servers/src/agent_servers.rs
+++ b/crates/agent_servers/src/agent_servers.rs
@@ -12,7 +12,6 @@ use http_client::read_no_proxy_from_env;
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};
@@ -61,13 +60,13 @@ pub trait AgentServer: Send {
fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
- fn default_mode(&self, _cx: &App) -> Option<acp_schema::SessionModeId> {
+ fn default_mode(&self, _cx: &App) -> Option<acp_v2::SessionConfigValueId> {
None
}
fn set_default_mode(
&self,
- _mode_id: Option<acp_schema::SessionModeId>,
+ _mode_id: Option<acp_v2::SessionConfigValueId>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
diff --git a/crates/agent_servers/src/custom.rs b/crates/agent_servers/src/custom.rs
index 45b8df58358..c84bd8034cd 100644
--- a/crates/agent_servers/src/custom.rs
+++ b/crates/agent_servers/src/custom.rs
@@ -1,6 +1,5 @@
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;
@@ -40,7 +39,7 @@ impl AgentServer for CustomAgentServer {
IconName::Terminal
}
- fn default_mode(&self, cx: &App) -> Option<acp::SessionModeId> {
+ fn default_mode(&self, cx: &App) -> Option<acp_v2::SessionConfigValueId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
@@ -50,7 +49,7 @@ impl AgentServer for CustomAgentServer {
settings
.as_ref()
- .and_then(|s| s.default_mode().map(acp::SessionModeId::new))
+ .and_then(|s| s.default_mode().map(acp_v2::SessionConfigValueId::new))
}
fn favorite_config_option_value_ids(
@@ -125,7 +124,12 @@ impl AgentServer for CustomAgentServer {
});
}
- fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
+ fn set_default_mode(
+ &self,
+ mode_id: Option<acp_v2::SessionConfigValueId>,
+ fs: Arc<dyn Fs>,
+ cx: &mut App,
+ ) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, _cx| {
let settings = settings
diff --git a/crates/agent_ui/src/mode_selector.rs b/crates/agent_ui/src/mode_selector.rs
index 46c1543bd25..34242c1ad5e 100644
--- a/crates/agent_ui/src/mode_selector.rs
+++ b/crates/agent_ui/src/mode_selector.rs
@@ -1,5 +1,5 @@
use acp_thread::AgentSessionModes;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_servers::AgentServer;
use fs::Fs;
@@ -50,19 +50,19 @@ impl ModeSelector {
let current_index = all_modes
.iter()
- .position(|mode| mode.id.0 == current_mode.0)
+ .position(|mode| mode.value == current_mode)
.unwrap_or(0);
if let Some(next_mode) = all_modes.get((current_index + 1) % all_modes.len()) {
- self.set_mode(next_mode.id.clone(), cx);
+ self.set_mode(next_mode.value.clone(), cx);
}
}
- pub fn mode(&self) -> acp::SessionModeId {
+ pub fn mode(&self) -> acp::SessionConfigValueId {
self.connection.current_mode()
}
- pub fn set_mode(&mut self, mode: acp::SessionModeId, cx: &mut Context<Self>) {
+ pub fn set_mode(&mut self, mode: acp::SessionConfigValueId, cx: &mut Context<Self>) {
self.agent_server
.set_default_mode(Some(mode.clone()), self.fs.clone(), cx);
@@ -97,7 +97,7 @@ impl ModeSelector {
let side = documentation_aside_side(cx);
for mode in all_modes {
- let is_selected = &mode.id == &current_mode;
+ let is_selected = &mode.value == &current_mode;
let entry = ContextMenuEntry::new(mode.name.clone())
.toggleable(IconPosition::End, is_selected);
@@ -112,7 +112,7 @@ impl ModeSelector {
};
menu.push_item(entry.handler({
- let mode_id = mode.id.clone();
+ let mode_id = mode.value.clone();
let weak_self = weak_self.clone();
move |_window, cx| {
weak_self
@@ -136,7 +136,7 @@ impl Render for ModeSelector {
.connection
.all_modes()
.iter()
- .find(|mode| mode.id == current_mode_id)
+ .find(|mode| mode.value == current_mode_id)
.map(|mode| mode.name.clone())
.unwrap_or_else(|| "Unknown".into());
@@ -217,23 +217,51 @@ mod tests {
let selector = cx.new(|_| ModeSelector::new(session_modes, agent_server, fs));
selector.update(cx, |selector, cx| {
- selector.set_mode(acp::SessionModeId::new("manual"), cx);
+ selector.set_mode(acp::SessionConfigValueId::new("manual"), cx);
});
});
assert_eq!(
agent_server.saved_defaults.lock().as_slice(),
- &[Some(acp::SessionModeId::new("manual"))]
+ &[Some(acp::SessionConfigValueId::new("manual"))]
);
assert_eq!(
session_modes.set_modes.borrow().as_slice(),
- &[acp::SessionModeId::new("manual")]
+ &[acp::SessionConfigValueId::new("manual")]
+ );
+ }
+
+ #[gpui::test]
+ fn cycling_modes_preserves_choice_order_and_wraps(cx: &mut TestAppContext) {
+ let agent_server = Rc::new(TestAgentServer::default());
+ let session_modes = Rc::new(TestSessionModes::new());
+ let fs: Arc<dyn Fs> = FakeFs::new(cx.executor());
+ let cx = cx.add_empty_window();
+ let selector = cx.new_window_entity(|_window, _cx| {
+ ModeSelector::new(session_modes.clone(), agent_server.clone(), fs)
+ });
+
+ for _ in 0..3 {
+ selector.update_in(cx, |selector, window, cx| {
+ selector.cycle_mode(window, cx);
+ });
+ }
+
+ let expected = [
+ acp::SessionConfigValueId::new("manual"),
+ acp::SessionConfigValueId::new("ask"),
+ acp::SessionConfigValueId::new("auto"),
+ ];
+ assert_eq!(session_modes.set_modes.borrow().as_slice(), &expected);
+ assert_eq!(
+ agent_server.saved_defaults.lock().as_slice(),
+ expected.map(Some).as_slice()
);
}
#[derive(Default)]
struct TestAgentServer {
- saved_defaults: Arc<Mutex<Vec<Option<acp::SessionModeId>>>>,
+ saved_defaults: Arc<Mutex<Vec<Option<acp::SessionConfigValueId>>>>,
}
impl AgentServer for TestAgentServer {
@@ -260,7 +288,7 @@ mod tests {
fn set_default_mode(
&self,
- mode_id: Option<acp::SessionModeId>,
+ mode_id: Option<acp::SessionConfigValueId>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
@@ -269,32 +297,37 @@ mod tests {
}
struct TestSessionModes {
- current_mode: RefCell<acp::SessionModeId>,
- set_modes: RefCell<Vec<acp::SessionModeId>>,
+ current_mode: RefCell<acp::SessionConfigValueId>,
+ set_modes: RefCell<Vec<acp::SessionConfigValueId>>,
}
impl TestSessionModes {
fn new() -> Self {
Self {
- current_mode: RefCell::new(acp::SessionModeId::new("auto")),
+ current_mode: RefCell::new(acp::SessionConfigValueId::new("auto")),
set_modes: RefCell::new(Vec::new()),
}
}
}
impl AgentSessionModes for TestSessionModes {
- fn current_mode(&self) -> acp::SessionModeId {
+ fn current_mode(&self) -> acp::SessionConfigValueId {
self.current_mode.borrow().clone()
}
- fn all_modes(&self) -> Vec<acp::SessionMode> {
+ fn all_modes(&self) -> Vec<acp::SessionConfigSelectOption> {
vec![
- acp::SessionMode::new("auto", "Auto"),
- acp::SessionMode::new("manual", "Manual"),
+ acp::SessionConfigSelectOption::new("auto", "Auto"),
+ acp::SessionConfigSelectOption::new("manual", "Manual"),
+ acp::SessionConfigSelectOption::new("ask", "Ask"),
]
}
- fn set_mode(&self, mode: acp::SessionModeId, _cx: &mut App) -> Task<anyhow::Result<()>> {
+ fn set_mode(
+ &self,
+ mode: acp::SessionConfigValueId,
+ _cx: &mut App,
+ ) -> Task<anyhow::Result<()>> {
*self.current_mode.borrow_mut() = mode.clone();
self.set_modes.borrow_mut().push(mode);
Task::ready(Ok(()))