diff --git a/packages/cli-rs/crates/plugin/src/lib.rs b/packages/cli-rs/crates/plugin/src/lib.rs index 54401876736..d0f8ab957e3 100644 --- a/packages/cli-rs/crates/plugin/src/lib.rs +++ b/packages/cli-rs/crates/plugin/src/lib.rs @@ -228,6 +228,9 @@ pub struct Entry { pub target: Option, pub source: Source, pub status: Status, + /// Whether the plugin has an activation, failed or not (TS `registered().active`): the plugin manager offers + /// to disable it. + pub active: bool, } /// Why a configured TypeScript TUI plugin is listed but not loaded (deviation of F16 until P.4). @@ -438,6 +441,7 @@ impl Registry { (Some(_), None) => Status::Active, (None, _) => Status::Inactive, }, + active: plugin.active.is_some(), }); let unloaded = self.unloaded.borrow(); let unloaded = unloaded.iter().map(|(target, status)| Entry { @@ -445,6 +449,7 @@ impl Registry { target: Some(target.clone()), source: Source::Configured, status: status.clone(), + active: false, }); active.chain(unloaded).collect() } diff --git a/packages/cli-rs/crates/plugin/src/loader/mod.rs b/packages/cli-rs/crates/plugin/src/loader/mod.rs index 05743dce6a1..4d8c36bd010 100644 --- a/packages/cli-rs/crates/plugin/src/loader/mod.rs +++ b/packages/cli-rs/crates/plugin/src/loader/mod.rs @@ -75,11 +75,13 @@ pub struct Loader { cwd: PathBuf, configured: Vec, seen: RefCell>, + /// The targets of the last reconcile, so a removed one leaves the registry whatever its status. + listed: RefCell>, } impl Loader { pub fn new(backend: Rc>, config_dir: PathBuf, cwd: PathBuf, configured: Vec) -> Self { - Self { backend, config_dir, cwd, configured, seen: RefCell::default() } + Self { backend, config_dir, cwd, configured, seen: RefCell::default(), listed: RefCell::default() } } /// The discovered directories, then the configured entries, merged by local path (TS `mergePluginTargets`: @@ -111,16 +113,16 @@ impl Loader { targets } - /// The directories whose changes can change the targets: the `plugins` directories (or, while one is - /// missing, the directory it would be made in), each local target's directory, and the directory of each - /// configured library. Missing ones are left out. + /// The directories whose changes can change the targets: the `plugins` directories and `cwd`'s (or, while + /// one is missing, the nearest of its `.opencode` directory and the one above that exists), each local + /// target's directory, + /// and the directory of each configured library. Missing ones are left out. pub fn watch_dirs(&self) -> Vec { - let mut dirs: Vec = plugin_directories(&self.config_dir, &self.cwd) - .into_iter() - .map(|dir| match (dir.is_dir(), dir.parent()) { - (false, Some(parent)) => parent.to_path_buf(), - _ => dir, - }) + let mut directories = plugin_directories(&self.config_dir, &self.cwd); + directories.push(self.cwd.join(".opencode/plugins")); + let mut dirs: Vec = directories + .iter() + .filter_map(|dir| dir.ancestors().take(3).find(|dir| dir.is_dir()).map(Path::to_path_buf)) .collect(); for target in self.targets() { let Some(local) = target.local else { continue }; @@ -148,12 +150,20 @@ impl Loader { .filter(|target| !targets.iter().any(|known| known.target == **target && known.library().is_some())) .cloned() .collect(); - for target in stale { + let removed = self + .listed + .borrow() + .iter() + .filter(|target| !targets.iter().any(|known| known.target == **target)) + .cloned() + .collect::>(); + for target in stale.into_iter().chain(removed) { self.seen.borrow_mut().remove(&target); registry.unload(&target); registry.set_unloaded(&target, None); changed = true; } + self.listed.replace(targets.iter().map(|target| target.target.clone()).collect()); for target in &targets { changed |= self.reconcile_target(host, registry, target); } @@ -209,6 +219,18 @@ impl Loader { let reload = reload.clone(); Rc::new(move || error().or_else(|| reload.borrow().clone())) }; + // Starting the plugin again (the plugin manager) starts this build; the failed build is old news. + let setup = definition.setup.clone(); + let definition = Definition { + setup: Rc::new({ + let reload = reload.clone(); + move |registering: &mut crate::Setup<'_, H>| { + reload.take(); + setup(registering); + } + }), + ..definition + }; self.seen.borrow_mut().insert(name.to_owned(), Seen { digest, reload }); registry.load(host, definition.external(name, failure)); true diff --git a/packages/cli-rs/crates/plugin/src/loader/native.rs b/packages/cli-rs/crates/plugin/src/loader/native.rs index 9b4fba5e067..615722f08f6 100644 --- a/packages/cli-rs/crates/plugin/src/loader/native.rs +++ b/packages/cli-rs/crates/plugin/src/loader/native.rs @@ -32,6 +32,7 @@ use opencode_plugin_abi::{ }; use opencode_ui::keymap::{Bind, KeymapLayer, Slash, TuiCommand}; use opencode_ui::theme::Theme; +use opentui::keymap::Disposer; use opentui::prelude::*; use opentui::style::Color; use serde::de::DeserializeOwned; @@ -104,6 +105,7 @@ impl Backend for Native { failure: failure.clone(), host, id: setup.id().to_owned(), + layer: RefCell::new(None), }); register(setup, &guest, &manifest); // What setup asked for (toasts, routes) happens now that the plugin is active. @@ -414,6 +416,8 @@ struct Guest { failure: Rc>>, host: Weak, id: String, + /// The commands' keymap layer, until deactivation or a panic removes it. + layer: RefCell>, } impl Guest { @@ -442,7 +446,12 @@ impl Guest { log::error!("plugin {} failed: {error}", self.id); *self.failure.borrow_mut() = Some(error); let id = self.id.clone(); + // The layer goes once the key that may have run the panicking command is handled. + let layer = self.layer.borrow_mut().take(); self.defer(move |host| { + if let Some(layer) = layer { + layer.dispose(); + } host.toast(Toast::Error, Some(&format!("Plugin failed: {id}")), "Run /plugins to view details."); }); None @@ -504,7 +513,18 @@ fn register(setup: &mut Setup<'_, H>, guest: &Rc>, manifest: & }) .collect(); if !commands.is_empty() { - setup.layer(KeymapLayer::global(commands)); + match setup.host().keymap().layer(KeymapLayer::global(commands)) { + Ok(disposer) => { + guest.layer.replace(Some(disposer)); + let guest = guest.clone(); + setup.on_dispose(move || { + if let Some(layer) = guest.layer.take() { + layer.dispose(); + } + }); + } + Err(error) => log::error!("plugin {} keymap layer: {error}", setup.id()), + } } for language in &manifest.fences { let guest = guest.clone(); diff --git a/packages/cli-rs/crates/plugin/src/loader/native/tests.rs b/packages/cli-rs/crates/plugin/src/loader/native/tests.rs index ce9fc43ef09..d3614857ddb 100644 --- a/packages/cli-rs/crates/plugin/src/loader/native/tests.rs +++ b/packages/cli-rs/crates/plugin/src/loader/native/tests.rs @@ -145,6 +145,14 @@ fn a_panicking_command_fails_the_plugin() { let registry = active(&host, &build("")); assert!(matches!(host.keymap().dispatch("sample.panic", None), RunResult::Ok)); assert_eq!(status(®istry), Status::Failed("run-command panicked: sample command panicked".to_owned())); + // Its commands leave the keymap once the key is handled; it stays active, so it can be disabled. + host.app.advance(Duration::from_millis(1)); + assert!(matches!(host.keymap().dispatch("sample.hello", None), RunResult::NotFound)); + assert!(entry(®istry.entries(), "sample.so").active); + assert!(registry.set_active(&host, "sample", false)); + assert_eq!(status(®istry), Status::Inactive); + assert!(registry.set_active(&host, "sample", true)); + assert!(matches!(host.keymap().dispatch("sample.hello", None), RunResult::Ok)); } #[test] diff --git a/packages/cli-rs/crates/plugin/src/loader/tests.rs b/packages/cli-rs/crates/plugin/src/loader/tests.rs index 1cd1ae16932..f66d647975e 100644 --- a/packages/cli-rs/crates/plugin/src/loader/tests.rs +++ b/packages/cli-rs/crates/plugin/src/loader/tests.rs @@ -212,6 +212,13 @@ fn reconcile_loads_reloads_keeps_and_unloads() { // The same broken build is not retried. assert!(!loader.reconcile(&host, ®istry)); assert_eq!(fake.loads.get(), 3); + // The running version can be disabled, and enabling it starts it afresh without the stale failure. + assert!(entry(®istry.entries(), &lib_target).active); + assert!(registry.set_active(&host, "fake", false)); + assert_eq!(entry(®istry.entries(), &lib_target).status, Status::Inactive); + assert!(registry.set_active(&host, "fake", true)); + assert_eq!(entry(®istry.entries(), &lib_target).status, Status::Active); + assert_eq!(fake.active.get(), 2); // A fixed build replaces it in place, under its new ID. write(&lib_dir.join(entry_file()), "id=fake2"); @@ -235,6 +242,15 @@ fn reconcile_loads_reloads_keeps_and_unloads() { assert_eq!(entry(&entries, &lib_target).status, Status::Skipped(SKIPPED.to_owned())); assert!(!entries.iter().any(|entry| entry.id == "fake2")); assert_eq!(fake.active.get(), 1); + + // Deleted directories leave the list, whether they were skipped or loaded. + fs::remove_dir_all(&lib_dir).unwrap(); + fs::remove_dir_all(&ts_dir).unwrap(); + assert!(loader.reconcile(&host, ®istry)); + let entries = registry.entries(); + let gone = |entry: &Entry| entry.target.as_ref().is_some_and(|target| [&lib_target, &ts_target].contains(&target)); + assert!(!entries.iter().any(gone), "{entries:?}"); + assert_eq!(entry(&entries, "@acme/tui").status, Status::Skipped(SKIPPED.to_owned())); } #[test] @@ -289,3 +305,23 @@ fn directives_after_an_entry_disable_an_external_plugin() { assert_eq!(status("one"), Status::Inactive); assert_eq!(status("two"), Status::Active); } + +// Expected: while `/.opencode/plugins` is missing, the directory it would be made in is watched, even when +// `/.opencode` is missing too and `cwd` is below the project root. +#[test] +fn watch_dirs_cover_a_plugins_directory_made_later() { + let root = tempfile::tempdir().unwrap(); + let config = root.path().join("config"); + let project = root.path().join("repo"); + let cwd = project.join("a"); + fs::create_dir_all(project.join(".git")).unwrap(); + fs::create_dir_all(&cwd).unwrap(); + let loader = Loader::::new(Rc::new(Fake::default()), config, cwd.clone(), Vec::new()); + let dirs = loader.watch_dirs(); + assert!(dirs.contains(&cwd) && dirs.contains(&project), "{dirs:?}"); + fs::create_dir_all(cwd.join(".opencode")).unwrap(); + assert!(loader.watch_dirs().contains(&cwd.join(".opencode"))); + fs::create_dir_all(cwd.join(".opencode/plugins")).unwrap(); + let dirs = loader.watch_dirs(); + assert!(dirs.contains(&cwd.join(".opencode/plugins")) && !dirs.contains(&cwd), "{dirs:?}"); +} diff --git a/packages/cli-rs/crates/tui/src/dialogs/plugins.rs b/packages/cli-rs/crates/tui/src/dialogs/plugins.rs index 21dbfeb9a81..d629328404c 100644 --- a/packages/cli-rs/crates/tui/src/dialogs/plugins.rs +++ b/packages/cli-rs/crates/tui/src/dialogs/plugins.rs @@ -72,6 +72,8 @@ enum Entry { target: String, status: &'static str, error: Option, + /// Has an activation, failed or not: Enter disables it. + active: bool, }, Server { key: String, @@ -242,30 +244,7 @@ impl Manager { let Some(tui) = self.tui.upgrade() else { return Vec::new(); }; - let mut local: Vec = tui - .plugins - .entries() - .into_iter() - .filter(|entry| entry.id != ID) - .map(|entry| { - let (status, error) = match &entry.status { - Status::Active => ("active", None), - Status::Inactive => ("inactive", None), - Status::Skipped(reason) => ("skipped", Some(reason.clone())), - Status::Failed(error) => ("failed", Some(error.clone())), - }; - // Only a plugin with a definition can be toggled; an unloaded target cannot. - let loaded = entry.source != Source::Configured; - Entry::Tui { - key: format!("tui:{}", entry.target.as_ref().unwrap_or(&entry.id)), - internal: entry.source == Source::Builtin, - id: loaded.then(|| entry.id.clone()), - target: entry.target.unwrap_or(entry.id), - status, - error, - } - }) - .collect(); + let mut local: Vec = tui.plugins.entries().into_iter().filter(|entry| entry.id != ID).map(row).collect(); // A package without a server part runs nothing there; its TUI part has its own row. let mut server: Vec = self .server @@ -316,8 +295,9 @@ impl Manager { entry.filter(|entry| matches!(entry, Entry::Tui { id: Some(_), .. })) } + /// TS `registered().active`: a plugin that failed while active is still active, so it can be disabled. fn active(entry: &Entry) -> bool { - status(entry) == "active" + matches!(entry, Entry::Tui { active: true, .. }) } fn updating(&self, entry: &Entry) -> bool { @@ -591,6 +571,27 @@ fn is_local(entry: &Entry) -> bool { } } +/// The row of a registry entry. +fn row(entry: opencode_plugin::Entry) -> Entry { + let (status, error) = match &entry.status { + Status::Active => ("active", None), + Status::Inactive => ("inactive", None), + Status::Skipped(reason) => ("skipped", Some(reason.clone())), + Status::Failed(error) => ("failed", Some(error.clone())), + }; + // Only a plugin with a definition can be toggled; an unloaded target cannot. + let loaded = entry.source != Source::Configured; + Entry::Tui { + key: format!("tui:{}", entry.target.as_ref().unwrap_or(&entry.id)), + internal: entry.source == Source::Builtin, + id: loaded.then(|| entry.id.clone()), + target: entry.target.unwrap_or(entry.id), + status, + error, + active: entry.active, + } +} + fn status(entry: &Entry) -> &str { match entry { Entry::Server { plugin, .. } => plugin.state.tag(), @@ -654,4 +655,22 @@ mod tests { labels.sort_by(|a, b| locale_compare(a, b)); assert_eq!(labels, ["alpha", "Alpha", "beta"]); } + + // Expected: as in TS, a plugin that failed while active (a panic, or a failed rebuild with the previous + // version running) offers disable, and an inactive one enable. + #[test] + fn a_failed_active_plugin_can_be_disabled() { + let entry = |status: Status, active: bool| { + row(opencode_plugin::Entry { + id: "sample".to_owned(), + target: Some("sample.so".to_owned()), + source: Source::External, + status, + active, + }) + }; + assert!(Manager::active(&entry(Status::Failed("boom (previous version still active)".to_owned()), true))); + assert!(Manager::active(&entry(Status::Active, true))); + assert!(!Manager::active(&entry(Status::Inactive, false))); + } } diff --git a/packages/cli-rs/crates/tui/src/plugins/host.rs b/packages/cli-rs/crates/tui/src/plugins/host.rs index 88b6b00b3f0..024bf98a0ac 100644 --- a/packages/cli-rs/crates/tui/src/plugins/host.rs +++ b/packages/cli-rs/crates/tui/src/plugins/host.rs @@ -143,7 +143,7 @@ pub fn external(tui: &Rc, external: External) { let loader = Rc::new(Loader::new(Rc::new(Native) as Rc>, external.config_dir, external.cwd, configured)); loader.reconcile(tui, &tui.plugins); - let watches: Rc>> = Rc::default(); + let watches: Rc>> = Rc::default(); watch(tui, &loader, &watches); tui.app.on_message(bind!(tui, |tui, _, _: &PluginsChanged| { loader.reconcile(&tui, &tui.plugins); @@ -151,13 +151,13 @@ pub fn external(tui: &Rc, external: External) { })); } -/// Watches the loader's directories that are not watched yet. A watch that stops seeing its directory costs a -/// handle until the TUI exits, as in TS. -fn watch(tui: &Tui, loader: &Loader, watches: &RefCell>) { - for dir in loader.watch_dirs() { - if watches.borrow().iter().any(|(known, _)| *known == dir) { - continue; - } +/// A watched directory, the identity of the directory it watches, and the watch. +type Watched = (PathBuf, Option, W); + +/// Watches the loader's directories: keeps the watches that still see them, and replaces one whose directory +/// went away or was made again, which the old watch no longer sees. +fn watch(tui: &Tui, loader: &Loader, watches: &RefCell>) { + for (dir, id) in unwatched(&mut watches.borrow_mut(), loader.watch_dirs()) { let proxy = tui.app.proxy(); let watch = opencode_local::watch::watch( &dir, @@ -168,11 +168,38 @@ fn watch(tui: &Tui, loader: &Loader, watches: &RefCell(watches: &mut Vec>, dirs: Vec) -> Vec<(PathBuf, Option)> { + let dirs: Vec<(PathBuf, Option)> = dirs + .into_iter() + .map(|dir| { + let id = identity(&dir); + (dir, id) + }) + .collect(); + watches.retain(|(known, id, _)| dirs.iter().any(|(dir, current)| dir == known && current == id)); + dirs.into_iter().filter(|(dir, _)| !watches.iter().any(|(known, _, _)| known == dir)).collect() +} + +/// What tells a directory from one made again at its path. +#[cfg(unix)] +fn identity(dir: &std::path::Path) -> Option { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(dir).ok().map(|metadata| metadata.ino()) +} + +#[cfg(not(unix))] +fn identity(dir: &std::path::Path) -> Option { + let created = std::fs::metadata(dir).ok()?.created().ok()?; + created.duration_since(std::time::UNIX_EPOCH).ok().map(|since| since.as_nanos() as u64) +} + /// Adds and activates one more plugin, then remounts the route so its claims show. pub fn add(tui: &Rc, plugin: Definition) { tui.plugins.add(plugin); @@ -194,3 +221,28 @@ pub fn route(tui: &Tui, id: &str, name: &str) -> Option>> { pub fn code_blocks(tui: &Tui) -> CodeBlockRenderers { tui.plugins.code_blocks(&tui.page()) } + +#[cfg(test)] +mod tests { + use super::*; + + // Expected: a watched directory that is removed and made again gets a fresh watch, and a directory that left + // the list loses its watch. + #[test] + fn a_directory_made_again_is_watched_again() { + let root = tempfile::tempdir().unwrap(); + let (a, b) = (root.path().join("a"), root.path().join("b")); + std::fs::create_dir(&a).unwrap(); + std::fs::create_dir(&b).unwrap(); + let mut watches: Vec> = Vec::new(); + let fresh = unwatched(&mut watches, vec![a.clone(), b.clone()]); + watches.extend(fresh.into_iter().map(|(dir, id)| (dir, id, ()))); + assert!(unwatched(&mut watches, vec![a.clone(), b.clone()]).is_empty()); + // Keep the old directory alive under another name, so the new one cannot reuse its inode. + std::fs::rename(&a, root.path().join("old")).unwrap(); + std::fs::create_dir(&a).unwrap(); + let fresh = unwatched(&mut watches, vec![a.clone()]); + assert_eq!(fresh.iter().map(|(dir, _)| dir).collect::>(), [&a]); + assert!(watches.is_empty()); + } +}