Skip to main content

jump_core/
plugin.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! Alfred-style plugin host.
5//!
6//! pop-launcher already has a plugin system, and it keeps working — anything
7//! installed under `/usr/lib/pop-launcher/plugins` shows up for free through the
8//! service. But writing one means implementing the full stateful IPC protocol
9//! (indices, activation, context menus, cancellation), which is far more than a
10//! shell script should have to do.
11//!
12//! This host covers the other end of that range: a manifest plus an executable
13//! that receives the query on argv and prints JSON. It is deliberately a subset
14//! of Alfred's Script Filter format so existing workflow scripts mostly port by
15//! changing the manifest.
16//!
17//! ## Layout
18//!
19//! ```text
20//! ~/.local/share/jump/plugins/github/
21//!   manifest.toml
22//!   search.sh
23//! ```
24//!
25//! ```toml
26//! name = "GitHub"
27//! description = "Search your repositories"
28//! keyword = "gh"          # optional; omit to run on every query
29//! query = "./search.sh"   # invoked as: query <text>
30//! activate = "./open.sh"  # invoked as: activate <arg>
31//! icon = "github"         # optional icon-theme name or path
32//! timeout_ms = 1000       # optional; up to 3000 for slow keyworded plugins
33//! ```
34//!
35//! Items may carry Alfred's `uid` (a stable identity, which is what feeds the
36//! launcher's frecency ranking) and `autocomplete` (text that replaces the
37//! query on Tab).
38//!
39//! ## Isolation
40//!
41//! A plugin is an arbitrary program on the interactive path, so it is held to a
42//! hard deadline. Exceeding it (180 ms by default, raised for a keyworded
43//! plugin with `timeout_ms`) kills the process and drops its results rather
44//! than delaying the frame — a broken plugin degrades its own results and
45//! nothing else.
46
47use std::path::{Path, PathBuf};
48use std::process::Stdio;
49use std::time::Duration;
50
51use serde::Deserialize;
52use tokio::process::Command;
53
54use crate::model::{Icon, Item, ItemKey, Mod, Source};
55
56/// A plugin that has not answered by this point is abandoned for this query.
57///
58/// Chosen to sit under a 100 ms interaction budget while leaving room for a
59/// script that shells out to a local index. A plugin that genuinely needs
60/// longer — a network search behind a keyword — raises it with `timeout_ms`,
61/// up to [`MAX_QUERY_TIMEOUT`]; stale results are discarded by the frontend's
62/// query guard, so a slow answer can be late without being wrong.
63const QUERY_TIMEOUT: Duration = Duration::from_millis(180);
64
65/// Hard ceiling on a manifest's `timeout_ms`.
66///
67/// Three seconds is generous for anything interactive; past it a plugin is not
68/// answering a keystroke, it is running a job.
69const MAX_QUERY_TIMEOUT: Duration = Duration::from_millis(3000);
70
71/// Ceiling on a plugin's stdout, so a runaway script cannot exhaust memory.
72///
73/// Enforced while reading: a plugin is cut off at this many bytes, never
74/// buffered in full first.
75const MAX_OUTPUT_BYTES: usize = 1 << 20;
76
77/// How much of a plugin's stderr is kept for the log line or lint report.
78/// The rest is read and discarded, so a chatty plugin cannot stall on a full
79/// pipe.
80const MAX_STDERR_BYTES: usize = 16 << 10;
81
82/// Why a query command produced no output to parse.
83#[derive(Debug, thiserror::Error)]
84enum RunError {
85    #[error("failed to run: {0}")]
86    Io(#[from] std::io::Error),
87    #[error("exceeded its {} ms deadline and was killed", .0.as_millis())]
88    Deadline(Duration),
89    #[error("printed more than {MAX_OUTPUT_BYTES} bytes and was killed")]
90    TooLarge,
91    #[error("exited {status}; stderr: {stderr}")]
92    Failed {
93        status: std::process::ExitStatus,
94        stderr: String,
95    },
96}
97
98/// Spawn a plugin's command, waiting out a script that is still open for
99/// writing.
100///
101/// Executing a file that any process holds open for writing fails with
102/// ETXTBSY, and a script written a moment ago can be held that way after its
103/// writer has closed it: a child that another thread forked meanwhile keeps a
104/// copy of the descriptor until it execs. That happens to a plugin just made
105/// by [`scaffold`] or saved by an editor, and lasts milliseconds, so a few
106/// short retries cover it; any other error is returned at once.
107async fn spawn_plugin(command: &mut Command) -> std::io::Result<tokio::process::Child> {
108    let mut wait = Duration::from_millis(5);
109    for _ in 0..6 {
110        match command.spawn() {
111            Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
112                tokio::time::sleep(wait).await;
113                wait *= 2;
114            }
115            result => return result,
116        }
117    }
118    command.spawn()
119}
120
121/// Run a query command under `deadline` and the output cap, returning its
122/// stdout.
123///
124/// The command leads its own process group, and overrunning either limit —
125/// or the query being abandoned, by dropping this future — kills the whole
126/// group: a shell script's background jobs are part of the query that
127/// started them, and must not outlive its dropped results. A command that
128/// finishes in time keeps anything it deliberately left behind (a cache
129/// refresh with its output redirected, say).
130async fn run_query(
131    program: &Path,
132    directory: &Path,
133    text: &str,
134    deadline: Duration,
135) -> Result<Vec<u8>, RunError> {
136    use tokio::io::AsyncReadExt;
137
138    let mut child = spawn_plugin(
139        Command::new(program)
140            .arg(text)
141            .current_dir(directory)
142            .stdin(Stdio::null())
143            .stdout(Stdio::piped())
144            .stderr(Stdio::piped())
145            .process_group(0)
146            .kill_on_drop(true),
147    )
148    .await?;
149    // The group id is the child's pid, which cannot be reused while the
150    // child or anything else in its group is alive.
151    let mut group = GroupKill(child.id());
152    let stdout = child.stdout.take().expect("stdout is piped");
153    let stderr = child.stderr.take().expect("stderr is piped");
154
155    // Drained on its own task so it progresses while stdout is read, and
156    // ends when the group is killed and the pipe closes.
157    let stderr = tokio::spawn(async move {
158        let mut kept = Vec::new();
159        let mut limited = stderr.take(MAX_STDERR_BYTES as u64);
160        let read = limited.read_to_end(&mut kept).await;
161        let drained = tokio::io::copy(&mut limited.into_inner(), &mut tokio::io::sink()).await;
162        if let Err(error) = read.and(drained) {
163            tracing::debug!(%error, "plugin stderr read failed");
164        }
165        String::from_utf8_lossy(&kept).trim().to_owned()
166    });
167
168    let run = async {
169        let mut output = Vec::new();
170        stdout
171            .take(MAX_OUTPUT_BYTES as u64 + 1)
172            .read_to_end(&mut output)
173            .await?;
174        if output.len() > MAX_OUTPUT_BYTES {
175            return Err(RunError::TooLarge);
176        }
177        let status = child.wait().await?;
178        // It exited on its own: whatever it left running was left on purpose.
179        group.disarm();
180        Ok((status, output))
181    };
182
183    match tokio::time::timeout(deadline, run).await {
184        Ok(Ok((status, output))) if status.success() => Ok(output),
185        Ok(Ok((status, _))) => Err(RunError::Failed {
186            status,
187            stderr: stderr.await.unwrap_or_default(),
188        }),
189        // On both of these `group` is still armed and kills on return.
190        Ok(Err(error)) => Err(error),
191        Err(_) => Err(RunError::Deadline(deadline)),
192    }
193}
194
195/// `SIGKILL`s a plugin's whole process group when dropped, unless
196/// [disarmed](Self::disarm).
197///
198/// A drop guard rather than a call on the error paths, because the query
199/// future can also be dropped from outside: the launcher abandons a query
200/// the moment the next keystroke supersedes it. `kill_on_drop` then reaches
201/// only the script itself.
202///
203/// Through `kill(1)`, as [`crate::process::terminate`] does, rather than a
204/// syscall binding: this runs only when a query was abandoned or a plugin
205/// misbehaved. It is spawned, not awaited — a destructor cannot wait — and
206/// tokio reaps the dropped `kill` process in the background.
207struct GroupKill(Option<u32>);
208
209impl GroupKill {
210    fn disarm(&mut self) {
211        self.0 = None;
212    }
213}
214
215impl Drop for GroupKill {
216    fn drop(&mut self) {
217        let Some(group) = self.0 else {
218            return;
219        };
220        let spawned = Command::new("kill")
221            .args(["-KILL", "--", &format!("-{group}")])
222            .stdin(Stdio::null())
223            .stdout(Stdio::null())
224            .stderr(Stdio::null())
225            .spawn();
226        if let Err(error) = spawned {
227            tracing::warn!(group, %error, "could not kill plugin process group");
228        }
229    }
230}
231
232/// Whether `text` can be a plugin keyword: one non-empty word. A keyword is
233/// matched up to the first space of the query, so one containing whitespace
234/// could never match. The manifest, the Settings override and the Alfred
235/// importer all hold keywords to this.
236#[must_use]
237pub fn is_keyword(text: &str) -> bool {
238    !text.is_empty() && !text.contains(char::is_whitespace)
239}
240
241/// Parsed `manifest.toml`.
242#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
243pub struct Manifest {
244    /// Human-readable name, shown as the result category.
245    pub name: String,
246    /// One-line explanation, shown as the result subtitle.
247    #[serde(default)]
248    pub description: String,
249    /// When set, the plugin only runs for queries starting with this word.
250    /// When absent the plugin runs on every query and must be fast.
251    #[serde(default)]
252    pub keyword: Option<String>,
253    /// Executable invoked with the query text as a single argument.
254    pub query: String,
255    /// Executable invoked with the selected item's `arg` on activation.
256    /// Without it, activation falls back to the `query` program with
257    /// `--activate`.
258    #[serde(default)]
259    pub activate: Option<String>,
260    /// Icon-theme name or path used for items that do not specify their own.
261    #[serde(default)]
262    pub icon: Option<String>,
263    /// Query deadline override in milliseconds, clamped to a hard ceiling.
264    /// Only a keyworded plugin may raise it past the interactive default.
265    #[serde(default)]
266    pub timeout_ms: Option<u64>,
267}
268
269impl Manifest {
270    /// The deadline this plugin's query command runs under while it answers
271    /// to `keyword` — the effective one, which a user override may have
272    /// added or removed.
273    ///
274    /// `timeout_ms` is clamped to 50 ms–3 s, and without a keyword it can
275    /// only lower the interactive default: an always-on plugin runs on every
276    /// keystroke, and letting it hold a process for seconds each time is
277    /// exactly what the default exists to prevent.
278    #[must_use]
279    pub fn timeout(&self, keyword: Option<&str>) -> Duration {
280        let requested = self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
281            Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
282        });
283        if keyword.is_some() {
284            requested
285        } else {
286            requested.min(QUERY_TIMEOUT)
287        }
288    }
289}
290
291/// One item emitted by a plugin. A subset of Alfred's Script Filter schema.
292#[derive(Debug, Clone, Deserialize)]
293struct PluginItem {
294    title: String,
295    #[serde(default)]
296    subtitle: String,
297    /// Payload handed back on activation. Defaults to the title.
298    #[serde(default)]
299    arg: Option<String>,
300    /// Icon-theme name or path. Alfred nests this under an object; both the
301    /// bare string and `{ "path": "..." }` forms are accepted.
302    #[serde(default)]
303    icon: Option<PluginIcon>,
304    /// Alfred marks unselectable rows with `valid: false`.
305    #[serde(default = "default_valid")]
306    valid: bool,
307    /// Stable identity across queries, Alfred's `uid`. When present it keys
308    /// the row — which is what lets frecency learn plugin items — and rows
309    /// with the same uid keep their widget state across keystrokes.
310    #[serde(default)]
311    uid: Option<String>,
312    /// Text that replaces the query on Tab, Alfred's `autocomplete`.
313    #[serde(default)]
314    autocomplete: Option<String>,
315    /// State carried from query to activation, Alfred's `variables`: exported
316    /// as environment variables to the activation command. Merged over the
317    /// response's top-level `variables`, the item's own winning.
318    #[serde(default)]
319    variables: std::collections::HashMap<String, String>,
320    /// Alternate actions on modifier+Enter, Alfred's `mods`, keyed by the
321    /// modifier name. Alfred's `cmd` is accepted and mapped to Super, which
322    /// is the key in that position on a PC keyboard.
323    #[serde(default)]
324    mods: std::collections::HashMap<String, PluginMod>,
325}
326
327/// One alternate action as a plugin writes it.
328#[derive(Debug, Clone, Deserialize)]
329struct PluginMod {
330    #[serde(default)]
331    subtitle: String,
332    #[serde(default)]
333    arg: Option<String>,
334    /// Alfred lets a mod be switched off without removing it.
335    #[serde(default = "default_valid")]
336    valid: bool,
337    #[serde(default)]
338    variables: std::collections::HashMap<String, String>,
339}
340
341/// Modifier names a plugin may use, normalised to what the frontend binds.
342///
343/// Anything unrecognised is dropped rather than guessed at: a mod nobody can
344/// press is worse than no mod, because it takes a row in the action panel.
345fn normalise_modifier(name: &str) -> Option<&'static str> {
346    match name.trim().to_lowercase().as_str() {
347        "ctrl" | "control" => Some("ctrl"),
348        "alt" | "option" => Some("alt"),
349        "shift" => Some("shift"),
350        // Alfred's `cmd` is the key in the Super position on a PC keyboard.
351        "cmd" | "command" | "super" | "meta" => Some("super"),
352        _ => None,
353    }
354}
355
356const fn default_valid() -> bool {
357    true
358}
359
360#[derive(Debug, Clone, Deserialize)]
361#[serde(untagged)]
362enum PluginIcon {
363    Named(String),
364    Path {
365        #[serde(alias = "name")]
366        path: String,
367    },
368}
369
370impl PluginIcon {
371    fn into_icon(self) -> Icon {
372        match self {
373            Self::Named(name) | Self::Path { path: name } => Icon::Name(name),
374        }
375    }
376}
377
378#[derive(Debug, Clone, Deserialize)]
379struct PluginResponse {
380    items: Vec<PluginItem>,
381    /// Variables applied to every item, Alfred's top-level `variables`.
382    #[serde(default)]
383    variables: std::collections::HashMap<String, String>,
384    /// Seconds after which the same query should run again, Alfred's `rerun`
385    /// — how a progress-reporting or polling plugin streams updates.
386    #[serde(default)]
387    rerun: Option<f64>,
388}
389
390/// Bounds on a plugin's `rerun` interval. Alfred allows 0.1–5.0 s; the floor
391/// here is higher because every rerun forks a process, and a launcher that
392/// respawns scripts ten times a second shows up in power measurements.
393const RERUN_RANGE: std::ops::RangeInclusive<f64> = 0.5..=5.0;
394
395/// A completed plugin query: the items, plus how long until the plugins that
396/// asked to be re-run should see the same query again.
397#[derive(Debug, Clone, Default)]
398pub struct QueryResults {
399    /// Everything the plugins returned, concatenated.
400    pub items: Vec<Item>,
401    /// Soonest requested rerun across the plugins that answered.
402    pub rerun: Option<Duration>,
403}
404
405/// The item's variables over the response's, sorted for a stable identity —
406/// the result lives inside [`Source::Plugin`], which is compared by `Eq`.
407fn merge_variables(
408    response: &std::collections::HashMap<String, String>,
409    item: std::collections::HashMap<String, String>,
410) -> Vec<(String, String)> {
411    let mut merged = response.clone();
412    merged.extend(item);
413    let mut variables: Vec<(String, String)> = merged.into_iter().collect();
414    variables.sort();
415    variables
416}
417
418/// A discovered plugin: its manifest plus the directory it lives in.
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub struct Plugin {
421    /// The parsed `manifest.toml`.
422    pub manifest: Manifest,
423    /// Where the plugin lives. Commands are resolved relative to it.
424    pub directory: PathBuf,
425    /// Directory name, used as the stable plugin identifier.
426    pub id: String,
427}
428
429impl Plugin {
430    /// Resolve a manifest command against the plugin directory so `./search.sh`
431    /// works regardless of the launcher's working directory.
432    fn resolve(&self, command: &str) -> PathBuf {
433        let path = Path::new(command);
434        if path.is_absolute() {
435            path.to_path_buf()
436        } else {
437            self.directory.join(path)
438        }
439    }
440
441    /// Whether this plugin should run for `query`, and the text it should see.
442    ///
443    /// A keyworded plugin receives the query with its keyword stripped, matching
444    /// Alfred: typing `gh jump` hands the plugin `jump`. The host passes the
445    /// *effective* keyword, so a user override replaces the manifest's here.
446    #[must_use]
447    pub fn match_query_as<'a>(&self, keyword: Option<&str>, query: &'a str) -> Option<&'a str> {
448        match keyword {
449            None => Some(query),
450            Some(keyword) => {
451                let rest = query.strip_prefix(keyword)?;
452                match rest.strip_prefix(' ') {
453                    Some(rest) => Some(rest.trim_start()),
454                    // Bare keyword with nothing after it: run with an empty
455                    // query so the plugin can show a default list.
456                    None if rest.is_empty() => Some(""),
457                    None => None,
458                }
459            }
460        }
461    }
462
463    /// [`Self::match_query_as`] with the manifest's own keyword.
464    #[must_use]
465    pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
466        self.match_query_as(self.manifest.keyword.as_deref(), query)
467    }
468
469    /// Run the plugin's query command under `deadline` and parse its
470    /// results, plus the rerun interval it asked for, if any.
471    async fn query(&self, text: &str, deadline: Duration) -> (Vec<Item>, Option<Duration>) {
472        let program = self.resolve(&self.manifest.query);
473
474        let stdout = match run_query(&program, &self.directory, text, deadline).await {
475            Ok(stdout) => stdout,
476            Err(error) => {
477                tracing::warn!(plugin = %self.id, ?program, %error, "plugin query dropped");
478                return (Vec::new(), None);
479            }
480        };
481
482        let response: PluginResponse = match serde_json::from_slice(&stdout) {
483            Ok(response) => response,
484            Err(error) => {
485                tracing::warn!(plugin = %self.id, %error, "plugin emitted invalid JSON");
486                return (Vec::new(), None);
487            }
488        };
489
490        let fallback_icon = self.manifest.icon.as_ref().map(|n| Icon::Name(n.clone()));
491        let PluginResponse {
492            items,
493            variables: response_variables,
494            rerun,
495        } = response;
496
497        // NaN and absurd values from a script must not become a timer.
498        let rerun = rerun.filter(|seconds| seconds.is_finite()).map(|seconds| {
499            Duration::from_secs_f64(seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end()))
500        });
501
502        let items = items
503            .into_iter()
504            .filter(|item| item.valid)
505            .map(|item| {
506                let arg = item.arg.unwrap_or_else(|| item.title.clone());
507                let variables = merge_variables(&response_variables, item.variables);
508
509                // Alternates inherit the item's arg and variables unless they
510                // override them, which is what makes the common case — same
511                // payload, different action — a two-line mod.
512                let mut mods: Vec<Mod> = item
513                    .mods
514                    .into_iter()
515                    .filter(|(_, alternate)| alternate.valid)
516                    .filter_map(|(modifier, alternate)| {
517                        let modifier = normalise_modifier(&modifier)?;
518                        let mut merged: std::collections::HashMap<String, String> =
519                            variables.iter().cloned().collect();
520                        merged.extend(alternate.variables);
521                        let mut alternate_variables: Vec<(String, String)> =
522                            merged.into_iter().collect();
523                        alternate_variables.sort();
524
525                        Some(Mod {
526                            modifier: modifier.to_owned(),
527                            subtitle: alternate.subtitle,
528                            arg: alternate.arg.unwrap_or_else(|| arg.clone()),
529                            variables: alternate_variables,
530                        })
531                    })
532                    .collect();
533                // HashMap iteration order is not stable; the action panel is.
534                mods.sort_by(|a, b| a.modifier.cmp(&b.modifier));
535                // Prefer the uid: an item whose arg changes with the query — a
536                // search URL, say — would otherwise get a new identity every
537                // keystroke, and frecency could never learn it.
538                let identity = item.uid.as_deref().unwrap_or(&arg);
539                Item {
540                    // Namespaced by plugin id so two plugins returning the same
541                    // title stay distinct rows.
542                    key: ItemKey(format!("plugin:{}:{identity}", self.id)),
543                    // Plugin items are not addressable by pop-launcher indice.
544                    id: 0,
545                    title: item.title,
546                    subtitle: if item.subtitle.is_empty() {
547                        self.manifest.description.clone()
548                    } else {
549                        item.subtitle
550                    },
551                    icon: item
552                        .icon
553                        .map(PluginIcon::into_icon)
554                        .or_else(|| fallback_icon.clone()),
555                    category_icon: fallback_icon.clone(),
556                    window: None,
557                    source: Source::Plugin {
558                        plugin: self.id.clone(),
559                        arg,
560                        variables,
561                        mods,
562                    },
563                    autocomplete: item.autocomplete,
564                    score: 0.0,
565                }
566            })
567            .collect();
568
569        (items, rerun)
570    }
571
572    /// Run the plugin's activation command for `arg`.
573    ///
574    /// `variables` — the item's merged `variables`, Alfred-style — are
575    /// exported into the command's environment, which is how a plugin carries
576    /// state from query to activation without encoding it all into `arg`.
577    ///
578    /// Spawned detached: the launcher dismisses immediately and does not wait
579    /// for the action to finish.
580    pub fn activate(&self, arg: &str, variables: &[(String, String)]) {
581        let (program, extra) = match self.manifest.activate.as_deref() {
582            Some(activate) => (self.resolve(activate), Vec::new()),
583            None => (
584                self.resolve(&self.manifest.query),
585                vec!["--activate".to_owned()],
586            ),
587        };
588
589        let mut command = Command::new(&program);
590        command
591            .envs(variables.iter().map(|(key, value)| (key, value)))
592            .args(extra)
593            .arg(arg)
594            .current_dir(&self.directory)
595            .stdin(Stdio::null())
596            .stdout(Stdio::null())
597            .stderr(Stdio::null());
598
599        let id = self.id.clone();
600        tokio::spawn(async move {
601            match spawn_plugin(&mut command).await {
602                // Waited on so the child does not become a zombie.
603                Ok(mut child) => {
604                    let _ = child.wait().await;
605                }
606                Err(error) => {
607                    tracing::error!(plugin = %id, ?program, %error, "failed to activate plugin item");
608                }
609            }
610        });
611    }
612}
613
614/// All discovered plugins.
615#[derive(Debug, Default, Clone)]
616pub struct PluginHost {
617    plugins: Vec<Plugin>,
618    /// Plugin ids the user has switched off. They stay discovered — the
619    /// settings window needs to list them — but never run.
620    disabled: std::collections::HashSet<String>,
621    /// Per-plugin keyword overrides: the alias mechanism. An entry replaces
622    /// the manifest's keyword without editing the plugin; an empty string
623    /// removes the keyword, making the plugin run on every query.
624    keyword_overrides: std::collections::HashMap<String, String>,
625}
626
627impl PluginHost {
628    /// Discover plugins in [`Self::roots`].
629    #[must_use]
630    pub fn discover() -> Self {
631        Self::discover_in(&Self::roots())
632    }
633
634    /// Where plugins are discovered, in shadowing order: the user's data
635    /// directory, then the system data directories (`$XDG_DATA_DIRS`, so
636    /// distro packages under `/usr/share/jump/plugins` are picked up with no
637    /// configuration).
638    ///
639    /// The user's directory is searched first and wins on an id collision, so
640    /// copying a packaged plugin into `~/.local/share/jump/plugins` to modify
641    /// it shadows the packaged one rather than duplicating it.
642    #[must_use]
643    pub fn roots() -> Vec<PathBuf> {
644        let mut roots: Vec<PathBuf> = dirs::data_dir()
645            .map(|dir| dir.join("jump").join("plugins"))
646            .into_iter()
647            .collect();
648
649        let system = std::env::var_os("XDG_DATA_DIRS")
650            .filter(|value| !value.is_empty())
651            .map_or_else(
652                || {
653                    vec![
654                        PathBuf::from("/usr/local/share"),
655                        PathBuf::from("/usr/share"),
656                    ]
657                },
658                |value| std::env::split_paths(&value).collect(),
659            );
660        roots.extend(
661            system
662                .into_iter()
663                .map(|dir| dir.join("jump").join("plugins")),
664        );
665        roots
666    }
667
668    /// Discover plugins under `roots`, earlier roots shadowing later ones.
669    ///
670    /// Directories without a readable manifest are skipped with a warning; a
671    /// malformed plugin must never prevent the launcher from starting.
672    #[must_use]
673    pub fn discover_in(roots: &[PathBuf]) -> Self {
674        let mut plugins: Vec<Plugin> = Vec::new();
675
676        for root in roots {
677            let entries = match std::fs::read_dir(root) {
678                Ok(entries) => entries,
679                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
680                Err(error) => {
681                    tracing::warn!(%error, ?root, "failed to read plugin directory");
682                    continue;
683                }
684            };
685
686            for entry in entries.flatten() {
687                let directory = entry.path();
688                if !directory.is_dir() {
689                    continue;
690                }
691
692                let Some(id) = directory
693                    .file_name()
694                    .and_then(|name| name.to_str())
695                    .map(ToOwned::to_owned)
696                else {
697                    continue;
698                };
699
700                if plugins.iter().any(|plugin| plugin.id == id) {
701                    tracing::debug!(plugin = %id, ?directory, "shadowed by an earlier root");
702                    continue;
703                }
704
705                let manifest_path = directory.join("manifest.toml");
706                let contents = match std::fs::read_to_string(&manifest_path) {
707                    Ok(contents) => contents,
708                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
709                    Err(error) => {
710                        tracing::warn!(%error, ?manifest_path, "failed to read plugin manifest");
711                        continue;
712                    }
713                };
714
715                let manifest: Manifest = match toml::from_str(&contents) {
716                    Ok(manifest) => manifest,
717                    Err(error) => {
718                        tracing::warn!(%error, ?manifest_path, "invalid plugin manifest");
719                        continue;
720                    }
721                };
722
723                tracing::info!(plugin = %id, keyword = ?manifest.keyword, "loaded plugin");
724                plugins.push(Plugin {
725                    manifest,
726                    directory,
727                    id,
728                });
729            }
730        }
731
732        Self {
733            plugins,
734            disabled: std::collections::HashSet::new(),
735            keyword_overrides: std::collections::HashMap::new(),
736        }
737    }
738
739    /// Take the plugins from a fresh discovery, keeping the user's disabled
740    /// set and keyword overrides, which belong to settings rather than to
741    /// what is on disk. Returns whether the plugin set actually changed.
742    pub fn replace_plugins(&mut self, discovered: Self) -> bool {
743        if self.plugins == discovered.plugins {
744            return false;
745        }
746        self.plugins = discovered.plugins;
747        true
748    }
749
750    /// Replace the set of switched-off plugins, e.g. when settings change.
751    pub fn set_disabled<I, S>(&mut self, ids: I)
752    where
753        I: IntoIterator<Item = S>,
754        S: Into<String>,
755    {
756        self.disabled = ids.into_iter().map(Into::into).collect();
757    }
758
759    /// Replace the keyword overrides, e.g. when settings change.
760    pub fn set_keyword_overrides<I, K, V>(&mut self, overrides: I)
761    where
762        I: IntoIterator<Item = (K, V)>,
763        K: Into<String>,
764        V: Into<String>,
765    {
766        self.keyword_overrides = overrides
767            .into_iter()
768            .map(|(id, keyword)| (id.into(), keyword.into()))
769            .collect();
770    }
771
772    /// The keyword `plugin` currently answers to: the user's override when
773    /// one exists (empty meaning "no keyword"), else the manifest's.
774    #[must_use]
775    pub fn effective_keyword<'a>(&'a self, plugin: &'a Plugin) -> Option<&'a str> {
776        match self.keyword_overrides.get(&plugin.id) {
777            Some(keyword) if keyword.is_empty() => None,
778            Some(keyword) => Some(keyword.as_str()),
779            None => plugin.manifest.keyword.as_deref(),
780        }
781    }
782
783    /// Every discovered plugin, the switched-off ones included, with whether
784    /// each is currently enabled. This is the settings window's list.
785    pub fn all(&self) -> impl Iterator<Item = (&Plugin, bool)> {
786        self.plugins
787            .iter()
788            .map(|plugin| (plugin, !self.disabled.contains(&plugin.id)))
789    }
790
791    /// Whether no plugins were discovered.
792    #[must_use]
793    pub fn is_empty(&self) -> bool {
794        self.plugins.is_empty()
795    }
796
797    /// Look up an *enabled* plugin. Activation goes through here, so a plugin
798    /// disabled between query and click does nothing rather than running.
799    #[must_use]
800    pub fn get(&self, id: &str) -> Option<&Plugin> {
801        self.plugins
802            .iter()
803            .filter(|plugin| !self.disabled.contains(&plugin.id))
804            .find(|plugin| plugin.id == id)
805    }
806
807    /// Query every plugin that matches, concurrently.
808    ///
809    /// Plugins run in parallel and share the same deadline, so total latency is
810    /// the slowest matching plugin rather than the sum.
811    pub async fn query(&self, text: &str) -> QueryResults {
812        let matching: Vec<_> = self
813            .plugins
814            .iter()
815            .filter(|plugin| !self.disabled.contains(&plugin.id))
816            .filter_map(|plugin| {
817                plugin
818                    .match_query_as(self.effective_keyword(plugin), text)
819                    .map(|query| (plugin, query))
820            })
821            .collect();
822
823        if matching.is_empty() {
824            return QueryResults::default();
825        }
826
827        // A keyworded plugin takes over the query entirely: once the user types
828        // `gh …` they are addressing that plugin, not searching their apps.
829        let keyworded: Vec<_> = matching
830            .iter()
831            .filter(|(plugin, _)| self.effective_keyword(plugin).is_some())
832            .collect();
833
834        let selected: Vec<_> = if keyworded.is_empty() {
835            matching.iter().collect()
836        } else {
837            keyworded
838        };
839
840        let futures = selected.into_iter().map(|(plugin, query)| {
841            let deadline = plugin.manifest.timeout(self.effective_keyword(plugin));
842            plugin.query(query, deadline)
843        });
844
845        let mut results = QueryResults::default();
846        for (items, rerun) in futures::future::join_all(futures).await {
847            results.items.extend(items);
848            // The soonest rerun wins: a plugin that asked to stream must not
849            // be held to a slower neighbour's interval.
850            results.rerun = match (results.rerun, rerun) {
851                (Some(a), Some(b)) => Some(a.min(b)),
852                (a, b) => a.or(b),
853            };
854        }
855        results
856    }
857
858    /// Whether a keyworded plugin claims this query, meaning pop-launcher
859    /// results should be suppressed.
860    #[must_use]
861    pub fn is_claimed(&self, text: &str) -> bool {
862        self.plugins
863            .iter()
864            .filter(|plugin| !self.disabled.contains(&plugin.id))
865            .any(|plugin| {
866                let keyword = self.effective_keyword(plugin);
867                keyword.is_some() && plugin.match_query_as(keyword, text).is_some()
868            })
869    }
870}
871
872/// What `lint` found. Errors stop the plugin working; warnings do not.
873#[derive(Debug, Default)]
874pub struct LintReport {
875    /// Problems that stop the plugin from working at all.
876    pub errors: Vec<String>,
877    /// Problems worth fixing that do not stop it working.
878    pub warnings: Vec<String>,
879    /// Items the sample query produced, when it ran at all.
880    pub items: usize,
881}
882
883impl LintReport {
884    /// Whether nothing blocking was found. Warnings are still allowed.
885    #[must_use]
886    pub fn is_clean(&self) -> bool {
887        self.errors.is_empty()
888    }
889}
890
891/// Check a plugin directory: the manifest, the commands it names, and the
892/// output of one sample query against the item schema.
893///
894/// This *runs* the plugin's query command — that is the point: the schema
895/// violations that break a plugin live in its output, not its manifest.
896pub async fn lint(directory: &Path, sample_query: &str) -> LintReport {
897    let mut report = LintReport::default();
898
899    let manifest_path = directory.join("manifest.toml");
900    let contents = match std::fs::read_to_string(&manifest_path) {
901        Ok(contents) => contents,
902        Err(error) => {
903            report
904                .errors
905                .push(format!("cannot read {}: {error}", manifest_path.display()));
906            return report;
907        }
908    };
909
910    let manifest: Manifest = match toml::from_str(&contents) {
911        Ok(manifest) => manifest,
912        Err(error) => {
913            report
914                .errors
915                .push(format!("manifest does not parse: {error}"));
916            return report;
917        }
918    };
919
920    if let Some(keyword) = manifest.keyword.as_deref() {
921        if !is_keyword(keyword) {
922            report.errors.push(format!(
923                "keyword {keyword:?} must be one non-empty word — it is matched \
924                 up to the first space of the query"
925            ));
926        }
927    } else {
928        report.warnings.push(
929            "no keyword: the plugin runs on every keystroke and must answer \
930             well inside 180 ms"
931                .to_owned(),
932        );
933    }
934
935    if let Some(ms) = manifest.timeout_ms {
936        let applied = manifest.timeout(manifest.keyword.as_deref()).as_millis();
937        if u128::from(ms) != applied {
938            let why = if manifest.keyword.is_none() && applied == QUERY_TIMEOUT.as_millis() {
939                " — only a keyworded plugin may take longer than the interactive default"
940            } else {
941                ""
942            };
943            report
944                .warnings
945                .push(format!("timeout_ms = {ms} is clamped to {applied} ms{why}"));
946        }
947    }
948
949    let check_command = |report: &mut LintReport, label: &str, command: &str| {
950        let path = if Path::new(command).is_absolute() {
951            PathBuf::from(command)
952        } else {
953            directory.join(command)
954        };
955        if !path.is_file() {
956            report
957                .errors
958                .push(format!("{label} command {} does not exist", path.display()));
959            return;
960        }
961        #[cfg(unix)]
962        {
963            use std::os::unix::fs::PermissionsExt;
964            let executable = path
965                .metadata()
966                .map(|meta| meta.permissions().mode() & 0o111 != 0)
967                .unwrap_or(false);
968            if !executable {
969                report.errors.push(format!(
970                    "{label} command {} is not executable (chmod +x)",
971                    path.display()
972                ));
973            }
974        }
975    };
976    check_command(&mut report, "query", &manifest.query);
977    if let Some(activate) = manifest.activate.as_deref() {
978        check_command(&mut report, "activate", activate);
979    }
980    if !report.errors.is_empty() {
981        return report;
982    }
983
984    // Run the sample query exactly the way the launcher would.
985    let plugin = Plugin {
986        manifest,
987        directory: directory.to_path_buf(),
988        id: directory
989            .file_name()
990            .and_then(|name| name.to_str())
991            .unwrap_or("plugin")
992            .to_owned(),
993    };
994    let program = plugin.resolve(&plugin.manifest.query);
995    let stdout = match run_query(
996        &program,
997        &plugin.directory,
998        sample_query,
999        plugin.manifest.timeout(plugin.manifest.keyword.as_deref()),
1000    )
1001    .await
1002    {
1003        Ok(stdout) => stdout,
1004        Err(error) => {
1005            report.errors.push(format!("query command {error}"));
1006            return report;
1007        }
1008    };
1009
1010    match serde_json::from_slice::<PluginResponse>(&stdout) {
1011        Ok(response) => {
1012            report.items = response.items.len();
1013            if response.items.is_empty() {
1014                report
1015                    .warnings
1016                    .push("sample query produced no items".to_owned());
1017            }
1018            for item in &response.items {
1019                if item.uid.is_none() {
1020                    report.warnings.push(format!(
1021                        "item {:?} has no uid — without one, usage ranking \
1022                         cannot learn it",
1023                        item.title
1024                    ));
1025                }
1026            }
1027        }
1028        Err(error) => {
1029            report
1030                .errors
1031                .push(format!("output is not valid script-filter JSON: {error}"));
1032        }
1033    }
1034
1035    report
1036}
1037
1038/// The keyword, and plugin directory name, `jump plugin new <name>` derives
1039/// from `name`: lowercased, with runs of whitespace joined by dashes.
1040///
1041/// `None` when that cannot name a directory inside the plugin root — empty,
1042/// hidden, or containing a path separator — so `../x` cannot scaffold
1043/// outside it.
1044#[must_use]
1045pub fn scaffold_keyword(name: &str) -> Option<String> {
1046    let keyword = name
1047        .to_lowercase()
1048        .split_whitespace()
1049        .collect::<Vec<_>>()
1050        .join("-");
1051    let usable =
1052        !keyword.is_empty() && !keyword.starts_with('.') && !keyword.contains(['/', '\\', '\0']);
1053    usable.then_some(keyword)
1054}
1055
1056/// Write a runnable plugin skeleton for `name` into a new directory under
1057/// `root`, named by [`scaffold_keyword`]. Returns the directory and the
1058/// keyword.
1059///
1060/// Refuses to touch a directory that already exists — a scaffolder that can
1061/// overwrite a real plugin is a footgun, not a convenience. `name` is
1062/// arbitrary user text, so it reaches the manifest as an escaped TOML string
1063/// and the script as a quoted shell variable, never as syntax.
1064///
1065/// # Errors
1066///
1067/// [`std::io::ErrorKind::InvalidInput`] if `name` yields no usable
1068/// directory name, [`std::io::ErrorKind::AlreadyExists`] if the directory is
1069/// already there, and any I/O error from creating the directory or writing
1070/// the files in it.
1071pub fn scaffold(root: &Path, name: &str) -> std::io::Result<(PathBuf, String)> {
1072    let Some(keyword) = scaffold_keyword(name) else {
1073        return Err(std::io::Error::new(
1074            std::io::ErrorKind::InvalidInput,
1075            format!("{name:?} does not make a plugin directory name"),
1076        ));
1077    };
1078    let directory = root.join(&keyword);
1079    if directory.exists() {
1080        return Err(std::io::Error::new(
1081            std::io::ErrorKind::AlreadyExists,
1082            format!("{} already exists", directory.display()),
1083        ));
1084    }
1085    std::fs::create_dir_all(&directory)?;
1086
1087    let toml_string = |text: &str| toml::Value::String(text.to_owned()).to_string();
1088    std::fs::write(
1089        directory.join("manifest.toml"),
1090        format!(
1091            "name = {}\n\
1092             description = \"Describe what this plugin searches\"\n\
1093             keyword = {}\n\
1094             query = \"./search.sh\"\n\
1095             # activate = \"./open.sh\"   # separate action command, optional\n\
1096             icon = \"system-search-symbolic\"\n\
1097             # timeout_ms = 1000          # up to 3000 for slow keyworded plugins\n",
1098            toml_string(name),
1099            toml_string(&keyword),
1100        ),
1101    )?;
1102
1103    // Single-quoted for the shell: only a quote itself needs escaping there.
1104    let shell_name = name.replace('\'', r"'\''");
1105    let script = directory.join("search.sh");
1106    std::fs::write(
1107        &script,
1108        format!(
1109            "#!/bin/sh\n\
1110             # jump runs this with the query as $1 and reads script-filter\n\
1111             # JSON from stdout. Without an `activate` command in the\n\
1112             # manifest, activation re-runs this script as: search.sh\n\
1113             # --activate <arg>.\n\
1114             if [ \"$1\" = \"--activate\" ]; then\n\
1115             \t# \"$2\" is the chosen item's arg.\n\
1116             \texit 0\n\
1117             fi\n\
1118             \n\
1119             name='{shell_name}'\n\
1120             query=\"$1\"\n\
1121             # Text going into a JSON string needs its backslashes and quotes\n\
1122             # escaped.\n\
1123             json() {{ printf '%s' \"$1\" | sed 's/[\\\\\"]/\\\\&/g'; }}\n\
1124             printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
1125             \"subtitle\":\"%s\",\"arg\":\"%s\"}}]}}' \
1126             \"$(json \"${{query:-world}}\")\" \"$(json \"$name\")\" \"$(json \"$query\")\"\n"
1127        ),
1128    )?;
1129    #[cfg(unix)]
1130    {
1131        use std::os::unix::fs::PermissionsExt;
1132        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
1133    }
1134    Ok((directory, keyword))
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use super::*;
1140
1141    fn plugin(keyword: Option<&str>) -> Plugin {
1142        Plugin {
1143            manifest: Manifest {
1144                name: "Test".to_owned(),
1145                description: String::new(),
1146                keyword: keyword.map(ToOwned::to_owned),
1147                query: "./q".to_owned(),
1148                activate: None,
1149                icon: None,
1150                timeout_ms: None,
1151            },
1152            directory: PathBuf::from("/tmp"),
1153            id: "test".to_owned(),
1154        }
1155    }
1156
1157    #[test]
1158    fn keywordless_plugin_sees_whole_query() {
1159        assert_eq!(plugin(None).match_query("hello there"), Some("hello there"));
1160    }
1161
1162    #[test]
1163    fn keyword_is_stripped() {
1164        assert_eq!(plugin(Some("gh")).match_query("gh jump"), Some("jump"));
1165    }
1166
1167    #[test]
1168    fn bare_keyword_yields_empty_query() {
1169        assert_eq!(plugin(Some("gh")).match_query("gh"), Some(""));
1170    }
1171
1172    #[test]
1173    fn a_keyword_is_one_non_empty_word() {
1174        assert!(is_keyword("gh"));
1175        assert!(is_keyword("=="));
1176        for bad in ["", "gh x", " gh", "gh\t"] {
1177            assert!(!is_keyword(bad), "{bad:?}");
1178        }
1179    }
1180
1181    #[test]
1182    fn keyword_requires_word_boundary() {
1183        // "ghost" must not be read as the "gh" keyword plus "ost".
1184        assert_eq!(plugin(Some("gh")).match_query("ghost"), None);
1185    }
1186
1187    #[test]
1188    fn non_matching_keyword_is_skipped() {
1189        assert_eq!(plugin(Some("gh")).match_query("firefox"), None);
1190    }
1191
1192    #[test]
1193    fn timeout_is_clamped_to_the_ceiling() {
1194        let mut manifest = plugin(None).manifest;
1195        let keyword = Some("gh");
1196        assert_eq!(manifest.timeout(keyword), Duration::from_millis(180));
1197
1198        manifest.timeout_ms = Some(60_000);
1199        assert_eq!(manifest.timeout(keyword), Duration::from_millis(3000));
1200
1201        manifest.timeout_ms = Some(1);
1202        assert_eq!(manifest.timeout(keyword), Duration::from_millis(50));
1203    }
1204
1205    #[test]
1206    fn only_a_keyworded_plugin_may_raise_its_deadline() {
1207        // An always-on plugin runs on every keystroke; `timeout_ms` exists so
1208        // a keyworded network plugin can be slow, not so every plugin can.
1209        let mut manifest = plugin(None).manifest;
1210        manifest.timeout_ms = Some(3000);
1211        assert_eq!(manifest.timeout(None), Duration::from_millis(180));
1212        assert_eq!(manifest.timeout(Some("gh")), Duration::from_millis(3000));
1213
1214        manifest.timeout_ms = Some(100);
1215        assert_eq!(manifest.timeout(None), Duration::from_millis(100));
1216    }
1217
1218    #[tokio::test(flavor = "multi_thread")]
1219    async fn the_host_holds_an_always_on_plugin_to_the_interactive_deadline() {
1220        // The deadline follows the keyword the plugin answers to right now,
1221        // so an override that removes the keyword removes the allowance.
1222        let root = tempfile::tempdir().expect("tempdir");
1223        let mut slow = scripted(
1224            root.path(),
1225            "#!/bin/sh\nsleep 0.5\necho '{\"items\":[{\"title\":\"late\"}]}'\n",
1226            Some(3000),
1227        );
1228        slow.id = "slow".to_owned();
1229        let mut host = PluginHost {
1230            plugins: vec![slow],
1231            ..PluginHost::default()
1232        };
1233        assert_eq!(host.query("t x").await.items.len(), 1);
1234
1235        // Empty is the proof: the script answers after half a second, so an
1236        // answer here could only mean the 180 ms deadline was not applied.
1237        // (A wall-clock bound on top of that measured how busy the machine
1238        // was, and failed when it was.)
1239        host.set_keyword_overrides([("slow", "")]);
1240        assert!(host.query("x").await.items.is_empty());
1241    }
1242
1243    #[test]
1244    fn uid_and_autocomplete_parse_from_alfred_json() {
1245        let response: PluginResponse = serde_json::from_str(
1246            r#"{"items":[
1247                {"uid":"repo","title":"jump","arg":"https://example.com/?q=jump",
1248                 "autocomplete":"gh jump ", "icon":{"path":"/tmp/icon.png"}},
1249                {"title":"plain"}
1250            ]}"#,
1251        )
1252        .expect("alfred json parses");
1253
1254        assert_eq!(response.items[0].uid.as_deref(), Some("repo"));
1255        assert_eq!(response.items[0].autocomplete.as_deref(), Some("gh jump "));
1256        assert_eq!(response.items[1].uid, None);
1257    }
1258
1259    #[test]
1260    fn rerun_parses_and_is_clamped_sanely() {
1261        let parse = |json: &str| -> Option<f64> {
1262            serde_json::from_str::<PluginResponse>(json)
1263                .expect("json parses")
1264                .rerun
1265        };
1266        assert_eq!(parse(r#"{"items":[]}"#), None);
1267        assert_eq!(parse(r#"{"items":[],"rerun":1.5}"#), Some(1.5));
1268
1269        // The clamp applied where the value becomes a timer.
1270        let clamp = |seconds: f64| seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end());
1271        assert_eq!(clamp(0.1), 0.5);
1272        assert_eq!(clamp(60.0), 5.0);
1273        assert_eq!(clamp(2.0), 2.0);
1274    }
1275
1276    #[test]
1277    fn mods_normalise_inherit_and_override() {
1278        let response: PluginResponse = serde_json::from_str(
1279            r#"{"variables":{"SESSION":"abc"},
1280                "items":[{"title":"repo","arg":"main",
1281                  "mods":{
1282                    "cmd":{"subtitle":"Open on the web","arg":"https://example.com"},
1283                    "alt":{"subtitle":"Copy","variables":{"MODE":"copy"}},
1284                    "shift":{"subtitle":"Off","valid":false},
1285                    "hyper":{"subtitle":"Unbindable"}
1286                  }}]}"#,
1287        )
1288        .expect("alfred json parses");
1289
1290        let item = &response.items[0];
1291        assert_eq!(normalise_modifier("cmd"), Some("super"));
1292        assert_eq!(normalise_modifier("Control"), Some("ctrl"));
1293        assert_eq!(normalise_modifier("hyper"), None);
1294
1295        // valid:false and unbindable modifiers are dropped before they can
1296        // take a row in the action panel.
1297        let usable: Vec<&String> = item
1298            .mods
1299            .iter()
1300            .filter(|(_, m)| m.valid)
1301            .filter(|(name, _)| normalise_modifier(name).is_some())
1302            .map(|(name, _)| name)
1303            .collect();
1304        assert_eq!(usable.len(), 2);
1305
1306        // An alternate without its own arg inherits the item's.
1307        assert_eq!(item.mods["alt"].arg, None);
1308        assert_eq!(item.mods["cmd"].arg.as_deref(), Some("https://example.com"));
1309    }
1310
1311    #[test]
1312    fn item_variables_win_over_response_variables() {
1313        let response: PluginResponse = serde_json::from_str(
1314            r#"{"variables":{"SESSION":"abc","MODE":"list"},
1315                "items":[{"title":"one","variables":{"MODE":"open"}},
1316                         {"title":"two"}]}"#,
1317        )
1318        .expect("alfred json parses");
1319
1320        let merged = merge_variables(&response.variables, response.items[0].variables.clone());
1321        assert_eq!(
1322            merged,
1323            vec![
1324                ("MODE".to_owned(), "open".to_owned()),
1325                ("SESSION".to_owned(), "abc".to_owned()),
1326            ]
1327        );
1328
1329        // An item without its own variables inherits the response's.
1330        let inherited = merge_variables(&response.variables, response.items[1].variables.clone());
1331        assert_eq!(inherited.len(), 2);
1332        assert!(inherited.contains(&("MODE".to_owned(), "list".to_owned())));
1333    }
1334
1335    #[tokio::test(flavor = "multi_thread")]
1336    async fn scaffold_produces_a_plugin_that_lints_clean() {
1337        let root = tempfile::tempdir().expect("tempdir");
1338
1339        let (directory, keyword) = scaffold(root.path(), "Demo").expect("scaffold succeeds");
1340        assert_eq!(directory, root.path().join("demo"));
1341        assert_eq!(keyword, "demo");
1342        // Refuses to overwrite what it just made.
1343        assert!(scaffold(root.path(), "Demo").is_err());
1344
1345        let report = lint(&directory, "hello").await;
1346        assert!(report.is_clean(), "unexpected errors: {:?}", report.errors);
1347        assert_eq!(report.items, 1);
1348        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1349    }
1350
1351    #[tokio::test(flavor = "multi_thread")]
1352    async fn a_scaffold_name_is_data_not_syntax() {
1353        // The name is whatever the user typed; quotes, `%` and `'` must reach
1354        // the manifest and the output as text, not break either.
1355        let root = tempfile::tempdir().expect("tempdir");
1356        let name = r#"It's "100%" done"#;
1357        let (directory, keyword) = scaffold(root.path(), name).expect("scaffold succeeds");
1358        assert_eq!(keyword, r#"it's-"100%"-done"#);
1359
1360        let manifest: Manifest = toml::from_str(
1361            &std::fs::read_to_string(directory.join("manifest.toml")).expect("manifest"),
1362        )
1363        .expect("the manifest parses");
1364        assert_eq!(manifest.name, name);
1365
1366        let output = std::process::Command::new(directory.join("search.sh"))
1367            .arg(r#"say "hi" \"#)
1368            .output()
1369            .expect("the script runs");
1370        let response: serde_json::Value =
1371            serde_json::from_slice(&output.stdout).expect("the output is JSON");
1372        let item = &response["items"][0];
1373        assert_eq!(item["subtitle"], name);
1374        assert_eq!(item["title"], r#"Hello say "hi" \"#);
1375    }
1376
1377    #[tokio::test(flavor = "multi_thread")]
1378    async fn a_query_script_still_open_for_writing_runs_once_it_is_closed() {
1379        // Executing a file that any process holds open for writing fails with
1380        // ETXTBSY. A script just written can be held that way for a moment
1381        // after its writer closes it — a child forked by another thread keeps
1382        // the descriptor until it execs — which made a freshly scaffolded
1383        // plugin fail its lint now and then.
1384        use std::io::Write;
1385        use std::os::unix::fs::PermissionsExt;
1386
1387        let root = tempfile::tempdir().expect("tempdir");
1388        let script = root.path().join("search.sh");
1389        let mut held = std::fs::File::create(&script).expect("create");
1390        held.write_all(b"#!/bin/sh\nprintf ok\n").expect("write");
1391        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1392        let release = std::thread::spawn(move || {
1393            std::thread::sleep(Duration::from_millis(30));
1394            drop(held);
1395        });
1396
1397        let stdout = run_query(&script, root.path(), "", Duration::from_secs(3))
1398            .await
1399            .expect("the query runs once the writer has closed the script");
1400        assert_eq!(stdout, b"ok");
1401        release.join().expect("release thread");
1402    }
1403
1404    #[test]
1405    fn a_scaffold_cannot_name_a_directory_outside_the_root() {
1406        for name in ["../x", "a/b", ".hidden", "   ", ""] {
1407            assert_eq!(scaffold_keyword(name), None, "{name:?}");
1408        }
1409        assert_eq!(scaffold_keyword("My  Plugin").as_deref(), Some("my-plugin"));
1410        let root = tempfile::tempdir().expect("tempdir");
1411        let error = scaffold(&root.path().join("plugins"), "../x").expect_err("refused");
1412        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
1413        assert!(!root.path().join("x").exists());
1414    }
1415
1416    #[tokio::test(flavor = "multi_thread")]
1417    async fn lint_reports_missing_and_broken_pieces() {
1418        let root = tempfile::tempdir().expect("tempdir");
1419
1420        // No manifest at all.
1421        let report = lint(root.path(), "x").await;
1422        assert!(!report.is_clean());
1423
1424        // A manifest naming a command that does not exist.
1425        let directory = root.path().join("broken");
1426        std::fs::create_dir_all(&directory).expect("dir");
1427        std::fs::write(
1428            directory.join("manifest.toml"),
1429            "name = \"Broken\"\nkeyword = \"two words\"\nquery = \"./missing.sh\"\n",
1430        )
1431        .expect("manifest");
1432        let report = lint(&directory, "x").await;
1433        assert_eq!(report.errors.len(), 2, "{:?}", report.errors);
1434    }
1435
1436    /// A plugin in a fresh directory whose query command is `script`.
1437    fn scripted(root: &Path, script: &str, timeout_ms: Option<u64>) -> Plugin {
1438        use std::os::unix::fs::PermissionsExt;
1439
1440        let path = root.join("q");
1441        std::fs::write(&path, script).expect("script");
1442        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1443        let mut plugin = plugin(Some("t"));
1444        plugin.directory = root.to_path_buf();
1445        plugin.manifest.timeout_ms = timeout_ms;
1446        plugin
1447    }
1448
1449    /// Whether `pid` is still a running process (a zombie counts as gone).
1450    fn alive(pid: u32) -> bool {
1451        std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
1452            stat.rsplit(") ")
1453                .next()
1454                .is_some_and(|rest| !rest.starts_with('Z'))
1455        })
1456    }
1457
1458    #[tokio::test(flavor = "multi_thread")]
1459    async fn oversized_output_is_refused_without_waiting_for_the_deadline() {
1460        // The cap is a memory bound, so it has to be enforced while reading:
1461        // a plugin that has already printed more than the cap is cut off
1462        // there, not buffered in full until it exits or the deadline fires.
1463        let root = tempfile::tempdir().expect("tempdir");
1464        let plugin = scripted(
1465            root.path(),
1466            "#!/bin/sh\nhead -c 2000000 /dev/zero\nsleep 5\n",
1467            Some(3000),
1468        );
1469
1470        let started = std::time::Instant::now();
1471        let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1472        assert!(items.is_empty());
1473        assert!(
1474            started.elapsed() < Duration::from_millis(1500),
1475            "took {:?}: output was buffered until the deadline",
1476            started.elapsed()
1477        );
1478    }
1479
1480    #[tokio::test(flavor = "multi_thread")]
1481    async fn an_overrunning_plugin_is_killed_with_its_children() {
1482        // "Killed" has to mean everything the plugin started for this query,
1483        // not just the script: a shell's background job would otherwise keep
1484        // running, detached, after its results were dropped.
1485        //
1486        // A second, not the 100 ms this once used: on a machine busy enough
1487        // for the shell to take longer than that to start, the deadline
1488        // killed the script before it had a child to record.
1489        let root = tempfile::tempdir().expect("tempdir");
1490        let plugin = scripted(
1491            root.path(),
1492            "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1493            Some(1000),
1494        );
1495
1496        let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
1497        assert!(items.is_empty());
1498
1499        assert!(
1500            !outlives(&root.path().join("child.pid")).await,
1501            "the plugin's child outlived the deadline"
1502        );
1503    }
1504
1505    /// Whether the process whose pid was written to `pid_file` is still
1506    /// running two seconds on. Kills it either way, so a failing test does
1507    /// not leave a stray behind for the rest of the suite.
1508    async fn outlives(pid_file: &Path) -> bool {
1509        let pid: u32 = std::fs::read_to_string(pid_file)
1510            .expect("the script recorded its child")
1511            .trim()
1512            .parse()
1513            .expect("pid");
1514        let deadline = std::time::Instant::now() + Duration::from_secs(2);
1515        while alive(pid) && std::time::Instant::now() < deadline {
1516            tokio::time::sleep(Duration::from_millis(20)).await;
1517        }
1518        let survived = alive(pid);
1519        if survived {
1520            let _ = std::process::Command::new("kill")
1521                .args(["-KILL", &pid.to_string()])
1522                .status();
1523        }
1524        survived
1525    }
1526
1527    #[tokio::test(flavor = "multi_thread")]
1528    async fn an_abandoned_query_is_killed_with_its_children() {
1529        // The launcher drops a query's future when the next keystroke
1530        // supersedes it; that has to stop the plugin, not just forget it.
1531        let root = tempfile::tempdir().expect("tempdir");
1532        let plugin = scripted(
1533            root.path(),
1534            "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
1535            Some(3000),
1536        );
1537        let pid_file = root.path().join("child.pid");
1538
1539        let running = tokio::spawn(async move {
1540            let deadline = plugin.manifest.timeout(Some("t"));
1541            plugin.query("x", deadline).await
1542        });
1543        let started = std::time::Instant::now();
1544        let recorded =
1545            |path: &Path| std::fs::read_to_string(path).is_ok_and(|pid| pid.ends_with('\n'));
1546        while !recorded(&pid_file) && started.elapsed() < Duration::from_secs(2) {
1547            tokio::time::sleep(Duration::from_millis(10)).await;
1548        }
1549        running.abort();
1550        assert!(running.await.is_err_and(|error| error.is_cancelled()));
1551
1552        assert!(
1553            !outlives(&pid_file).await,
1554            "the abandoned query's child kept running"
1555        );
1556    }
1557
1558    #[tokio::test(flavor = "multi_thread")]
1559    async fn lint_applies_the_launchers_output_cap() {
1560        // Lint promises to run the plugin exactly the way the launcher does,
1561        // so output the launcher would drop cannot lint clean.
1562        let root = tempfile::tempdir().expect("tempdir");
1563        let directory = root.path().join("big");
1564        std::fs::create_dir_all(&directory).expect("dir");
1565        std::fs::write(
1566            directory.join("manifest.toml"),
1567            "name = \"Big\"\nkeyword = \"big\"\nquery = \"./q\"\n",
1568        )
1569        .expect("manifest");
1570        scripted(
1571            &directory,
1572            "#!/bin/sh\nprintf '{\"items\":[{\"uid\":\"a\",\"title\":\"'\n\
1573             head -c 1100000 /dev/zero | tr '\\0' a\nprintf '\"}]}'\n",
1574            None,
1575        );
1576
1577        let report = lint(&directory, "x").await;
1578        assert!(!report.is_clean(), "oversized output linted clean");
1579    }
1580
1581    #[test]
1582    fn discovery_walks_roots_in_order_and_user_shadows_system() {
1583        let user = tempfile::tempdir().expect("tempdir");
1584        let system = tempfile::tempdir().expect("tempdir");
1585
1586        let write = |root: &std::path::Path, id: &str, name: &str| {
1587            let dir = root.join(id);
1588            std::fs::create_dir_all(&dir).expect("plugin dir");
1589            std::fs::write(
1590                dir.join("manifest.toml"),
1591                format!("name = \"{name}\"\nquery = \"./q\"\n"),
1592            )
1593            .expect("manifest");
1594        };
1595
1596        write(user.path(), "shared", "User copy");
1597        write(user.path(), "mine", "User only");
1598        write(system.path(), "shared", "System copy");
1599        write(system.path(), "packaged", "System only");
1600        // A directory without a manifest is not a plugin.
1601        std::fs::create_dir_all(system.path().join("junk")).expect("junk dir");
1602
1603        let host =
1604            PluginHost::discover_in(&[user.path().to_path_buf(), system.path().to_path_buf()]);
1605
1606        let mut ids: Vec<&str> = host.all().map(|(plugin, _)| plugin.id.as_str()).collect();
1607        ids.sort_unstable();
1608        assert_eq!(ids, ["mine", "packaged", "shared"]);
1609
1610        // The user's copy shadowed the packaged one.
1611        let shared = host.get("shared").expect("shared plugin");
1612        assert_eq!(shared.manifest.name, "User copy");
1613    }
1614
1615    #[test]
1616    fn a_fresh_discovery_keeps_the_users_settings() {
1617        // Rediscovery replaces what is on disk, never what the user chose:
1618        // a switched-off plugin must stay off, and an alias must survive.
1619        let root = tempfile::tempdir().expect("tempdir");
1620        let write = |id: &str| {
1621            let dir = root.path().join(id);
1622            std::fs::create_dir_all(&dir).expect("plugin dir");
1623            std::fs::write(
1624                dir.join("manifest.toml"),
1625                "name = \"P\"\nkeyword = \"p\"\nquery = \"./q\"\n",
1626            )
1627            .expect("manifest");
1628        };
1629        write("old");
1630        let roots = [root.path().to_path_buf()];
1631        let mut host = PluginHost::discover_in(&roots);
1632        host.set_disabled(["old"]);
1633        host.set_keyword_overrides([("new", "n")]);
1634
1635        assert!(!host.replace_plugins(PluginHost::discover_in(&roots)));
1636
1637        write("new");
1638        assert!(host.replace_plugins(PluginHost::discover_in(&roots)));
1639        assert!(
1640            host.get("old").is_none(),
1641            "the disabled plugin came back on"
1642        );
1643        let new = host.get("new").expect("the new plugin was picked up");
1644        assert_eq!(host.effective_keyword(new), Some("n"));
1645    }
1646
1647    #[test]
1648    fn keyword_overrides_replace_and_remove_the_manifest_keyword() {
1649        let mut host = PluginHost {
1650            plugins: vec![plugin(Some("gh"))],
1651            disabled: std::collections::HashSet::new(),
1652            keyword_overrides: std::collections::HashMap::new(),
1653        };
1654
1655        // Manifest keyword applies untouched.
1656        assert!(host.is_claimed("gh jump"));
1657
1658        // An override is a rename: the old keyword stops answering.
1659        host.set_keyword_overrides([("test", "g")]);
1660        assert!(host.is_claimed("g jump"));
1661        assert!(!host.is_claimed("gh jump"));
1662
1663        // An empty override removes the keyword entirely: the plugin runs on
1664        // every query and claims none.
1665        host.set_keyword_overrides([("test", "")]);
1666        assert!(!host.is_claimed("g jump"));
1667        assert!(!host.is_claimed("gh jump"));
1668        let plugin = &host.plugins[0];
1669        assert_eq!(host.effective_keyword(plugin), None);
1670
1671        // Overrides for unknown plugins are inert.
1672        host.set_keyword_overrides([("other", "x")]);
1673        assert!(host.is_claimed("gh jump"));
1674    }
1675
1676    #[test]
1677    fn disabled_plugins_neither_run_nor_activate() {
1678        let mut host = PluginHost {
1679            plugins: vec![plugin(Some("gh"))],
1680            disabled: std::collections::HashSet::new(),
1681            keyword_overrides: std::collections::HashMap::new(),
1682        };
1683
1684        assert!(host.is_claimed("gh jump"));
1685        assert!(host.get("test").is_some());
1686
1687        host.set_disabled(["test"]);
1688        assert!(!host.is_claimed("gh jump"));
1689        assert!(host.get("test").is_none());
1690        // Still listed for the settings window, marked disabled.
1691        assert_eq!(host.all().map(|(_, on)| on).collect::<Vec<_>>(), [false]);
1692    }
1693}