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