Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

refactor(agent): dedupe plugin-dir discovery and guard reserved env keys

thinhlpg64fb4dc7ef27
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
index 203be2879..e8cbf8921 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
@@ -4,7 +4,7 @@
//! top-level shell. Without this, any command that spawns children (a build, a
//! `foo &`, a pipeline) leaks orphans when the run is torn down.
-use std::collections::HashMap;
+use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Mutex, OnceLock, RwLock};
@@ -20,16 +20,16 @@ use tokio::process::{Child, Command};
/// plugin's manifest *declares* (see the host's `plugins::required_env`) may
/// land here, and only with a value the user typed into the masked setup
/// prompt; the map is replaced wholesale by the host on every run start.
-static PLUGIN_ENV: OnceLock<RwLock<std::collections::BTreeMap<String, String>>> = OnceLock::new();
+static PLUGIN_ENV: OnceLock<RwLock<BTreeMap<String, String>>> = OnceLock::new();
/// Replace the plugin-declared environment values handed to sandboxed shells.
-pub fn set_plugin_env(vars: std::collections::BTreeMap<String, String>) {
+pub fn set_plugin_env(vars: BTreeMap<String, String>) {
let lock = PLUGIN_ENV.get_or_init(|| RwLock::new(Default::default()));
*lock.write().unwrap() = vars;
}
/// A snapshot of the current plugin-declared environment values.
-fn plugin_env() -> std::collections::BTreeMap<String, String> {
+fn plugin_env() -> BTreeMap<String, String> {
PLUGIN_ENV
.get()
.map(|lock| lock.read().unwrap().clone())
@@ -38,10 +38,23 @@ fn plugin_env() -> std::collections::BTreeMap<String, String> {
/// Read back the current plugin env values (tests / diagnostics).
#[doc(hidden)]
-pub fn plugin_env_snapshot() -> std::collections::BTreeMap<String, String> {
+pub fn plugin_env_snapshot() -> BTreeMap<String, String> {
plugin_env()
}
+/// True for variable names the sandbox owns itself: the static allowlist, the
+/// scratch temp keys, and the classic dynamic-linker/loader injection
+/// prefixes. The host refuses to store or inject plugin-declared values under
+/// these names -- a plugin declaring `PATH` or `LD_PRELOAD` would otherwise
+/// let one pasted value clobber (or escape) the sandbox environment wholesale.
+pub fn is_reserved_env_key(key: &str) -> bool {
+ SANDBOX_ENV_ALLOW.contains(&key)
+ || TEMP_ENV_KEYS.contains(&key)
+ || key.starts_with("LD_")
+ || key.starts_with("DYLD_")
+ || key.starts_with("SUDO_")
+}
+
/// How to invoke the host shell. `program` + `args` are fixed; the command
/// string is appended as the final argv element, or piped to stdin when
/// `via_stdin` is set (legacy WSL `bash.exe`, which cannot take `-c`).
@@ -421,7 +434,8 @@ pub async fn spawn_with_stdin(
cmd.env(key, val);
}
// Plugin-declared credentials come last so they always win over an
- // allowlist key of the same name.
+ // allowlist key of the same name (reserved names never get this far --
+ // see `is_reserved_env_key`).
for (key, val) in plugin_env() {
cmd.env(key, val);
}
diff --git a/src-tauri/src/core/agent/plugin_commands.rs b/src-tauri/src/core/agent/plugin_commands.rs
index e1ba47c9b..648331b85 100644
--- a/src-tauri/src/core/agent/plugin_commands.rs
+++ b/src-tauri/src/core/agent/plugin_commands.rs
@@ -36,44 +36,24 @@ pub(crate) struct ParsedCommand {
/// linked git worktree also sees the main worktree's plugins, project-local
/// shadowing shared ones (see `skills::discovery_roots`).
pub(crate) fn discover(root: &Path) -> Vec<CommandEntry> {
- let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
- for r in crate::core::agent::skills::discovery_roots(root) {
- let dir = crate::core::agent::skills::plugins_dir(&r);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- continue;
- };
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
- continue;
- };
- if plugin.starts_with(".installing-") {
- continue;
- }
- if !seen.insert(plugin.to_string()) {
- continue;
- }
- crate::core::agent::skills::walk_markdown_files(&path.join("commands"), &mut |path| {
- let raw = std::fs::read_to_string(path).unwrap_or_default();
- let name = path
- .file_stem()
- .and_then(|s| s.to_str())
- .unwrap_or_default();
- let parsed = parse_command(&raw);
- out.push(CommandEntry {
- name: name.to_string(),
- plugin: plugin.to_string(),
- description: parsed.description,
- file: path.to_path_buf(),
- hints: template_hints(&parsed.body),
- });
+ crate::core::agent::skills::plugin_dirs_across_roots(root, |plugin, path| {
+ crate::core::agent::skills::walk_markdown_files(&path.join("commands"), &mut |path| {
+ let raw = std::fs::read_to_string(path).unwrap_or_default();
+ let name = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or_default();
+ let parsed = parse_command(&raw);
+ out.push(CommandEntry {
+ name: name.to_string(),
+ plugin: plugin.to_string(),
+ description: parsed.description,
+ file: path.to_path_buf(),
+ hints: template_hints(&parsed.body),
});
- }
- }
+ });
+ });
out.sort_by(|a, b| (&a.plugin, &a.name).cmp(&(&b.plugin, &b.name)));
out
}
diff --git a/src-tauri/src/core/agent/plugins.rs b/src-tauri/src/core/agent/plugins.rs
index 81b09b575..4c6ae9301 100644
--- a/src-tauri/src/core/agent/plugins.rs
+++ b/src-tauri/src/core/agent/plugins.rs
@@ -175,11 +175,15 @@ struct McpServerDecl {
impl Manifest {
/// Environment variables this plugin requires, as `(var, url)` pairs —
/// the URL the user can obtain the value from, empty when unknown.
+ /// Variables the sandbox owns (`PATH`, temp keys, loader injection
+ /// prefixes) are refused: a pasted value under one of those names could
+ /// clobber or escape the sandbox environment wholesale.
fn required_env(&self) -> std::collections::BTreeMap<String, String> {
+ use tauri_plugin_agent_tools::tools::proc::is_reserved_env_key;
let mut out = std::collections::BTreeMap::new();
if let Some(setup) = &self.setup {
for (key, url) in setup.env.iter().flatten() {
- if is_env_name(key) {
+ if is_env_name(key) && !is_reserved_env_key(key) {
out.insert(key.clone(), url.trim().to_string());
}
}
@@ -187,7 +191,7 @@ impl Manifest {
for server in self.mcp_servers.iter().flat_map(|m| m.values()) {
for value in server.env.iter().flatten().map(|(_, v)| v) {
for var in template_refs(value) {
- if is_env_name(&var) {
+ if is_env_name(&var) && !is_reserved_env_key(&var) {
out.entry(var).or_default();
}
}
@@ -258,12 +262,8 @@ pub(crate) fn find_installed(root: &Path, query: &str) -> Option<(String, Instal
}
/// `~/.jan/agent/plugin-env/` — where the setup prompt stores plugin API keys.
-/// Resolved from the home directory directly (not the cli-gated global config
-/// helpers) so the desktop run path syncs the same registry.
fn plugin_env_dir() -> Result<PathBuf, String> {
- dirs::home_dir()
- .map(|home| home.join(".jan").join("agent").join("plugin-env"))
- .ok_or_else(|| "could not resolve the user's home directory".to_string())
+ crate::core::agent::global_config::global_jan_dir().map(|jan| jan.join("agent").join("plugin-env"))
}
/// `plugin-env/<plugin>.toml` under `dir`.
@@ -274,8 +274,7 @@ fn plugin_env_path(dir: &Path, plugin: &str) -> Result<PathBuf, String> {
/// The stored env values for one plugin, resolved against the real plugin-env
/// store directory. Missing or malformed file -> empty.
-/// [`stored_plugin_env_in`] is the variant taking an explicit directory (tests).
-pub(crate) fn stored_plugin_env_in(
+fn stored_plugin_env_in(
dir: &Path,
plugin: &str,
) -> std::collections::BTreeMap<String, String> {
@@ -303,11 +302,26 @@ pub(crate) fn save_plugin_env_in(
if !is_env_name(key) {
return Err(format!("invalid environment variable name '{key}'"));
}
+ if tauri_plugin_agent_tools::tools::proc::is_reserved_env_key(key) {
+ return Err(format!("'{key}' is reserved by the sandbox and cannot be set for a plugin"));
+ }
let path = plugin_env_path(dir, plugin)?;
- let mut values: std::collections::BTreeMap<String, String> = std::fs::read_to_string(&path)
- .ok()
- .and_then(|raw| toml::from_str(&raw).ok())
- .unwrap_or_default();
+ let mut values: std::collections::BTreeMap<String, String> = match
+ std::fs::read_to_string(&path)
+ {
+ Ok(raw) => match toml::from_str(&raw) {
+ Ok(v) => v,
+ // Refuse to merge into a file we cannot parse: saving would
+ // silently destroy the other stored keys for this plugin.
+ Err(_) => {
+ return Err(format!(
+ "stored env file {} is malformed - delete it and re-run setup",
+ path.display()
+ ))
+ }
+ },
+ Err(_) => Default::default(),
+ };
values.insert(key.to_string(), value.to_string());
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("could not create {parent:?}: {e}"))?;
@@ -345,8 +359,11 @@ pub(crate) fn declared_plugin_env(root: &Path, plugin: &str) -> Vec<(String, Str
}
/// Setup requirements that are not yet satisfied: `(plugin, var, url)` in
-/// scan order. A var is satisfied when the user stored a value or the process
-/// environment already provides one (CI, shells, direnv...).
+/// scan order. A var is satisfied only when the user stored a value via the
+/// setup prompt: the sandboxed shell drops every host variable except the
+/// static allowlist, so a var provided by the host environment would never
+/// reach the plugin's commands even though the prompt claimed it was
+/// satisfied.
#[cfg(feature = "cli")]
pub(crate) fn missing_plugin_env(root: &Path) -> Vec<(String, String, String)> {
match plugin_env_dir() {
@@ -365,9 +382,7 @@ fn missing_plugin_env_in(root: &Path, env_dir: &Path) -> Vec<(String, String, St
};
let stored = stored_plugin_env_in(env_dir, &directory);
for (var, url) in read_manifest(&dir).required_env() {
- let in_store = stored.get(&var).is_some_and(|v| !v.is_empty());
- let in_host = std::env::var_os(&var).is_some_and(|v| !v.is_empty());
- if !in_store && !in_host {
+ if stored.get(&var).is_none_or(|v| v.is_empty()) {
out.push((directory.clone(), var, url));
}
}
@@ -407,32 +422,11 @@ fn installed_entries(root: &Path) -> Vec<(String, InstalledPlugin)> {
// A linked git worktree also sees the main worktree's plugins, the
// project-local one shadowing a same-named shared one. Counts come from
// the merged discovery above, so shared plugins report real payloads.
- let mut seen = std::collections::HashSet::new();
let all_skills = skills::discover_plugins(root);
let all_commands = crate::core::agent::plugin_commands::discover(root);
let mut out = Vec::new();
- for r in skills::discovery_roots(root) {
- let dir = skills::plugins_dir(&r);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- continue;
- };
- // Scan each artifact kind once; per-plugin counts filter the shared
- // lists rather than re-walking the whole plugin tree per plugin.
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(directory) = path.file_name().and_then(|s| s.to_str()) else {
- continue;
- };
- if directory.starts_with(".installing-") {
- continue;
- }
- if !seen.insert(directory.to_string()) {
- continue;
- }
- let manifest = read_manifest(&path);
+ skills::plugin_dirs_across_roots(root, |directory, path| {
+ let manifest = read_manifest(path);
let plugin_skills = all_skills
.iter()
.filter(|e| e.plugin.as_deref() == Some(directory))
@@ -458,8 +452,7 @@ fn installed_entries(root: &Path) -> Vec<(String, InstalledPlugin)> {
.len(),
},
));
- }
- }
+ });
out.sort_by(|a, b| a.1.name.cmp(&b.1.name));
out
}
@@ -1116,7 +1109,18 @@ pub(crate) fn remove(root: &Path, name: &str) -> Result<(), String> {
if !target.is_dir() {
return Err(format!("ERROR: plugin '{name}' is not installed"));
}
- std::fs::remove_dir_all(&target).map_err(|e| format!("ERROR: {e}"))
+ std::fs::remove_dir_all(&target).map_err(|e| format!("ERROR: {e}"))?;
+ // Drop the stored credentials too: they live outside the plugin
+ // directory (a reinstall must not silently reactivate them), so removing
+ // the plugin has to clean them up here. Then refresh the live registry so
+ // the sandboxed shells of the current session stop receiving the values.
+ if let Ok(dir) = plugin_env_dir() {
+ if let Ok(path) = plugin_env_path(&dir, name) {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ sync_env_registry(root);
+ Ok(())
}
/// List marketplace plugins matching `query` (name or description, case
diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rs
index b0d55c9cb..deae66015 100644
--- a/src-tauri/src/core/agent/skills.rs
+++ b/src-tauri/src/core/agent/skills.rs
@@ -247,6 +247,34 @@ pub(crate) fn find_plugin_dir(root: &Path, plugin: &str) -> Option<PathBuf> {
.find(|p| p.is_dir())
}
+/// Visit every installed plugin directory across the discovery roots, with
+/// first-root-wins shadowing: a project-local plugin hides a same-named one
+/// shared from the main worktree. Skips non-directories and interrupted
+/// `.installing-*` staging directories (a partially-copied plugin must not
+/// leak its payload mid-install). Shared by the skill, command, agent, and
+/// plugin-listing discovery passes so they all agree on what is installed.
+pub(crate) fn plugin_dirs_across_roots(root: &Path, mut visit: impl FnMut(&str, &Path)) {
+ let mut seen = std::collections::HashSet::new();
+ for r in discovery_roots(root) {
+ let Ok(rd) = std::fs::read_dir(plugins_dir(&r)) else {
+ continue;
+ };
+ for entry in rd.flatten() {
+ let path = entry.path();
+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
+ continue;
+ }
+ let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ if plugin.starts_with(".installing-") || !seen.insert(plugin.to_string()) {
+ continue;
+ }
+ visit(plugin, &path);
+ }
+ }
+}
+
/// Recursively yield every `*.md` file under `dir`, skipping dotfiles and
/// `README` files (any case). Callers read each file themselves so read-failure
/// handling stays with them. Shared by plugin command and plugin agent
@@ -297,33 +325,9 @@ pub(crate) fn invocation_wrapper(name: &str, kind: &str) -> String {
/// (folder and flat forms, same rules as project skills) plus an optional
/// single `SKILL.md` at the plugin root (a repo that is itself one skill).
pub(crate) fn discover_plugins(root: &Path) -> Vec<SkillEntry> {
- let mut seen = std::collections::HashSet::new();
let mut out: Vec<SkillEntry> = Vec::new();
- for r in discovery_roots(root) {
- let dir = plugins_dir(&r);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- continue;
- };
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
- continue;
- };
- // Ignore interrupted `.installing-*` staging directories, matching
- // the command/agent loaders: a partially-copied plugin must not
- // leak its skills into the catalog during an install.
- if plugin.starts_with(".installing-") {
- continue;
- }
- // Earlier roots shadow: a plugin installed in this checkout hides
- // a same-named one shared from the main worktree.
- if !seen.insert(plugin.to_string()) {
- continue;
- }
- let mut tagged = Vec::new();
+ plugin_dirs_across_roots(root, |plugin, path| {
+ let mut tagged = Vec::new();
for e in scan_skill_dir(&path.join("skills")) {
tagged.push(SkillEntry {
plugin: Some(plugin.to_string()),
@@ -340,8 +344,7 @@ pub(crate) fn discover_plugins(root: &Path) -> Vec<SkillEntry> {
});
}
out.extend(tagged);
- }
- }
+ });
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index e3219eb6d..a0f6086e3 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -254,23 +254,9 @@ impl SubagentRegistry {
/// metadata and ignored (the parent's model runs the child); `tools` maps
/// Claude tool names onto Jan tool names, dropping names with no equivalent.
fn load_plugin_agents(project_root: &Path, out: &mut Vec<SubagentDefinition>) {
- let dir = crate::core::agent::skills::plugins_dir(project_root);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- return;
- };
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
- continue;
- };
- if plugin.starts_with(".installing-") {
- continue;
- }
+ crate::core::agent::skills::plugin_dirs_across_roots(project_root, |_, path| {
scan_agent_dir(&path.join("agents"), out);
- }
+ });
}
/// Number of agent markdown files one plugin ships, for the plugin listing.
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 7cb9f4acc..fc6ac67f4 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -996,7 +996,7 @@ impl PluginSetupPrompt {
self.input.push_str(super::secret_input::pasted(text));
}
- /// Advance past the current entry; `None` once every entry is done.
+ /// Advance past the current entry, clearing the field and any error.
fn advance(&mut self) {
self.current += 1;
self.input.clear();
@@ -10850,18 +10850,7 @@ fn handle_account_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {
return;
}
if ctrl && key.code == KeyCode::Char('v') {
- match clipboard_text() {
- Ok(text) => {
- if let Some(prompt) = app.account_login.as_mut() {
- prompt.paste(&text);
- }
- }
- Err(e) => {
- if let Some(prompt) = app.account_login.as_mut() {
- prompt.error = Some(format!("could not read the clipboard: {e}"));
- }
- }
- }
+ paste_clipboard_into(app, |app| &mut app.account_login);
return;
}
@@ -10946,18 +10935,7 @@ fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {
if !app.login.as_ref().is_some_and(LoginPrompt::editable) {
return;
}
- match super::secret_input::clipboard_text() {
- Ok(text) => {
- if let Some(prompt) = app.login.as_mut() {
- prompt.paste(&text);
- }
- }
- Err(e) => {
- if let Some(prompt) = app.login.as_mut() {
- prompt.error = Some(format!("could not read the clipboard: {e}"));
- }
- }
- }
+ paste_clipboard_into(app, |app| &mut app.login);
return;
}
@@ -10995,6 +10973,62 @@ fn clipboard_text() -> Result<String, String> {
super::secret_input::clipboard_text()
}
+/// Input handling the three masked prompts (`/login`, account login,
+/// `/plugin setup`) share for Ctrl-V routing.
+trait MaskedPrompt {
+ /// Store the pasted text (each impl applies its own masking/editability
+ /// rules).
+ fn paste_text(&mut self, text: &str);
+ /// Surface a failure on the prompt's error line.
+ fn set_error(&mut self, message: String);
+}
+
+/// Some terminals deliver a paste as a key rather than an `Event::Paste`, so
+/// the masked prompts' key handlers route Ctrl-V here: read the clipboard,
+/// feed the text to the prompt, or record the failure on its error line.
+/// `prompt` selects the docked prompt from the app state.
+fn paste_clipboard_into<P: MaskedPrompt>(app: &mut App, prompt: fn(&mut App) -> &mut Option<P>) {
+ match clipboard_text() {
+ Ok(text) => {
+ if let Some(p) = prompt(app) {
+ p.paste_text(&text);
+ }
+ }
+ Err(e) => {
+ if let Some(p) = prompt(app) {
+ p.set_error(format!("could not read the clipboard: {e}"));
+ }
+ }
+ }
+}
+
+impl MaskedPrompt for LoginPrompt {
+ fn paste_text(&mut self, text: &str) {
+ self.paste(text);
+ }
+ fn set_error(&mut self, message: String) {
+ self.error = Some(message);
+ }
+}
+
+impl MaskedPrompt for AccountLoginPrompt {
+ fn paste_text(&mut self, text: &str) {
+ self.paste(text);
+ }
+ fn set_error(&mut self, message: String) {
+ self.error = Some(message);
+ }
+}
+
+impl MaskedPrompt for PluginSetupPrompt {
+ fn paste_text(&mut self, text: &str) {
+ self.paste(text);
+ }
+ fn set_error(&mut self, message: String) {
+ self.error = Some(message);
+ }
+}
+
/// Open `/plugin setup` for the first installed plugin whose declared env
/// variables are not yet satisfied. Returns whether a dock opened.
fn open_plugin_setup(app: &mut App) -> bool {
@@ -11044,8 +11078,9 @@ fn start_plugin_setup(app: &mut App, plugin: &str, entries: Vec<PluginEnvEntry>)
}
/// Keys for the `/plugin setup` prompt: Enter saves the value and advances,
-/// `s` skips an entry, Esc/Ctrl-C abandons the rest. Same masked-entry rules
-/// as the `/login` paste field.
+/// `s` skips the current entry when the field is still empty (once something
+/// is typed, `s` is just a character of the secret), Esc/Ctrl-C abandons the
+/// rest. Same masked-entry rules as the `/login` paste field.
fn handle_plugin_setup_key(app: &mut App, key: KeyEvent, ctrl: bool) {
let cancel = key.code == KeyCode::Esc
|| (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')));
@@ -11056,25 +11091,12 @@ fn handle_plugin_setup_key(app: &mut App, key: KeyEvent, ctrl: bool) {
}
// Ctrl-V: some terminals send a paste as a key rather than Event::Paste.
if ctrl && key.code == KeyCode::Char('v') {
- match super::secret_input::clipboard_text() {
- Ok(text) => {
- if let Some(prompt) = app.plugin_setup.as_mut() {
- prompt.paste(&text);
- }
- }
- Err(e) => {
- if let Some(prompt) = app.plugin_setup.as_mut() {
- prompt.error = Some(format!("could not read the clipboard: {e}"));
- }
- }
- }
+ paste_clipboard_into(app, |app| &mut app.plugin_setup);
return;
}
- let Some(prompt) = app.plugin_setup.as_mut() else {
- return;
- };
match key.code {
KeyCode::Enter => {
+ let Some(prompt) = app.plugin_setup.as_mut() else { return };
let plugin = prompt.plugin.clone();
let Some(entry) = prompt.entry() else { return };
let value = prompt.input.trim().to_string();
@@ -11088,36 +11110,50 @@ fn handle_plugin_setup_key(app: &mut App, key: KeyEvent, ctrl: bool) {
return;
}
let key_name = entry.key.clone();
- prompt.advance();
- if prompt.done() {
+ // Advance and test completion inside a block so the `prompt` borrow
+ // ends before the app-level calls below (which re-borrow `app`).
+ let done = {
+ prompt.advance();
+ prompt.done()
+ };
+ // Sync on every save, not just at completion: a cancel after key
+ // 1 must still leave the live registry holding key 1.
+ crate::core::agent::plugins::sync_env_registry(&app.project_root);
+ app.note(&format!("plugin setup · {plugin} · {key_name} saved"));
+ if done {
app.plugin_setup = None;
- crate::core::agent::plugins::sync_env_registry(&app.project_root);
- app.note(&format!("plugin setup · {plugin} · {key_name} saved"));
// Chain into the next plugin that still needs keys.
open_plugin_setup(app);
- } else {
- app.note(&format!(
- "plugin setup · {plugin} · {key_name} saved"
- ));
}
}
KeyCode::Char('s') | KeyCode::Char('S') if !ctrl => {
+ let Some(prompt) = app.plugin_setup.as_mut() else { return };
+ if !prompt.input.is_empty() {
+ return;
+ }
let plugin = prompt.plugin.clone();
let key_name = prompt
.entry()
.map(|e| e.key.clone())
.unwrap_or_default();
- prompt.advance();
- if prompt.done() {
+ let done = {
+ prompt.advance();
+ prompt.done()
+ };
+ if done {
app.plugin_setup = None;
app.note(&format!("plugin setup · {plugin} · skipped {key_name}"));
open_plugin_setup(app);
}
}
KeyCode::Backspace => {
+ let Some(prompt) = app.plugin_setup.as_mut() else { return };
prompt.input.pop();
}
- KeyCode::Char(ch) if !ctrl => prompt.input.push(ch),
+ KeyCode::Char(ch) if !ctrl => {
+ let Some(prompt) = app.plugin_setup.as_mut() else { return };
+ prompt.input.push(ch);
+ }
_ => {}
}
}