the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
feat: update managed plugins from GitHub (#4245)
JJ Liebigb977116cd7c1
diff --git a/docs/next/website/src/content/docs/cli-reference.mdx b/docs/next/website/src/content/docs/cli-reference.mdxindex 31fe26a9b..5186fe79c 100644--- a/docs/next/website/src/content/docs/cli-reference.mdx+++ b/docs/next/website/src/content/docs/cli-reference.mdx@@ -466,13 +466,14 @@ Install, list, and remove plugins:```bashherdr plugin install <owner>/<repo>[/subdir...] [--ref REF] [--yes]+herdr plugin update [<plugin_id|owner/repo[/subdir...]>...] [--yes]herdr plugin list [--plugin ID] [--json]herdr plugin uninstall <plugin_id|owner/repo[/subdir...]>herdr plugin enable <plugin_id>herdr plugin disable <plugin_id>```-`plugin install` accepts GitHub shorthand only, such as `ogulcancelik/herdr-plugin-examples/worktree-bootstrap`. It uses `git`, shows a trust preview in interactive terminals, runs supported manifest build commands, and stores GitHub installs in a Herdr-managed directory. Use `--yes` for noninteractive installs. Reinstalling a GitHub-managed plugin replaces that managed checkout. Installing over a locally linked plugin is refused. Plugin manifests must declare `min_herdr_version`; install and link fail when the plugin requires a newer Herdr binary. `plugin list` is human-readable by default; pass `--json` for the raw API response.+`plugin install` accepts GitHub shorthand only, such as `ogulcancelik/herdr-plugin-examples/worktree-bootstrap`. It uses `git`, shows a trust preview in interactive terminals, runs supported manifest build commands, and stores GitHub installs in a Herdr-managed directory. Use `--yes` for noninteractive installs. `plugin update` refreshes every GitHub-managed plugin when no targets are given, or only the listed plugin ids or GitHub sources. It preserves each install's requested ref, skips unchanged commits and ignores locally linked plugins during bulk updates. Reinstalling a GitHub-managed plugin creates a new installation directory. Running plugins keep their original files; new invocations use the new installation. Installing over a locally linked plugin is refused. Plugin manifests must declare `min_herdr_version`; install and link fail when the plugin requires a newer Herdr binary. `plugin list` is human-readable by default; pass `--json` for the raw API response.Plugin installation and enabled state are global to the current user. A plugin installed, linked, enabled, or disabled through one Herdr session is immediately available with the same state in every session.@@ -483,7 +484,7 @@ herdr plugin link <path> [--disabled]herdr plugin unlink <plugin_id>```-`plugin link` accepts a plugin directory containing `herdr-plugin.toml` or a direct manifest path. Use it while authoring or testing a plugin from a local checkout. `plugin unlink` unregisters the plugin and leaves files alone. `plugin uninstall` unregisters a plugin and also removes Herdr-managed GitHub checkout files. For GitHub installs, uninstall accepts either the plugin id or the same `owner/repo[/subdir...]` shorthand used by install. Actions, event hooks, panes, and link handlers are declared in the manifest; runtime action registration is not part of v1.+`plugin link` accepts a plugin directory containing `herdr-plugin.toml` or a direct manifest path. Use it while authoring or testing a plugin from a local checkout. `plugin unlink` and `plugin uninstall` unregister the plugin and leave files in place so running plugins can finish. Updates and reinstalls also retain previous installations; new invocations use the replacement without a config reload. A later successful installation/update or server startup removes obsolete managed installations after the servers using them have exited. Config reload does not release old installations. Plugins must stop detached background processes before their parent command or pane exits; processes surviving server exit are not protected from cleanup. Legacy installations without cleanup tracking and locally linked files are retained. For GitHub installs, uninstall accepts either the plugin id or the same `owner/repo[/subdir...]` shorthand used by install. Actions, event hooks, panes, and link handlers are declared in the manifest; runtime action registration is not part of v1.Config directory:diff --git a/docs/next/website/src/content/docs/plugins.mdx b/docs/next/website/src/content/docs/plugins.mdxindex 4085e2423..defceef26 100644--- a/docs/next/website/src/content/docs/plugins.mdx+++ b/docs/next/website/src/content/docs/plugins.mdx@@ -172,6 +172,7 @@ Install an example plugin:```bashherdr plugin install ogulcancelik/herdr-plugin-examples/agent-telegram-notify+herdr plugin updateherdr plugin config-dir examples.agent-telegram-notifyherdr plugin listherdr plugin action list --plugin examples.agent-telegram-notify@@ -190,9 +191,16 @@ herdr plugin log list --plugin example.layout`plugin install` accepts GitHub shorthand only, such as`owner/repo/subdir`. It clones with `git`, shows a preview in interactive-terminals, runs supported build commands, then stores the checkout under-Herdr-managed plugin data and registers it. Use `--yes` for noninteractive-installs. Reinstalling a GitHub-managed plugin replaces that managed checkout.+terminals, builds in a new Herdr-managed installation directory, and registers+it. Use `--yes` for noninteractive installs. Updates and reinstalls leave the+previous installation in place: running commands and panes keep their original+files, while new invocations use the new installation without a config reload.+Existing processes are not restarted, and startup hooks run at the next server+startup as usual.+`plugin update` refreshes every GitHub-managed plugin when called without a+target, or only the listed plugin ids or GitHub sources. It refetches the ref+recorded during install, skips unchanged commits, and ignores locally linked+plugins during bulk updates. Use `--yes` for noninteractive updates.Installed and linked plugins, including their enabled state, are global to thecurrent user and available in every Herdr session. Both `plugin install` and`plugin link` can register plugins while no Herdr server is running. Plugins@@ -203,12 +211,18 @@ local plugin first. `plugin install` and `plugin link` create the plugin'sconfig and state directories, and `plugin config-dir <id>` prints the configdirectory for setup docs and shell scripts.-`plugin uninstall <id-or-source>` unregisters the plugin. For GitHub-managed-installs it also removes the managed checkout, and it accepts either the plugin-id or the same `owner/repo[/subdir...]` shorthand used by install.+`plugin uninstall <id-or-source>` unregisters the plugin and accepts either the+plugin id or the same `owner/repo[/subdir...]` shorthand used by install.+Installation files are retained after updates, reinstalls, and uninstall so+running plugins can finish. A later successful installation/update or server+startup automatically removes obsolete managed installations once the servers+using them have exited. Reloading config does not release old installations.+Stop plugin work before shutting down its server: processes surviving server+exit are not protected from cleanup. Plugins must stop detached background+processes before their parent command or pane exits. Legacy installations+without cleanup tracking are retained. Config and state are preserved.`plugin unlink <id>` only unregisters a plugin and leaves files alone, which is-useful for local development. There is no separate `plugin update` in v1;-reinstall from GitHub to refresh a managed plugin.+useful for local development.The example cookbook repo is `ogulcancelik/herdr-plugin-examples`. It containsseparate example plugins in subdirectories, including `agent-telegram-notify`,diff --git a/src/app/api/plugins/manifest.rs b/src/app/api/plugins/manifest.rsindex fb650065d..74ce05254 100644--- a/src/app/api/plugins/manifest.rs+++ b/src/app/api/plugins/manifest.rs@@ -290,10 +290,19 @@ pub(super) fn normalize_plugin_source(let plugin_root = std::path::PathBuf::from(&plugin.plugin_root).canonicalize().map_err(|err| ("invalid_plugin_source", err.to_string()))?;- let expected = crate::plugin_paths::managed_checkout_path(&plugin.plugin_id)- .canonicalize()- .map_err(|err| ("invalid_plugin_source", err.to_string()))?;- if managed_path != expected {+ let legacy = crate::plugin_paths::managed_checkout_path(&plugin.plugin_id).canonicalize();+ let installations =+ crate::plugin_paths::managed_installations_dir(&plugin.plugin_id).canonicalize();+ let is_installation = installations.as_ref().is_ok_and(|root| {+ managed_path+ .file_name()+ .is_some_and(|name| name == "checkout")+ && managed_path+ .parent()+ .and_then(|generation| generation.parent())+ == Some(root.as_path())+ });+ if !is_installation && !legacy.as_ref().is_ok_and(|path| path == &managed_path) {return Err(("invalid_plugin_source","GitHub plugin managed_path does not match the plugin id".to_string(),diff --git a/src/app/api/plugins/mod.rs b/src/app/api/plugins/mod.rsindex 9644453d8..120a3aa1a 100644--- a/src/app/api/plugins/mod.rs+++ b/src/app/api/plugins/mod.rs@@ -40,7 +40,7 @@ impl App {if !self.policy.persist_plugin_registry {return Ok(());}- let entries = crate::persist::plugin_registry::try_load()?;+ let entries = crate::plugin_installations::load(&mut self.plugin_installation_leases)?;self.replace_installed_plugins(entries);Ok(())}@@ -52,7 +52,7 @@ impl App {if !self.policy.persist_plugin_registry {return Ok(mutation(&mut self.state.installed_plugins));}- let (result, entries) = crate::persist::plugin_registry::update(|entries| {+ let (result, _) = crate::persist::plugin_registry::update(|entries| {let mut registry = entries.drain(..).map(|plugin| (plugin.plugin_id.clone(), plugin))@@ -61,7 +61,7 @@ impl App {*entries = registry.into_values().collect();result})?;- self.replace_installed_plugins(entries);+ self.refresh_installed_plugins()?;Ok(result)}@@ -2656,6 +2656,86 @@ command = ["sh", "-c", "printf %s ${{HERDR_PANE_ID-unset}} > '{}'; sleep 1"]}}+ #[test]+ fn running_plugin_command_keeps_its_files_after_app_teardown() {+ let _guard = crate::config::test_config_env_lock().lock().unwrap();+ let base = unique_temp_path("plugin-worker-lease");+ let previous_config = std::env::var_os("XDG_CONFIG_HOME");+ let previous_state = std::env::var_os("XDG_STATE_HOME");+ std::env::set_var("XDG_CONFIG_HOME", &base);+ std::env::set_var("XDG_STATE_HOME", base.join("state"));+ let installation =+ crate::plugin_paths::create_managed_installation("example.worktree-bootstrap").unwrap();+ let root = installation.join("checkout");+ write_manifest(&root);+ std::fs::create_dir_all(crate::plugin_paths::managed_plugins_dir().join(".locks")).unwrap();+ std::fs::write(root.join("payload"), "original").unwrap();+ drop(crate::plugin_installations::create_lease(&installation).unwrap());+ let mut plugin = load_plugin_manifest(&root.to_string_lossy(), true).unwrap();+ plugin.source.managed_path = Some(root.display().to_string());+ crate::persist::plugin_registry::update(|entries| *entries = vec![plugin.clone()]).unwrap();+ let mut app = test_app();+ crate::plugin_installations::load(&mut app.plugin_installation_leases).unwrap();+ let command = if cfg!(windows) {+ vec![+ "powershell.exe",+ "-NoProfile",+ "-Command",+ "Set-Content ready ready; $deadline = [DateTime]::UtcNow.AddSeconds(10); while (!(Test-Path release) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 10 }; Get-Content payload | Set-Content result",+ ]+ } else {+ vec![+ "sh",+ "-c",+ "printf ready > ready; i=0; while [ ! -f release ] && [ $i -lt 500 ]; do sleep 0.02; i=$((i+1)); done; cat payload > result",+ ]+ }+ .into_iter()+ .map(str::to_string)+ .collect();+ app.start_plugin_command(+ &plugin,+ None,+ None,+ command,+ &app.current_plugin_context("lease-test"),+ None,+ )+ .unwrap();+ assert_eq!(+ read_capture_when_ready(&root.join("ready"), || {}).trim(),+ "ready"+ );+ crate::persist::plugin_registry::update(Vec::clear).unwrap();+ drop(app);+ crate::plugin_installations::cleanup().unwrap();+ assert!(root.exists(), "the worker still owns the old installation");+ std::fs::write(root.join("release"), "").unwrap();+ assert_eq!(+ read_capture_when_ready(&root.join("result"), || {}).trim(),+ "original"+ );+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while installation.exists() {+ crate::plugin_installations::cleanup().unwrap();+ assert!(+ std::time::Instant::now() < deadline,+ "finished worker must release its installation"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ for (key, previous) in [+ ("XDG_CONFIG_HOME", previous_config),+ ("XDG_STATE_HOME", previous_state),+ ] {+ match previous {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ std::fs::remove_dir_all(base).unwrap();+ }+#[cfg(unix)]#[test]fn manifest_action_invoke_runs_command_and_captures_log() {diff --git a/src/app/api/plugins/runtime.rs b/src/app/api/plugins/runtime.rsindex 30e2f7ae5..07b794cdf 100644--- a/src/app/api/plugins/runtime.rs+++ b/src/app/api/plugins/runtime.rs@@ -118,7 +118,11 @@ impl App {self.push_plugin_command_log(log.clone());self.state.plugin_commands_in_flight += 1;let event_tx = self.event_tx.clone();+ let installation_lease =+ crate::plugin_installations::command_lease(&self.plugin_installation_leases, plugin);std::thread::spawn(move || {+ // The worker may outlive App during normal server teardown.+ let _installation_lease = installation_lease;let child =crate::plugin_command::command_for_argv_in_dir(&program, &args, &plugin_root).envs(env)@@ -181,6 +185,13 @@ impl App {}pub(crate) fn run_plugin_startup_hooks(&mut self) {+ if self.policy.persist_plugin_registry && !self.plugin_installation_cleanup_allowed {+ tracing::warn!("plugin cleanup skipped: some installations could not be pinned");+ } else if self.policy.persist_plugin_registry {+ if let Err(err) = crate::plugin_installations::cleanup() {+ tracing::warn!(%err, "plugin cleanup deferred");+ }+ }let mut context = self.current_plugin_context("plugin.startup");context.invocation_source = Some("startup".to_string());let mut plugins = selfdiff --git a/src/app/mod.rs b/src/app/mod.rsindex 540b57941..1f70ecfdc 100644--- a/src/app/mod.rs+++ b/src/app/mod.rs@@ -160,6 +160,14 @@ pub struct App {pub(crate) config_reloaded_from_disk: bool,client_shell_keybindings_profile: Option<String>,endpoint_commands: custom_commands::EndpointCommandRegistry,+ // Drop after terminal runtimes have shut down their processes. Command+ // workers retain their own references until completion.+ // ponytail: server-lifetime pins defer reclamation until restart; use+ // per-pane leases only if reclamation during long-running sessions matters.+ pub(crate) plugin_installation_leases: crate::plugin_installations::Leases,+ // False when startup could not pin every installation; cleanup could+ // otherwise reclaim files a restored consumer still uses.+ pub(crate) plugin_installation_cleanup_allowed: bool,}pub(crate) const APP_EVENT_CHANNEL_CAPACITY: usize = 256;@@ -175,11 +183,15 @@ fn background_update_check_enabled(background_updates: bool, check_enabled: boolfn load_plugin_registry(persist_plugin_registry: bool,+ leases: &mut crate::plugin_installations::Leases,) -> crate::app::state::InstalledPluginRegistry {if !persist_plugin_registry {return std::collections::HashMap::new();}- let entries = crate::persist::plugin_registry::load();+ let entries = crate::plugin_installations::load(leases).unwrap_or_else(|err| {+ tracing::warn!(%err, "failed to load plugin installations");+ Vec::new()+ });let entries = crate::persist::plugin_registry::reload_manifests(entries, |path, enabled| {crate::app::api::plugins::load_plugin_manifest(path, enabled).map_err(|(_, msg)| msg)});@@ -356,6 +368,7 @@ pub(crate) fn client_palette_for_appearance(}impl App {+ #[cfg(test)]pub fn new(config: &Config,policy: AppPolicy,@@ -363,6 +376,17 @@ impl App {api_rx: tokio::sync::mpsc::UnboundedReceiver<crate::api::ApiRequestMessage>,event_hub: crate::api::EventHub,) -> Self {+ Self::try_new(config, policy, config_diagnostic, api_rx, event_hub)+ .expect("test app startup")+ }++ pub fn try_new(+ config: &Config,+ policy: AppPolicy,+ config_diagnostic: Option<String>,+ api_rx: tokio::sync::mpsc::UnboundedReceiver<crate::api::ApiRequestMessage>,+ event_hub: crate::api::EventHub,+ ) -> std::io::Result<Self> {let prefix_keys = config.prefix_keys();crate::kitty_graphics::set_enabled(config.kitty_graphics_enabled());let (event_tx, event_rx) = mpsc::channel::<AppEvent>(APP_EVENT_CHANNEL_CAPACITY);@@ -373,6 +397,23 @@ impl App {let mut restored_terminals = std::collections::HashMap::new();let mut restored_terminal_runtimes = crate::terminal::TerminalRuntimeRegistry::new();let snapshot = policy.restore_session.then(crate::persist::load).flatten();+ let mut plugin_installation_leases = crate::plugin_installations::Leases::new();+ let mut plugin_installation_cleanup_allowed = true;+ if policy.persist_plugin_registry {+ let restored_cwds = snapshot+ .as_ref()+ .into_iter()+ .flat_map(|snapshot| &snapshot.workspaces)+ .flat_map(|workspace| &workspace.tabs)+ .flat_map(|tab| tab.panes.values())+ .map(|pane| pane.cwd.clone())+ .collect::<Vec<_>>();+ plugin_installation_cleanup_allowed = crate::plugin_installations::retain_startup(+ &mut plugin_installation_leases,+ &restored_cwds,+ false,+ );+ }let session_writer = Arc::new(std::sync::Mutex::new(crate::persist::SessionWriter::new(policy.restore_session && snapshot.is_none(),)));@@ -516,7 +557,10 @@ impl App {integration_recommendations: crate::integration::integration_recommendations(),agent_manifest_summaries,agent_manifest_update_status: crate::detect::manifest_update::load_status(),- installed_plugins: load_plugin_registry(policy.persist_plugin_registry),+ installed_plugins: load_plugin_registry(+ policy.persist_plugin_registry,+ &mut plugin_installation_leases,+ ),plugin_panes: std::collections::HashMap::new(),popup_pane: None,plugin_command_logs: Vec::new(),@@ -561,6 +605,8 @@ impl App {custom_commands::EndpointCommandRegistry::new(&state.keybinds.custom_commands);let mut app = Self {+ plugin_installation_leases,+ plugin_installation_cleanup_allowed,config_diagnostic_deadline: None,toast_deadline: None,last_api_notification_at: None,@@ -624,7 +670,7 @@ impl App {app.configure_tab_bar_status(&config.ui.tab_bar_right, &config.ui.tab_bar_right_separator);app.configure_window_title(&config.ui.window_title);app.refresh_restored_workspace_git_metadata();- app+ Ok(app)}#[cfg(unix)]@@ -639,13 +685,20 @@ impl App {crate::handoff_runtime::ImportedHandoffRuntime,>,) -> io::Result<Self> {- let mut app = Self::new(+ let mut app = Self::try_new(config,AppPolicy::HANDOFF_REPLACEMENT,config_diagnostic,api_rx,event_hub,- );+ )?;+ if !crate::plugin_installations::retain_startup(+ &mut app.plugin_installation_leases,+ &[],+ true,+ ) {+ app.plugin_installation_cleanup_allowed = false;+ }let (workspaces, terminals, runtimes) = crate::persist::restore_handoff(snapshot,config.advanced.scrollback_limit_bytes,diff --git a/src/cli/plugin.rs b/src/cli/plugin.rsindex 46caf509d..3d9b4a541 100644--- a/src/cli/plugin.rs+++ b/src/cli/plugin.rs@@ -26,6 +26,7 @@ pub(super) fn run_plugin_command(args: &[String]) -> std::io::Result<i32> {match subcommand {"install" => plugin_install(&args[1..]),+ "update" => plugin_update(&args[1..]),"uninstall" => plugin_uninstall(&args[1..]),"link" => plugin_link(&args[1..]),"list" => plugin_list(&args[1..]),@@ -211,74 +212,241 @@ fn plugin_install(args: &[String]) -> std::io::Result<i32> {return Ok(2);}- let temp_root = create_plugin_temp_dir("install")?;+ match install_github_plugin(source, requested_ref, yes, true, None) {+ Ok(code) => Ok(code),+ Err(err) => {+ eprintln!("{err}");+ Ok(1)+ }+ }+}++fn plugin_update(args: &[String]) -> std::io::Result<i32> {+ let mut targets = Vec::new();+ let mut yes = false;+ for arg in args {+ match arg.as_str() {+ "--yes" | "-y" => yes = true,+ other if other.starts_with('-') => {+ eprintln!("unknown option: {other}");+ return Ok(2);+ }+ _ => targets.push(arg.as_str()),+ }+ }++ let installed = match live_installed_plugins() {+ Ok(plugins) => plugins,+ Err(err) if is_connection_error(&err) => crate::persist::plugin_registry::try_load()?,+ Err(err) => return Err(err),+ };+ let plugins = if targets.is_empty() {+ installed+ .into_iter()+ .filter(|plugin| plugin.source.kind == PluginSourceKind::Github)+ .collect::<Vec<_>>()+ } else {+ let mut plugins: Vec<InstalledPluginInfo> = Vec::new();+ for target in targets {+ let plugin = if target.contains('/') {+ let source = match GithubPluginSource::parse(target) {+ Ok(source) => source,+ Err(err) => {+ eprintln!("{err}");+ return Ok(2);+ }+ };+ installed+ .iter()+ .find(|plugin| plugin_matches_github_source(plugin, &source))+ } else {+ installed.iter().find(|plugin| plugin.plugin_id == target)+ };+ let Some(plugin) = plugin else {+ eprintln!("plugin not installed: {target}");+ return Ok(1);+ };+ if plugin.source.kind != PluginSourceKind::Github {+ eprintln!("plugin is locally linked and cannot be updated: {target}");+ return Ok(1);+ }+ if !plugins+ .iter()+ .any(|selected| selected.plugin_id == plugin.plugin_id)+ {+ plugins.push(plugin.clone());+ }+ }+ plugins+ };++ if plugins.is_empty() {+ println!("No GitHub-managed plugins installed.");+ return Ok(0);+ }+ if !yes && !io::stdin().is_terminal() {+ eprintln!("plugin update requires --yes when stdin is not interactive");+ return Ok(2);+ }++ let mut exit_code = 0;+ for plugin in plugins {+ let plugin_id = plugin.plugin_id.clone();+ let source = match GithubPluginSource::from_installed(&plugin) {+ Ok(source) => source,+ Err(err) => {+ eprintln!("error updating {plugin_id}: {err}");+ exit_code = 1;+ continue;+ }+ };+ match install_github_plugin(+ source,+ plugin.source.requested_ref.clone(),+ yes,+ plugin.enabled,+ Some(&plugin),+ ) {+ Ok(code) => exit_code = exit_code.max(code),+ Err(err) => {+ eprintln!("error updating {plugin_id}: {err}");+ exit_code = 1;+ }+ }+ }+ Ok(exit_code)+}++fn install_github_plugin(+ source: GithubPluginSource,+ requested_ref: Option<String>,+ yes: bool,+ enabled: bool,+ updating_plugin: Option<&InstalledPluginInfo>,+) -> std::io::Result<i32> {+ let updating = updating_plugin.is_some();+ let temp_root = create_plugin_temp_dir(if updating { "update" } else { "install" })?;let checkout = temp_root.join("checkout");let install_result = (|| {git_checkout(&source, requested_ref.as_deref(), &checkout)?;let resolved_commit = git_output(&checkout, ["rev-parse", "HEAD"])?;let manifest_root = source.manifest_root(&checkout);- let preview_plugin = load_cli_plugin_manifest(&manifest_root, true)?;+ let preview_plugin = load_cli_plugin_manifest(&manifest_root, enabled)?;+ if let Some(plugin) = updating_plugin {+ if preview_plugin.plugin_id != plugin.plugin_id {+ return Err(io::Error::other(format!(+ "update source now contains plugin {}, expected {}",+ preview_plugin.plugin_id, plugin.plugin_id+ )));+ }+ }+ let _checkout_lock = lock_managed_checkout(&preview_plugin.plugin_id)?;let existing = installed_plugin_info(&preview_plugin.plugin_id)?;+ if let Some(expected) = updating_plugin {+ ensure_update_target_unchanged(expected, existing.as_ref())?;+ }ensure_replacement_allowed(&preview_plugin, existing.as_ref())?;+ if updating+ && existing+ .as_ref()+ .and_then(|plugin| plugin.source.resolved_commit.as_deref())+ == Some(resolved_commit.as_str())+ {+ println!("{} is already up to date.", preview_plugin.plugin_id);+ return Ok(true);+ }let mut source_info =source.to_source_info(requested_ref, resolved_commit, None, current_unix_ms());- print_install_preview(&preview_plugin, &source_info, existing.as_ref());- if !yes && !confirm("Install this plugin?")? {- eprintln!("plugin install cancelled");- return Ok(0);- }- if let Err(err) = run_plugin_build_commands(&preview_plugin, &manifest_root) {- eprintln!("{err}");- return Ok(1);- }- let post_build_plugin = load_cli_plugin_manifest(&manifest_root, true)?;- ensure_manifest_unchanged_after_build(&preview_plugin, &post_build_plugin)?;-- let final_checkout = crate::plugin_paths::managed_checkout_path(&preview_plugin.plugin_id);- let backup_checkout = temp_root.join("previous-checkout");- let mut backup_moved = false;- if final_checkout.exists() {- std::fs::rename(&final_checkout, &backup_checkout)- .map_err(|err| plugin_checkout_lifecycle_error("replace", &final_checkout, err))?;- backup_moved = true;+ print_install_preview(&preview_plugin, &source_info, existing.as_ref(), updating);+ let prompt = if updating {+ "Update this plugin?"+ } else {+ "Install this plugin?"+ };+ if !yes && !confirm(prompt)? {+ eprintln!(+ "plugin {} cancelled",+ if updating { "update" } else { "install" }+ );+ return Ok(false);}+ let installation =+ crate::plugin_paths::create_managed_installation(&preview_plugin.plugin_id)?;+ let installation_lease = crate::plugin_installations::create_lease(&installation)?;+ let final_checkout = installation.join("checkout");+ let mut activation_attempted = false;let install_attempt = (|| {- if let Some(parent) = final_checkout.parent() {- std::fs::create_dir_all(parent).map_err(InstallFailure::Rollback)?;- }- std::fs::rename(&checkout, &final_checkout)- .map_err(|err| plugin_checkout_lifecycle_error("install", &final_checkout, err))- .map_err(InstallFailure::Rollback)?;-- source_info.managed_path = Some(final_checkout.display().to_string());+ std::fs::rename(&checkout, &final_checkout)?;let final_manifest_root = source.manifest_root(&final_checkout);- let mut plugin = load_cli_plugin_manifest(&final_manifest_root, true)- .map_err(InstallFailure::Rollback)?;- plugin.source = source_info.clone();- register_installed_plugin(plugin.clone(), source_info.clone())?;- Ok::<InstalledPluginInfo, InstallFailure>(plugin)+ let mut preview_plugin = preview_plugin.clone();+ let relocated_plugin = load_cli_plugin_manifest(&final_manifest_root, enabled)?;+ preview_plugin.manifest_path = relocated_plugin.manifest_path;+ preview_plugin.plugin_root = relocated_plugin.plugin_root;+ run_plugin_build_commands(&preview_plugin, &final_manifest_root).map_err(|err| {+ io::Error::other(format!(+ "{err}\n\nPlugin was not {}.",+ if updating { "updated" } else { "installed" }+ ))+ })?;+ let mut plugin = load_cli_plugin_manifest(&final_manifest_root, enabled)?;+ ensure_manifest_unchanged_after_build(&preview_plugin, &plugin)?;+ source_info.managed_path = Some(final_checkout.display().to_string());+ plugin.source = source_info;+ activation_attempted = true;+ if let Some(expected) = updating_plugin {+ persist_updated_plugin(&plugin, expected)?;+ } else {+ persist_plugin_offline(&plugin, true)?;+ }+ Ok::<InstalledPluginInfo, io::Error>(plugin)})();let plugin = match install_attempt {Ok(plugin) => plugin,- Err(InstallFailure::Rollback(err)) => {- let _ = std::fs::remove_dir_all(&final_checkout);- if backup_moved && backup_checkout.exists() {- let _ = std::fs::rename(&backup_checkout, &final_checkout);+ Err(err) => {+ drop(installation_lease);+ // A failed activation may have published the path. Never delete files+ // that a server or a plugin process could already be using.+ if activation_attempted {+ return Err(io::Error::other(format!(+ "{err}; plugin files retained at {}",+ final_checkout.display()+ )));+ }+ if let Err(cleanup_err) =+ crate::persist::plugin_registry::with_registry_lock(|| {+ std::fs::remove_dir_all(&installation)+ })+ {+ return Err(io::Error::other(format!(+ "{err}; could not remove failed installation at {}: {cleanup_err}",+ installation.display()+ )));}return Err(err);}- Err(InstallFailure::KeepCheckout(err)) => return Err(err),};- println!("Installed {} from {}.", plugin.plugin_id, source.display());+ println!(+ "{} {} from {}.",+ if updating { "Updated" } else { "Installed" },+ plugin.plugin_id,+ source.display()+ );println!("Config: {}",crate::plugin_paths::plugin_config_dir(&plugin.plugin_id).display());- Ok(0)+ Ok(true)})();let _ = std::fs::remove_dir_all(&temp_root);- install_result+ install_result.map(|cleanup| {+ if cleanup {+ if let Err(err) = crate::plugin_installations::cleanup() {+ eprintln!("Plugin cleanup deferred: {err}");+ }+ }+ 0+ })}fn plugin_uninstall(args: &[String]) -> std::io::Result<i32> {@@ -309,6 +477,11 @@ fn plugin_uninstall(args: &[String]) -> std::io::Result<i32> {(target.clone(), existing)}};+ let _checkout_lock = existing+ .as_ref()+ .filter(|plugin| plugin.source.kind == PluginSourceKind::Github)+ .map(|_| lock_managed_checkout(&plugin_id))+ .transpose()?;match super::send_request(&Request {id: "cli:plugin".into(),@@ -339,9 +512,6 @@ fn plugin_uninstall(args: &[String]) -> std::io::Result<i32> {Err(err) => return Err(err),}- if let Some(plugin) = existing.as_ref() {- remove_managed_plugin_files(plugin)?;- }println!("Uninstalled {plugin_id}.");Ok(0)}@@ -784,6 +954,23 @@ impl GithubPluginSource {format!("https://github.com/{}/{}.git", self.owner, self.repo)}+ fn from_installed(plugin: &InstalledPluginInfo) -> std::io::Result<Self> {+ let owner = plugin+ .source+ .owner+ .clone()+ .ok_or_else(|| io::Error::other("installed GitHub plugin has no source owner"))?;+ let repo =+ plugin.source.repo.clone().ok_or_else(|| {+ io::Error::other("installed GitHub plugin has no source repository")+ })?;+ Ok(Self {+ owner,+ repo,+ subdir: plugin.source.subdir.clone(),+ })+ }+fn display(&self) -> String {match &self.subdir {Some(subdir) => format!("{}/{}/{}", self.owner, self.repo, subdir),@@ -834,6 +1021,23 @@ fn ensure_replacement_allowed(Ok(())}+fn ensure_update_target_unchanged(+ expected: &InstalledPluginInfo,+ current: Option<&InstalledPluginInfo>,+) -> std::io::Result<()> {+ if current.is_some_and(|current| same_update_target(expected, current)) {+ return Ok(());+ }+ Err(io::Error::other(format!(+ "plugin {} changed while its update was in progress; retry the update",+ expected.plugin_id+ )))+}++fn same_update_target(expected: &InstalledPluginInfo, current: &InstalledPluginInfo) -> bool {+ current.manifest_path == expected.manifest_path && current.source == expected.source+}+fn validate_github_segment(label: &str, value: &str) -> Result<(), String> {if value.is_empty() {return Err(format!("GitHub {label} must not be empty"));@@ -932,106 +1136,54 @@ fn load_cli_plugin_manifest(path: &Path, enabled: bool) -> std::io::Result<Insta.map_err(|(_, message)| std::io::Error::other(message))}-fn persist_plugin_offline(plugin: &InstalledPluginInfo) -> std::io::Result<()> {+fn persist_plugin_offline(+ plugin: &InstalledPluginInfo,+ preserve_enabled: bool,+) -> std::io::Result<()> {crate::plugin_paths::ensure_plugin_user_dirs(&plugin.plugin_id)?;crate::persist::plugin_registry::update(|plugins| {- plugins.retain(|entry| entry.plugin_id != plugin.plugin_id);- plugins.push(plugin.clone());- })?;- Ok(())-}--fn register_installed_plugin(- plugin: InstalledPluginInfo,- source: PluginSourceInfo,-) -> Result<(), InstallFailure> {- let request = Request {- id: "cli:plugin".into(),- method: Method::PluginLink(PluginLinkParams {- path: plugin.manifest_path.clone(),- enabled: plugin.enabled,- source: Some(source.clone()),- }),- };- match super::send_request(&request) {- Ok(response) => {- if response.get("error").is_some() {- return Err(InstallFailure::Rollback(std::io::Error::other(- serde_json::to_string(&response).unwrap(),- )));- }- if let Err(err) =- verify_plugin_link_source_response(response, &plugin.plugin_id, &source)+ let mut plugin = plugin.clone();+ if preserve_enabled {+ if let Some(existing) = plugins+ .iter()+ .find(|entry| entry.plugin_id == plugin.plugin_id){- let unlink = super::send_request(&Request {- id: "cli:plugin".into(),- method: Method::PluginUnlink(PluginUnlinkParams {- plugin_id: plugin.plugin_id.clone(),- }),- });- match unlink {- Ok(response) if response.get("error").is_none() => {- return Err(InstallFailure::Rollback(err));- }- Ok(response) => {- return Err(InstallFailure::KeepCheckout(std::io::Error::other(- format!(- "{err}; failed to undo incompatible plugin registration: {}",- serde_json::to_string(&response).unwrap()- ),- )));- }- Err(unlink_err) if super::protocol_mismatch_was_reported(&unlink_err) => {- return Err(InstallFailure::KeepCheckout(unlink_err));- }- Err(unlink_err) => {- return Err(InstallFailure::KeepCheckout(std::io::Error::other(- format!(- "{err}; failed to undo incompatible plugin registration: {unlink_err}"- ),- )));- }- }+ plugin.enabled = existing.enabled;}- Ok(())- }- Err(err) if is_connection_error(&err) => {- persist_plugin_offline(&plugin).map_err(InstallFailure::Rollback)}- Err(err) => Err(InstallFailure::Rollback(err)),- }-}--#[derive(Debug)]-enum InstallFailure {- Rollback(std::io::Error),- KeepCheckout(std::io::Error),+ plugins.retain(|entry| entry.plugin_id != plugin.plugin_id);+ plugins.push(plugin);+ })?;+ Ok(())}-fn verify_plugin_link_source_response(- response: serde_json::Value,- plugin_id: &str,- expected: &PluginSourceInfo,+fn persist_updated_plugin(+ plugin: &InstalledPluginInfo,+ expected: &InstalledPluginInfo,) -> std::io::Result<()> {- let parsed: SuccessResponse =- serde_json::from_value(response).map_err(std::io::Error::other)?;- let ResponseResult::PluginLinked { plugin } = parsed.result else {- return Err(std::io::Error::other("expected plugin_linked response"));- };- if plugin.plugin_id != plugin_id- || plugin.source.kind != PluginSourceKind::Github- || plugin.source.owner != expected.owner- || plugin.source.repo != expected.repo- || plugin.source.subdir != expected.subdir- || plugin.source.requested_ref != expected.requested_ref- || plugin.source.resolved_commit != expected.resolved_commit- || plugin.source.managed_path != expected.managed_path- {- return Err(std::io::Error::other(- "running Herdr server did not persist GitHub plugin source metadata",- ));+ let (updated, _) = crate::persist::plugin_registry::update(|plugins| {+ let Some(current) = plugins+ .iter_mut()+ .find(|entry| entry.plugin_id == expected.plugin_id)+ else {+ return false;+ };+ if !same_update_target(expected, current) {+ return false;+ }+ let enabled = current.enabled;+ *current = plugin.clone();+ current.enabled = enabled;+ true+ })?;+ if updated {+ Ok(())+ } else {+ Err(io::Error::other(format!(+ "plugin {} changed while its update was in progress; retry the update",+ expected.plugin_id+ )))}- Ok(())}fn installed_plugin_info(plugin_id: &str) -> std::io::Result<Option<InstalledPluginInfo>> {@@ -1121,14 +1273,22 @@ fn plugin_by_github_source(fn plugin_matches_github_source(plugin: &InstalledPluginInfo, source: &GithubPluginSource) -> bool {plugin.source.kind == PluginSourceKind::Github- && plugin.source.owner.as_deref() == Some(source.owner.as_str())- && plugin.source.repo.as_deref() == Some(source.repo.as_str())+ && plugin+ .source+ .owner+ .as_deref()+ .is_some_and(|owner| owner.eq_ignore_ascii_case(&source.owner))+ && plugin+ .source+ .repo+ .as_deref()+ .is_some_and(|repo| repo.eq_ignore_ascii_case(&source.repo))&& plugin.source.subdir.as_deref() == source.subdir.as_deref()}fn offline_plugin_link_response(params: &PluginLinkParams) -> std::io::Result<serde_json::Value> {let plugin = load_cli_plugin_manifest(Path::new(¶ms.path), params.enabled)?;- persist_plugin_offline(&plugin)?;+ persist_plugin_offline(&plugin, false)?;serde_json::to_value(SuccessResponse {id: "cli:plugin".into(),result: ResponseResult::PluginLinked { plugin },@@ -1233,8 +1393,12 @@ fn print_install_preview(plugin: &InstalledPluginInfo,source: &PluginSourceInfo,existing: Option<&InstalledPluginInfo>,+ updating: bool,) {- eprintln!("Plugin install preview:");+ eprintln!(+ "Plugin {} preview:",+ if updating { "update" } else { "install" }+ );eprintln!(" id: {}", plugin.plugin_id);eprintln!(" name: {}", plugin.name);eprintln!(" version: {}", plugin.version);@@ -1467,8 +1631,7 @@ impl fmt::Display for PluginBuildFailure {write_output_section(f, "stdout", stdout)?;}}- writeln!(f)?;- write!(f, "Plugin was not installed.")+ Ok(())}}@@ -1595,49 +1758,19 @@ fn create_plugin_temp_dir(label: &str) -> std::io::Result<PathBuf> {Ok(path)}-fn remove_managed_plugin_files(plugin: &InstalledPluginInfo) -> std::io::Result<()> {- if plugin.source.kind != PluginSourceKind::Github {- return Ok(());- }- let Some(path) = plugin.source.managed_path.as_deref() else {- return Ok(());- };- let path = PathBuf::from(path);- if !path.exists() {- return Ok(());- }- if !is_expected_managed_path(plugin, &path) {- return Err(std::io::Error::other(format!(- "refusing to delete unmanaged plugin path: {}",- path.display()- )));- }- std::fs::remove_dir_all(&path)- .map_err(|err| plugin_checkout_lifecycle_error("remove", &path, err))-}--fn plugin_checkout_lifecycle_error(operation: &str, path: &Path, err: io::Error) -> io::Error {- if cfg!(windows) && err.kind() == io::ErrorKind::PermissionDenied {- return io::Error::new(- err.kind(),- format!(- "failed to {operation} managed plugin checkout at {}; close any Herdr plugin panes or plugin commands using that checkout, then retry: {err}",- path.display()- ),- );+fn lock_managed_checkout(plugin_id: &str) -> std::io::Result<std::fs::File> {+ let lock_path = crate::plugin_paths::managed_checkout_lock_path(plugin_id);+ if let Some(parent) = lock_path.parent() {+ std::fs::create_dir_all(parent)?;}- err-}--fn is_expected_managed_path(plugin: &InstalledPluginInfo, path: &Path) -> bool {- let Ok(path) = path.canonicalize() else {- return false;- };- let expected = crate::plugin_paths::managed_checkout_path(&plugin.plugin_id);- let Ok(expected) = expected.canonicalize() else {- return false;- };- path == expected+ let lock = std::fs::OpenOptions::new()+ .create(true)+ .truncate(false)+ .read(true)+ .write(true)+ .open(lock_path)?;+ lock.lock()?;+ Ok(lock)}fn current_unix_ms() -> u64 {@@ -1676,6 +1809,7 @@ fn print_plugin_response(method: Method) -> std::io::Result<i32> {fn print_plugin_help() {eprintln!("herdr plugin commands:");eprintln!(" herdr plugin install <owner>/<repo>[/subdir...] [--ref REF] [--yes]");+ eprintln!(" herdr plugin update [<plugin_id|owner/repo[/subdir...]>...] [--yes]");eprintln!(" herdr plugin uninstall <plugin_id|owner/repo[/subdir...]>");eprintln!(" herdr plugin link <path> [--disabled]");eprintln!(" herdr plugin list [--plugin ID] [--json]");@@ -1895,6 +2029,22 @@ mod tests {assert!(plugin_by_github_source(plugins, &source).is_none());}+ #[test]+ fn github_source_lookup_ignores_owner_and_repo_case() {+ let source = GithubPluginSource::parse("OGULCANCELIK/HERDR-PLUGIN-EXAMPLES").unwrap();+ let plugins = vec![github_plugin(+ "examples.root",+ "ogulcancelik",+ "herdr-plugin-examples",+ None,+ )];++ assert_eq!(+ plugin_by_github_source(plugins, &source).unwrap().plugin_id,+ "examples.root"+ );+ }+#[test]fn github_source_lookup_ignores_local_plugins() {let source = GithubPluginSource::parse("ogulcancelik/herdr-plugin-examples").unwrap();@@ -1909,6 +2059,24 @@ mod tests {assert!(plugin_by_github_source([plugin], &source).is_none());}+ #[test]+ fn update_target_revalidation_allows_state_changes_but_rejects_install_changes() {+ let expected = github_plugin("examples.root", "owner", "repo", None);+ let mut current = expected.clone();+ current.enabled = false;+ assert!(ensure_update_target_unchanged(&expected, Some(¤t)).is_ok());++ current.source.resolved_commit = Some("newer".to_string());+ assert!(ensure_update_target_unchanged(&expected, Some(¤t)).is_err());+ current = expected.clone();+ current.source = PluginSourceInfo::default();+ assert!(ensure_update_target_unchanged(&expected, Some(¤t)).is_err());+ current = expected.clone();+ current.manifest_path.push_str(".reinstalled");+ assert!(ensure_update_target_unchanged(&expected, Some(¤t)).is_err());+ assert!(ensure_update_target_unchanged(&expected, None).is_err());+ }+#[test]fn cli_user_dir_creation_seeds_legacy_config_before_printing_config_dir() {let plugin_id = unique_plugin_id("legacy-config");diff --git a/src/cli/spec.rs b/src/cli/spec.rsindex c6bde2252..9a503a18a 100644--- a/src/cli/spec.rs+++ b/src/cli/spec.rs@@ -807,6 +807,17 @@ fn plugin_command() -> Command {.about("Uninstall a plugin").arg(required("plugin", "PLUGIN")),)+ .subcommand(+ Command::new("update")+ .about("Update GitHub-installed plugins")+ .arg(Arg::new("plugins").value_name("PLUGIN").num_args(0..))+ .arg(+ Arg::new("yes")+ .short('y')+ .long("yes")+ .action(ArgAction::SetTrue),+ ),+ ).subcommand(Command::new("link").about("Link a local plugin")diff --git a/src/main.rs b/src/main.rsindex 32ef0e76f..940b5127f 100644--- a/src/main.rs+++ b/src/main.rs@@ -38,6 +38,7 @@ use ghostty_vt::pane_graphics_files;mod persist;mod platform;mod plugin_command;+mod plugin_installations;mod plugin_paths;mod popup_size;mod product_announcements;diff --git a/src/persist/plugin_registry.rs b/src/persist/plugin_registry.rsindex 8b1efa2ce..58c13596b 100644--- a/src/persist/plugin_registry.rs+++ b/src/persist/plugin_registry.rs@@ -16,7 +16,9 @@ fn registry_lock_path() -> PathBuf {crate::config::config_dir().join(REGISTRY_LOCK_FILE)}-fn with_registry_lock<T>(operation: impl FnOnce() -> std::io::Result<T>) -> std::io::Result<T> {+pub(crate) fn with_registry_lock<T>(+ operation: impl FnOnce() -> std::io::Result<T>,+) -> std::io::Result<T> {let lock_path = registry_lock_path();if let Some(parent) = lock_path.parent() {std::fs::create_dir_all(parent)?;@@ -64,14 +66,7 @@ fn save_json_to_path<T: serde::Serialize + ?Sized>(path: &Path, value: &T) -> stlet json = serde_json::to_string_pretty(value)?;let tmp_path = path.with_extension("json.tmp");std::fs::write(&tmp_path, json)?;- #[cfg(windows)]- if path.exists() {- if let Err(err) = std::fs::remove_file(path) {- let _ = std::fs::remove_file(&tmp_path);- return Err(err);- }- }- if let Err(err) = std::fs::rename(&tmp_path, path) {+ if let Err(err) = crate::platform::replace_file(&tmp_path, path) {let _ = std::fs::remove_file(&tmp_path);return Err(err);}@@ -95,7 +90,13 @@ pub fn update<T>(}pub fn try_load() -> std::io::Result<Vec<InstalledPluginInfo>> {- with_registry_lock(|| load_from_path_strict(®istry_path()))+ read(Ok)+}++pub(crate) fn read<T>(+ operation: impl FnOnce(Vec<InstalledPluginInfo>) -> std::io::Result<T>,+) -> std::io::Result<T> {+ with_registry_lock(|| operation(load_from_path_strict(®istry_path())?))}/// Load the global registry. Returns an empty vec on failure so a corrupt or@@ -436,4 +437,15 @@ mod tests {assert_eq!(loaded.len(), 1);assert_eq!(loaded[0].plugin_id, "example.second");}++ #[test]+ fn failed_save_preserves_previous_registry() {+ let path = temp_registry_path("failed-save");+ save_to_path(&path, &[sample_plugin("example.original")]).unwrap();+ let original = std::fs::read(&path).unwrap();+ std::fs::create_dir(path.with_extension("json.tmp")).unwrap();+ assert!(save_to_path(&path, &[sample_plugin("example.replacement")]).is_err());+ assert_eq!(std::fs::read(&path).unwrap(), original);+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();+ }}diff --git a/src/plugin_installations.rs b/src/plugin_installations.rsnew file mode 100644index 000000000..2d646c61f--- /dev/null+++ b/src/plugin_installations.rs@@ -0,0 +1,470 @@+use std::collections::HashMap;+use std::fs::{File, OpenOptions, TryLockError};+use std::io;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use crate::api::schema::InstalledPluginInfo;++const LEASE_FILE: &str = ".in-use";+pub(crate) type Leases = HashMap<PathBuf, Arc<File>>;++pub(crate) fn create_lease(installation: &Path) -> io::Result<File> {+ let file = OpenOptions::new()+ .create_new(true)+ .read(true)+ .write(true)+ .open(installation.join(LEASE_FILE))?;+ file.lock_shared()?;+ Ok(file)+}++fn lease_path(path: &Path) -> Option<PathBuf> {+ let root = crate::plugin_paths::managed_plugins_dir()+ .join("github-installations")+ .canonicalize()+ .ok()?;+ let path = path.canonicalize().ok()?;+ let mut components = path.strip_prefix(&root).ok()?.components();+ let installation = root.join(components.next()?).join(components.next()?);+ (components.next()?.as_os_str() == "checkout").then_some(installation)+}++pub(crate) fn command_lease(leases: &Leases, plugin: &InstalledPluginInfo) -> Option<Arc<File>> {+ let installation = lease_path(Path::new(&plugin.plugin_root))?;+ leases.get(&installation).cloned()+}++// The caller holds the registry lock, preventing cleanup between registry+// selection and acquisition. Missing markers denote untracked installations.+fn retain_checkout(leases: &mut Leases, checkout: &Path) -> io::Result<()> {+ let Some(installation) = lease_path(checkout) else {+ return Ok(());+ };+ if leases.contains_key(&installation) {+ return Ok(());+ }+ let file = match OpenOptions::new()+ .read(true)+ .write(true)+ .open(installation.join(LEASE_FILE))+ {+ Ok(file) => file,+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(err) => return Err(err),+ };+ file.lock_shared()?;+ leases.insert(installation, Arc::new(file));+ Ok(())+}++// Pin failures leave a registered installation unprotected only after it is+// replaced; plugin store errors must not hide every plugin.+pub(crate) fn load(leases: &mut Leases) -> io::Result<Vec<InstalledPluginInfo>> {+ crate::persist::plugin_registry::read(|entries| {+ for entry in &entries {+ if let Err(err) = retain_checkout(leases, Path::new(&entry.plugin_root)) {+ tracing::warn!(%err, plugin_root = %entry.plugin_root, "failed to pin plugin installation");+ }+ }+ Ok(entries)+ })+}++// Unreadable entries are skipped and reported so callers can stay conservative.+fn installations(errors: &mut Vec<io::Error>) -> Vec<PathBuf> {+ let root = crate::plugin_paths::managed_plugins_dir().join("github-installations");+ let plugins = match std::fs::read_dir(root) {+ Ok(plugins) => plugins,+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Vec::new(),+ Err(err) => {+ errors.push(err);+ return Vec::new();+ }+ };+ let mut result = Vec::new();+ let generations = |plugin: io::Result<std::fs::DirEntry>| -> io::Result<Vec<PathBuf>> {+ let plugin = plugin?;+ if !plugin.file_type()?.is_dir() {+ return Ok(Vec::new());+ }+ let mut paths = Vec::new();+ for generation in std::fs::read_dir(plugin.path())? {+ let generation = generation?;+ if generation.file_type()?.is_dir() {+ paths.push(generation.path().canonicalize()?);+ }+ }+ Ok(paths)+ };+ for plugin in plugins {+ match generations(plugin) {+ Ok(paths) => result.extend(paths),+ Err(err) => errors.push(err),+ }+ }+ result+}++fn retain_startup_installation(+ leases: &mut Leases,+ installation: PathBuf,+ restored_cwds: &[PathBuf],+ handoff: bool,+) -> io::Result<()> {+ if leases.contains_key(&installation) {+ return Ok(());+ }+ let file = match OpenOptions::new()+ .read(true)+ .write(true)+ .open(installation.join(LEASE_FILE))+ {+ Ok(file) => file,+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(err) => return Err(err),+ };+ let referenced = restored_cwds.iter().any(|cwd| {+ cwd.canonicalize()+ .unwrap_or_else(|_| cwd.clone())+ .starts_with(installation.join("checkout"))+ });+ if !referenced && !handoff {+ return Ok(());+ }+ match file.try_lock() {+ Ok(()) if !referenced => return Ok(()),+ Ok(()) => file.unlock()?,+ Err(TryLockError::WouldBlock) => {}+ Err(TryLockError::Error(err)) => return Err(err),+ }+ // Also retain generations held by the outgoing server during handoff.+ file.lock_shared()?;+ leases.insert(installation, Arc::new(file));+ Ok(())+}++/// Best-effort: plugin store errors never block startup or handoff. Returns+/// false when an installation may be unpinned; the caller must then skip+/// startup cleanup so it never reclaims files a restored consumer still uses.+pub(crate) fn retain_startup(+ leases: &mut Leases,+ restored_cwds: &[PathBuf],+ handoff: bool,+) -> bool {+ let result = crate::persist::plugin_registry::with_registry_lock(|| {+ let mut errors = Vec::new();+ let installations = installations(&mut errors);+ for err in &errors {+ tracing::warn!(%err, "failed to scan plugin installations");+ }+ let mut complete = errors.is_empty();+ for installation in installations {+ if let Err(err) =+ retain_startup_installation(leases, installation.clone(), restored_cwds, handoff)+ {+ tracing::warn!(%err, installation = %installation.display(), "failed to pin plugin installation");+ complete = false;+ }+ }+ Ok(complete)+ });+ result.unwrap_or_else(|err| {+ tracing::warn!(%err, "failed to pin plugin installations");+ false+ })+}++fn reclaim(installation: &Path) -> io::Result<()> {+ let Some(component) = installation.parent().and_then(Path::file_name) else {+ return Ok(());+ };+ let mutation_path = crate::plugin_paths::managed_plugins_dir()+ .join(".locks")+ .join(format!(".{}.lock", component.to_string_lossy()));+ let mutation = OpenOptions::new()+ .create(true)+ .truncate(false)+ .read(true)+ .write(true)+ .open(mutation_path)?;+ match mutation.try_lock() {+ Ok(()) => {}+ Err(TryLockError::WouldBlock) => return Ok(()),+ Err(TryLockError::Error(err)) => return Err(err),+ }+ let lease = match OpenOptions::new()+ .read(true)+ .write(true)+ .open(installation.join(LEASE_FILE))+ {+ Ok(file) => file,+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(err) => return Err(err),+ };+ match lease.try_lock() {+ Ok(()) => {}+ Err(TryLockError::WouldBlock) => return Ok(()),+ Err(TryLockError::Error(err)) => return Err(err),+ }+ // Windows cannot remove the open lease file. Registry + mutation+ // locks exclude new readers/installers while the handle is closed.+ drop(lease);+ // Keep the marker if removing checkout files fails so a later+ // cleanup can retry (for example, an open Windows build artifact).+ match std::fs::remove_dir_all(installation.join("checkout")) {+ Ok(()) => {}+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}+ Err(err) => return Err(err),+ }+ std::fs::remove_dir_all(installation)+}++/// Reclaims every unused installation it can and returns the first error.+pub(crate) fn cleanup() -> io::Result<()> {+ crate::persist::plugin_registry::read(|entries| {+ let mut errors = Vec::new();+ for installation in installations(&mut errors) {+ if entries.iter().any(|entry| {+ lease_path(Path::new(&entry.plugin_root)).as_ref() == Some(&installation)+ }) {+ continue;+ }+ if let Err(err) = reclaim(&installation) {+ errors.push(err);+ }+ }+ errors.into_iter().next().map_or(Ok(()), Err)+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn with_config(test: impl FnOnce()) {+ let _guard = crate::config::test_config_env_lock().lock().unwrap();+ let root = std::env::temp_dir().join(format!(+ "herdr-plugin-cleanup-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let previous = std::env::var_os("XDG_CONFIG_HOME");+ std::env::set_var("XDG_CONFIG_HOME", &root);+ std::fs::create_dir_all(crate::plugin_paths::managed_plugins_dir().join(".locks")).unwrap();+ test();+ match previous {+ Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),+ None => std::env::remove_var("XDG_CONFIG_HOME"),+ }+ std::fs::remove_dir_all(root).unwrap();+ }++ fn installation(id: &str) -> (PathBuf, InstalledPluginInfo) {+ let root = crate::plugin_paths::create_managed_installation(id).unwrap();+ let checkout = root.join("checkout");+ std::fs::create_dir(&checkout).unwrap();+ std::fs::write(+ checkout.join("herdr-plugin.toml"),+ format!(+ "id = {id:?}\nname = 'Cleanup'\nversion = '0.1.0'\nmin_herdr_version = '0.6.10'\n"+ ),+ )+ .unwrap();+ let mut plugin =+ crate::app::load_plugin_manifest(&checkout.to_string_lossy(), true).unwrap();+ plugin.source.managed_path = Some(checkout.display().to_string());+ drop(create_lease(&root).unwrap());+ (root, plugin)+ }++ #[test]+ fn cleanup_waits_for_all_servers_and_command_references_and_preserves_current_paths() {+ with_config(|| {+ let (current, mut registered) = installation("example.current");+ // Registry paths and config paths can use different aliases.+ registered.plugin_root = current.join("checkout/../checkout").display().to_string();+ let (retired, old) = installation("example.retired");+ let untracked =+ crate::plugin_paths::create_managed_installation("example.legacy").unwrap();+ crate::persist::plugin_registry::update(|entries| {+ *entries = vec![registered.clone(), old.clone()];+ })+ .unwrap();+ let mut first_server = Leases::new();+ let mut second_server = Leases::new();+ load(&mut first_server).unwrap();+ load(&mut second_server).unwrap();+ let command = command_lease(&first_server, &old).unwrap();+ crate::persist::plugin_registry::update(|entries| *entries = vec![registered]).unwrap();+ drop(first_server);+ cleanup().unwrap();+ assert!(retired.exists());+ drop(second_server);+ cleanup().unwrap();+ assert!(retired.exists(), "running commands outlive the server map");+ drop(command);+ cleanup().unwrap();+ assert!(!retired.exists());+ assert!(+ current.exists(),+ "registered alias must protect the current files"+ );+ assert!(+ untracked.exists(),+ "untracked installations are never reclaimed"+ );++ let (building, _) = installation("example.building");+ let mutation = OpenOptions::new()+ .create(true)+ .truncate(false)+ .read(true)+ .write(true)+ .open(crate::plugin_paths::managed_checkout_lock_path(+ "example.building",+ ))+ .unwrap();+ mutation.lock().unwrap();+ cleanup().unwrap();+ assert!(+ building.exists(),+ "a building checkout is not yet registered"+ );+ drop(mutation);+ cleanup().unwrap();+ assert!(!building.exists());++ // Relinking a checkout subdirectory clears managed source metadata,+ // but it still needs registry and running-server protection.+ let (linked, mut local) = installation("example.linked");+ let subdir = linked.join("checkout/subplugin");+ std::fs::create_dir(&subdir).unwrap();+ local.plugin_root = subdir.display().to_string();+ local.source = Default::default();+ crate::persist::plugin_registry::update(|entries| *entries = vec![local]).unwrap();+ cleanup().unwrap();+ assert!(+ subdir.exists(),+ "registered local roots protect their files"+ );+ let mut server = Leases::new();+ load(&mut server).unwrap();+ crate::persist::plugin_registry::update(Vec::clear).unwrap();+ cleanup().unwrap();+ assert!(+ subdir.exists(),+ "unlinked local roots retain live server protection"+ );+ drop(server);+ cleanup().unwrap();+ assert!(!linked.exists());++ let (retry, _) = installation("example.retry");+ std::fs::remove_dir_all(retry.join("checkout")).unwrap();+ std::fs::write(retry.join("checkout"), "not a directory").unwrap();+ assert!(cleanup().is_err());+ assert!(+ retry.join(LEASE_FILE).exists(),+ "failed cleanup remains tracked"+ );+ std::fs::remove_file(retry.join("checkout")).unwrap();+ cleanup().unwrap();+ assert!(!retry.exists(), "a later cleanup retries the installation");+ });+ }++ #[test]+ fn startup_retains_restored_and_handoff_generations_and_survives_pin_errors() {+ with_config(|| {+ let (restored, _) = installation("example.restored");+ let (handoff, _) = installation("example.handoff");+ let outgoing = OpenOptions::new()+ .read(true)+ .write(true)+ .open(handoff.join(LEASE_FILE))+ .unwrap();+ outgoing.lock_shared().unwrap();+ let mut unrelated = Leases::new();+ assert!(retain_startup(&mut unrelated, &[], false));+ assert!(+ unrelated.is_empty(),+ "ordinary startup must not inherit other servers' pins"+ );+ let mut incoming = Leases::new();+ assert!(retain_startup(+ &mut incoming,+ &[restored.join("checkout")],+ true+ ));+ drop(outgoing);+ cleanup().unwrap();+ assert!(restored.exists());+ assert!(handoff.exists());+ drop(incoming);+ cleanup().unwrap();+ assert!(!restored.exists());+ assert!(!handoff.exists());++ // Corrupt registry contents disable plugins, not the server. The+ // startup scan needs serialization, not registry deserialization.+ let registry = crate::config::config_dir().join("plugins.json");+ std::fs::write(®istry, "not json").unwrap();+ let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();+ let app = crate::app::App::try_new(+ &crate::config::Config::default(),+ crate::app::AppPolicy {+ persist_plugin_registry: true,+ ..crate::app::AppPolicy::TEST+ },+ None,+ rx,+ crate::api::EventHub::default(),+ )+ .expect("corrupt registry must not prevent server startup");+ assert!(app.state.installed_plugins.is_empty());+ drop(app);+ std::fs::remove_file(registry).unwrap();++ let broken =+ crate::plugin_paths::create_managed_installation("example.broken").unwrap();+ std::fs::create_dir(broken.join(LEASE_FILE)).unwrap();+ let (retired, _) = installation("example.unused");+ assert!(!retain_startup(&mut Leases::new(), &[], true));+ let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = crate::app::App::try_new(+ &crate::config::Config::default(),+ crate::app::AppPolicy {+ persist_plugin_registry: true,+ ..crate::app::AppPolicy::TEST+ },+ None,+ rx,+ crate::api::EventHub::default(),+ )+ .expect("plugin pin errors must not prevent server startup");+ assert!(!app.plugin_installation_cleanup_allowed);+ app.run_plugin_startup_hooks();+ assert!(+ retired.exists(),+ "startup cleanup is skipped when an installation could not be pinned"+ );+ });+ }++ #[test]+ fn cleanup_continues_past_installations_it_cannot_remove() {+ with_config(|| {+ let (stuck, _) = installation("example.stuck");+ std::fs::remove_dir_all(stuck.join("checkout")).unwrap();+ std::fs::write(stuck.join("checkout"), "not a directory").unwrap();+ let (unused, _) = installation("example.unused");+ assert!(cleanup().is_err(), "the failure is still reported");+ assert!(stuck.join(LEASE_FILE).exists());+ assert!(!unused.exists(), "other installations are still reclaimed");+ });+ }+}diff --git a/src/plugin_paths.rs b/src/plugin_paths.rsindex 62eed4ff5..9f075781e 100644--- a/src/plugin_paths.rs+++ b/src/plugin_paths.rs@@ -12,6 +12,35 @@ pub(crate) fn managed_checkout_path(plugin_id: &str) -> PathBuf {.join(crate::api::schema::plugin_managed_path_component(plugin_id))}+pub(crate) fn managed_checkout_lock_path(plugin_id: &str) -> PathBuf {+ managed_plugins_dir().join(".locks").join(format!(+ ".{}.lock",+ crate::api::schema::plugin_managed_path_component(plugin_id)+ ))+}++pub(crate) fn managed_installations_dir(plugin_id: &str) -> PathBuf {+ managed_plugins_dir()+ .join("github-installations")+ .join(crate::api::schema::plugin_managed_path_component(plugin_id))+}++pub(crate) fn create_managed_installation(plugin_id: &str) -> std::io::Result<PathBuf> {+ let parent = managed_installations_dir(plugin_id);+ std::fs::create_dir_all(&parent)?;+ for generation in 0u64.. {+ let path = parent.join(format!("{}-{generation}", std::process::id()));+ match std::fs::create_dir(&path) {+ Ok(()) => return Ok(path),+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(err) => return Err(err),+ }+ }+ Err(std::io::Error::other(+ "plugin installation directory exhausted",+ ))+}+pub(crate) fn plugin_config_dir(plugin_id: &str) -> PathBuf {managed_plugins_dir().join("config")@@ -47,8 +76,11 @@ fn ensure_plugin_config_dir(plugin_id: &str) -> std::io::Result<()> {fn legacy_plugin_config_dirs(plugin_id: &str) -> Vec<PathBuf> {let plugins_dir = managed_plugins_dir();- let old_unhashed =- (!matches!(plugin_id, "config" | "github")).then(|| plugins_dir.join(plugin_id));+ let old_unhashed = (!matches!(+ plugin_id,+ "config" | "github" | "github-installations" | ".locks"+ ))+ .then(|| plugins_dir.join(plugin_id));let current_hashed =plugins_dir.join(crate::api::schema::plugin_managed_path_component(plugin_id));let mut candidates = Vec::new();@@ -110,6 +142,46 @@ fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {mod tests {use super::*;+ #[test]+ fn installations_never_reuse_or_move_existing_files() {+ let _guard = crate::config::test_config_env_lock().lock().unwrap();+ let base = std::env::temp_dir().join(format!(+ "herdr-installations-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let previous = std::env::var_os("XDG_CONFIG_HOME");+ std::env::set_var("XDG_CONFIG_HOME", &base);+ let id = format!("example.generations-{}", std::process::id());+ let first = create_managed_installation(&id).unwrap();+ std::fs::write(first.join("keep"), "original").unwrap();+ let second = create_managed_installation(&id).unwrap();+ assert_ne!(first, second);+ assert_eq!(+ std::fs::read_to_string(first.join("keep")).unwrap(),+ "original"+ );+ ensure_plugin_config_dir("github-installations").unwrap();+ assert!(+ std::fs::read_dir(plugin_config_dir("github-installations"))+ .unwrap()+ .next()+ .is_none(),+ "managed installations are not legacy user configuration"+ );+ std::fs::remove_dir_all(&first).unwrap();+ std::fs::remove_dir_all(&second).unwrap();+ std::fs::remove_dir(managed_installations_dir(&id)).unwrap();+ match previous {+ Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),+ None => std::env::remove_var("XDG_CONFIG_HOME"),+ }+ std::fs::remove_dir_all(base).unwrap();+ }+#[test]fn plugin_config_path_component_is_readable_and_collision_free() {assert_eq!(diff --git a/src/server/headless/bootstrap.rs b/src/server/headless/bootstrap.rsindex 664aa9a2a..019148db3 100644--- a/src/server/headless/bootstrap.rs+++ b/src/server/headless/bootstrap.rs@@ -57,13 +57,13 @@ pub fn run_server() -> io::Result<()> {let result = rt.block_on(async {// Create the App (with AppState, event channels, etc.).- let mut app = app::App::new(+ let mut app = app::App::try_new(&loaded_config.config,app::AppPolicy::PRODUCTION,config::config_diagnostic_summary(&loaded_config.diagnostics),api_rx,event_hub,- );+ )?;seed_startup_workspace_if_empty(&mut app);// Create the headless server.diff --git a/tests/cli/harness.rs b/tests/cli/harness.rsindex c4b83b42c..b55eb5f75 100644--- a/tests/cli/harness.rs+++ b/tests/cli/harness.rs@@ -12,9 +12,6 @@ pub(super) use crate::support::{};use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize};-pub(super) const WORKTREE_BOOTSTRAP_MANAGED_COMPONENT: &str =- "example.worktree-bootstrap-ef876653ffc3";-pub(super) fn unique_test_dir() -> PathBuf {let nanos = SystemTime::now().duration_since(UNIX_EPOCH)@@ -24,7 +21,10 @@ pub(super) fn unique_test_dir() -> PathBuf {}pub(super) fn managed_github_plugin_dir(config_home: &Path) -> PathBuf {- config_home.join("herdr-dev").join("plugins").join("github")+ config_home+ .join("herdr-dev")+ .join("plugins")+ .join("github-installations")}pub(super) fn path_missing_or_empty(path: &Path) -> bool {diff --git a/tests/cli/plugins.rs b/tests/cli/plugins.rsindex 23f1b352f..6cbb3ccd9 100644--- a/tests/cli/plugins.rs+++ b/tests/cli/plugins.rs@@ -81,6 +81,7 @@ fn named_sessions_share_live_plugin_registry() {&runtime_dir,&["--session", "beta", "plugin", "disable", "example.first"],);+let disabled = run_named_cli(&config_home,&runtime_dir,@@ -247,6 +248,591 @@ platforms = ["linux", "macos", "windows"]cleanup_test_base(&base);}+#[test]+fn plugin_update_refreshes_selected_then_all_github_plugins() {+ let base = unique_test_dir();+ let config_home = base.join("config");+ let runtime_dir = base.join("runtime");+ let source_repo = base.join("source-repo");+ create_committed_repo(&source_repo);+ run_git(&source_repo, &["checkout", "-b", "plugin-updates"]);++ for (subdir, id) in [("first", "example.first"), ("second", "example.second")] {+ let plugin_dir = source_repo.join(subdir);+ fs::create_dir_all(&plugin_dir).unwrap();+ fs::write(+ plugin_dir.join("herdr-plugin.toml"),+ format!(+ "id = \"{id}\"\nname = \"{id}\"\nversion = \"0.1.0\"\nmin_herdr_version = \"0.6.10\"\n"+ ),+ )+ .unwrap();+ }+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "add plugins"]);++ let git_config = base.join("gitconfig");+ fs::write(+ &git_config,+ format!(+ "[url \"file://{}\"]\n insteadOf = https://github.com/example/plugins.git\n",+ source_repo.display()+ ),+ )+ .unwrap();+ for subdir in ["first", "second"] {+ let source = format!("example/plugins/{subdir}");+ let ref_args = (subdir == "first").then_some(["--ref", "plugin-updates"]);+ let mut args = vec!["plugin", "install", source.as_str(), "--yes"];+ if let Some(ref_args) = ref_args {+ args.extend(ref_args);+ }+ let output = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &args,+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let server = spawn_named_server(&config_home, &runtime_dir, "updates");+ wait_for_socket(+ &named_session_socket(&config_home, "updates"),+ Duration::from_secs(5),+ );+ run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "disable", "example.first"],+ );+ let reinstalled = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "updates",+ "plugin",+ "install",+ "example/plugins/first",+ "--ref",+ "plugin-updates",+ "--yes",+ ],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(reinstalled.status.success());+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "list", "--json"],+ );+ assert_eq!(listed["result"]["plugins"][0]["enabled"], false);+ let first_installation = PathBuf::from(+ listed["result"]["plugins"][0]["plugin_root"]+ .as_str()+ .unwrap(),+ );+ let offline_reinstall = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "offline-update",+ "plugin",+ "install",+ "example/plugins/first",+ "--ref",+ "plugin-updates",+ "--yes",+ ],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(offline_reinstall.status.success());+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "list", "--json"],+ );+ assert_eq!(listed["result"]["plugins"][0]["enabled"], false);+ let second_installation = PathBuf::from(+ listed["result"]["plugins"][0]["plugin_root"]+ .as_str()+ .unwrap(),+ );+ assert_ne!(first_installation, second_installation);+ assert!(first_installation.join("herdr-plugin.toml").exists());+ let malformed = run_named_cli(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "updates",+ "plugin",+ "update",+ "example/plugins/..",+ "--yes",+ ],+ );+ assert_eq!(malformed.status.code(), Some(2));+ assert!(String::from_utf8_lossy(&malformed.stderr).contains("invalid plugin subdir segment"));++ for (subdir, id) in [("first", "example.first"), ("second", "example.second")] {+ fs::write(+ source_repo.join(subdir).join("herdr-plugin.toml"),+ format!(+ "id = \"{id}\"\nname = \"{id}\"\nversion = \"0.2.0\"\nmin_herdr_version = \"0.6.10\"\n"+ ),+ )+ .unwrap();+ }+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "update plugins"]);++ let selected = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "updates",+ "plugin",+ "update",+ "EXAMPLE/PLUGINS/first",+ "example.first",+ "--yes",+ ],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(selected.status.success());+ assert!(String::from_utf8_lossy(&selected.stdout).contains("Updated example.first"));+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "list", "--json"],+ );+ assert_eq!(listed["result"]["plugins"][0]["version"], "0.2.0");+ assert_eq!(listed["result"]["plugins"][0]["enabled"], false);+ assert_eq!(listed["result"]["plugins"][1]["version"], "0.1.0");++ let local_dir = base.join("local-plugin");+ fs::create_dir_all(&local_dir).unwrap();+ fs::write(+ local_dir.join("herdr-plugin.toml"),+ "id = \"example.local\"\nname = \"Local\"\nversion = \"0.1.0\"\nmin_herdr_version = \"0.6.10\"\n",+ )+ .unwrap();+ let linked = run_named_cli(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "updates",+ "plugin",+ "link",+ local_dir.to_str().unwrap(),+ ],+ );+ assert!(linked.status.success());++ let all = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "update", "--yes"],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(all.status.success());+ let stdout = String::from_utf8_lossy(&all.stdout);+ assert!(stdout.contains("example.first is already up to date"));+ assert!(stdout.contains("Updated example.second"));+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "updates", "plugin", "list", "--json"],+ );+ let plugins = listed["result"]["plugins"].as_array().unwrap();+ for id in ["example.first", "example.second"] {+ let plugin = plugins+ .iter()+ .find(|plugin| plugin["plugin_id"] == id)+ .unwrap();+ assert_eq!(plugin["version"], "0.2.0");+ }+ assert!(plugins+ .iter()+ .any(|plugin| plugin["plugin_id"] == "example.local"));++ let _ = run_named_cli(&config_home, &runtime_dir, &["session", "stop", "updates"]);+ drop(server);+ let unchanged = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &["plugin", "update", "--yes"],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(unchanged.status.success());+ assert!(+ !first_installation.exists(),+ "stopped servers release old files"+ );+ assert!(!second_installation.exists());+ assert!(local_dir.exists(), "cleanup never removes local plugins");+ cleanup_test_base(&base);+}++#[test]+fn plugin_update_does_not_resurrect_a_plugin_unlinked_during_build() {+ let base = unique_test_dir();+ let config_home = base.join("config");+ let runtime_dir = base.join("runtime");+ let source_repo = base.join("source-repo");+ let plugin_dir = source_repo.join("plugin");+ let build_started = base.join("build-started");+ let release_build = base.join("release-build");+ create_committed_repo(&source_repo);+ fs::create_dir_all(&plugin_dir).unwrap();+ fs::write(+ plugin_dir.join("herdr-plugin.toml"),+ "id = \"example.race\"\nname = \"Race\"\nversion = \"0.1.0\"\nmin_herdr_version = \"0.6.10\"\n",+ )+ .unwrap();+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "add plugin"]);++ let git_config = base.join("gitconfig");+ fs::write(+ &git_config,+ format!(+ "[url \"file://{}\"]\n insteadOf = https://github.com/example/race.git\n",+ source_repo.display()+ ),+ )+ .unwrap();+ let installed = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "race",+ "plugin",+ "install",+ "example/race/plugin",+ "--yes",+ ],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(installed.status.success());++ let server = spawn_named_server(&config_home, &runtime_dir, "race");+ wait_for_socket(+ &named_session_socket(&config_home, "race"),+ Duration::from_secs(5),+ );+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "race", "plugin", "list", "--json"],+ );+ let managed_path = PathBuf::from(+ listed["result"]["plugins"][0]["source"]["managed_path"]+ .as_str()+ .unwrap(),+ );++ fs::write(+ plugin_dir.join("herdr-plugin.toml"),+ format!(+ "id = \"example.race\"\nname = \"Race\"\nversion = \"0.2.0\"\nmin_herdr_version = \"0.6.10\"\n\n[[build]]\ncommand = [\"sh\", \"-c\", \"touch {}; while [ ! -e {} ]; do sleep 0.05; done\"]\n",+ build_started.display(),+ release_build.display()+ ),+ )+ .unwrap();+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "update plugin"]);++ let mut update = Command::new(env!("CARGO_BIN_EXE_herdr"));+ update+ .args([+ "--session",+ "race",+ "plugin",+ "update",+ "example.race",+ "--yes",+ ])+ .env("XDG_CONFIG_HOME", &config_home)+ .env("XDG_RUNTIME_DIR", &runtime_dir)+ .env("GIT_CONFIG_GLOBAL", &git_config)+ .env_remove("HERDR_SOCKET_PATH")+ .env_remove("HERDR_CLIENT_SOCKET_PATH")+ .env_remove("HERDR_ENV")+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ let child = update.spawn().unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ while !build_started.exists() && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(20));+ }+ if !build_started.exists() {+ fs::write(&release_build, "release").unwrap();+ let output = child.wait_with_output().unwrap();+ panic!(+ "plugin update never reached its build: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let unlinked = run_named_cli(+ &config_home,+ &runtime_dir,+ &["--session", "race", "plugin", "unlink", "example.race"],+ );+ assert!(unlinked.status.success());+ fs::write(&release_build, "release").unwrap();+ let updated = child.wait_with_output().unwrap();+ assert!(!updated.status.success());+ assert!(String::from_utf8_lossy(&updated.stderr)+ .contains("changed while its update was in progress"));++ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "race", "plugin", "list", "--json"],+ );+ assert!(listed["result"]["plugins"].as_array().unwrap().is_empty());+ assert!(+ fs::read_to_string(managed_path.join("plugin/herdr-plugin.toml"))+ .unwrap()+ .contains("version = \"0.1.0\"")+ );++ let _ = run_named_cli(&config_home, &runtime_dir, &["session", "stop", "race"]);+ drop(server);+ cleanup_test_base(&base);+}++#[test]+fn plugin_updates_preserve_running_consumers_and_failed_activation() {+ let base = unique_test_dir();+ let config_home = base.join("config");+ let runtime_dir = base.join("runtime");+ let source_repo = base.join("source");+ create_committed_repo(&source_repo);+ let manifest = r#"+id = "example.live"+name = "Live"+version = "0.1.0"+min_herdr_version = "0.6.10"+[[actions]]+id = "read"+title = "Read"+command = ["sh", "./read.sh", "action"]+[[panes]]+id = "read"+title = "Read"+placement = "tab"+command = ["sh", "./read.sh", "pane"]+"#;+ fs::write(source_repo.join("herdr-plugin.toml"), manifest).unwrap();+ fs::write(source_repo.join("version"), "old").unwrap();+ fs::write(source_repo.join("read.sh"), r#"+kind="$1"+touch "$HERDR_PLUGIN_ROOT/ready-$kind"+while [ ! -e "$HERDR_PLUGIN_ROOT/release" ]; do sleep 0.05; done+printf '%s:%s' "$(cat version)" "$(cat "$HERDR_PLUGIN_ROOT/version")" > "$HERDR_PLUGIN_ROOT/result-$kind.tmp"+mv "$HERDR_PLUGIN_ROOT/result-$kind.tmp" "$HERDR_PLUGIN_ROOT/result-$kind"+"#).unwrap();+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "old plugin"]);+ let git_config = base.join("gitconfig");+ fs::write(+ &git_config,+ format!(+ "[url \"file://{}\"]\n insteadOf = https://github.com/example/live.git\n",+ source_repo.display()+ ),+ )+ .unwrap();+ let install = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &["plugin", "install", "example/live", "--yes"],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(+ install.status.success(),+ "{}",+ String::from_utf8_lossy(&install.stderr)+ );++ // Model an existing installation from before generation directories.+ let registry = config_home.join("herdr-dev/plugins.json");+ let mut entries: serde_json::Value =+ serde_json::from_slice(&fs::read(®istry).unwrap()).unwrap();+ let installed_root = PathBuf::from(entries[0]["plugin_root"].as_str().unwrap());+ let component = installed_root+ .parent()+ .unwrap()+ .parent()+ .unwrap()+ .file_name()+ .unwrap();+ let legacy_root = config_home.join("herdr-dev/plugins/github").join(component);+ fs::create_dir_all(legacy_root.parent().unwrap()).unwrap();+ fs::rename(&installed_root, &legacy_root).unwrap();+ entries[0]["plugin_root"] = serde_json::json!(legacy_root);+ entries[0]["manifest_path"] = serde_json::json!(legacy_root.join("herdr-plugin.toml"));+ entries[0]["source"]["managed_path"] = serde_json::json!(legacy_root);+ fs::write(®istry, serde_json::to_vec(&entries).unwrap()).unwrap();++ let alpha = spawn_named_server(&config_home, &runtime_dir, "alpha");+ let beta = spawn_named_server(&config_home, &runtime_dir, "beta");+ for name in ["alpha", "beta"] {+ wait_for_socket(+ &named_session_socket(&config_home, name),+ Duration::from_secs(5),+ );+ }+ let socket = named_session_socket(&config_home, "alpha");+ run_cli_json(+ &socket,+ &[+ "workspace",+ "create",+ "--cwd",+ base.to_str().unwrap(),+ "--focus",+ ],+ );+ let current_root = || {+ let listed = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &["--session", "beta", "plugin", "list", "--json"],+ );+ PathBuf::from(+ listed["result"]["plugins"][0]["plugin_root"]+ .as_str()+ .unwrap(),+ )+ };+ let launch = || {+ let action = run_named_cli_json(+ &config_home,+ &runtime_dir,+ &[+ "--session",+ "beta",+ "plugin",+ "action",+ "invoke",+ "read",+ "--plugin",+ "example.live",+ ],+ );+ assert_eq!(action["result"]["type"], "plugin_action_invoked");+ let pane = run_cli_json(+ &socket,+ &[+ "plugin",+ "pane",+ "open",+ "--plugin",+ "example.live",+ "--entrypoint",+ "read",+ ],+ );+ assert_eq!(pane["result"]["type"], "plugin_pane_opened");+ };+ let wait_file = |path: &Path| {+ let deadline = Instant::now() + Duration::from_secs(10);+ while !path.exists() && Instant::now() < deadline {+ thread::sleep(Duration::from_millis(20));+ }+ assert!(path.exists(), "missing {}", path.display());+ };+ let old_root = current_root();+ launch();+ for kind in ["action", "pane"] {+ wait_file(&old_root.join(format!("ready-{kind}")));+ }+ fs::write(source_repo.join("version"), "new").unwrap();+ run_git(&source_repo, &["add", "."]);+ run_git(&source_repo, &["commit", "--quiet", "-m", "new plugin"]);+ let update = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &["--session", "alpha", "plugin", "update", "--yes"],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(+ update.status.success(),+ "{}",+ String::from_utf8_lossy(&update.stderr)+ );+ let new_root = current_root();+ assert_ne!(old_root, new_root);+ launch();+ for root in [&old_root, &new_root] {+ fs::write(root.join("release"), "").unwrap();+ for kind in ["action", "pane"] {+ wait_file(&root.join(format!("result-{kind}")));+ }+ }+ for kind in ["action", "pane"] {+ assert_eq!(+ fs::read_to_string(old_root.join(format!("result-{kind}"))).unwrap(),+ "old:old"+ );+ assert_eq!(+ fs::read_to_string(new_root.join(format!("result-{kind}"))).unwrap(),+ "new:new"+ );+ }++ // Fail registry activation after the build, preserving the working version+ // and both running consumers' directories without a restore operation.+ let registry = config_home.join("herdr-dev/plugins.json");+ let original_registry = fs::read(®istry).unwrap();+ let block_write = format!("mkdir '{}'", registry.with_extension("json.tmp").display());+ fs::write(+ source_repo.join("herdr-plugin.toml"),+ format!(+ "{manifest}\n[[build]]\ncommand = {}\n",+ serde_json::to_string(&["sh", "-c", block_write.as_str()]).unwrap()+ ),+ )+ .unwrap();+ run_git(&source_repo, &["add", "."]);+ run_git(+ &source_repo,+ &["commit", "--quiet", "-m", "fail activation"],+ );+ let failed = run_named_cli_with_env(+ &config_home,+ &runtime_dir,+ &["--session", "alpha", "plugin", "update", "--yes"],+ &[("GIT_CONFIG_GLOBAL", &git_config)],+ );+ assert!(!failed.status.success());+ assert!(String::from_utf8_lossy(&failed.stderr).contains("plugin files retained at"));+ assert_eq!(fs::read(®istry).unwrap(), original_registry);+ assert_eq!(current_root(), new_root);+ assert_eq!(fs::read_to_string(old_root.join("version")).unwrap(), "old");+ assert_eq!(fs::read_to_string(new_root.join("version")).unwrap(), "new");+ for name in ["alpha", "beta"] {+ let _ = run_named_cli(&config_home, &runtime_dir, &["session", "stop", name]);+ }+ drop((alpha, beta));+ cleanup_test_base(&base);+}+#[test]fn plugin_link_list_unlink_cli_smoke_test() {let base = unique_test_dir();@@ -539,8 +1125,8 @@ command = ["sh", "-c", "echo bootstrap"]String::from_utf8_lossy(&uninstall.stderr));assert!(- !managed_path.exists(),- "managed checkout should be deleted on uninstall"+ managed_path.exists(),+ "uninstall must preserve files used by running plugins");let listed = run_named_cli_json(@@ -640,7 +1226,9 @@ command = ["sh", "-c", "echo should-not-install"]assert!(listed["result"]["plugins"].as_array().unwrap().is_empty());assert!(- path_missing_or_empty(&managed_github_plugin_dir(&config_home)),+ fs::read_dir(managed_github_plugin_dir(&config_home))+ .unwrap()+ .all(|plugin| path_missing_or_empty(&plugin.unwrap().path())),"failed build should not leave managed checkouts");@@ -833,383 +1421,11 @@ EOFassert!(listed["result"]["plugins"].as_array().unwrap().is_empty());assert!(- path_missing_or_empty(&managed_github_plugin_dir(&config_home)),+ fs::read_dir(managed_github_plugin_dir(&config_home))+ .unwrap()+ .all(|plugin| path_missing_or_empty(&plugin.unwrap().path())),"manifest mutation should not leave managed checkouts");cleanup_test_base(&base);}--#[test]-fn plugin_install_restores_previous_checkout_when_registration_fails() {- let base = unique_test_dir();- let config_home = base.join("config");- let runtime_dir = base.join("runtime");- let socket_path = runtime_dir.join("fake-herdr.sock");- let source_repo = base.join("source-repo");- let plugin_dir = source_repo.join("worktree-bootstrap");- fs::create_dir_all(&plugin_dir).unwrap();- create_committed_repo(&source_repo);- fs::write(- plugin_dir.join("herdr-plugin.toml"),- r#"-id = "example.worktree-bootstrap"-name = "Worktree Bootstrap"-version = "0.2.0"-min_herdr_version = "0.6.10"-platforms = ["linux", "macos", "windows"]--[[actions]]-id = "bootstrap"-title = "Bootstrap"-command = ["sh", "-c", "echo new"]-"#,- )- .unwrap();- run_git(- &source_repo,- &["add", "worktree-bootstrap/herdr-plugin.toml"],- );- run_git(&source_repo, &["commit", "--quiet", "-m", "add plugin"]);-- fs::create_dir_all(&config_home).unwrap();- fs::create_dir_all(&runtime_dir).unwrap();- let managed_checkout = config_home- .join("herdr-dev")- .join("plugins")- .join("github")- .join(WORKTREE_BOOTSTRAP_MANAGED_COMPONENT);- fs::create_dir_all(&managed_checkout).unwrap();- fs::write(managed_checkout.join("old-marker"), "old checkout\n").unwrap();-- let git_config = base.join("gitconfig");- fs::write(- &git_config,- format!(- "[url \"file://{}\"]\n insteadOf = https://github.com/ogulcancelik/herdr-plugin-examples.git\n",- source_repo.display()- ),- )- .unwrap();-- let listener = UnixListener::bind(&socket_path).unwrap();- let managed_checkout_for_server = managed_checkout.clone();- let server = thread::spawn(move || {- let (mut first, first_line) = accept_fake_cli_operation(&listener);- let first_request: serde_json::Value = serde_json::from_str(&first_line).unwrap();- assert_eq!(first_request["method"], "plugin.list");- writeln!(- first,- "{}",- serde_json::json!({- "id": "cli:plugin",- "result": {- "type": "plugin_list",- "plugins": [{- "plugin_id": "example.worktree-bootstrap",- "name": "Worktree Bootstrap",- "version": "0.1.0",- "min_herdr_version": "0.6.10",- "manifest_path": managed_checkout_for_server.join("herdr-plugin.toml").display().to_string(),- "plugin_root": managed_checkout_for_server.display().to_string(),- "enabled": true,- "source": {- "kind": "github",- "owner": "ogulcancelik",- "repo": "herdr-plugin-examples",- "subdir": "worktree-bootstrap",- "resolved_commit": "old",- "managed_path": managed_checkout_for_server.display().to_string(),- "installed_unix_ms": 1- }- }]- }- })- )- .unwrap();- first.flush().unwrap();-- let (mut second, second_line) = accept_fake_cli_operation(&listener);- let second_request: serde_json::Value = serde_json::from_str(&second_line).unwrap();- assert_eq!(second_request["method"], "plugin.link");- second- .write_all(- br#"{"id":"cli:plugin","error":{"code":"plugin_registry_save_failed","message":"forced failure"}}"#,- )- .unwrap();- second.write_all(b"\n").unwrap();- second.flush().unwrap();- });-- let install = run_named_cli_with_env_and_socket_override(- &config_home,- &runtime_dir,- &[- "plugin",- "install",- "ogulcancelik/herdr-plugin-examples/worktree-bootstrap",- "--yes",- ],- &[("GIT_CONFIG_GLOBAL", &git_config)],- Some(&socket_path),- );- assert!(- !install.status.success(),- "install should fail when plugin.link fails"- );- server.join().unwrap();- assert!(- managed_checkout.join("old-marker").exists(),- "old checkout should be restored after registration failure"- );-- cleanup_test_base(&base);-}--#[test]-fn plugin_install_rejects_server_that_drops_source_metadata() {- let base = unique_test_dir();- let config_home = base.join("config");- let runtime_dir = base.join("runtime");- let socket_path = runtime_dir.join("fake-herdr.sock");- let source_repo = base.join("source-repo");- let plugin_dir = source_repo.join("worktree-bootstrap");- fs::create_dir_all(&plugin_dir).unwrap();- create_committed_repo(&source_repo);- fs::write(- plugin_dir.join("herdr-plugin.toml"),- r#"-id = "example.worktree-bootstrap"-name = "Worktree Bootstrap"-version = "0.1.0"-min_herdr_version = "0.6.10"-platforms = ["linux", "macos", "windows"]--[[actions]]-id = "bootstrap"-title = "Bootstrap"-command = ["sh", "-c", "echo install"]-"#,- )- .unwrap();- run_git(- &source_repo,- &["add", "worktree-bootstrap/herdr-plugin.toml"],- );- run_git(&source_repo, &["commit", "--quiet", "-m", "add plugin"]);-- fs::create_dir_all(&config_home).unwrap();- fs::create_dir_all(&runtime_dir).unwrap();- let managed_checkout = config_home- .join("herdr-dev")- .join("plugins")- .join("github")- .join(WORKTREE_BOOTSTRAP_MANAGED_COMPONENT);- let git_config = base.join("gitconfig");- fs::write(- &git_config,- format!(- "[url \"file://{}\"]\n insteadOf = https://github.com/ogulcancelik/herdr-plugin-examples.git\n",- source_repo.display()- ),- )- .unwrap();-- let listener = UnixListener::bind(&socket_path).unwrap();- let managed_checkout_for_server = managed_checkout.clone();- let server = thread::spawn(move || {- let (mut first, first_line) = accept_fake_cli_operation(&listener);- let first_request: serde_json::Value = serde_json::from_str(&first_line).unwrap();- assert_eq!(first_request["method"], "plugin.list");- first- .write_all(br#"{"id":"cli:plugin","result":{"type":"plugin_list","plugins":[]}}"#)- .unwrap();- first.write_all(b"\n").unwrap();- first.flush().unwrap();-- let (mut second, second_line) = accept_fake_cli_operation(&listener);- let second_request: serde_json::Value = serde_json::from_str(&second_line).unwrap();- assert_eq!(second_request["method"], "plugin.link");- writeln!(- second,- "{}",- serde_json::json!({- "id": "cli:plugin",- "result": {- "type": "plugin_linked",- "plugin": {- "plugin_id": "example.worktree-bootstrap",- "name": "Worktree Bootstrap",- "version": "0.1.0",- "min_herdr_version": "0.6.10",- "manifest_path": managed_checkout_for_server.join("herdr-plugin.toml").display().to_string(),- "plugin_root": managed_checkout_for_server.display().to_string(),- "enabled": true,- "source": {"kind": "local"}- }- }- })- )- .unwrap();- second.flush().unwrap();-- let (mut third, third_line) = accept_fake_cli_operation(&listener);- let third_request: serde_json::Value = serde_json::from_str(&third_line).unwrap();- assert_eq!(third_request["method"], "plugin.unlink");- assert_eq!(- third_request["params"]["plugin_id"],- "example.worktree-bootstrap"- );- third- .write_all(- br#"{"id":"cli:plugin","result":{"type":"plugin_unlinked","plugin_id":"example.worktree-bootstrap","removed":true}}"#,- )- .unwrap();- third.write_all(b"\n").unwrap();- third.flush().unwrap();- });-- let install = run_named_cli_with_env_and_socket_override(- &config_home,- &runtime_dir,- &[- "plugin",- "install",- "ogulcancelik/herdr-plugin-examples/worktree-bootstrap",- "--yes",- ],- &[("GIT_CONFIG_GLOBAL", &git_config)],- Some(&socket_path),- );- assert!(- !install.status.success(),- "install should fail when server drops GitHub source metadata"- );- server.join().unwrap();- assert!(- !managed_checkout.exists(),- "new checkout should be removed after incompatible plugin.link response"- );-- cleanup_test_base(&base);-}--#[test]-fn plugin_install_keeps_checkout_when_incompatible_server_cleanup_fails() {- let base = unique_test_dir();- let config_home = base.join("config");- let runtime_dir = base.join("runtime");- let socket_path = runtime_dir.join("fake-herdr.sock");- let source_repo = base.join("source-repo");- let plugin_dir = source_repo.join("worktree-bootstrap");- fs::create_dir_all(&plugin_dir).unwrap();- create_committed_repo(&source_repo);- fs::write(- plugin_dir.join("herdr-plugin.toml"),- r#"-id = "example.worktree-bootstrap"-name = "Worktree Bootstrap"-version = "0.1.0"-min_herdr_version = "0.6.10"-platforms = ["linux", "macos", "windows"]--[[actions]]-id = "bootstrap"-title = "Bootstrap"-command = ["sh", "-c", "echo install"]-"#,- )- .unwrap();- run_git(- &source_repo,- &["add", "worktree-bootstrap/herdr-plugin.toml"],- );- run_git(&source_repo, &["commit", "--quiet", "-m", "add plugin"]);-- fs::create_dir_all(&config_home).unwrap();- fs::create_dir_all(&runtime_dir).unwrap();- let managed_checkout = config_home- .join("herdr-dev")- .join("plugins")- .join("github")- .join(WORKTREE_BOOTSTRAP_MANAGED_COMPONENT);- let git_config = base.join("gitconfig");- fs::write(- &git_config,- format!(- "[url \"file://{}\"]\n insteadOf = https://github.com/ogulcancelik/herdr-plugin-examples.git\n",- source_repo.display()- ),- )- .unwrap();-- let listener = UnixListener::bind(&socket_path).unwrap();- let managed_checkout_for_server = managed_checkout.clone();- let server = thread::spawn(move || {- let (mut first, _first_line) = accept_fake_cli_operation(&listener);- first- .write_all(br#"{"id":"cli:plugin","result":{"type":"plugin_list","plugins":[]}}"#)- .unwrap();- first.write_all(b"\n").unwrap();- first.flush().unwrap();-- let (mut second, _second_line) = accept_fake_cli_operation(&listener);- writeln!(- second,- "{}",- serde_json::json!({- "id": "cli:plugin",- "result": {- "type": "plugin_linked",- "plugin": {- "plugin_id": "example.worktree-bootstrap",- "name": "Worktree Bootstrap",- "version": "0.1.0",- "min_herdr_version": "0.6.10",- "manifest_path": managed_checkout_for_server.join("herdr-plugin.toml").display().to_string(),- "plugin_root": managed_checkout_for_server.display().to_string(),- "enabled": true,- "source": {"kind": "local"}- }- }- })- )- .unwrap();- second.flush().unwrap();-- let (mut third, third_line) = accept_fake_cli_operation(&listener);- let third_request: serde_json::Value = serde_json::from_str(&third_line).unwrap();- assert_eq!(third_request["method"], "plugin.unlink");- third- .write_all(- br#"{"id":"cli:plugin","error":{"code":"plugin_registry_save_failed","message":"forced unlink failure"}}"#,- )- .unwrap();- third.write_all(b"\n").unwrap();- third.flush().unwrap();- });-- let install = run_named_cli_with_env_and_socket_override(- &config_home,- &runtime_dir,- &[- "plugin",- "install",- "ogulcancelik/herdr-plugin-examples/worktree-bootstrap",- "--yes",- ],- &[("GIT_CONFIG_GLOBAL", &git_config)],- Some(&socket_path),- );- assert!(- !install.status.success(),- "install should fail when source metadata is dropped and cleanup fails"- );- server.join().unwrap();- assert!(- managed_checkout.exists(),- "checkout should stay when server cleanup fails"- );-- cleanup_test_base(&base);-}