fix(cli-rs): let /plugins disable failed plugins and track removed dirs

/plugins offered enable for a plugin that failed while active (a panic, or a failed rebuild with the previous version running), so it restarted instead of stopping. Registry entries now carry active, which the dialog uses as TS does; a runtime panic removes the plugin's keymap layer; starting a build again clears its stale rebuild failure. The loader drops deleted skipped directories, watches where a missing <cwd>/.opencode/plugins would be made, and the TUI replaces a watch whose directory was made again.
This commit is contained in:
Simon Klee
2026-11-06 03:13:44 +01:00
Unverified
parent 866af9bc53
commit f9da7aa0fb
7 changed files with 208 additions and 46 deletions
+5
View File
@@ -228,6 +228,9 @@ pub struct Entry {
pub target: Option<String>,
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<H: Host> Registry<H> {
(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<H: Host> Registry<H> {
target: Some(target.clone()),
source: Source::Configured,
status: status.clone(),
active: false,
});
active.chain(unloaded).collect()
}
+33 -11
View File
@@ -75,11 +75,13 @@ pub struct Loader<H: Host> {
cwd: PathBuf,
configured: Vec<Configured>,
seen: RefCell<HashMap<String, Seen>>,
/// The targets of the last reconcile, so a removed one leaves the registry whatever its status.
listed: RefCell<Vec<String>>,
}
impl<H: Host> Loader<H> {
pub fn new(backend: Rc<dyn Backend<H>>, config_dir: PathBuf, cwd: PathBuf, configured: Vec<Configured>) -> 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<H: Host> Loader<H> {
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<PathBuf> {
let mut dirs: Vec<PathBuf> = 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<PathBuf> = 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<H: Host> Loader<H> {
.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::<Vec<_>>();
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<H: Host> Loader<H> {
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
@@ -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<H: Host> Backend<H> 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<H: Host> {
failure: Rc<RefCell<Option<String>>>,
host: Weak<H>,
id: String,
/// The commands' keymap layer, until deactivation or a panic removes it.
layer: RefCell<Option<Disposer>>,
}
impl<H: Host> Guest<H> {
@@ -442,7 +446,12 @@ impl<H: Host> Guest<H> {
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<H: Host>(setup: &mut Setup<'_, H>, guest: &Rc<Guest<H>>, 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();
@@ -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(&registry), 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(&registry.entries(), "sample.so").active);
assert!(registry.set_active(&host, "sample", false));
assert_eq!(status(&registry), Status::Inactive);
assert!(registry.set_active(&host, "sample", true));
assert!(matches!(host.keymap().dispatch("sample.hello", None), RunResult::Ok));
}
#[test]
@@ -212,6 +212,13 @@ fn reconcile_loads_reloads_keeps_and_unloads() {
// The same broken build is not retried.
assert!(!loader.reconcile(&host, &registry));
assert_eq!(fake.loads.get(), 3);
// The running version can be disabled, and enabling it starts it afresh without the stale failure.
assert!(entry(&registry.entries(), &lib_target).active);
assert!(registry.set_active(&host, "fake", false));
assert_eq!(entry(&registry.entries(), &lib_target).status, Status::Inactive);
assert!(registry.set_active(&host, "fake", true));
assert_eq!(entry(&registry.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, &registry));
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 `<cwd>/.opencode/plugins` is missing, the directory it would be made in is watched, even when
// `<cwd>/.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::<TestHost>::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:?}");
}
@@ -72,6 +72,8 @@ enum Entry {
target: String,
status: &'static str,
error: Option<String>,
/// 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<Entry> = 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<Entry> = 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<Entry> = 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)));
}
}
+61 -9
View File
@@ -143,7 +143,7 @@ pub fn external(tui: &Rc<Tui>, external: External) {
let loader =
Rc::new(Loader::new(Rc::new(Native) as Rc<dyn Backend<Tui>>, external.config_dir, external.cwd, configured));
loader.reconcile(tui, &tui.plugins);
let watches: Rc<RefCell<Vec<(PathBuf, opencode_local::watch::Watch)>>> = Rc::default();
let watches: Rc<RefCell<Vec<Watched>>> = 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<Tui>, 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<Tui>, watches: &RefCell<Vec<(PathBuf, opencode_local::watch::Watch)>>) {
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<W = opencode_local::watch::Watch> = (PathBuf, Option<u64>, 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<Tui>, watches: &RefCell<Vec<Watched>>) {
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<Tui>, watches: &RefCell<Vec<(PathBuf, openco
},
);
if let Some(watch) = watch {
watches.borrow_mut().push((dir, watch));
watches.borrow_mut().push((dir, id, watch));
}
}
}
/// Drops the watches of directories that are no longer in `dirs` or are not the directory they watched, and
/// returns the directories to watch, with their identity.
fn unwatched<W>(watches: &mut Vec<Watched<W>>, dirs: Vec<PathBuf>) -> Vec<(PathBuf, Option<u64>)> {
let dirs: Vec<(PathBuf, Option<u64>)> = 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<u64> {
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<u64> {
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<Tui>, plugin: Definition<Tui>) {
tui.plugins.add(plugin);
@@ -194,3 +221,28 @@ pub fn route(tui: &Tui, id: &str, name: &str) -> Option<Box<dyn Slotted<Tui>>> {
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<Watched<()>> = 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::<Vec<_>>(), [&a]);
assert!(watches.is_empty());
}
}