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_servers: Apply config defaults only to new ACP sessions (#65850)

Ben Brandt3c8e3b5a0156
diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rs
index 61496557be1..4289e873ddd 100644
--- a/crates/agent_servers/src/acp/v1.rs
+++ b/crates/agent_servers/src/acp/v1.rs
@@ -942,7 +942,7 @@ impl AcpConnection {
let connection = self.connection.clone();
let dispatch_tx = self.dispatch_tx.clone();
let supports_close = self.agent_supports_session_close();
- 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());
@@ -986,14 +986,7 @@ impl AcpConnection {
)));
};
session.session_modes = modes;
- session.config_options = config_options.clone();
- session.default_config_task = config_options.as_ref().map(|options| {
- connection_state.apply_default_config_options(
- &session_id,
- options,
- cx,
- )
- });
+ session.config_options = config_options;
}
connection_state.remove_pending_session(&session_id, thread.entity_id());
return Ok(());
@@ -6271,6 +6264,65 @@ mod tests {
assert_eq!(harness.connection.defaults.config_option("mode"), None);
}
+ #[gpui::test]
+ async fn loaded_sessions_do_not_apply_config_defaults(cx: &mut gpui::TestAppContext) {
+ cx.update(|cx| {
+ let store = SettingsStore::test(cx);
+ cx.set_global(store);
+ });
+ let fs = fs::FakeFs::new(cx.executor());
+ fs.insert_tree("/", serde_json::json!({"a": {}})).await;
+ let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
+ let (connection, requests) = connect_config_defaults_test_agent(cx).await;
+ connection.defaults.set(
+ None,
+ HashMap::from_iter([("web_search".into(), AgentConfigOptionValue::Boolean(true))]),
+ );
+ let connection = Rc::new(connection);
+ let returned = vec![acp::SessionConfigOption::boolean(
+ "web_search",
+ "Web Search",
+ false,
+ )];
+ let session_id = acp_v2::SessionId::new("saved-config");
+ let thread = cx
+ .update(|cx| {
+ connection.clone().open_or_create_session(
+ session_id.clone(),
+ project,
+ PathList::new(&[std::path::Path::new("/a")]),
+ None,
+ {
+ let returned = returned.clone();
+ |_, _, _| {
+ async move {
+ Ok(SessionConfigResponse {
+ modes: None,
+ config_options: Some(returned),
+ })
+ }
+ .boxed_local()
+ }
+ },
+ cx,
+ )
+ })
+ .await
+ .expect("load preserves saved settings");
+ cx.run_until_parked();
+ assert!(
+ requests.lock().expect("config requests").is_empty(),
+ "load must not send saved defaults"
+ );
+ let options = cx
+ .read(|cx| connection.session_config_options(thread.read(cx).session_id(), cx))
+ .expect("loaded config");
+ assert_eq!(
+ options.config_options(),
+ acp_thread::config_options::from_v1(returned).expect("v2 projection")
+ );
+ }
+
#[gpui::test]
async fn default_config_options_apply_boolean_defaults(cx: &mut gpui::TestAppContext) {
let (connection, set_config_requests) = connect_config_defaults_test_agent_with_handler(
@@ -6606,6 +6658,21 @@ mod tests {
})
.await
.expect("load initial session");
+ // Exercise the new-session task lifetime without making load apply defaults.
+ let options = connection
+ .sessions
+ .borrow()
+ .get(&session_id)
+ .and_then(|session| session.config_options.clone())
+ .expect("session config");
+ let defaults =
+ connection.apply_default_config_options(&session_id, &options, &mut cx.to_async());
+ connection
+ .sessions
+ .borrow_mut()
+ .get_mut(&session_id)
+ .expect("registered session")
+ .default_config_task = Some(defaults);
cx.run_until_parked();
assert_eq!(requests.lock().expect("requests").len(), 1);
drop(thread);
diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs
index 32434908bfc..2b954c33e0a 100644
--- a/crates/agent_servers/src/acp/v2.rs
+++ b/crates/agent_servers/src/acp/v2.rs
@@ -8,8 +8,8 @@ use super::{
};
use acp_thread::{
AcpThread, AgentConnection, AgentSessionConfigOptions, AgentSessionInfo, AgentSessionList,
- AgentSessionListRequest, AgentSessionListResponse, ElicitationStore, ReceiptSessionSubmissions,
- ReceiptSubmission, SubmissionDisconnected,
+ AgentSessionListRequest, AgentSessionListResponse, ElicitationStore, ProtocolErrorInfo,
+ ReceiptSessionSubmissions, ReceiptSubmission, SubmissionDisconnected,
};
use action_log::ActionLog;
use agent_client_protocol::{
@@ -25,7 +25,11 @@ use futures::{
future::{LocalBoxFuture, Shared},
};
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, SharedString, Task, WeakEntity};
-use project::{AgentId, AgentServerStore, Project, agent_server_store::AgentServerCommand};
+use project::{
+ AgentId, AgentServerStore, Project,
+ agent_server_store::{AgentServerCommand, AllAgentServersSettings},
+};
+use settings::SettingsStore;
use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
use task::SpawnInTerminal;
use util::ResultExt as _;
@@ -96,6 +100,27 @@ fn validate_prompt_content(
Ok(())
}
+fn config_option_supports_value(
+ option: &acp::SessionConfigOption,
+ value: &acp::SessionConfigOptionValue,
+) -> bool {
+ match (&option.kind, value) {
+ (acp::SessionConfigKind::Boolean(_), acp::SessionConfigOptionValue::Boolean { .. }) => true,
+ (acp::SessionConfigKind::Select(select), acp::SessionConfigOptionValue::Id { value }) => {
+ match &select.options {
+ acp::SessionConfigSelectOptions::Ungrouped(options) => {
+ options.iter().any(|option| &option.value == value)
+ }
+ acp::SessionConfigSelectOptions::Grouped(groups) => groups
+ .iter()
+ .any(|group| group.options.iter().any(|option| &option.value == value)),
+ _ => false,
+ }
+ }
+ _ => false,
+ }
+}
+
#[derive(Clone)]
struct SessionInitialization {
task: Shared<Task<Result<(), Arc<anyhow::Error>>>>,
@@ -701,6 +726,86 @@ impl AcpV2Connection {
Ok(())
}
+ async fn apply_new_session_defaults(
+ &self,
+ thread: &Entity<AcpThread>,
+ cx: &mut AsyncApp,
+ ) -> Result<()> {
+ let config_options = cx
+ .update(|cx| self.session_config_options(thread.read(cx).session_id(), cx))
+ .context("New session was released before applying defaults")?;
+ let mut attempted = Vec::new();
+ loop {
+ let next = cx.update(|cx| {
+ let settings = cx
+ .try_global::<SettingsStore>()?
+ .get::<AllAgentServersSettings>(None);
+ let defaults = settings.get(self.id.as_ref())?;
+ config_options
+ .config_options()
+ .into_iter()
+ .find_map(|option| {
+ if attempted.contains(&option.config_id) {
+ return None;
+ }
+ let default =
+ defaults.default_config_option(option.config_id.0.as_ref())?;
+ let value = match &option.kind {
+ acp::SessionConfigKind::Boolean(boolean) => default
+ .as_bool()
+ .filter(|value| *value != boolean.current_value)
+ .map(acp::SessionConfigOptionValue::boolean),
+ acp::SessionConfigKind::Select(select) => default
+ .as_value_id()
+ .filter(|value| *value != select.current_value.0.as_ref())
+ .map(|value| acp::SessionConfigOptionValue::id(value.to_owned())),
+ _ => None,
+ }?;
+ config_option_supports_value(&option, &value)
+ .then_some((option.config_id, value))
+ })
+ });
+ let Some((config_id, value)) = next else {
+ break;
+ };
+ // Re-read dependent offers after each reply, but never fight the agent
+ // by retrying a rejected or normalized default for the same option.
+ attempted.push(config_id.clone());
+ let result = cx
+ .update(|cx| config_options.set_config_option(config_id.clone(), value, cx))
+ .await
+ .with_context(|| format!("Failed to apply default config option {config_id}"));
+ if result.as_ref().err().is_some_and(|error| {
+ error.is::<ResponseCallbackDropped>()
+ || self.connection.is_incoming_closed()
+ || error
+ .downcast_ref::<agent_client_protocol::Error>()
+ .is_some_and(agent_client_protocol::is_incoming_transport_closed)
+ }) {
+ return result.map(|_| ());
+ }
+ if let Err(error) = result {
+ log::warn!("{error:#}");
+ let message = ProtocolErrorInfo::from_error(&error)
+ .map(|info| info.message.to_owned())
+ .unwrap_or_else(|| error.to_string());
+ cx.update(|cx| {
+ thread.update(cx, |thread, cx| {
+ thread.push_notice(
+ acp::Notice::new(
+ acp::NoticeSeverity::Warning,
+ "Saved config default was not applied",
+ )
+ .description(format!("{config_id}: {message}")),
+ cx,
+ );
+ });
+ });
+ }
+ }
+ Ok(())
+ }
+
fn initialized_thread(
thread: Entity<AcpThread>,
initialization: SessionInitialization,
@@ -1156,9 +1261,29 @@ impl AgentConnection for AcpV2Connection {
let dispatch_tx = self.dispatch_tx.clone();
move || enqueue_notification(&dispatch_tx, request_id, finish_session_creation)
});
- cx.foreground_executor().spawn(async move {
- let _cleanup = cleanup;
- response.await
+ cx.spawn(async move |cx| {
+ let thread = {
+ let _cleanup = cleanup;
+ response.await?
+ };
+ let session_id = cx.update(|cx| thread.read(cx).session_id().clone());
+ let abandoned = util::defer({
+ let this = self.clone();
+ let thread_id = thread.entity_id();
+ move || {
+ this.remove_session(&session_id, thread_id);
+ enqueue_notification(
+ &this.dispatch_tx,
+ (session_id, this.connection.clone()),
+ close_undelivered_session,
+ );
+ }
+ });
+ // Further requests must follow the creation acknowledgement, not await
+ // later SDK traffic inside its ordered response callback.
+ self.apply_new_session_defaults(&thread, cx).await?;
+ abandoned.abort();
+ Ok(thread)
})
}
@@ -1507,28 +1632,7 @@ impl V2SessionConfigOptions {
self.sessions.borrow().get(&self.session_id),
)?;
let valid = self.options.config_options.borrow().iter().any(|option| {
- if &option.config_id != config_id {
- return false;
- }
- match (&option.kind, value) {
- (
- acp::SessionConfigKind::Boolean(_),
- acp::SessionConfigOptionValue::Boolean { .. },
- ) => true,
- (
- acp::SessionConfigKind::Select(select),
- acp::SessionConfigOptionValue::Id { value },
- ) => match &select.options {
- acp::SessionConfigSelectOptions::Ungrouped(options) => {
- options.iter().any(|option| &option.value == value)
- }
- acp::SessionConfigSelectOptions::Grouped(groups) => groups
- .iter()
- .any(|group| group.options.iter().any(|option| &option.value == value)),
- _ => false,
- },
- _ => false,
- }
+ &option.config_id == config_id && config_option_supports_value(option, value)
});
if !valid {
return Err(anyhow!(
@@ -2102,6 +2206,243 @@ mod tests {
.meta(meta("delivery-not-session"))
}
+ fn set_startup_defaults(
+ defaults: HashMap<String, settings::AgentConfigOptionValue>,
+ cx: &mut TestAppContext,
+ ) {
+ use project::agent_server_store::AllAgentServersSettings;
+ use settings::Settings;
+
+ cx.update(|cx| {
+ AllAgentServersSettings::override_global(
+ AllAgentServersSettings(HashMap::from_iter([(
+ "session-test".into(),
+ settings::CustomAgentServerSettings::Custom {
+ path: "test-agent".into(),
+ args: Vec::new(),
+ env: HashMap::default(),
+ default_mode: Some("legacy-must-not-run".into()),
+ default_config_options: defaults,
+ favorite_config_option_values: HashMap::default(),
+ }
+ .into(),
+ )])),
+ cx,
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn v2_new_session_applies_defaults_before_delivery(cx: &mut TestAppContext) {
+ use settings::AgentConfigOptionValue::{Boolean, ValueId};
+
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ set_startup_defaults(
+ HashMap::from_iter([
+ ("enabled".into(), Boolean(true)),
+ ("model".into(), ValueId("large".into())),
+ ("already".into(), Boolean(false)),
+ ("wrong-type".into(), ValueId("invalid".into())),
+ ("future".into(), Boolean(true)),
+ ("missing".into(), Boolean(true)),
+ ]),
+ cx,
+ );
+ let mut offered = vec![
+ acp::SessionConfigOption::select(
+ "model",
+ "Model",
+ "small",
+ vec![acp::SessionConfigSelectOption::new("small", "Small")],
+ ),
+ acp::SessionConfigOption::boolean("enabled", "Enabled", false),
+ acp::SessionConfigOption::boolean("already", "Already", false),
+ acp::SessionConfigOption::boolean("wrong-type", "Wrong type", false),
+ acp::SessionConfigOption::new(
+ "future",
+ "Future",
+ acp::SessionConfigKind::Other(acp::OtherSessionConfigKind::new(
+ "_future",
+ Default::default(),
+ )),
+ ),
+ ];
+ let mut creation = harness.create(cx);
+ harness.new_request(&mut creation, cx).await;
+ harness
+ .new_responses
+ .try_send(Ok(initial_response().config_options(offered.clone())))
+ .expect("new response");
+ harness.drain_updates(cx).await;
+ assert!(
+ (&mut creation).now_or_never().is_none(),
+ "defaults finish before delivery"
+ );
+ let request = bounded(harness.config_requests.recv(), cx)
+ .await
+ .expect("default request");
+ assert_eq!(request.config_id, acp::SessionConfigId::new("enabled"));
+ assert_eq!(request.value, acp::SessionConfigOptionValue::boolean(true));
+ offered[0] = acp::SessionConfigOption::select(
+ "model",
+ "Model",
+ "small",
+ vec![
+ acp::SessionConfigSelectOption::new("small", "Small"),
+ acp::SessionConfigSelectOption::new("large", "Large"),
+ ],
+ );
+ harness
+ .config_responses
+ .try_send(Ok(acp::SetSessionConfigOptionResponse::new(
+ offered.clone(),
+ )))
+ .expect("normalized response exposes dependent model");
+ let request = bounded(harness.config_requests.recv(), cx)
+ .await
+ .expect("dependent default");
+ assert_eq!(request.config_id, acp::SessionConfigId::new("model"));
+ assert_eq!(request.value, acp::SessionConfigOptionValue::id("large"));
+ if let acp::SessionConfigKind::Select(model) = &mut offered[0].kind {
+ model.current_value = "large".into();
+ }
+ harness
+ .config_responses
+ .try_send(Ok(acp::SetSessionConfigOptionResponse::new(
+ offered.clone(),
+ )))
+ .expect("model response");
+ let thread = bounded(creation, cx).await.expect("initialized");
+ let options = cx
+ .read(|cx| {
+ harness
+ .client
+ .session_config_options(thread.read(cx).session_id(), cx)
+ })
+ .expect("config");
+ assert_eq!(options.config_options(), offered);
+ assert!(
+ harness.config_requests.is_empty(),
+ "do not retry normalized or invalid defaults"
+ );
+
+ for replay in [false, true] {
+ let loading = harness.reopen(replay, cx);
+ let (_, response) = bounded(harness.resume_requests.recv(), cx)
+ .await
+ .expect("resume");
+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));
+ response
+ .respond(
+ acp::ResumeSessionResponse::new()
+ .config_options(initial_response().config_options),
+ )
+ .expect("agent's saved settings");
+ let resumed = bounded(loading, cx).await.expect("resumed");
+ let settings = cx
+ .read(|cx| {
+ harness
+ .client
+ .session_config_options(resumed.read(cx).session_id(), cx)
+ })
+ .expect("saved config");
+ assert_eq!(settings.config_options(), initial_response().config_options);
+ assert!(
+ harness.config_requests.is_empty(),
+ "resume/load must not apply startup defaults"
+ );
+ drop(resumed);
+ cx.run_until_parked();
+ }
+ }
+
+ #[gpui::test]
+ async fn v2_new_session_defaults_handle_interrupted_startup(cx: &mut TestAppContext) {
+ for (abandoned, disconnected) in [(false, false), (true, false), (false, true)] {
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ *harness.hold_config.lock().expect("config mode") = abandoned || disconnected;
+ set_startup_defaults(
+ HashMap::from_iter([(
+ "enabled".into(),
+ settings::AgentConfigOptionValue::Boolean(true),
+ )]),
+ cx,
+ );
+ let mut creation = harness.create(cx);
+ harness.new_request(&mut creation, cx).await;
+ harness
+ .new_responses
+ .try_send(Ok(initial_response()))
+ .expect("new response");
+ bounded(harness.config_requests.recv(), cx)
+ .await
+ .expect("startup default");
+ if disconnected {
+ let _response = bounded(harness.config_replies.recv(), cx)
+ .await
+ .expect("held config response");
+ drop(harness._agent_task);
+ drop(harness.agent);
+ assert!(
+ bounded(creation, cx).await.is_err(),
+ "transport loss must not publish a usable session"
+ );
+ continue;
+ }
+ if abandoned {
+ let response = bounded(harness.config_replies.recv(), cx)
+ .await
+ .expect("held config response");
+ drop(creation);
+ cx.run_until_parked();
+ assert!(
+ harness.client.sessions.borrow().is_empty(),
+ "abandonment releases the provisional owner"
+ );
+ assert_eq!(
+ bounded(harness.closes.recv(), cx)
+ .await
+ .expect("undelivered session closed"),
+ acp::SessionId::new("session")
+ );
+ assert!(harness.client.sessions.borrow().is_empty());
+ response
+ .respond(acp::SetSessionConfigOptionResponse::new(
+ initial_response().config_options,
+ ))
+ .expect("late config reply");
+ harness.drain_updates(cx).await;
+ assert!(harness.client.sessions.borrow().is_empty());
+ } else {
+ harness
+ .config_responses
+ .try_send(Err(
+ agent_client_protocol::Error::invalid_params().data("default rejected")
+ ))
+ .expect("rejection");
+ let thread = bounded(creation, cx)
+ .await
+ .expect("rejected default keeps new session usable");
+ assert!(harness.closes.is_empty());
+ assert!(
+ harness.config_requests.is_empty(),
+ "do not retry a rejected default"
+ );
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(
+ thread.foreground_activity(),
+ acp_thread::ForegroundActivity::Idle
+ );
+ assert_eq!(
+ thread.notices().len(),
+ 1,
+ "rejected default is visible to the user"
+ );
+ });
+ }
+ }
+ }
+
#[gpui::test]
async fn v2_cancel_sdk_preserves_receipt_and_waits_for_reported_idle(cx: &mut TestAppContext) {
use acp_thread::{ForegroundActivity, SubmissionResponse, SubmissionState};