logiguard fork: GPUI xdg-activation keyboard-focus serial fix
Some checks failed
Update All Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Triage Project Sync (#84) / Sync triage project (push) Has been cancelled
release_nightly / notify_on_failure (push) Has been cancelled
release_nightly / check_style (push) Has been cancelled
release_nightly / run_tests_windows (push) Has been cancelled
release_nightly / clippy_windows (push) Has been cancelled
release_nightly / bundle_linux_aarch64 (push) Has been cancelled
release_nightly / bundle_linux_x86_64 (push) Has been cancelled
release_nightly / bundle_mac_aarch64 (push) Has been cancelled
release_nightly / bundle_mac_x86_64 (push) Has been cancelled
release_nightly / bundle_windows_aarch64 (push) Has been cancelled
release_nightly / bundle_windows_x86_64 (push) Has been cancelled
release_nightly / build_nix_linux_x86_64 (push) Has been cancelled
release_nightly / build_nix_mac_aarch64 (push) Has been cancelled
release_nightly / update_nightly_tag (push) Has been cancelled
Hotfix Review Monitor / check-hotfix-reviews (push) Has been cancelled
Stale PR Review Reminder / check-stale-prs (push) Has been cancelled
Update Weekly Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Bump collab-staging Tag / update-collab-staging-tag (push) Has been cancelled
compliance_check / scheduled_compliance_check (push) Has been cancelled

Single-commit orphan branch: full zed-industries/zed @ 8c74db0 source tree
with a 3-file patch applied (no upstream history).

Patch (crates/gpui_linux/src/linux/wayland/):
  - serial.rs: add SerialKind::KeyboardEnter
  - client.rs: store wl_keyboard.enter serial; add latest_serial_of()
  - window.rs: activate() uses keyboard-enter serial (Mutter focus gate)

Mutter honors window activation only when the token carries the keyboard-
focus serial from wl_keyboard.enter; GPUI used a stale mouse-press serial.
See docs/tray-window-focus-wayland.md in logiguard.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mohamad Khani
2026-07-14 02:22:17 +03:30
commit b72a46db68
3984 changed files with 1583326 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
[package]
name = "agent_servers"
version = "0.1.0"
edition.workspace = true
publish.workspace = true
license = "GPL-3.0-or-later"
[features]
test-support = ["acp_thread/test-support", "gpui/test-support", "project/test-support", "dep:env_logger", "client/test-support", "dep:gpui_tokio", "reqwest_client/test-support"]
e2e = []
[lints]
workspace = true
[lib]
path = "src/agent_servers.rs"
doctest = false
[dependencies]
acp_thread.workspace = true
action_log.workspace = true
async-channel.workspace = true
agent-client-protocol.workspace = true
anyhow.workspace = true
chrono.workspace = true
client.workspace = true
collections.workspace = true
env_logger = { workspace = true, optional = true }
fs.workspace = true
futures.workspace = true
gpui.workspace = true
feature_flags.workspace = true
gpui_tokio = { workspace = true, optional = true }
google_ai.workspace = true
http_client.workspace = true
indoc.workspace = true
language_model.workspace = true
log.workspace = true
project.workspace = true
release_channel.workspace = true
remote.workspace = true
reqwest_client = { workspace = true, optional = true }
serde.workspace = true
serde_json.workspace = true
settings.workspace = true
task.workspace = true
tempfile.workspace = true
thiserror.workspace = true
ui.workspace = true
terminal.workspace = true
uuid.workspace = true
util.workspace = true
watch.workspace = true
zed_credentials_provider.workspace = true
[target.'cfg(unix)'.dependencies]
libc.workspace = true
nix.workspace = true
[dev-dependencies]
client = { workspace = true, features = ["test-support"] }
env_logger.workspace = true
fs.workspace = true
indoc.workspace = true
acp_thread = { workspace = true, features = ["test-support"] }
gpui = { workspace = true, features = ["test-support"] }
gpui_tokio.workspace = true
project = { workspace = true, features = ["test-support"] }
reqwest_client = { workspace = true, features = ["test-support"] }
settings = { workspace = true, features = ["test-support"] }

View File

@@ -0,0 +1 @@
../../LICENSE-GPL

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,157 @@
mod acp;
mod custom;
#[cfg(any(test, feature = "test-support"))]
pub mod e2e_tests;
use client::ProxySettings;
use collections::{HashMap, HashSet};
pub use custom::*;
use fs::Fs;
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 as acp_schema;
use anyhow::Result;
use gpui::{App, AppContext, Entity, Task};
use settings::SettingsStore;
use std::{any::Any, rc::Rc, sync::Arc};
#[cfg(any(test, feature = "test-support"))]
pub use acp::test_support::{
FakeAcpAgentServer, FakeAcpConnectionHarness, connect_fake_acp_connection,
};
pub use acp::{
AcpConnection, AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection,
GEMINI_TERMINAL_AUTH_METHOD_ID,
};
pub struct AgentServerDelegate {
store: Entity<AgentServerStore>,
new_version_available: Option<watch::Sender<Option<String>>>,
}
impl AgentServerDelegate {
pub fn new(
store: Entity<AgentServerStore>,
new_version_tx: Option<watch::Sender<Option<String>>>,
) -> Self {
Self {
store,
new_version_available: new_version_tx,
}
}
}
pub trait AgentServer: Send {
fn logo(&self) -> ui::IconName;
fn agent_id(&self) -> AgentId;
fn connect(
&self,
delegate: AgentServerDelegate,
project: Entity<Project>,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>>;
fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
fn default_mode(&self, _cx: &App) -> Option<acp_schema::SessionModeId> {
None
}
fn set_default_mode(
&self,
_mode_id: Option<acp_schema::SessionModeId>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
}
fn default_model(&self, _cx: &App) -> Option<acp_schema::ModelId> {
None
}
fn set_default_model(
&self,
_model_id: Option<acp_schema::ModelId>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
}
fn favorite_model_ids(&self, _cx: &mut App) -> HashSet<acp_schema::ModelId> {
HashSet::default()
}
fn default_config_option(&self, _config_id: &str, _cx: &App) -> Option<String> {
None
}
fn set_default_config_option(
&self,
_config_id: &str,
_value_id: Option<&str>,
_fs: Arc<dyn Fs>,
_cx: &mut App,
) {
}
fn favorite_config_option_value_ids(
&self,
_config_id: &acp_schema::SessionConfigId,
_cx: &mut App,
) -> HashSet<acp_schema::SessionConfigValueId> {
HashSet::default()
}
fn toggle_favorite_config_option_value(
&self,
_config_id: acp_schema::SessionConfigId,
_value_id: acp_schema::SessionConfigValueId,
_should_be_favorite: bool,
_fs: Arc<dyn Fs>,
_cx: &App,
) {
}
fn toggle_favorite_model(
&self,
_model_id: acp_schema::ModelId,
_should_be_favorite: bool,
_fs: Arc<dyn Fs>,
_cx: &App,
) {
}
}
impl dyn AgentServer {
pub fn downcast<T: 'static + AgentServer + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
self.into_any().downcast().ok()
}
}
/// Load the default proxy environment variables to pass through to the agent
pub fn load_proxy_env(cx: &mut App) -> HashMap<String, String> {
let proxy_url = cx
.read_global(|settings: &SettingsStore, _| settings.get::<ProxySettings>(None).proxy_url());
let mut env = HashMap::default();
if let Some(proxy_url) = &proxy_url {
let env_var = if proxy_url.scheme() == "https" {
"HTTPS_PROXY"
} else {
"HTTP_PROXY"
};
env.insert(env_var.to_owned(), proxy_url.to_string());
}
if let Some(no_proxy) = read_no_proxy_from_env() {
env.insert("NO_PROXY".to_owned(), no_proxy);
} else if proxy_url.is_some() {
// We sometimes need local MCP servers that we don't want to proxy
env.insert("NO_PROXY".to_owned(), "localhost,127.0.0.1".to_owned());
}
env
}

View File

@@ -0,0 +1,599 @@
use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use agent_client_protocol::schema as acp;
use anyhow::{Context as _, Result};
use collections::HashSet;
use fs::Fs;
use gpui::{App, AppContext as _, Entity, Task};
use language_model::{ApiKey, EnvVar};
use project::{
Project,
agent_server_store::{AgentId, AllAgentServersSettings},
};
use settings::{SettingsStore, update_settings_file};
use std::{rc::Rc, sync::Arc};
use ui::IconName;
pub const GEMINI_ID: &str = "gemini";
pub const CLAUDE_AGENT_ID: &str = "claude-acp";
pub const CODEX_ID: &str = "codex-acp";
/// A generic agent server implementation for custom user-defined agents
pub struct CustomAgentServer {
agent_id: AgentId,
}
impl CustomAgentServer {
pub fn new(agent_id: AgentId) -> Self {
Self { agent_id }
}
}
impl AgentServer for CustomAgentServer {
fn agent_id(&self) -> AgentId {
self.agent_id.clone()
}
fn logo(&self) -> IconName {
IconName::Terminal
}
fn default_mode(&self, cx: &App) -> Option<acp::SessionModeId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().0.as_ref())
.cloned()
});
settings
.as_ref()
.and_then(|s| s.default_mode().map(acp::SessionModeId::new))
}
fn favorite_config_option_value_ids(
&self,
config_id: &acp::SessionConfigId,
cx: &mut App,
) -> HashSet<acp::SessionConfigValueId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().0.as_ref())
.cloned()
});
settings
.as_ref()
.and_then(|s| s.favorite_config_option_values(config_id.0.as_ref()))
.map(|values| {
values
.iter()
.cloned()
.map(acp::SessionConfigValueId::new)
.collect()
})
.unwrap_or_default()
}
fn toggle_favorite_config_option_value(
&self,
config_id: acp::SessionConfigId,
value_id: acp::SessionConfigValueId,
should_be_favorite: bool,
fs: Arc<dyn Fs>,
cx: &App,
) {
let agent_id = self.agent_id();
let config_id = config_id.to_string();
let value_id = value_id.to_string();
update_settings_file(fs, cx, move |settings, cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
match settings {
settings::CustomAgentServerSettings::Custom {
favorite_config_option_values,
..
}
| settings::CustomAgentServerSettings::Extension {
favorite_config_option_values,
..
}
| settings::CustomAgentServerSettings::Registry {
favorite_config_option_values,
..
} => {
let entry = favorite_config_option_values
.entry(config_id.clone())
.or_insert_with(Vec::new);
if should_be_favorite {
if !entry.iter().any(|v| v == &value_id) {
entry.push(value_id.clone());
}
} else {
entry.retain(|v| v != &value_id);
if entry.is_empty() {
favorite_config_option_values.remove(&config_id);
}
}
}
}
});
}
fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
match settings {
settings::CustomAgentServerSettings::Custom { default_mode, .. }
| settings::CustomAgentServerSettings::Extension { default_mode, .. }
| settings::CustomAgentServerSettings::Registry { default_mode, .. } => {
*default_mode = mode_id.map(|m| m.to_string());
}
}
});
}
fn default_model(&self, cx: &App) -> Option<acp::ModelId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().as_ref())
.cloned()
});
settings
.as_ref()
.and_then(|s| s.default_model().map(acp::ModelId::new))
}
fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
match settings {
settings::CustomAgentServerSettings::Custom { default_model, .. }
| settings::CustomAgentServerSettings::Extension { default_model, .. }
| settings::CustomAgentServerSettings::Registry { default_model, .. } => {
*default_model = model_id.map(|m| m.to_string());
}
}
});
}
fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().as_ref())
.cloned()
});
settings
.as_ref()
.map(|s| {
s.favorite_models()
.iter()
.map(|id| acp::ModelId::new(id.clone()))
.collect()
})
.unwrap_or_default()
}
fn toggle_favorite_model(
&self,
model_id: acp::ModelId,
should_be_favorite: bool,
fs: Arc<dyn Fs>,
cx: &App,
) {
let agent_id = self.agent_id();
update_settings_file(fs, cx, move |settings, cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
let favorite_models = match settings {
settings::CustomAgentServerSettings::Custom {
favorite_models, ..
}
| settings::CustomAgentServerSettings::Extension {
favorite_models, ..
}
| settings::CustomAgentServerSettings::Registry {
favorite_models, ..
} => favorite_models,
};
let model_id_str = model_id.to_string();
if should_be_favorite {
if !favorite_models.contains(&model_id_str) {
favorite_models.push(model_id_str);
}
} else {
favorite_models.retain(|id| id != &model_id_str);
}
});
}
fn default_config_option(&self, config_id: &str, cx: &App) -> Option<String> {
let settings = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().as_ref())
.cloned()
});
settings
.as_ref()
.and_then(|s| s.default_config_option(config_id).map(|s| s.to_string()))
}
fn set_default_config_option(
&self,
config_id: &str,
value_id: Option<&str>,
fs: Arc<dyn Fs>,
cx: &mut App,
) {
let agent_id = self.agent_id();
let config_id = config_id.to_string();
let value_id = value_id.map(|s| s.to_string());
update_settings_file(fs, cx, move |settings, cx| {
let settings = settings
.agent_servers
.get_or_insert_default()
.entry(agent_id.0.to_string())
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
match settings {
settings::CustomAgentServerSettings::Custom {
default_config_options,
..
}
| settings::CustomAgentServerSettings::Extension {
default_config_options,
..
}
| settings::CustomAgentServerSettings::Registry {
default_config_options,
..
} => {
if let Some(value) = value_id.clone() {
default_config_options.insert(config_id.clone(), value);
} else {
default_config_options.remove(&config_id);
}
}
}
});
}
fn connect(
&self,
delegate: AgentServerDelegate,
project: Entity<Project>,
cx: &mut App,
) -> Task<Result<Rc<dyn AgentConnection>>> {
let agent_id = self.agent_id();
let default_mode = self.default_mode(cx);
let default_model = self.default_model(cx);
let is_registry_agent = is_registry_agent(agent_id.clone(), cx);
let default_config_options = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(self.agent_id().as_ref())
.map(|s| match s {
project::agent_server_store::CustomAgentServerSettings::Custom {
default_config_options,
..
}
| project::agent_server_store::CustomAgentServerSettings::Extension {
default_config_options,
..
}
| project::agent_server_store::CustomAgentServerSettings::Registry {
default_config_options,
..
} => default_config_options.clone(),
})
.unwrap_or_default()
});
if is_registry_agent {
if let Some(registry_store) = project::AgentRegistryStore::try_global(cx) {
registry_store.update(cx, |store, cx| store.refresh_if_stale(cx));
}
}
let mut extra_env = load_proxy_env(cx);
if delegate.store.read(cx).no_browser() {
extra_env.insert("NO_BROWSER".to_owned(), "1".to_owned());
}
if is_registry_agent {
match agent_id.as_ref() {
CLAUDE_AGENT_ID => {
extra_env.insert("ANTHROPIC_API_KEY".into(), "".into());
}
CODEX_ID => {
if let Ok(api_key) = std::env::var("CODEX_API_KEY") {
extra_env.insert("CODEX_API_KEY".into(), api_key);
}
if let Ok(api_key) = std::env::var("OPEN_AI_API_KEY") {
extra_env.insert("OPEN_AI_API_KEY".into(), api_key);
}
}
GEMINI_ID => {
extra_env.insert("SURFACE".to_owned(), "zed".to_owned());
}
_ => {}
}
}
let store = delegate.store.downgrade();
cx.spawn(async move |cx| {
if is_registry_agent && agent_id.as_ref() == GEMINI_ID {
if let Some(api_key) = cx.update(api_key_for_gemini_cli).await.ok() {
extra_env.insert("GEMINI_API_KEY".into(), api_key);
}
}
let command = store
.update(cx, |store, cx| {
let agent = store.get_external_agent(&agent_id).with_context(|| {
format!("Custom agent server `{}` is not registered", agent_id)
})?;
if let Some(new_version_available_tx) = delegate.new_version_available {
agent.set_new_version_available_tx(new_version_available_tx);
}
anyhow::Ok(agent.get_command(vec![], extra_env, &mut cx.to_async()))
})??
.await?;
let connection = crate::acp::connect(
agent_id,
project,
command,
store.clone(),
default_mode,
default_model,
default_config_options,
cx,
)
.await?;
Ok(connection)
})
}
fn into_any(self: Rc<Self>) -> Rc<dyn std::any::Any> {
self
}
}
fn api_key_for_gemini_cli(cx: &mut App) -> Task<Result<String>> {
let env_var = EnvVar::new("GEMINI_API_KEY".into()).or(EnvVar::new("GOOGLE_AI_API_KEY".into()));
if let Some(key) = env_var.value {
return Task::ready(Ok(key));
}
let credentials_provider = zed_credentials_provider::global(cx);
let api_url = google_ai::API_URL.to_string();
cx.spawn(async move |cx| {
Ok(
ApiKey::load_from_system_keychain(&api_url, credentials_provider.as_ref(), cx)
.await?
.key()
.to_string(),
)
})
}
fn is_registry_agent(agent_id: impl Into<AgentId>, cx: &App) -> bool {
let agent_id = agent_id.into();
let is_in_registry = project::AgentRegistryStore::try_global(cx)
.map(|store| store.read(cx).agent(&agent_id).is_some())
.unwrap_or(false);
let is_settings_registry = cx.read_global(|settings: &SettingsStore, _| {
settings
.get::<AllAgentServersSettings>(None)
.get(agent_id.as_ref())
.is_some_and(|s| {
matches!(
s,
project::agent_server_store::CustomAgentServerSettings::Registry { .. }
)
})
});
is_in_registry || is_settings_registry
}
fn default_settings_for_agent(
agent_id: impl Into<AgentId>,
cx: &App,
) -> settings::CustomAgentServerSettings {
if is_registry_agent(agent_id, cx) {
settings::CustomAgentServerSettings::Registry {
default_model: None,
default_mode: None,
env: Default::default(),
favorite_models: Vec::new(),
default_config_options: Default::default(),
favorite_config_option_values: Default::default(),
}
} else {
settings::CustomAgentServerSettings::Extension {
default_model: None,
default_mode: None,
env: Default::default(),
favorite_models: Vec::new(),
default_config_options: Default::default(),
favorite_config_option_values: Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use collections::HashMap;
use gpui::TestAppContext;
use project::agent_registry_store::{
AgentRegistryStore, RegistryAgent, RegistryAgentMetadata, RegistryNpxAgent,
};
use settings::Settings as _;
use ui::SharedString;
fn init_test(cx: &mut TestAppContext) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store);
});
}
fn init_registry_with_agents(cx: &mut TestAppContext, agent_ids: &[&str]) {
let agents: Vec<RegistryAgent> = agent_ids
.iter()
.map(|id| {
let id = SharedString::from(id.to_string());
RegistryAgent::Npx(RegistryNpxAgent {
metadata: RegistryAgentMetadata {
id: AgentId::new(id.clone()),
name: id.clone(),
description: SharedString::from(""),
version: SharedString::from("1.0.0"),
repository: None,
website: None,
icon_path: None,
},
package: id,
args: Vec::new(),
env: HashMap::default(),
})
})
.collect();
cx.update(|cx| {
AgentRegistryStore::init_test_global(cx, agents);
});
}
fn set_agent_server_settings(
cx: &mut TestAppContext,
entries: Vec<(&str, settings::CustomAgentServerSettings)>,
) {
cx.update(|cx| {
AllAgentServersSettings::override_global(
project::agent_server_store::AllAgentServersSettings(
entries
.into_iter()
.map(|(name, settings)| (name.to_string(), settings.into()))
.collect(),
),
cx,
);
});
}
#[gpui::test]
fn test_unknown_agent_is_not_registry(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
assert!(!is_registry_agent("my-custom-agent", cx));
});
}
#[gpui::test]
fn test_agent_in_registry_store_is_registry(cx: &mut TestAppContext) {
init_test(cx);
init_registry_with_agents(cx, &["some-new-registry-agent"]);
cx.update(|cx| {
assert!(is_registry_agent("some-new-registry-agent", cx));
assert!(!is_registry_agent("not-in-registry", cx));
});
}
#[gpui::test]
fn test_agent_with_registry_settings_type_is_registry(cx: &mut TestAppContext) {
init_test(cx);
set_agent_server_settings(
cx,
vec![(
"agent-from-settings",
settings::CustomAgentServerSettings::Registry {
env: HashMap::default(),
default_mode: None,
default_model: None,
favorite_models: Vec::new(),
default_config_options: HashMap::default(),
favorite_config_option_values: HashMap::default(),
},
)],
);
cx.update(|cx| {
assert!(is_registry_agent("agent-from-settings", cx));
});
}
#[gpui::test]
fn test_agent_with_extension_settings_type_is_not_registry(cx: &mut TestAppContext) {
init_test(cx);
set_agent_server_settings(
cx,
vec![(
"my-extension-agent",
settings::CustomAgentServerSettings::Extension {
env: HashMap::default(),
default_mode: None,
default_model: None,
favorite_models: Vec::new(),
default_config_options: HashMap::default(),
favorite_config_option_values: HashMap::default(),
},
)],
);
cx.update(|cx| {
assert!(!is_registry_agent("my-extension-agent", cx));
});
}
#[gpui::test]
fn test_default_settings_for_extension_agent(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
assert!(matches!(
default_settings_for_agent("some-extension-agent", cx),
settings::CustomAgentServerSettings::Extension { .. }
));
});
}
#[gpui::test]
fn test_default_settings_for_agent_in_registry(cx: &mut TestAppContext) {
init_test(cx);
init_registry_with_agents(cx, &["new-registry-agent"]);
cx.update(|cx| {
assert!(matches!(
default_settings_for_agent("new-registry-agent", cx),
settings::CustomAgentServerSettings::Registry { .. }
));
assert!(matches!(
default_settings_for_agent("not-in-registry", cx),
settings::CustomAgentServerSettings::Extension { .. }
));
});
}
}

