Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project: Restart context servers when their working directory changes (#61365)
Apoorva Vermaac44e9f5df57
diff --git a/crates/project/src/context_server_store.rs b/crates/project/src/context_server_store.rsindex 9e3a65134dc..00dfafd4500 100644--- a/crates/project/src/context_server_store.rs+++ b/crates/project/src/context_server_store.rs@@ -296,6 +296,13 @@ pub struct ContextServerStore {registry: Entity<ContextServerDescriptorRegistry>,update_servers_task: Option<Task<Result<()>>>,context_server_factory: Option<ContextServerFactory>,+ /// The working directory each server was last started with. The working+ /// directory of a stdio server depends on the resolved project root, which+ /// can only become available after the server has already started (e.g. a+ /// worktree is added moments after launch). Tracking it lets+ /// `maintain_servers` restart a server when its working directory changes,+ /// since the working directory is not part of `ContextServerConfiguration`.+ server_working_directories: HashMap<ContextServerId, Option<Arc<Path>>>,needs_server_update: bool,ai_disabled: bool,_subscriptions: Vec<Subscription>,@@ -511,6 +518,7 @@ impl ContextServerStore {server_ids: Default::default(),update_servers_task: None,context_server_factory,+ server_working_directories: HashMap::default(),};if maintain_server_loop && !DisableAiSettings::get_global(cx).disable_ai {this.available_context_servers_changed(cx);@@ -855,6 +863,7 @@ impl ContextServerStore {.servers.remove(id).context("Context server not found")?;+ self.server_working_directories.remove(id);if let ContextServerConfiguration::Http { url, .. } = state.configuration().as_ref() {let server_url = url.clone();@@ -878,6 +887,31 @@ impl ContextServerStore {Ok(())}+ /// The project root a locally-spawned stdio server should use as its working+ /// directory: the active project directory, falling back to the first visible+ /// worktree. Resolves to `None` before any worktree is available.+ fn resolve_root_path(&self, cx: &App) -> Option<Arc<Path>> {+ self.project+ .as_ref()+ .and_then(|project| {+ project+ .read_with(cx, |project, cx| project.active_project_directory(cx))+ .ok()+ .flatten()+ })+ .or_else(|| {+ self.worktree_store.read_with(cx, |store, cx| {+ store.visible_worktrees(cx).fold(None, |acc, item| {+ if acc.is_none() {+ item.read(cx).root_dir()+ } else {+ acc+ }+ })+ })+ })+ }+pub async fn create_context_server(this: WeakEntity<Self>,id: ContextServerId,@@ -902,27 +936,8 @@ impl ContextServerStore {(remote_state, this.is_remote_project())})?;- let root_path: Option<Arc<Path>> = this.update(cx, |this, cx| {- this.project- .as_ref()- .and_then(|project| {- project- .read_with(cx, |project, cx| project.active_project_directory(cx))- .ok()- .flatten()- })- .or_else(|| {- this.worktree_store.read_with(cx, |store, cx| {- store.visible_worktrees(cx).fold(None, |acc, item| {- if acc.is_none() {- item.read(cx).root_dir()- } else {- acc- }- })- })- })- })?;+ let root_path: Option<Arc<Path>> =+ this.update(cx, |this, cx| this.resolve_root_path(cx))?;let configuration = if let Some((project_id, upstream_client)) = remote_state {let root_dir = root_path.as_ref().map(|p| p.display().to_string());@@ -1767,7 +1782,7 @@ impl ContextServerStore {let mut servers_to_remove = HashSet::default();let mut servers_to_stop = HashSet::default();- this.update(cx, |this, _cx| {+ this.update(cx, |this, cx| {for server_id in this.servers.keys() {// All servers that are not in desired_servers should be removed from the store.// This can happen if the user removed a server from the context server settings.@@ -1780,13 +1795,28 @@ impl ContextServerStore {}}+ let is_remote_project = this.is_remote_project();+ let root_path = this.resolve_root_path(cx);+for (id, config) in configured_servers {let state = this.servers.get(&id);let is_stopped = matches!(state, Some(ContextServerState::Stopped { .. }));let existing_config = state.as_ref().map(|state| state.configuration());- if existing_config.as_deref() != Some(&config) || is_stopped {+ let working_directory =+ working_directory_for(&config, root_path.clone(), is_remote_project);+ // A running server that was started before the project root became+ // available keeps its stale working directory, since the working+ // directory is not part of `ContextServerConfiguration`. Restart it+ // when the resolved working directory no longer matches.+ let working_directory_changed = state.is_some()+ && !is_stopped+ && this.server_working_directories.get(&id) != Some(&working_directory);+ if existing_config.as_deref() != Some(&config)+ || is_stopped+ || working_directory_changed+ {let config = Arc::new(config);- servers_to_start.push((id.clone(), config));+ servers_to_start.push((id.clone(), config, working_directory));if this.servers.contains_key(&id) {servers_to_stop.insert(id);}@@ -1806,10 +1836,12 @@ impl ContextServerStore {anyhow::Ok(())})??;- for (id, config) in servers_to_start {+ for (id, config, working_directory) in servers_to_start {match Self::create_context_server(this.clone(), id.clone(), config, cx).await {Ok((server, config)) => {this.update(cx, |this, cx| {+ this.server_working_directories+ .insert(id.clone(), working_directory);this.run_server(server, config, cx);})?;}@@ -1830,6 +1862,21 @@ impl ContextServerStore {}}+/// The working directory a server will be spawned with, mirroring the choice+/// made in [`ContextServerStore::create_context_server`]: only locally-spawned+/// stdio servers use the project root; HTTP and remote servers use none.+fn working_directory_for(+ configuration: &ContextServerConfiguration,+ root_path: Option<Arc<Path>>,+ is_remote_project: bool,+) -> Option<Arc<Path>> {+ match configuration {+ ContextServerConfiguration::Http { .. } => None,+ _ if is_remote_project => None,+ _ => root_path,+ }+}+/// Determines the appropriate server state after a start attempt fails.////// When the error is an HTTP 401 with no static auth header configured,diff --git a/crates/project/tests/integration/context_server_store.rs b/crates/project/tests/integration/context_server_store.rsindex 984bb334edb..e6814c29856 100644--- a/crates/project/tests/integration/context_server_store.rs+++ b/crates/project/tests/integration/context_server_store.rs@@ -751,6 +751,98 @@ async fn test_context_server_refreshed_when_worktree_added(cx: &mut TestAppConte});}+#[gpui::test]+async fn test_stdio_server_restarts_when_project_root_becomes_available(cx: &mut TestAppContext) {+ const SERVER_ID: &str = "mcp-1";+ let server_id = ContextServerId(SERVER_ID.into());++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ path!("/"),+ json!({"lonely.rs": "", "project": {"code.rs": ""}}),+ )+ .await;++ cx.update(|cx| {+ let settings_store = SettingsStore::test(cx);+ cx.set_global(settings_store);+ });++ // Open a single-file worktree, whose `root_dir()` is `None`, so the server is+ // spawned with no working directory even though it is configured.+ let project = Project::test(fs.clone(), [path!("/lonely.rs").as_ref()], cx).await;++ let executor = cx.executor();+ let store = project.read_with(cx, |project, _| project.context_server_store());+ store.update(cx, |store, _| {+ store.set_context_server_factory(Box::new(move |id, _| {+ Arc::new(ContextServer::new(+ id.clone(),+ Arc::new(create_fake_transport(id.0.to_string(), executor.clone())),+ ))+ }));+ });++ // Configure the server globally so it starts against the file worktree.+ {+ let _server_events = assert_server_events(+ &store,+ vec![+ (server_id.clone(), ContextServerStatus::Starting),+ (server_id.clone(), ContextServerStatus::Running),+ ],+ cx,+ );+ set_context_server_configuration(+ vec![(+ server_id.0.clone(),+ settings::ContextServerSettingsContent::Stdio {+ enabled: true,+ remote: false,+ command: ContextServerCommand {+ path: "somebinary".into(),+ args: vec!["arg".to_string()],+ env: None,+ timeout: None,+ },+ },+ )],+ cx,+ );+ cx.run_until_parked();+ }++ // Adding a directory worktree makes the project root resolvable. Since the+ // server was started with working directory `None`, it must be restarted so+ // it picks up the new root — otherwise it keeps running under Zed's own cwd.+ {+ let _server_events = assert_server_events(+ &store,+ vec![+ (server_id.clone(), ContextServerStatus::Stopped),+ (server_id.clone(), ContextServerStatus::Starting),+ (server_id.clone(), ContextServerStatus::Running),+ ],+ cx,+ );+ project+ .update(cx, |project, cx| {+ project.find_or_create_worktree(path!("/project"), true, cx)+ })+ .await+ .expect("Failed to add worktree");+ cx.run_until_parked();+ }++ cx.update(|cx| {+ assert_eq!(+ store.read(cx).status_for_server(&server_id),+ Some(ContextServerStatus::Running),+ "Server should be running again after restarting with the project root"+ );+ });+}+#[gpui::test]async fn test_server_ids_includes_disabled_servers(cx: &mut TestAppContext) {const ENABLED_SERVER_ID: &str = "enabled-server";