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: Add subagent model selection (#64498)

itsfuade5221fa2956c
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 9ea7e6bbfa7..135c970ce01 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -2683,6 +2683,20 @@ impl acp_thread::AgentModelSelector for NativeAgentModelSelector {
}
}
+fn subagent_model_id_to_selection(model_id: &AgentModelId, cx: &App) -> LanguageModelSelection {
+ let settings = agent_settings::AgentSettings::get_global(cx);
+ let Some((provider, model)) = model_id.as_ref().split_once('/') else {
+ return model_id_to_selection(model_id, cx);
+ };
+ if let Some(selection) = settings.subagent_model.as_ref()
+ && selection.provider.0 == provider
+ && selection.model == model
+ {
+ return selection.clone();
+ }
+ model_id_to_selection(model_id, cx)
+}
+
fn model_id_to_selection(model_id: &AgentModelId, cx: &App) -> LanguageModelSelection {
let id = model_id.as_ref();
let (provider, model) = id.split_once('/').unwrap_or(("", id));
@@ -2723,6 +2737,36 @@ fn model_id_to_selection(model_id: &AgentModelId, cx: &App) -> LanguageModelSele
pub static ZED_AGENT_ID: LazyLock<AgentId> = LazyLock::new(|| AgentId::new("Zed Agent"));
+pub fn available_native_agent(cx: &App) -> AvailableAgent {
+ let registry = LanguageModelRegistry::read_global(cx);
+ let default = registry.default_model();
+ let mut models = Vec::new();
+ for provider in registry.visible_providers() {
+ if !provider.is_authenticated(cx) {
+ continue;
+ }
+ let provider_id = provider.id();
+ for model in provider.provided_models(cx) {
+ let id = format!("{}/{}", provider_id.0, model.id().0);
+ let is_default = default.as_ref().is_some_and(|default| {
+ default.provider.id() == provider_id && default.model.id() == model.id()
+ });
+ models.push(AvailableModel {
+ id,
+ name: model.name().0,
+ is_default,
+ });
+ }
+ }
+
+ AvailableAgent {
+ id: ZED_AGENT_ID.to_string(),
+ name: ZED_AGENT_ID.0.clone(),
+ is_native: true,
+ models,
+ }
+}
+
impl acp_thread::AgentConnection for NativeAgentConnection {
fn agent_id(&self) -> AgentId {
ZED_AGENT_ID.clone()
@@ -3184,8 +3228,22 @@ impl NativeThreadEnvironment {
pub(crate) fn create_subagent_thread(
&self,
label: String,
+ model: Option<AgentModelId>,
cx: &mut App,
) -> Result<Rc<dyn SubagentHandle>> {
+ let model = if let Some(model_id) = model {
+ let available = self.agent.read_with(cx, |agent, _| {
+ agent.models.model_from_id(&model_id).is_some()
+ })?;
+ if !available {
+ anyhow::bail!(
+ "Model {model_id} is unavailable. Call list_agents_and_models to inspect available models."
+ );
+ }
+ Some(subagent_model_id_to_selection(&model_id, cx))
+ } else {
+ None
+ };
let Some(parent_thread_entity) = self.thread.upgrade() else {
anyhow::bail!("Parent thread no longer exists".to_string());
};
@@ -3201,7 +3259,7 @@ impl NativeThreadEnvironment {
}
let subagent_thread: Entity<Thread> = cx.new(|cx| {
- let mut thread = Thread::new_subagent(&parent_thread_entity, cx);
+ let mut thread = Thread::new_subagent(&parent_thread_entity, model.as_ref(), cx);
thread.set_title(label.into(), cx);
thread
});
@@ -3393,8 +3451,13 @@ impl ThreadEnvironment for NativeThreadEnvironment {
})
}
- fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>> {
- self.create_subagent_thread(label, cx)
+ fn create_subagent(
+ &self,
+ label: String,
+ model: Option<AgentModelId>,
+ cx: &mut App,
+ ) -> Result<Rc<dyn SubagentHandle>> {
+ self.create_subagent_thread(label, model, cx)
}
fn resume_subagent(
@@ -3429,14 +3492,14 @@ impl ThreadEnvironment for NativeThreadEnvironment {
fn list_available_agents(&self, cx: &mut App) -> Result<AvailableAgents> {
let host = self
.agent
- .read_with(cx, |agent, _| agent.sibling_thread_host())?
- .ok_or_else(|| {
- anyhow!(
- "No sibling-thread host is registered. This usually means the \
- agent panel hasn't been initialized in this workspace."
- )
- })?;
- host.list_available_agents(cx)
+ .read_with(cx, |agent, _| agent.sibling_thread_host())?;
+ if let Some(host) = host {
+ host.list_available_agents(cx)
+ } else {
+ Ok(AvailableAgents {
+ agents: vec![available_native_agent(cx)],
+ })
+ }
}
}
@@ -3865,12 +3928,104 @@ mod internal_tests {
use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};
use language_model::{
CompletionIntent, LanguageModelCompletionError, LanguageModelCompletionEvent,
- LanguageModelProviderId, LanguageModelProviderName,
+ LanguageModelProviderId, LanguageModelProviderName, Speed,
};
use serde_json::json;
- use settings::SettingsStore;
+ use settings::{LanguageModelProviderSetting, SettingsStore};
use util::{path, rel_path::rel_path};
+ #[gpui::test]
+ fn test_available_native_agent_hides_hidden_providers(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ LanguageModelRegistry::test(cx);
+ let registry = LanguageModelRegistry::global(cx);
+ registry.update(cx, |registry, cx| {
+ registry.set_builtin_provider_hiding_fn(Box::new(|id| {
+ (id == "fake").then_some("fake-extension")
+ }));
+ registry.extension_installed("fake-extension".into(), cx);
+ });
+
+ assert!(available_native_agent(cx).models.is_empty());
+ });
+ }
+
+ #[gpui::test]
+ async fn test_explicit_subagent_model_preserves_configured_settings(cx: &mut TestAppContext) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/test"), json!({})).await;
+ let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
+ let thread_store = cx.new(|cx| ThreadStore::new(cx));
+ let agent = cx.update(|cx| NativeAgent::new(thread_store, Templates::new(), fs, cx));
+ let connection = Rc::new(NativeAgentConnection(agent.clone()));
+ let model = Arc::new(FakeLanguageModel::with_id_and_thinking(
+ "fake-corp",
+ "subagent-model",
+ "Subagent Model",
+ true,
+ ));
+ let provider = Arc::new(
+ FakeLanguageModelProvider::new(
+ LanguageModelProviderId::from("fake-corp".to_string()),
+ LanguageModelProviderName::from("Fake Corp".to_string()),
+ )
+ .with_models(vec![model.clone()]),
+ );
+ cx.update(|cx| {
+ LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
+ registry.register_provider(provider, cx);
+ });
+ });
+ agent.update(cx, |agent, cx| agent.models.refresh_list(cx));
+
+ let mut settings = cx.update(|cx| agent_settings::AgentSettings::get_global(cx).clone());
+ settings.subagent_model = Some(LanguageModelSelection {
+ provider: LanguageModelProviderSetting("fake-corp".to_string()),
+ model: "subagent-model".to_string(),
+ enable_thinking: true,
+ effort: Some("high".to_string()),
+ speed: Some(Speed::Fast),
+ });
+ cx.update(|cx| agent_settings::AgentSettings::override_global(settings, cx));
+
+ let acp_thread = cx
+ .update(|cx| connection.new_session(project, PathList::new(&[Path::new("/test")]), cx))
+ .await
+ .unwrap();
+ let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let parent_thread = agent.read_with(cx, |agent, _| {
+ agent.sessions.get(&session_id).unwrap().thread.clone()
+ });
+ let environment = NativeThreadEnvironment {
+ agent: agent.downgrade(),
+ thread: parent_thread.downgrade(),
+ acp_thread: acp_thread.downgrade(),
+ };
+
+ let handle = cx
+ .update(|cx| {
+ environment.create_subagent_thread(
+ "subagent".to_string(),
+ Some(AgentModelId::from("fake-corp/subagent-model".to_string())),
+ cx,
+ )
+ })
+ .unwrap();
+ let subagent_thread = agent.read_with(cx, |agent, _| {
+ agent.sessions.get(&handle.id()).unwrap().thread.clone()
+ });
+ subagent_thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.model().map(|model| model.id()), Some(model.id()));
+ assert!(thread.thinking_enabled());
+ assert_eq!(thread.thinking_effort(), Some(&"high".to_string()));
+ // The fake model does not support fast mode, so the configured speed is
+ // intentionally filtered while the model selection is applied.
+ assert_eq!(thread.speed(), None);
+ });
+ }
+
#[cfg(target_os = "macos")]
#[gpui::test]
async fn test_native_terminal_tool_releases_pty_resources(cx: &mut TestAppContext) {
@@ -5828,7 +5983,8 @@ mod internal_tests {
// Build the subagent thread the same way
// `NativeThreadEnvironment::create_subagent_thread` does.
- let subagent_thread = cx.update(|cx| cx.new(|cx| Thread::new_subagent(&parent_thread, cx)));
+ let subagent_thread =
+ cx.update(|cx| cx.new(|cx| Thread::new_subagent(&parent_thread, None, cx)));
// Run the subagent through the production registration path.
// This is what installs the `SkillTool` on the thread.
@@ -7392,10 +7548,10 @@ mod internal_tests {
};
let first_subagent = cx
- .update(|cx| environment.create_subagent_thread("first".to_string(), cx))
+ .update(|cx| environment.create_subagent_thread("first".to_string(), None, cx))
.unwrap();
let second_subagent = cx
- .update(|cx| environment.create_subagent_thread("second".to_string(), cx))
+ .update(|cx| environment.create_subagent_thread("second".to_string(), None, cx))
.unwrap();
cx.run_until_parked();
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index 358b1145383..fdd16eb3281 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -1,7 +1,7 @@
use super::*;
use acp_thread::{
- AgentConnection, AgentModelGroupName, AgentModelList, ClientUserMessageId, PermissionOptions,
- ThreadStatus,
+ AgentConnection, AgentModelGroupName, AgentModelId, AgentModelList, ClientUserMessageId,
+ PermissionOptions, ThreadStatus,
};
use agent_client_protocol::schema::v1 as acp;
use agent_settings::{AgentProfileId, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT};
@@ -177,7 +177,7 @@ impl SubagentHandle for FakeSubagentHandle {
}
fn num_entries(&self, _cx: &App) -> usize {
- unimplemented!()
+ 0
}
fn send(&self, _message: String, cx: &AsyncApp) -> Task<Result<String>> {
@@ -192,6 +192,7 @@ pub(crate) struct FakeThreadEnvironment {
subagent_handle: Option<Rc<FakeSubagentHandle>>,
terminal_creations: Arc<AtomicUsize>,
terminal_output_limits: std::cell::RefCell<Vec<Option<u64>>>,
+ subagent_models: std::cell::RefCell<Vec<Option<AgentModelId>>>,
}
impl FakeThreadEnvironment {
@@ -202,6 +203,13 @@ impl FakeThreadEnvironment {
}
}
+ fn with_subagent(self, subagent_handle: FakeSubagentHandle) -> Self {
+ Self {
+ subagent_handle: Some(subagent_handle.into()),
+ ..self
+ }
+ }
+
pub(crate) fn terminal_creation_count(&self) -> usize {
self.terminal_creations.load(Ordering::SeqCst)
}
@@ -209,6 +217,10 @@ impl FakeThreadEnvironment {
pub(crate) fn terminal_output_limits(&self) -> Vec<Option<u64>> {
self.terminal_output_limits.borrow().clone()
}
+
+ fn subagent_models(&self) -> Vec<Option<AgentModelId>> {
+ self.subagent_models.borrow().clone()
+ }
}
impl crate::ThreadEnvironment for FakeThreadEnvironment {
@@ -232,7 +244,13 @@ impl crate::ThreadEnvironment for FakeThreadEnvironment {
Task::ready(Ok(handle as Rc<dyn crate::TerminalHandle>))
}
- fn create_subagent(&self, _label: String, _cx: &mut App) -> Result<Rc<dyn SubagentHandle>> {
+ fn create_subagent(
+ &self,
+ _label: String,
+ model: Option<AgentModelId>,
+ _cx: &mut App,
+ ) -> Result<Rc<dyn SubagentHandle>> {
+ self.subagent_models.borrow_mut().push(model);
Ok(self
.subagent_handle
.clone()
@@ -273,7 +291,12 @@ impl crate::ThreadEnvironment for MultiTerminalEnvironment {
Task::ready(Ok(handle as Rc<dyn crate::TerminalHandle>))
}
- fn create_subagent(&self, _label: String, _cx: &mut App) -> Result<Rc<dyn SubagentHandle>> {
+ fn create_subagent(
+ &self,
+ _label: String,
+ _model: Option<AgentModelId>,
+ _cx: &mut App,
+ ) -> Result<Rc<dyn SubagentHandle>> {
unimplemented!()
}
}
@@ -5514,6 +5537,77 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
}
}
+#[gpui::test]
+async fn test_spawn_agent_tool_forwards_explicit_model(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let environment = Rc::new(
+ FakeThreadEnvironment::default().with_subagent(FakeSubagentHandle {
+ session_id: acp::SessionId::new("subagent-id"),
+ send_task: Task::ready("done".to_string()).shared(),
+ }),
+ );
+ #[allow(clippy::arc_with_non_send_sync)]
+ let tool = Arc::new(SpawnAgentTool::new(environment.clone()));
+ let (event_stream, _rx) = ToolCallEventStream::test();
+
+ let result = cx
+ .update(|cx| {
+ tool.run(
+ ToolInput::resolved(SpawnAgentToolInput {
+ label: "task".to_string(),
+ message: "prompt".to_string(),
+ session_id: None,
+ model: Some("fake-corp/cheap-model".to_string()),
+ }),
+ event_stream,
+ cx,
+ )
+ })
+ .await;
+
+ assert!(matches!(result, Ok(SpawnAgentToolOutput::Success { .. })));
+ assert_eq!(
+ environment.subagent_models(),
+ vec![Some(AgentModelId::from(
+ "fake-corp/cheap-model".to_string()
+ ))]
+ );
+}
+
+#[gpui::test]
+async fn test_spawn_agent_tool_rejects_model_when_resuming(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ let environment = Rc::new(FakeThreadEnvironment::default());
+ #[allow(clippy::arc_with_non_send_sync)]
+ let tool = Arc::new(SpawnAgentTool::new(environment));
+ let (event_stream, _rx) = ToolCallEventStream::test();
+
+ let result = cx
+ .update(|cx| {
+ tool.run(
+ ToolInput::resolved(SpawnAgentToolInput {
+ label: "task".to_string(),
+ message: "prompt".to_string(),
+ session_id: Some(acp::SessionId::new("subagent-id")),
+ model: Some("fake-corp/other-model".to_string()),
+ }),
+ event_stream,
+ cx,
+ )
+ })
+ .await;
+
+ let Err(SpawnAgentToolOutput::Error { error, .. }) = result else {
+ panic!("expected model override on resumed session to fail");
+ };
+ assert_eq!(
+ error,
+ "model cannot be changed when resuming a subagent session"
+ );
+}
+
#[gpui::test]
async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {
init_test(cx);
@@ -5567,6 +5661,7 @@ async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {
label: "label".to_string(),
message: "subagent task prompt".to_string(),
session_id: None,
+ model: None,
};
let subagent_tool_use = LanguageModelToolUse {
id: "subagent_1".into(),
@@ -5704,6 +5799,7 @@ async fn test_subagent_tool_output_does_not_include_thinking(cx: &mut TestAppCon
label: "label".to_string(),
message: "subagent task prompt".to_string(),
session_id: None,
+ model: None,
};
let subagent_tool_use = LanguageModelToolUse {
id: "subagent_1".into(),
@@ -5854,6 +5950,7 @@ async fn test_subagent_tool_call_cancellation_during_task_prompt(cx: &mut TestAp
label: "label".to_string(),
message: "subagent task prompt".to_string(),
session_id: None,
+ model: None,
};
let subagent_tool_use = LanguageModelToolUse {
id: "subagent_1".into(),
@@ -5986,6 +6083,7 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {
label: "initial task".to_string(),
message: "do the first task".to_string(),
session_id: None,
+ model: None,
};
let subagent_tool_use = LanguageModelToolUse {
id: "subagent_1".into(),
@@ -6050,6 +6148,7 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {
label: "follow-up task".to_string(),
message: "do the follow-up task".to_string(),
session_id: Some(subagent_session_id.clone()),
+ model: None,
};
let resume_tool_use = LanguageModelToolUse {
id: "subagent_2".into(),
@@ -6145,7 +6244,7 @@ async fn test_subagent_thread_inherits_parent_thread_properties(cx: &mut TestApp
)
});
- let subagent_thread = cx.new(|cx| Thread::new_subagent(&parent_thread, cx));
+ let subagent_thread = cx.new(|cx| Thread::new_subagent(&parent_thread, None, cx));
subagent_thread.read_with(cx, |subagent_thread, cx| {
assert!(subagent_thread.is_subagent());
assert_eq!(subagent_thread.depth(), 1);
@@ -6166,7 +6265,7 @@ async fn test_subagent_thread_inherits_parent_thread_properties(cx: &mut TestApp
}
#[gpui::test]
-async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppContext) {
+async fn test_subagent_thread_model_selection(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
@@ -6183,6 +6282,12 @@ async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppCon
"Subagent Model",
true,
));
+ let explicit_model = Arc::new(FakeLanguageModel::with_id_and_thinking(
+ "fake-corp",
+ "explicit-model",
+ "Explicit Model",
+ false,
+ ));
cx.update(|cx| {
LanguageModelRegistry::test(cx);
@@ -6192,7 +6297,7 @@ async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppCon
LanguageModelProviderId::from("fake-corp".to_string()),
LanguageModelProviderName::from("Fake Corp".to_string()),
)
- .with_models(vec![subagent_model.clone()]),
+ .with_models(vec![subagent_model.clone(), explicit_model.clone()]),
);
LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
registry.register_provider(provider, cx);
@@ -6220,7 +6325,17 @@ async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppCon
)
});
- let subagent_thread = cx.new(|cx| Thread::new_subagent(&parent_thread, cx));
+ let subagent_thread = cx.new(|cx| Thread::new_subagent(&parent_thread, None, cx));
+ let explicit_selection = LanguageModelSelection {
+ provider: LanguageModelProviderSetting("fake-corp".to_string()),
+ model: "explicit-model".to_string(),
+ enable_thinking: false,
+ effort: None,
+ speed: None,
+ };
+ let explicit_subagent_thread =
+ cx.new(|cx| Thread::new_subagent(&parent_thread, Some(&explicit_selection), cx));
+
subagent_thread.read_with(cx, |subagent_thread, _cx| {
assert_eq!(
subagent_thread.model().map(|model| model.id()),
@@ -6230,8 +6345,18 @@ async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppCon
assert_eq!(subagent_thread.thinking_effort(), Some(&"high".to_string()));
});
+ explicit_subagent_thread.read_with(cx, |subagent_thread, _cx| {
+ assert_eq!(
+ subagent_thread.model().map(|model| model.id()),
+ Some(explicit_model.id())
+ );
+ assert!(!subagent_thread.thinking_enabled());
+ assert_eq!(subagent_thread.thinking_effort(), None);
+ });
+
parent_thread.update(cx, |parent_thread, _cx| {
parent_thread.register_running_subagent(subagent_thread.downgrade());
+ parent_thread.register_running_subagent(explicit_subagent_thread.downgrade());
});
parent_thread.update(cx, |parent_thread, cx| {
parent_thread.set_model(parent_model.clone(), cx);
@@ -6247,6 +6372,14 @@ async fn test_subagent_thread_uses_configured_subagent_model(cx: &mut TestAppCon
assert!(subagent_thread.thinking_enabled());
assert_eq!(subagent_thread.thinking_effort(), Some(&"high".to_string()));
});
+ explicit_subagent_thread.read_with(cx, |subagent_thread, _cx| {
+ assert_eq!(
+ subagent_thread.model().map(|model| model.id()),
+ Some(explicit_model.id())
+ );
+ assert!(!subagent_thread.thinking_enabled());
+ assert_eq!(subagent_thread.thinking_effort(), None);
+ });
}
#[gpui::test]
@@ -6285,7 +6418,7 @@ async fn test_max_subagent_depth_prevents_tool_registration(cx: &mut TestAppCont
thread
});
let deep_subagent_thread = cx.new(|cx| {
- let mut thread = Thread::new_subagent(&deep_parent_thread, cx);
+ let mut thread = Thread::new_subagent(&deep_parent_thread, None, cx);
thread.add_default_tools(environment, cx);
thread
});
@@ -6414,7 +6547,7 @@ async fn test_lsp_tools_gated_by_feature_flag(cx: &mut TestAppContext) {
}
#[gpui::test]
-async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext) {
+async fn test_thread_tools_feature_gating(cx: &mut TestAppContext) {
init_test(cx);
// `CreateThreadToolFeatureFlag::enabled_for_staff()` returns true, which
@@ -6468,21 +6601,14 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
thread
});
- let sibling_tool_names = [CreateThreadTool::NAME, ListAgentsAndModelsTool::NAME];
-
- // Like the LSP/rename tools, sibling-thread tools are registered
- // unconditionally and gated only at exposure time. The registration must
- // be visible regardless of the flag's current value.
+ // Both tools are registered regardless of feature state. Only creating a
+ // sibling thread is gated; model discovery is also used by subagents.
thread.read_with(cx, |thread, _| {
- for name in &sibling_tool_names {
- assert!(
- thread.has_registered_tool(name),
- "expected sibling-thread tool {name} to be registered"
- );
- }
+ assert!(thread.has_registered_tool(CreateThreadTool::NAME));
+ assert!(thread.has_registered_tool(ListAgentsAndModelsTool::NAME));
});
- // Flag explicitly off: a completion request must omit the tools.
+ // Flag explicitly off: model discovery remains available.
set_flag_override("off", cx);
thread
.update(cx, |thread, cx| {
@@ -6493,13 +6619,12 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
let completion = model.pending_completions().pop().unwrap();
let tool_names = tool_names_for_completion(&completion);
- for name in &sibling_tool_names {
- assert!(
- !tool_names.iter().any(|t| t == name),
- "expected {name} to be hidden when create-thread-tool flag is off, \
- but completion tools were: {tool_names:?}"
- );
- }
+ assert!(!tool_names.iter().any(|tool| tool == CreateThreadTool::NAME));
+ assert!(
+ tool_names
+ .iter()
+ .any(|tool| tool == ListAgentsAndModelsTool::NAME)
+ );
// Sanity check: an unrelated default tool should still be exposed.
assert!(
tool_names.iter().any(|t| t == ReadFileTool::NAME),
@@ -6508,7 +6633,7 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
model.end_last_completion_stream();
cx.run_until_parked();
- // Flag explicitly on: the next completion request must include both tools.
+ // Flag explicitly on: the next completion request includes both tools.
set_flag_override("on", cx);
thread
.update(cx, |thread, cx| {
@@ -6519,13 +6644,12 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
let completion = model.pending_completions().pop().unwrap();
let tool_names = tool_names_for_completion(&completion);
- for name in &sibling_tool_names {
- assert!(
- tool_names.iter().any(|t| t == name),
- "expected {name} to be exposed when create-thread-tool flag is on, \
- but completion tools were: {tool_names:?}"
- );
- }
+ assert!(tool_names.iter().any(|tool| tool == CreateThreadTool::NAME));
+ assert!(
+ tool_names
+ .iter()
+ .any(|tool| tool == ListAgentsAndModelsTool::NAME)
+ );
}
#[gpui::test]
@@ -6556,7 +6680,7 @@ async fn test_parent_cancel_stops_subagent(cx: &mut TestAppContext) {
)
});
- let subagent = cx.new(|cx| Thread::new_subagent(&parent, cx));
+ let subagent = cx.new(|cx| Thread::new_subagent(&parent, None, cx));
parent.update(cx, |thread, _cx| {
thread.register_running_subagent(subagent.downgrade());
@@ -6999,6 +7123,7 @@ async fn test_subagent_error_propagation(cx: &mut TestAppContext) {
label: "label".to_string(),
message: "subagent task prompt".to_string(),
session_id: None,
+ model: None,
};
let subagent_tool_use = LanguageModelToolUse {
id: "subagent_1".into(),
@@ -8873,7 +8998,7 @@ impl SubagentCompactionTest {
acp_thread: acp_thread.downgrade(),
};
let handle = cx
- .update(|cx| environment.create_subagent_thread("subagent".to_string(), cx))
+ .update(|cx| environment.create_subagent_thread("subagent".to_string(), None, cx))
.unwrap();
let thread = agent.read_with(cx, |agent, _| {
agent.sessions.get(&handle.id()).unwrap().thread.clone()
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index c14739b2491..be234e5147b 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -7,7 +7,7 @@ use crate::{
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision, WebSearchTool,
WriteFileTool, decide_permission_from_settings,
};
-use acp_thread::{ClientUserMessageId, MentionUri};
+use acp_thread::{AgentModelId, ClientUserMessageId, MentionUri};
use action_log::ActionLog;
use agent_settings::UserAgentsMd;
@@ -787,7 +787,12 @@ pub trait ThreadEnvironment {
cx: &mut AsyncApp,
) -> Task<Result<Rc<dyn TerminalHandle>>>;
- fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>>;
+ fn create_subagent(
+ &self,
+ label: String,
+ model: Option<AgentModelId>,
+ cx: &mut App,
+ ) -> Result<Rc<dyn SubagentHandle>>;
fn resume_subagent(
&self,
@@ -884,6 +889,7 @@ pub struct AvailableAgent {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AvailableModel {
/// Identifier to pass as the `model` field when creating a thread.
+ /// For `spawn_agent`, use a model from the native Zed agent entry.
pub id: String,
/// Human-readable name.
pub name: SharedString,
@@ -1333,12 +1339,16 @@ impl Thread {
.embedded_context(true)
}
- pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
+ pub fn new_subagent(
+ parent_thread: &Entity<Thread>,
+ model_selection: Option<&LanguageModelSelection>,
+ cx: &mut Context<Self>,
+ ) -> Self {
let project = parent_thread.read(cx).project.clone();
let project_context = parent_thread.read(cx).project_context.clone();
let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
let templates = parent_thread.read(cx).templates.clone();
- let model = parent_thread.read(cx).model().cloned();
+ let parent_model = parent_thread.read(cx).model().cloned();
let parent_action_log = parent_thread.read(cx).action_log().clone();
let action_log =
cx.new(|_cx| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));
@@ -1347,7 +1357,7 @@ impl Thread {
project_context,
context_server_registry,
templates,
- model,
+ parent_model,
action_log,
cx,
);
@@ -1356,9 +1366,12 @@ impl Thread {
depth: parent_thread.read(cx).depth() + 1,
});
thread.inherit_parent_settings(parent_thread, cx);
- if let Some(subagent_model) = AgentSettings::get_global(cx).subagent_model.clone() {
+ let model_selection = model_selection
+ .cloned()
+ .or_else(|| AgentSettings::get_global(cx).subagent_model.clone());
+ if let Some(model_selection) = model_selection {
thread.inherits_parent_model_settings = false;
- thread.apply_model_selection(&subagent_model, cx);
+ thread.apply_model_selection(&model_selection, cx);
}
thread
}
@@ -8351,7 +8364,7 @@ mod tests {
cx.update(|cx| {
let mut subagents = Vec::new();
for _ in 0..count {
- let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
+ let subagent = cx.new(|cx| Thread::new_subagent(parent, None, cx));
parent.update(cx, |thread, _cx| {
thread.register_running_subagent(subagent.downgrade());
});
diff --git a/crates/agent/src/tools.rs b/crates/agent/src/tools.rs
index 0059a1ba128..9b37432bfa8 100644
--- a/crates/agent/src/tools.rs
+++ b/crates/agent/src/tools.rs
@@ -237,9 +237,7 @@ pub fn tool_feature_flag_enabled(tool_name: &str, cx: &App) -> bool {
| GetCodeActionsTool::NAME
| ApplyCodeActionTool::NAME
| GoToDefinitionTool::NAME => cx.has_flag::<LspToolFeatureFlag>(),
- CreateThreadTool::NAME | ListAgentsAndModelsTool::NAME => {
- cx.has_flag::<CreateThreadToolFeatureFlag>()
- }
+ CreateThreadTool::NAME => cx.has_flag::<CreateThreadToolFeatureFlag>(),
_ => true,
}
}
diff --git a/crates/agent/src/tools/list_agents_and_models_tool.rs b/crates/agent/src/tools/list_agents_and_models_tool.rs
index c4fe9c7e33c..a3df18d0931 100644
--- a/crates/agent/src/tools/list_agents_and_models_tool.rs
+++ b/crates/agent/src/tools/list_agents_and_models_tool.rs
@@ -9,9 +9,14 @@ use std::sync::Arc;
use crate::{AgentTool, AvailableAgents, ThreadEnvironment, ToolCallEventStream, ToolInput};
-/// List the agents and models available for use with the `create_thread` tool.
+/// List the agents and models available for use with the `create_thread` and
+/// `spawn_agent` tools.
///
-/// Call this before `create_thread` if you need to pick a specific agent or a
+/// The result may include external agents. The `spawn_agent` tool creates a
+/// native Zed subagent, so its `model` must be an exact `models[].id` from the
+/// agent entry where `is_native` is `true`.
+///
+/// Call this before either tool if you need to pick a specific agent or a
/// non-default model (for example, to use a cheaper model for bulk work). If
/// you're happy with the user's current defaults, you don't need to call this.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
diff --git a/crates/agent/src/tools/spawn_agent_tool.rs b/crates/agent/src/tools/spawn_agent_tool.rs
index bc871a2f2c7..ddb4c66a65f 100644
--- a/crates/agent/src/tools/spawn_agent_tool.rs
+++ b/crates/agent/src/tools/spawn_agent_tool.rs
@@ -8,6 +8,8 @@ use serde::{Deserialize, Deserializer, Serialize};
use std::rc::Rc;
use std::sync::Arc;
+use acp_thread::AgentModelId;
+
use crate::{AgentTool, ThreadEnvironment, ToolCallEventStream, ToolInput};
/// Spawn a sub-agent for a well-scoped task.
@@ -30,6 +32,12 @@ use crate::{AgentTool, ThreadEnvironment, ToolCallEventStream, ToolInput};
/// - When a plan has multiple independent steps, prefer delegating those steps in parallel rather than serializing them unnecessarily.
/// - Reuse the returned session_id when you want to follow up on the same delegated subproblem instead of creating a duplicate session.
///
+/// ### Model selection
+/// - When the user requests a particular model or asks you to choose based on cost or capability, call `list_agents_and_models` first, then pass the exact `models[].id` from the native Zed agent entry (`is_native: true`) in `model`.
+/// - Omit `model` to use the user's configured subagent model, or the parent model when no subagent model is configured.
+/// - Do not silently choose a different model when an explicit model is unavailable unless the user allowed fallback.
+/// - A resumed session keeps its existing model, so `model` cannot be combined with `session_id`.
+///
/// ### Output
/// - You will receive only the agent's final message as output.
/// - Successful calls return a session_id that you can use for follow-up messages.
@@ -44,6 +52,11 @@ pub struct SpawnAgentToolInput {
/// Session ID of an existing agent session to continue instead of creating a new one. Omit to create a new agent.
#[serde(default, deserialize_with = "deserialize_session_id")]
pub session_id: Option<acp::SessionId>,
+ /// Optional model override. Pass the exact `models[].id` returned for the
+ /// native Zed agent (`is_native: true`) by `list_agents_and_models`.
+ /// Omit to preserve default behavior.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub model: Option<String>,
}
fn deserialize_session_id<'de, D>(deserializer: D) -> Result<Option<acp::SessionId>, D::Error>
@@ -161,11 +174,22 @@ impl AgentTool for SpawnAgentTool {
session_info: None,
})?;
+ let SpawnAgentToolInput {
+ label,
+ message,
+ session_id,
+ model,
+ } = input;
let (subagent, mut session_info) = cx.update(|cx| {
- let subagent = if let Some(session_id) = input.session_id {
- self.environment.resume_subagent(session_id, cx)
- } else {
- self.environment.create_subagent(input.label, cx)
+ let subagent = match (session_id, model) {
+ (Some(_), Some(_)) => Err(anyhow::anyhow!(
+ "model cannot be changed when resuming a subagent session"
+ )),
+ (Some(session_id), None) => self.environment.resume_subagent(session_id, cx),
+ (None, model) => {
+ self.environment
+ .create_subagent(label, model.map(AgentModelId::from), cx)
+ }
};
let subagent = subagent.map_err(|err| SpawnAgentToolOutput::Error {
session_id: None,
@@ -190,7 +214,7 @@ impl AgentTool for SpawnAgentTool {
Ok((subagent, session_info))
})?;
- let send_result = subagent.send(input.message, cx).await;
+ let send_result = subagent.send(message, cx).await;
let status = if send_result.is_ok() {
"completed"
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 064faad4309..8a146247b87 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -4906,40 +4906,7 @@ impl agent::SiblingThreadHost for AgentPanelSiblingHost {
.upgrade()
.ok_or_else(|| anyhow!("Agent panel is no longer available"))?;
- let mut agents = Vec::new();
-
- // Native Zed agent — always available, and we can enumerate models
- // directly from the language model registry.
- let native_models = {
- let registry = LanguageModelRegistry::read_global(cx);
- let default = registry.default_model();
- let mut models = Vec::new();
- for provider in registry.providers() {
- if !provider.is_authenticated(cx) {
- continue;
- }
- let provider_id = provider.id();
- for model in provider.provided_models(cx) {
- let id = format!("{}/{}", provider_id.0, model.id().0);
- let is_default = default
- .as_ref()
- .map(|cm| cm.provider.id() == provider_id && cm.model.id() == model.id())
- .unwrap_or(false);
- models.push(agent::AvailableModel {
- id,
- name: model.name().0,
- is_default,
- });
- }
- }
- models
- };
- agents.push(agent::AvailableAgent {
- id: agent::ZED_AGENT_ID.to_string(),
- name: Agent::NativeAgent.label(),
- is_native: true,
- models: native_models,
- });
+ let mut agents = vec![agent::available_native_agent(cx)];
let project = panel.read(cx).project.clone();
let agent_server_store = project.read(cx).agent_server_store().clone();
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index dea51ba96c4..38dda4b233d 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -10686,6 +10686,13 @@ impl ThreadView {
_ => false,
});
+ let model_name = thread_view
+ .and_then(|view| view.read(cx).as_native_thread(cx))
+ .and_then(|thread| {
+ let thread = thread.read(cx);
+ let model = thread.model()?;
+ Some(model.name().0)
+ });
let thread_title = thread
.as_ref()
.and_then(|t| t.read(cx).title())
@@ -10787,33 +10794,64 @@ impl ThreadView {
.child(
h_flex()
.min_w_0()
- .w_full()
+ .flex_1()
.gap_1p5()
- .child(icon)
+ .justify_between()
.child(
- Label::new(title.to_string())
- .size(LabelSize::Custom(self.tool_name_font_size()))
- .truncate(),
+ h_flex()
+ .min_w_0()
+ .flex_initial()
+ .gap_1p5()
+ .child(icon)
+ .child(
+ Label::new(title.to_string())
+ .size(LabelSize::Custom(
+ self.tool_name_font_size(),
+ ))
+ .flex_1()
+ .truncate(),
+ )
+ .when_some(model_name, |this, model_name| {
+ this.child(
+ Label::new(format!("· {model_name}"))
+ .size(LabelSize::Custom(
+ self.tool_name_font_size(),
+ ))
+ .color(Color::Muted)
+ .truncate(),
+ )
+ }),
)
.when(files_changed > 0, |this| {
this.child(
- Label::new(format!(
- "— {} {} changed",
- files_changed,
- if files_changed == 1 { "file" } else { "files" }
- ))
- .size(LabelSize::Custom(self.tool_name_font_size()))
- .color(Color::Muted),
- )
- .child(
- DiffStat::new(
- diff_stat_id.clone(),
- diff_stats.lines_added as usize,
- diff_stats.lines_removed as usize,
- )
- .label_size(LabelSize::Custom(
- self.tool_name_font_size(),
- )),
+ h_flex()
+ .flex_none()
+ .gap_1p5()
+ .child(
+ Label::new(format!(
+ "— {} {} changed",
+ files_changed,
+ if files_changed == 1 {
+ "file"
+ } else {
+ "files"
+ }
+ ))
+ .size(LabelSize::Custom(
+ self.tool_name_font_size(),
+ ))
+ .color(Color::Muted),
+ )
+ .child(
+ DiffStat::new(
+ diff_stat_id.clone(),
+ diff_stats.lines_added as usize,
+ diff_stats.lines_removed as usize,
+ )
+ .label_size(LabelSize::Custom(
+ self.tool_name_font_size(),
+ )),
+ ),
)
}),
)