View File

@@ -0,0 +1,500 @@
use crate::{AgentServer, AgentServerDelegate};
use acp_thread::{AcpThread, AgentThreadEntry, ToolCall, ToolCallStatus};
use agent_client_protocol::schema as acp;
use client::RefreshLlmTokenListener;
use futures::{FutureExt, StreamExt, channel::mpsc, select};
use gpui::AppContext;
use gpui::{Entity, TestAppContext};
use indoc::indoc;
use project::{FakeFs, Project};
#[cfg(test)]
use settings::Settings;
use std::{
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use util::path;
use util::path_list::PathList;
pub async fn test_basic<T, F>(server: F, cx: &mut TestAppContext)
where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as Arc<dyn fs::Fs>;
let project = Project::test(fs.clone(), [], cx).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), "/private/tmp", cx).await;
thread
.update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
.await
.unwrap();
thread.read_with(cx, |thread, _| {
assert!(
thread.entries().len() >= 2,
"Expected at least 2 entries. Got: {:?}",
thread.entries()
);
assert!(matches!(
thread.entries()[0],
AgentThreadEntry::UserMessage(_)
));
assert!(matches!(
thread.entries()[1],
AgentThreadEntry::AssistantMessage(_)
));
});
}
pub async fn test_path_mentions<T, F>(server: F, cx: &mut TestAppContext)
where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as _;
let tempdir = tempfile::tempdir().unwrap();
std::fs::write(
tempdir.path().join("foo.rs"),
indoc! {"
fn main() {
println!(\"Hello, world!\");
}
"},
)
.expect("failed to write file");
let project = Project::example([tempdir.path()], &mut cx.to_async()).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), tempdir.path(), cx).await;
thread
.update(cx, |thread, cx| {
thread.send(
vec![
"Read the file ".into(),
acp::ContentBlock::ResourceLink(acp::ResourceLink::new("foo.rs", "foo.rs")),
" and tell me what the content of the println! is".into(),
],
cx,
)
})
.await
.unwrap();
thread.read_with(cx, |thread, cx| {
assert!(matches!(
thread.entries()[0],
AgentThreadEntry::UserMessage(_)
));
let assistant_message = &thread
.entries()
.iter()
.rev()
.find_map(|entry| match entry {
AgentThreadEntry::AssistantMessage(msg) => Some(msg),
_ => None,
})
.unwrap();
assert!(
assistant_message.to_markdown(cx).contains("Hello, world!"),
"unexpected assistant message: {:?}",
assistant_message.to_markdown(cx)
);
});
drop(tempdir);
}
pub async fn test_tool_call<T, F>(server: F, cx: &mut TestAppContext)
where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as _;
let tempdir = tempfile::tempdir().unwrap();
let foo_path = tempdir.path().join("foo");
std::fs::write(&foo_path, "Lorem ipsum dolor").expect("failed to write file");
let project = Project::example([tempdir.path()], &mut cx.to_async()).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), "/private/tmp", cx).await;
thread
.update(cx, |thread, cx| {
thread.send_raw(
&format!("Read {} and tell me what you see.", foo_path.display()),
cx,
)
})
.await
.unwrap();
thread.read_with(cx, |thread, _cx| {
assert!(thread.entries().iter().any(|entry| {
matches!(
entry,
AgentThreadEntry::ToolCall(ToolCall {
status: ToolCallStatus::Pending
| ToolCallStatus::InProgress
| ToolCallStatus::Completed,
..
})
)
}));
assert!(
thread
.entries()
.iter()
.any(|entry| { matches!(entry, AgentThreadEntry::AssistantMessage(_)) })
);
});
drop(tempdir);
}
pub async fn test_tool_call_with_permission<T, F>(
server: F,
allow_option_id: acp::PermissionOptionId,
cx: &mut TestAppContext,
) where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as Arc<dyn fs::Fs>;
let project = Project::test(fs.clone(), [path!("/private/tmp").as_ref()], cx).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), "/private/tmp", cx).await;
let full_turn = thread.update(cx, |thread, cx| {
thread.send_raw(
r#"Run exactly `touch hello.txt && echo "Hello, world!" | tee hello.txt` in the terminal."#,
cx,
)
});
run_until_first_tool_call(
&thread,
|entry| {
matches!(
entry,
AgentThreadEntry::ToolCall(ToolCall {
status: ToolCallStatus::WaitingForConfirmation { .. },
..
})
)
},
cx,
)
.await;
let tool_call_id = thread.read_with(cx, |thread, cx| {
let AgentThreadEntry::ToolCall(ToolCall {
id,
label,
status: ToolCallStatus::WaitingForConfirmation { .. },
..
}) = &thread
.entries()
.iter()
.find(|entry| matches!(entry, AgentThreadEntry::ToolCall(_)))
.unwrap()
else {
panic!();
};
let label = label.read(cx).source();
assert!(label.contains("touch"), "Got: {}", label);
id.clone()
});
thread.update(cx, |thread, cx| {
thread.authorize_tool_call(
tool_call_id,
acp_thread::SelectedPermissionOutcome::new(
allow_option_id,
acp::PermissionOptionKind::AllowOnce,
),
cx,
);
assert!(thread.entries().iter().any(|entry| matches!(
entry,
AgentThreadEntry::ToolCall(ToolCall {
status: ToolCallStatus::Pending
| ToolCallStatus::InProgress
| ToolCallStatus::Completed,
..
})
)));
});
full_turn.await.unwrap();
thread.read_with(cx, |thread, cx| {
let AgentThreadEntry::ToolCall(ToolCall {
content,
status: ToolCallStatus::Pending
| ToolCallStatus::InProgress
| ToolCallStatus::Completed,
..
}) = thread
.entries()
.iter()
.find(|entry| matches!(entry, AgentThreadEntry::ToolCall(_)))
.unwrap()
else {
panic!();
};
assert!(
content.iter().any(|c| c.to_markdown(cx).contains("Hello")),
"Expected content to contain 'Hello'"
);
});
}
pub async fn test_cancel<T, F>(server: F, cx: &mut TestAppContext)
where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as Arc<dyn fs::Fs>;
let project = Project::test(fs.clone(), [path!("/private/tmp").as_ref()], cx).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), "/private/tmp", cx).await;
let _ = thread.update(cx, |thread, cx| {
thread.send_raw(
r#"Run exactly `touch hello.txt && echo "Hello, world!" | tee hello.txt` in the terminal."#,
cx,
)
});
let first_tool_call_ix = run_until_first_tool_call(
&thread,
|entry| {
matches!(
entry,
AgentThreadEntry::ToolCall(ToolCall {
status: ToolCallStatus::WaitingForConfirmation { .. },
..
})
)
},
cx,
)
.await;
thread.read_with(cx, |thread, cx| {
let AgentThreadEntry::ToolCall(ToolCall {
id,
label,
status: ToolCallStatus::WaitingForConfirmation { .. },
..
}) = &thread.entries()[first_tool_call_ix]
else {
panic!("{:?}", thread.entries()[1]);
};
let label = label.read(cx).source();
assert!(label.contains("touch"), "Got: {}", label);
id.clone()
});
thread.update(cx, |thread, cx| thread.cancel(cx)).await;
thread.read_with(cx, |thread, _cx| {
let AgentThreadEntry::ToolCall(ToolCall {
status: ToolCallStatus::Canceled,
..
}) = &thread.entries()[first_tool_call_ix]
else {
panic!();
};
});
thread
.update(cx, |thread, cx| {
thread.send_raw(r#"Stop running and say goodbye to me."#, cx)
})
.await
.unwrap();
thread.read_with(cx, |thread, _| {
assert!(matches!(
&thread.entries().last().unwrap(),
AgentThreadEntry::AssistantMessage(..),
))
});
}
pub async fn test_thread_drop<T, F>(server: F, cx: &mut TestAppContext)
where
T: AgentServer + 'static,
F: AsyncFn(&Arc<dyn fs::Fs>, &mut TestAppContext) -> T,
{
let fs = init_test(cx).await as Arc<dyn fs::Fs>;
let project = Project::test(fs.clone(), [], cx).await;
let thread = new_test_thread(server(&fs, cx).await, project.clone(), "/private/tmp", cx).await;
thread
.update(cx, |thread, cx| thread.send_raw("Hello from test!", cx))
.await
.unwrap();
thread.read_with(cx, |thread, _| {
assert!(thread.entries().len() >= 2, "Expected at least 2 entries");
});
let weak_thread = thread.downgrade();
drop(thread);
cx.executor().run_until_parked();
assert!(!weak_thread.is_upgradable());
}
#[macro_export]
macro_rules! common_e2e_tests {
($server:expr, allow_option_id = $allow_option_id:expr) => {
mod common_e2e {
use super::*;
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn basic(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_basic($server, cx).await;
}
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn path_mentions(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_path_mentions($server, cx).await;
}
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn tool_call(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_tool_call($server, cx).await;
}
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn tool_call_with_permission(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_tool_call_with_permission(
$server,
::agent_client_protocol::schema::PermissionOptionId::new($allow_option_id),
cx,
)
.await;
}
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn cancel(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_cancel($server, cx).await;
}
#[::gpui::test]
#[cfg_attr(not(feature = "e2e"), ignore)]
async fn thread_drop(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_thread_drop($server, cx).await;
}
}
};
}
pub use common_e2e_tests;
// Helpers
pub async fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
env_logger::try_init().ok();
cx.update(|cx| {
let settings_store = settings::SettingsStore::test(cx);
cx.set_global(settings_store);
gpui_tokio::init(cx);
let http_client = reqwest_client::ReqwestClient::user_agent("agent tests").unwrap();
cx.set_http_client(Arc::new(http_client));
let client = client::Client::production(cx);
let user_store = cx.new(|cx| client::UserStore::new(client.clone(), cx));
language_model::init(cx);
RefreshLlmTokenListener::register(client.clone(), user_store, cx);
#[cfg(test)]
project::agent_server_store::AllAgentServersSettings::override_global(
project::agent_server_store::AllAgentServersSettings(collections::HashMap::default()),
cx,
);
});
cx.executor().allow_parking();
FakeFs::new(cx.executor())
}
pub async fn new_test_thread(
server: impl AgentServer + 'static,
project: Entity<Project>,
current_dir: impl AsRef<Path>,
cx: &mut TestAppContext,
) -> Entity<AcpThread> {
let store = project.read_with(cx, |project, _| project.agent_server_store().clone());
let delegate = AgentServerDelegate::new(store, None);
let connection = cx
.update(|cx| server.connect(delegate, project.clone(), cx))
.await
.unwrap();
cx.update(|cx| {
connection.new_session(project.clone(), PathList::new(&[current_dir.as_ref()]), cx)
})
.await
.unwrap()
}
pub async fn run_until_first_tool_call(
thread: &Entity<AcpThread>,
wait_until: impl Fn(&AgentThreadEntry) -> bool + 'static,
cx: &mut TestAppContext,
) -> usize {
let (mut tx, mut rx) = mpsc::channel::<usize>(1);
let subscription = cx.update(|cx| {
cx.subscribe(thread, move |thread, _, cx| {
for (ix, entry) in thread.read(cx).entries().iter().enumerate() {
if wait_until(entry) {
return tx.try_send(ix).unwrap();
}
}
})
});
select! {
_ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(20))) => {
panic!("Timeout waiting for tool call")
}
ix = rx.next().fuse() => {
drop(subscription);
ix.unwrap()
}
}
}
pub fn get_zed_path() -> PathBuf {
let mut zed_path = std::env::current_exe().unwrap();
while zed_path
.file_name()
.is_none_or(|name| name.to_string_lossy() != "debug")
{
if !zed_path.pop() {
panic!("Could not find target directory");
}
}
zed_path.push("zed");
if !zed_path.exists() {
panic!("\n🚨 Run `cargo build` at least once before running e2e tests\n\n");
}
zed_path
}