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: Track subagent working directories (#66440)

Ben Brandt601a7cc8ac4f
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 869e22f847c..a6f34441d3a 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -4269,8 +4269,43 @@ impl AcpThread {
}
pub fn set_work_dirs(&mut self, work_dirs: PathList, cx: &mut Context<Self>) {
- self.session_info.work_dirs = Some(work_dirs);
- cx.emit(AcpThreadEvent::WorkingDirectoriesUpdated)
+ self.session_info.work_dirs = Some(work_dirs.clone());
+ cx.emit(AcpThreadEvent::WorkingDirectoriesUpdated);
+ for subagent in self.subagents.values() {
+ subagent.update(cx, |subagent, cx| {
+ subagent.inherit_subagent_work_dirs(Some(&work_dirs), cx)
+ });
+ }
+ }
+
+ /// Updates an ACP subagent's working directories from what its parent reported,
+ /// inheriting each unreported field from the parent's working directories.
+ pub fn inherit_subagent_work_dirs(
+ &mut self,
+ parent_work_dirs: Option<&PathList>,
+ cx: &mut Context<Self>,
+ ) {
+ if !matches!(
+ self.submissions.transport(),
+ SubmissionTransport::AgentOwned
+ ) {
+ return;
+ }
+ let Some(work_dirs) = self
+ .subagent_association
+ .as_ref()
+ .and_then(|association| association.effective_work_dirs(parent_work_dirs))
+ else {
+ return;
+ };
+ // `PathList` equality ignores order, but the first path is the cwd.
+ if self
+ .work_dirs()
+ .is_some_and(|current| current.ordered_paths().eq(work_dirs.ordered_paths()))
+ {
+ return;
+ }
+ self.set_work_dirs(work_dirs, cx);
}
pub fn status(&self) -> ThreadStatus {
diff --git a/crates/acp_thread/src/subagents.rs b/crates/acp_thread/src/subagents.rs
index 53fd4625c5a..06dc6d2b909 100644
--- a/crates/acp_thread/src/subagents.rs
+++ b/crates/acp_thread/src/subagents.rs
@@ -1,6 +1,8 @@
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::Result;
use gpui::SharedString;
+use std::path::PathBuf;
+use util::path_list::PathList;
/// What a parent ACP session has reported about a subagent session it owns.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -10,6 +12,12 @@ pub struct SubagentAssociation {
pub description: Option<SharedString>,
/// Whether Zed may cancel the subagent's current work.
pub can_cancel: bool,
+ /// The subagent's working directory, if the parent reported one. Otherwise the
+ /// subagent inherits its parent's.
+ pub cwd: Option<PathBuf>,
+ /// The subagent's additional directories, if the parent reported them. Otherwise the
+ /// subagent inherits its parent's.
+ pub additional_directories: Option<Vec<PathBuf>>,
}
impl SubagentAssociation {
@@ -26,6 +34,38 @@ impl SubagentAssociation {
self.can_cancel =
capabilities.is_some_and(|capabilities| capabilities.cancel.is_some());
}
+ if let Some(cwd) = update.cwd.as_opt_ref() {
+ self.cwd = cwd.map(|cwd| cwd.0.clone());
+ }
+ if let Some(directories) = update.additional_directories.as_opt_ref() {
+ self.additional_directories = directories.map(|directories| {
+ directories
+ .iter()
+ .map(|directory| directory.0.clone())
+ .collect()
+ });
+ }
+ }
+
+ /// The subagent's working directories, with the cwd first. Each field the parent
+ /// hasn't reported is inherited from the parent's own working directories.
+ pub fn effective_work_dirs(&self, parent_work_dirs: Option<&PathList>) -> Option<PathList> {
+ let mut parent_paths = parent_work_dirs
+ .into_iter()
+ .flat_map(|work_dirs| work_dirs.ordered_paths());
+ let parent_cwd = parent_paths.next();
+ let cwd = self.cwd.as_ref().or(parent_cwd)?;
+ let additional_directories = match &self.additional_directories {
+ Some(directories) => directories.iter().collect::<Vec<_>>(),
+ None => parent_paths.collect(),
+ };
+ let mut paths = vec![cwd];
+ for directory in additional_directories {
+ if !paths.contains(&directory) {
+ paths.push(directory);
+ }
+ }
+ Some(PathList::new(&paths))
}
}
@@ -49,7 +89,34 @@ pub fn update_from_v1(update: acp_v1::SubagentUpdate) -> Result<acp_v2::Subagent
)
.meta(capabilities.meta)
}))
- .state(state))
+ .state(state)
+ .cwd(match update.cwd {
+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,
+ MaybeUndefined::Null => MaybeUndefined::Null,
+ MaybeUndefined::Value(cwd) => {
+ absolute_path_from_v1(cwd).map_or(MaybeUndefined::Undefined, MaybeUndefined::Value)
+ }
+ })
+ .additional_directories(match update.additional_directories {
+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,
+ MaybeUndefined::Null => MaybeUndefined::Null,
+ MaybeUndefined::Value(directories) => directories
+ .into_iter()
+ .map(absolute_path_from_v1)
+ .collect::<Option<Vec<_>>>()
+ .map_or(MaybeUndefined::Undefined, MaybeUndefined::Value),
+ }))
+}
+
+/// v1 types these paths as plain paths, but the subagents RFD requires them to be absolute.
+/// Like a malformed v2 field, a relative one is ignored.
+fn absolute_path_from_v1(path: PathBuf) -> Option<acp_v2::AbsolutePath> {
+ if path.is_absolute() {
+ Some(acp_v2::AbsolutePath::new(path))
+ } else {
+ log::warn!("Ignoring relative subagent directory {path:?}");
+ None
+ }
}
/// The subagents RFD gives the v1 snapshot the same wire shape as the v2 `state_update`,
@@ -62,6 +129,7 @@ fn state_from_v1(state: acp_v1::StateUpdate) -> Result<acp_v2::StateUpdate> {
mod tests {
use super::*;
use serde_json::json;
+ use util::path;
fn v2_update(value: serde_json::Value) -> acp_v2::SubagentUpdate {
serde_json::from_value(value).expect("v2 subagent update")
@@ -80,6 +148,8 @@ mod tests {
title: Some("Investigator".into()),
description: Some("Looks into failures".into()),
can_cancel: true,
+ cwd: None,
+ additional_directories: None,
};
assert_eq!(association, announced);
@@ -97,6 +167,8 @@ mod tests {
title: None,
description: Some("Looks into failures".into()),
can_cancel: false,
+ cwd: None,
+ additional_directories: None,
},
"null clears a field, and capabilities are replaced as a whole"
);
@@ -111,6 +183,95 @@ mod tests {
assert!(!association.can_cancel, "null capabilities disable cancel");
}
+ #[test]
+ fn directories_follow_patch_semantics_and_inherit_independently() {
+ let parent = PathList::new(&[path!("/project"), path!("/shared")]);
+ let ordered = |work_dirs: Option<PathList>| {
+ work_dirs
+ .expect("effective directories")
+ .ordered_paths()
+ .map(|path| path.to_string_lossy().into_owned())
+ .collect::<Vec<_>>()
+ };
+ let mut association = SubagentAssociation::default();
+ assert_eq!(association.effective_work_dirs(None), None);
+ assert_eq!(
+ ordered(association.effective_work_dirs(Some(&parent))),
+ [path!("/project"), path!("/shared")],
+ "unreported directories are inherited"
+ );
+
+ association.apply(&v2_update(json!({
+ "sessionId": "child",
+ "cwd": path!("/worktree"),
+ })));
+ assert_eq!(
+ ordered(association.effective_work_dirs(Some(&parent))),
+ [path!("/worktree"), path!("/shared")],
+ "the cwd and additional directories are inherited independently"
+ );
+
+ association.apply(&v2_update(json!({
+ "sessionId": "child",
+ "additionalDirectories": [],
+ })));
+ assert_eq!(
+ ordered(association.effective_work_dirs(Some(&parent))),
+ [path!("/worktree")]
+ );
+ association.apply(&v2_update(json!({"sessionId": "child"})));
+ assert_eq!(
+ ordered(association.effective_work_dirs(None)),
+ [path!("/worktree")],
+ "omitted fields are unchanged"
+ );
+
+ association.apply(&v2_update(json!({
+ "sessionId": "child",
+ "cwd": null,
+ "additionalDirectories": [path!("/other"), path!("/project")],
+ })));
+ assert_eq!(
+ ordered(association.effective_work_dirs(Some(&parent))),
+ [path!("/project"), path!("/other")],
+ "null inherits the parent's cwd again, and directories are replaced whole"
+ );
+ }
+
+ #[test]
+ fn v1_directories_must_be_absolute() -> Result<()> {
+ for (v1, expected) in [
+ (
+ json!({
+ "sessionId": "child",
+ "cwd": path!("/worktree"),
+ "additionalDirectories": [path!("/shared")],
+ }),
+ json!({
+ "sessionId": "child",
+ "cwd": path!("/worktree"),
+ "additionalDirectories": [path!("/shared")],
+ }),
+ ),
+ (
+ json!({"sessionId": "child", "cwd": null, "additionalDirectories": null}),
+ json!({"sessionId": "child", "cwd": null, "additionalDirectories": null}),
+ ),
+ (
+ json!({
+ "sessionId": "child",
+ "cwd": "relative",
+ "additionalDirectories": [path!("/shared"), "relative"],
+ }),
+ json!({"sessionId": "child"}),
+ ),
+ ] {
+ let converted = update_from_v1(serde_json::from_value(v1.clone())?)?;
+ assert_eq!(serde_json::to_value(&converted)?, expected, "{v1}");
+ }
+ Ok(())
+ }
+
#[test]
fn v1_updates_convert_fields_and_state_snapshots() -> Result<()> {
for (v1, expected) in [
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 1918adb764d..091f35d080c 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -926,6 +926,8 @@ impl NativeAgent {
title: subagent_title,
description: None,
can_cancel: true,
+ cwd: None,
+ additional_directories: None,
});
}
acp_thread.set_draft_prompt(draft_prompt, cx);
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index f048fba0845..970dc0f5533 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -805,9 +805,12 @@ fn apply_subagent_update(
) -> Result<Entity<AcpThread>> {
let parent_session_id = parent.read(cx).session_id().clone();
let session_id = update.session_id.clone();
+ let parent_work_dirs = parent.read(cx).work_dirs().cloned();
if let Some(subagent) = parent.read(cx).subagent(&session_id).cloned() {
subagent.update(cx, |subagent, cx| {
- subagent.update_subagent_association(update, cx)
+ subagent.update_subagent_association(update, cx)?;
+ subagent.inherit_subagent_work_dirs(parent_work_dirs.as_ref(), cx);
+ anyhow::Ok(())
})?;
return Ok(subagent);
}
@@ -843,7 +846,9 @@ fn apply_subagent_update(
.agent_owned()
});
subagent.update(cx, |subagent, cx| {
- subagent.update_subagent_association(update, cx)
+ subagent.update_subagent_association(update, cx)?;
+ subagent.inherit_subagent_work_dirs(parent_work_dirs.as_ref(), cx);
+ anyhow::Ok(())
})?;
// Unlike a session Zed opened, releasing a subagent must not close it: the agent
// releases subagents when their parent closes.
diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rs
index 1cd858a2d92..2e19fad2c30 100644
--- a/crates/agent_servers/src/acp/v1.rs
+++ b/crates/agent_servers/src/acp/v1.rs
@@ -8463,6 +8463,31 @@ exit 7
.await
.expect_err("child config is read-only");
assert!(error.to_string().contains("read-only"));
+ notify(
+ &parent_id,
+ acp::SessionUpdate::SubagentUpdate(
+ acp::SubagentUpdate::new("child").cwd(PathBuf::from(util::path!("/worktree"))),
+ ),
+ cx,
+ );
+ child.read_with(cx, |child, _| {
+ assert_eq!(
+ terminal_cwd(child, None),
+ Some(PathBuf::from(util::path!("/worktree"))),
+ "a subagent terminal without a cwd runs in the subagent's cwd"
+ );
+ assert_eq!(
+ terminal_cwd(child, Some(PathBuf::from(util::path!("/explicit")))),
+ Some(PathBuf::from(util::path!("/explicit")))
+ );
+ });
+ parent.read_with(cx, |parent, _| {
+ assert_eq!(
+ terminal_cwd(parent, None),
+ None,
+ "root sessions are unchanged"
+ );
+ });
child.read_with(cx, |child, _| {
assert_eq!(child.parent_session_id(), Some(&parent_session_id));
assert_eq!(
@@ -10437,6 +10462,15 @@ fn handle_session_notification(
}
}
+/// The subagents RFD runs a subagent's terminal that has no `cwd` in the subagent's own
+/// working directory.
+fn terminal_cwd(thread: &AcpThread, cwd: Option<PathBuf>) -> Option<PathBuf> {
+ cwd.or_else(|| {
+ thread.parent_session_id()?;
+ thread.work_dirs()?.ordered_paths().next().cloned()
+ })
+}
+
fn handle_create_terminal(
args: acp::CreateTerminalRequest,
responder: Responder<acp::CreateTerminalResponse>,
@@ -10447,11 +10481,16 @@ fn handle_create_terminal(
Ok(t) => t,
Err(e) => return respond_err(responder, e),
};
- let project = match thread
- .read_with(cx, |thread, _cx| thread.project().clone())
+ let (project, cwd) = match thread
+ .read_with(cx, |thread, _cx| {
+ (
+ thread.project().clone(),
+ terminal_cwd(thread, args.cwd.clone()),
+ )
+ })
.map_err(agent_client_protocol::Error::from)
{
- Ok(p) => p,
+ Ok(read) => read,
Err(e) => return respond_err(responder, e),
};
@@ -10464,7 +10503,7 @@ fn handle_create_terminal(
.into_iter()
.map(|env| (env.name, env.value))
.collect(),
- args.cwd.clone(),
+ cwd.clone(),
&project,
cx,
)
@@ -10474,7 +10513,7 @@ fn handle_create_terminal(
thread.register_terminal_created(
acp_v2::TerminalId::new(uuid::Uuid::new_v4().to_string()),
format!("{} {}", args.command, args.args.join(" ")),
- args.cwd.clone(),
+ cwd,
args.output_byte_limit,
terminal_entity,
cx,
diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs
index 9a46fc18419..442b21a22b8 100644
--- a/crates/agent_servers/src/acp/v2.rs
+++ b/crates/agent_servers/src/acp/v2.rs
@@ -2697,6 +2697,85 @@ mod tests {
}
}
+ #[gpui::test]
+ async fn v2_subagent_directories_inherit_through_nested_subagents(cx: &mut TestAppContext) {
+ use agent_client_protocol::schema::MaybeUndefined;
+
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let parent = harness.thread(cx).await;
+ harness.send_update(
+ "session",
+ acp::SessionUpdate::SubagentUpdate(
+ acp::SubagentUpdate::new("child")
+ .cwd(acp::AbsolutePath::new(session_path("worktree"))),
+ ),
+ );
+ harness.send_update(
+ "child",
+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("grandchild")),
+ );
+ harness.drain_updates(cx).await;
+ let child = parent
+ .read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned())
+ .expect("child");
+ let grandchild = child
+ .read_with(cx, |child, _| child.subagent(&"grandchild".into()).cloned())
+ .expect("grandchild");
+ let work_dirs = |thread: &Entity<AcpThread>, cx: &mut TestAppContext| {
+ thread.read_with(cx, |thread, _| {
+ thread
+ .work_dirs()
+ .expect("working directories")
+ .ordered_paths()
+ .cloned()
+ .collect::<Vec<_>>()
+ })
+ };
+ let parent_dirs = work_dirs(&parent, cx);
+ let mut expected = parent_dirs.clone();
+ expected[0] = session_path("worktree");
+ assert_eq!(
+ work_dirs(&child, cx),
+ expected,
+ "the child keeps the parent's other dirs"
+ );
+ assert_eq!(
+ work_dirs(&grandchild, cx),
+ expected,
+ "the grandchild inherits the child's"
+ );
+
+ harness.send_update(
+ "session",
+ acp::SessionUpdate::SubagentUpdate(
+ acp::SubagentUpdate::new("child").additional_directories(Vec::new()),
+ ),
+ );
+ harness.drain_updates(cx).await;
+ assert_eq!(work_dirs(&child, cx), [session_path("worktree")]);
+ assert_eq!(
+ work_dirs(&grandchild, cx),
+ [session_path("worktree")],
+ "a change to the child's directories reaches the grandchild"
+ );
+
+ harness.send_update(
+ "session",
+ acp::SessionUpdate::SubagentUpdate(
+ acp::SubagentUpdate::new("child")
+ .cwd(MaybeUndefined::Null)
+ .additional_directories(MaybeUndefined::Null),
+ ),
+ );
+ harness.drain_updates(cx).await;
+ assert_eq!(
+ work_dirs(&child, cx),
+ parent_dirs,
+ "cleared fields inherit again"
+ );
+ assert_eq!(work_dirs(&grandchild, cx), parent_dirs);
+ }
+
#[gpui::test]
async fn v2_subagent_updates_route_and_patch_child_sessions(cx: &mut TestAppContext) {
use acp_thread::{ThreadStatus, subagents::SubagentAssociation};
@@ -2736,6 +2815,8 @@ mod tests {
title: Some("Investigator".into()),
description: None,
can_cancel: true,
+ cwd: None,
+ additional_directories: None,
})
);
assert_eq!(child.entries().len(), 1, "child traffic reaches the child");
@@ -2788,6 +2869,8 @@ mod tests {
title: None,
description: None,
can_cancel: true,
+ cwd: None,
+ additional_directories: None,
})
);
assert_eq!(child.subagents().count(), 0);