Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(plugins): let a plugin claim launcher input by pattern

Tioit-Wang68e2da823a83
diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
index 675bef859..8b6631813 100644
--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
@@ -10,6 +10,7 @@ import { PluginViewHost, pluginViewKey } from "../plugin-view-host";
import { PluginPanelHost } from "../plugin-panel-host";
import type { PluginPanelTheme } from "../../shared/plugin-panel-chrome";
import type { IpcRegistrar } from "./types";
+import { normalizeLauncherLaunch } from "./plugin-launcher-ipc";
import { pluginProviderCatalogEntries } from "../plugin-provider-catalog";
import { createSessionPushGate } from "../plugin-session-push-gate";
import {
@@ -128,30 +129,53 @@ export function registerPluginUiIpc({
return { ok: true };
},
);
- handle(IPC.invoke.pluginOpenPanel, async (id: string) => {
- const loaded = plugins.getLoaded(id);
- if (!loaded) throw new Error("plugin not loaded");
- const manifest = loaded.manifest;
- if (!manifest.ui?.panel) throw new Error("plugin has no panel");
- if (!(loaded.permissions.has("ui.panel"))) {
- throw new Error("PERMISSION_DENIED: ui.panel");
- }
- const htmlPath = resolveInsidePluginRoot(loaded.path, manifest.ui.panel);
- if (!htmlPath) throw new Error("plugin panel must stay inside the plugin");
- await pluginPanels.open({
- pluginId: id,
- title: resolvePluginLocalizedString(manifest.ui.title, getUpdaterLocale(), manifest.name),
- locale: getUpdaterLocale(),
- theme: getPluginPanelTheme(),
- shape: manifest.ui.shape,
- alwaysOnTop: manifest.ui.alwaysOnTop,
- resizable: manifest.ui.resizable,
- width: manifest.ui.width ?? 480,
- height: manifest.ui.height ?? 360,
- htmlPath,
- });
- return { ok: true };
- });
+ /**
+ * Open a plugin panel.
+ *
+ * The launcher passes an object so it can hand the plugin the input that
+ * summoned it; every other caller still passes the bare id, so the old shape
+ * keeps working unchanged (issue #2085).
+ */
+ handle(
+ IPC.invoke.pluginOpenPanel,
+ async (
+ request: string | { pluginId?: unknown; triggerId?: unknown; payload?: unknown },
+ ) => {
+ const pluginId =
+ typeof request === "string" ? request : String(request?.pluginId ?? "");
+ const loaded = plugins.getLoaded(pluginId);
+ if (!loaded) throw new Error("plugin not loaded");
+ const manifest = loaded.manifest;
+ if (!manifest.ui?.panel) throw new Error("plugin has no panel");
+ if (!(loaded.permissions.has("ui.panel"))) {
+ throw new Error("PERMISSION_DENIED: ui.panel");
+ }
+ const htmlPath = resolveInsidePluginRoot(loaded.path, manifest.ui.panel);
+ if (!htmlPath) throw new Error("plugin panel must stay inside the plugin");
+ const launch =
+ typeof request === "object" && request !== null
+ ? normalizeLauncherLaunch(request)
+ : undefined;
+ await pluginPanels.open({
+ pluginId,
+ title: resolvePluginLocalizedString(
+ manifest.ui.title,
+ getUpdaterLocale(),
+ manifest.name,
+ ),
+ locale: getUpdaterLocale(),
+ theme: getPluginPanelTheme(),
+ shape: manifest.ui.shape,
+ alwaysOnTop: manifest.ui.alwaysOnTop,
+ resizable: manifest.ui.resizable,
+ width: manifest.ui.width ?? 480,
+ height: manifest.ui.height ?? 360,
+ htmlPath,
+ ...(launch ? { launch } : {}),
+ });
+ return { ok: true };
+ },
+ );
/**
* Work panel views a plugin contributes (ADR 0104).
diff --git a/apps/desktop/electron/main/plugin-panel-host.ts b/apps/desktop/electron/main/plugin-panel-host.ts
index 6717dee11..2597c005f 100644
--- a/apps/desktop/electron/main/plugin-panel-host.ts
+++ b/apps/desktop/electron/main/plugin-panel-host.ts
@@ -19,6 +19,7 @@ import {
PLUGIN_PANEL_WINDOW_CONTROL_CHANNEL,
PLUGIN_PANEL_WINDOW_STATE_CHANNEL,
PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX,
+ PLUGIN_PANEL_LAUNCH_EVENT,
type PluginPanelTheme,
type PluginPanelWindowControlAction,
} from "../shared/plugin-panel-chrome";
@@ -59,6 +60,13 @@ export type PluginPanelOpenRequest = {
allowMicrophone?: boolean;
/** Adds a development-only reminder for the non-clickable drag band. */
development?: boolean;
+ /**
+ * Input that summoned this panel from the launcher (issue #2085). Delivered
+ * after the page loads and readable once through
+ * `pluginBridge.consumeLauncherPayload()`; the page never receives a payload
+ * the user did not type for it.
+ */
+ launch?: { triggerId: string; payload: string };
};
/**
@@ -460,6 +468,7 @@ export class PluginPanelHost {
if (existing.isMinimized()) existing.restore();
existing.show();
existing.focus();
+ this.deliverLaunch(request, existing);
return;
}
}
@@ -566,6 +575,7 @@ export class PluginPanelHost {
request.pluginId,
);
if (!win.isDestroyed()) {
+ this.deliverLaunch(request, win);
win.show();
}
} catch (error) {
@@ -623,6 +633,7 @@ export class PluginPanelHost {
* the host sends on that channel. Panels that do not subscribe are inert
* receivers; the event names are fixed by the host (e.g. `appearance:changed`).
*/
+
broadcast(event: string, payload: unknown): void {
const channel = `pi-plugin-panel-event:${event}`;
for (const win of this.windows.values()) {
@@ -634,4 +645,30 @@ export class PluginPanelHost {
}
}
}
+
+ /**
+ * Hand a launcher payload to one panel, once per open.
+ *
+ * The page reads it through `pluginBridge.consumeLauncherPayload()`, whose
+ * first call wins and returns null afterwards. An open without a payload
+ * sends nothing, so a plugin cannot read input the user typed for another
+ * time or for another plugin (docs/spec/07-plugins/17-plugin-launcher.md §5).
+ */
+ private deliverLaunch(
+ request: PluginPanelOpenRequest,
+ win: BrowserWindow,
+ ): void {
+ if (!request.launch || win.isDestroyed() || win.webContents.isDestroyed()) {
+ return;
+ }
+ try {
+ win.webContents.send(
+ `pi-plugin-panel-event:${PLUGIN_PANEL_LAUNCH_EVENT}`,
+ request.launch,
+ );
+ } catch {
+ // A payload that cannot be delivered leaves the panel open and empty
+ // rather than failing the open the user already committed to.
+ }
+ }
}
diff --git a/apps/desktop/electron/preload/plugin-panel.ts b/apps/desktop/electron/preload/plugin-panel.ts
index b372b419a..a7cd53f28 100644
--- a/apps/desktop/electron/preload/plugin-panel.ts
+++ b/apps/desktop/electron/preload/plugin-panel.ts
@@ -6,6 +6,7 @@ import {
PLUGIN_PANEL_CHROME_PAINT_THROUGH_VERSION,
PLUGIN_PANEL_EMBEDDED_ARGUMENT,
PLUGIN_PANEL_WIDGET_ARGUMENT,
+ PLUGIN_PANEL_LAUNCH_EVENT,
PLUGIN_PANEL_LOCALE_ARGUMENT_PREFIX,
PLUGIN_PANEL_WINDOW_CONTROL_CHANNEL,
PLUGIN_PANEL_WINDOW_STATE_CHANNEL,
@@ -16,6 +17,28 @@ import {
// built-in window palette from the same table main and the panel host use.
import { builtinWindowBackground } from "@pi-desktop/shared/theme";
+/**
+ * The launcher hands a panel the input that summoned it only after the page has
+ * loaded, so the event cannot race the document. Stashing it here lets the page
+ * ask for it whenever its own bootstrap is ready; `consumeLauncherPayload` then
+ * clears the stash so one typed input is delivered exactly once.
+ */
+let launcherPayload: { triggerId: string; payload: string } | null = null;
+ipcRenderer.on(`pi-plugin-panel-event:${PLUGIN_PANEL_LAUNCH_EVENT}`, (
+ _event,
+ incoming: { triggerId?: unknown; payload?: unknown },
+) => {
+ if (
+ typeof incoming?.triggerId !== "string" ||
+ typeof incoming?.payload !== "string"
+ ) {
+ return;
+ }
+ launcherPayload = {
+ triggerId: incoming.triggerId,
+ payload: incoming.payload,
+ };
+});
const bridge = {
invoke: async (channel: string, payload?: Record<string, unknown>) => {
return ipcRenderer.invoke("pi-plugin-panel-invoke", channel, payload ?? {});
@@ -29,6 +52,17 @@ const bridge = {
ipcRenderer.on(`pi-plugin-panel-event:${event}`, wrapped);
return () => ipcRenderer.removeListener(`pi-plugin-panel-event:${event}`, wrapped);
},
+ /**
+ * The launcher input that summoned this panel, or null.
+ *
+ * Reading it clears it, so a panel cannot read input the user typed for
+ * another time or for another plugin.
+ */
+ consumeLauncherPayload: (): { triggerId: string; payload: string } | null => {
+ const current = launcherPayload;
+ launcherPayload = null;
+ return current;
+ },
/** Resolve a real dropped File without exposing Node or Electron to the page. */
getDroppedFilePath: (file: File): string | null => {
try {
diff --git a/apps/desktop/electron/shared/plugin-panel-chrome.ts b/apps/desktop/electron/shared/plugin-panel-chrome.ts
index a682a9fc7..f4ec89468 100644
--- a/apps/desktop/electron/shared/plugin-panel-chrome.ts
+++ b/apps/desktop/electron/shared/plugin-panel-chrome.ts
@@ -59,6 +59,16 @@ export const PLUGIN_PANEL_EMBEDDED_ARGUMENT = "--pi-plugin-panel-embedded=1";
*/
export const PLUGIN_PANEL_WIDGET_ARGUMENT = "--pi-plugin-panel-widget=1";
+/**
+ * Event name the launcher uses to hand a plugin the input that summoned it.
+ *
+ * The payload arrives after the panel page has loaded, so it cannot race the
+ * document; `pluginBridge.consumeLauncherPayload()` reads it exactly once, which
+ * is what keeps one typed input from being delivered twice or kept available for
+ * a later time the user did not type it.
+ */
+export const PLUGIN_PANEL_LAUNCH_EVENT = "launcher:payload";
+
/**
* Smallest surface each placement may ask for. A panel is sized around
* plugin-drawn content; a widget draws its own silhouette — a floating orb —
diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rs
index 5f54ae329..2e76cfbfe 100644
--- a/crates/host-core/src/plugins/tests.rs
+++ b/crates/host-core/src/plugins/tests.rs
@@ -2053,6 +2053,182 @@ fn global_shortcut_entries_are_validated() {
.contains("contributes.globalShortcuts entry must be an object"));
}
+#[test]
+fn launcher_triggers_are_accepted_and_preserved() {
+ let dir = tempdir().unwrap();
+ let root = dir.path().join("launcher-triggers");
+ let triggers = json!([
+ {
+ "id": "calculator",
+ "pattern": "^[0-9+\\-*/(). ]+$",
+ "title": { "en": "Calculator", "zh-CN": "计算器" }
+ },
+ {
+ "id": "kilometres",
+ "pattern": "^\\d+\\s*km$",
+ "flags": "iu",
+ "title": "Kilometres"
+ },
+ { "id": "handles", "pattern": "^@\\w+$" }
+ ]);
+ write_plugin(
+ &root,
+ capability_manifest(json!({ "launcherTriggers": triggers }), json!(["ui.panel"])),
+ &[],
+ );
+ let manifest = PluginManager::read_manifest(&root).unwrap();
+ let contributes = manifest.contributes.as_ref().expect("contributes parsed");
+ assert_eq!(contributes["launcherTriggers"], triggers);
+
+ // An empty list activates nothing, so it needs no permission.
+ let empty = dir.path().join("launcher-triggers-empty");
+ write_plugin(
+ &empty,
+ capability_manifest(json!({ "launcherTriggers": [] }), json!([])),
+ &[],
+ );
+ PluginManager::read_manifest(&empty).unwrap();
+}
+
+#[test]
+fn launcher_triggers_require_the_ui_panel_permission() {
+ let dir = tempdir().unwrap();
+ let root = dir.path().join("launcher-triggers-no-permission");
+ write_plugin(
+ &root,
+ capability_manifest(
+ json!({ "launcherTriggers": [{ "id": "calc", "pattern": "^\\d+$" }] }),
+ json!(["ui.view"]),
+ ),
+ &[],
+ );
+ assert!(read_manifest_err(&root).contains("launcher triggers require the ui.panel permission"));
+}
+
+#[test]
+fn launcher_trigger_patterns_are_rejected_when_unsafe() {
+ let dir = tempdir().unwrap();
+ let cases: Vec<(&str, String)> = vec![
+ ("nested-quantifier", "(a+)+".to_string()),
+ ("nested-wildcard", "(.*)*".to_string()),
+ ("ambiguous-alternation", "(a|a)+".to_string()),
+ ("unbalanced-parens", "^(\\d+".to_string()),
+ ("unbalanced-brackets", "^[0-9+$".to_string()),
+ ("empty", " ".to_string()),
+ ("over-long", format!("^{}$", "9".repeat(200))),
+ ];
+ for (name, pattern) in cases {
+ let root = dir.path().join(name);
+ write_plugin(
+ &root,
+ capability_manifest(
+ json!({ "launcherTriggers": [{ "id": "calc", "pattern": pattern }] }),
+ json!(["ui.panel"]),
+ ),
+ &[],
+ );
+ let error = read_manifest_err(&root);
+ assert!(
+ error.contains("launcher trigger calc pattern"),
+ "{name} should be rejected, got: {error}"
+ );
+ }
+}
+
+#[test]
+fn launcher_trigger_ids_and_flags_are_validated() {
+ let dir = tempdir().unwrap();
+
+ let duplicate = dir.path().join("launcher-triggers-duplicate");
+ write_plugin(
+ &duplicate,
+ capability_manifest(
+ json!({
+ "launcherTriggers": [
+ { "id": "calc", "pattern": "^\\d+$" },
+ { "id": "calc", "pattern": "^[0-9]+$" }
+ ]
+ }),
+ json!(["ui.panel"]),
+ ),
+ &[],
+ );
+ assert!(read_manifest_err(&duplicate).contains("duplicate launcher trigger id calc"));
+
+ let bad_id = dir.path().join("launcher-triggers-bad-id");
+ write_plugin(
+ &bad_id,
+ capability_manifest(
+ json!({ "launcherTriggers": [{ "id": "1calc", "pattern": "^\\d+$" }] }),
+ json!(["ui.panel"]),
+ ),
+ &[],
+ );
+ assert!(read_manifest_err(&bad_id).contains("launcher trigger id is missing or invalid"));
+
+ for (name, flags) in [
+ ("unknown", json!("x")),
+ ("duplicate", json!("ii")),
+ ("too-many", json!("ismuu")),
+ ("not-a-string", json!(42)),
+ ] {
+ let root = dir.path().join(format!("launcher-triggers-flags-{name}"));
+ write_plugin(
+ &root,
+ capability_manifest(
+ json!({ "launcherTriggers": [{ "id": "calc", "pattern": "^\\d+$", "flags": flags }] }),
+ json!(["ui.panel"]),
+ ),
+ &[],
+ );
+ let error = read_manifest_err(&root);
+ assert!(
+ error.contains("launcher trigger calc flags is invalid"),
+ "{name} flags should be rejected, got: {error}"
+ );
+ }
+}
+
+#[test]
+fn launcher_trigger_entries_are_capped_and_must_be_an_array() {
+ let dir = tempdir().unwrap();
+
+ let too_many = dir.path().join("launcher-triggers-too-many");
+ write_plugin(
+ &too_many,
+ capability_manifest(
+ json!({
+ "launcherTriggers": (0..9)
+ .map(|index| json!({ "id": format!("slot{index}"), "pattern": "^\\d+$" }))
+ .collect::<Vec<_>>()
+ }),
+ json!(["ui.panel"]),
+ ),
+ &[],
+ );
+ assert!(read_manifest_err(&too_many)
+ .contains("contributes.launcherTriggers allows at most 8 entries"));
+
+ let not_an_array = dir.path().join("launcher-triggers-not-an-array");
+ write_plugin(
+ &not_an_array,
+ capability_manifest(json!({ "launcherTriggers": "^\\d+$" }), json!(["ui.panel"])),
+ &[],
+ );
+ assert!(
+ read_manifest_err(&not_an_array).contains("contributes.launcherTriggers must be an array")
+ );
+
+ let not_an_object = dir.path().join("launcher-triggers-not-an-object");
+ write_plugin(
+ &not_an_object,
+ capability_manifest(json!({ "launcherTriggers": ["calc"] }), json!(["ui.panel"])),
+ &[],
+ );
+ assert!(read_manifest_err(&not_an_object)
+ .contains("contributes.launcherTriggers entry must be an object"));
+}
+
#[test]
fn composer_transforms_require_permission_and_localized_titles() {
let dir = tempdir().unwrap();
diff --git a/crates/host-core/src/plugins/validation.rs b/crates/host-core/src/plugins/validation.rs
index d01b01c88..df80519c9 100644
--- a/crates/host-core/src/plugins/validation.rs
+++ b/crates/host-core/src/plugins/validation.rs
@@ -1,6 +1,7 @@
use super::*;
mod composer_transforms;
mod contribution_ids;
+mod launcher_triggers;
mod provider_catalog;
use contribution_ids::is_contrib_id;
@@ -175,6 +176,7 @@ pub(crate) fn validate_contributions(root: &Path, manifest: &PluginManifest) ->
}
}
}
+ launcher_triggers::validate(map, manifest)?;
composer_transforms::validate(map, manifest)?;
if let Some(skills) = map.get("skills") {
let entries = array_of(skills, "contributes.skills")?;
diff --git a/crates/host-core/src/plugins/validation/composer_transforms.rs b/crates/host-core/src/plugins/validation/composer_transforms.rs
index dcfa10e43..df38bcaf2 100644
--- a/crates/host-core/src/plugins/validation/composer_transforms.rs
+++ b/crates/host-core/src/plugins/validation/composer_transforms.rs
@@ -44,7 +44,7 @@ pub(super) fn validate(map: &Map<String, Value>, manifest: &PluginManifest) -> R
}
/// Composer labels accept either a plain string or both contract locales.
-fn is_plugin_label(value: &Value) -> bool {
+pub(super) fn is_plugin_label(value: &Value) -> bool {
if value.as_str().is_some_and(|label| !label.trim().is_empty()) {
return true;
}
diff --git a/crates/host-core/src/plugins/validation/launcher_triggers.rs b/crates/host-core/src/plugins/validation/launcher_triggers.rs
new file mode 100644
index 000000000..7e34f4f88
--- /dev/null
+++ b/crates/host-core/src/plugins/validation/launcher_triggers.rs
@@ -0,0 +1,247 @@
+use anyhow::{anyhow, bail, Result};
+use serde_json::{Map, Value};
+
+use super::composer_transforms::is_plugin_label;
+use super::{array_of, is_contrib_id, require_permission, PluginManifest};
+
+/// Mirrors `contributes.launcherTriggers` in the plugin SDK: at most eight
+/// triggers per plugin, a 200-character pattern, a 120-character label and the
+/// `i` / `s` / `m` / `u` flags the renderer accepts.
+const MAX_LAUNCHER_TRIGGERS_PER_PLUGIN: usize = 8;
+const LAUNCHER_PATTERN_MAX_CHARS: usize = 200;
+const LAUNCHER_TITLE_MAX_CHARS: usize = 120;
+const LAUNCHER_TRIGGER_FLAGS: [char; 4] = ['i', 's', 'm', 'u'];
+
+pub(super) fn validate(map: &Map<String, Value>, manifest: &PluginManifest) -> Result<()> {
+ let Some(triggers) = map.get("launcherTriggers") else {
+ return Ok(());
+ };
+ let entries = array_of(triggers, "contributes.launcherTriggers")?;
+ if entries.len() > MAX_LAUNCHER_TRIGGERS_PER_PLUGIN {
+ bail!("PLUGIN_INVALID: contributes.launcherTriggers allows at most 8 entries");
+ }
+ // A trigger opens this plugin's panel, so a declaration without `ui.panel`
+ // would be a match the launcher could never act on.
+ if !entries.is_empty() {
+ require_permission(manifest, "ui.panel", "launcher triggers")?;
+ }
+
+ let mut seen: Vec<&str> = Vec::new();
+ for entry in entries {
+ let obj = entry.as_object().ok_or_else(|| {
+ anyhow!("PLUGIN_INVALID: contributes.launcherTriggers entry must be an object")
+ })?;
+ let id = obj
+ .get("id")
+ .and_then(Value::as_str)
+ .filter(|id| is_contrib_id(id))
+ .ok_or_else(|| anyhow!("PLUGIN_INVALID: launcher trigger id is missing or invalid"))?;
+ if seen.contains(&id) {
+ bail!("PLUGIN_INVALID: duplicate launcher trigger id {id}");
+ }
+ seen.push(id);
+ let pattern = obj
+ .get("pattern")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("PLUGIN_INVALID: launcher trigger {id} requires a pattern"))?;
+ if let Some(problem) = pattern_problem(pattern) {
+ bail!("PLUGIN_INVALID: launcher trigger {id} pattern {problem}");
+ }
+ if let Some(flags) = obj.get("flags") {
+ let flags = flags
+ .as_str()
+ .ok_or_else(|| anyhow!("PLUGIN_INVALID: launcher trigger {id} flags is invalid"))?;
+ if !is_trigger_flags(flags) {
+ bail!("PLUGIN_INVALID: launcher trigger {id} flags is invalid");
+ }
+ }
+ if let Some(title) = obj.get("title") {
+ if !is_trigger_title(title) {
+ bail!("PLUGIN_INVALID: launcher trigger {id} has an invalid title");
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Why a declared trigger pattern is refused, or `None` when it is safe.
+///
+/// The renderer compiles the pattern and runs it against every keystroke, so a
+/// pattern that can backtrack catastrophically would freeze the panel. The scan
+/// is deliberately conservative: it refuses a quantifier applied to a group
+/// whose body already contains a quantifier or an alternation, because branch
+/// ambiguity inside a repeated group is what produces exponential
+/// backtracking. The host does not compile the pattern — Rust `regex` syntax
+/// and JavaScript syntax differ, and all that is needed here is a proof that
+/// the declaration cannot blow up.
+fn pattern_problem(pattern: &str) -> Option<&'static str> {
+ let trimmed = pattern.trim();
+ if trimmed.is_empty() {
+ return Some("is empty");
+ }
+ if trimmed.chars().count() > LAUNCHER_PATTERN_MAX_CHARS {
+ return Some("is longer than 200 characters");
+ }
+
+ let chars: Vec<char> = pattern.chars().collect();
+ // One flag per open group: does the body already contain a quantifier or an
+ // alternation? A group that does may not itself be repeated. The bottom
+ // frame is the whole pattern, which nothing quantifies.
+ let mut open_groups: Vec<bool> = vec![false];
+ let mut in_class = false;
+ let mut index = 0;
+ while index < chars.len() {
+ let ch = chars[index];
+ if ch == '\\' {
+ if index + 1 >= chars.len() {
+ return Some("ends with a dangling escape");
+ }
+ // An escaped bracket, parenthesis or quantifier is a literal atom.
+ index += 2;
+ continue;
+ }
+ if in_class {
+ if ch == ']' {
+ in_class = false;
+ }
+ index += 1;
+ continue;
+ }
+ match ch {
+ '[' => {
+ in_class = true;
+ index += 1;
+ }
+ '(' => {
+ open_groups.push(false);
+ index += 1;
+ // `(?:`, `(?=` and `(?<name>` use `?` as a group modifier, not
+ // as a quantifier over the open group.
+ if chars.get(index) == Some(&'?') {
+ index += 1;
+ }
+ }
+ ')' => {
+ if open_groups.len() == 1 {
+ return Some("has unbalanced parentheses");
+ }
+ let body_risky = open_groups.pop().unwrap_or(false);
+ index += 1;
+ // The quantifier itself is handled on the next pass and marks
+ // the enclosing frame.
+ if quantifier_at(&chars, index) && body_risky {
+ return Some(
+ "nests a quantifier in a repeated group, which can backtrack catastrophically",
+ );
+ }
+ }
+ '*' | '+' => {
+ mark_risky(&mut open_groups);
+ index += 1;
+ }
+ '?' => {
+ // A `?` right after a quantifier is its lazy modifier, not a
+ // second quantifier.
+ let lazy = index > 0 && matches!(chars[index - 1], '*' | '+' | '?' | '}');
+ if !lazy {
+ mark_risky(&mut open_groups);
+ }
+ index += 1;
+ }
+ '{' => match brace_quantifier_end(&chars, index) {
+ Some(end) => {
+ mark_risky(&mut open_groups);
+ index = end;
+ }
+ None => index += 1,
+ },
+ '|' => {
+ // Any alternation inside a group makes that group ambiguous, and
+ // the scan cannot prove the branches are disjoint.
+ mark_risky(&mut open_groups);
+ index += 1;
+ }
+ _ => index += 1,
+ }
+ }
+ if in_class {
+ return Some("has unbalanced brackets");
+ }
+ if open_groups.len() > 1 {
+ return Some("has unbalanced parentheses");
+ }
+ None
+}
+
+fn mark_risky(open_groups: &mut [bool]) {
+ if let Some(frame) = open_groups.last_mut() {
+ *frame = true;
+ }
+}
+
+/// Whether a quantifier starts at `index`: `*`, `+`, `?` or `{n}` / `{n,}` /
+/// `{n,m}`. A bare `{` is a literal in JavaScript, so it is not a quantifier.
+fn quantifier_at(chars: &[char], index: usize) -> bool {
+ match chars.get(index) {
+ Some('*') | Some('+') | Some('?') => true,
+ Some('{') => brace_quantifier_end(chars, index).is_some(),
+ _ => false,
+ }
+}
+
+/// End index (exclusive) of a brace quantifier starting at `index`.
+fn brace_quantifier_end(chars: &[char], index: usize) -> Option<usize> {
+ let mut cursor = index + 1;
+ let mut digits = 0;
+ while matches!(chars.get(cursor), Some(ch) if ch.is_ascii_digit()) {
+ cursor += 1;
+ digits += 1;
+ }
+ if digits == 0 {
+ return None;
+ }
+ if chars.get(cursor) == Some(&',') {
+ cursor += 1;
+ while matches!(chars.get(cursor), Some(ch) if ch.is_ascii_digit()) {
+ cursor += 1;
+ }
+ }
+ (chars.get(cursor) == Some(&'}')).then_some(cursor + 1)
+}
+
+fn is_trigger_flags(flags: &str) -> bool {
+ if flags.chars().count() > LAUNCHER_TRIGGER_FLAGS.len() {
+ return false;
+ }
+ let mut seen: Vec<char> = Vec::new();
+ for flag in flags.chars() {
+ if !LAUNCHER_TRIGGER_FLAGS.contains(&flag) || seen.contains(&flag) {
+ return false;
+ }
+ seen.push(flag);
+ }
+ true
+}
+
+/// A title is a plain string or both contract locales, as elsewhere in the
+/// manifest, and the launcher keeps its labels shorter than the composer's.
+fn is_trigger_title(value: &Value) -> bool {
+ match value {
+ Value::String(title) => fits_launcher_label(title),
+ Value::Object(_) => {
+ is_plugin_label(value)
+ && ["en", "zh-CN"].iter().all(|locale| {
+ value
+ .get(*locale)
+ .and_then(Value::as_str)
+ .is_some_and(fits_launcher_label)
+ })
+ }
+ _ => false,
+ }
+}
+
+fn fits_launcher_label(label: &str) -> bool {
+ let trimmed = label.trim();
+ !trimmed.is_empty() && trimmed.chars().count() <= LAUNCHER_TITLE_MAX_CHARS
+}
diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts
index 7953545f1..309ed8be8 100644
--- a/packages/plugin-sdk/src/index.test.ts
+++ b/packages/plugin-sdk/src/index.test.ts
@@ -14,6 +14,7 @@ import {
PLUGIN_PERMISSIONS,
PLUGIN_VIEW_ICONS,
type PluginProviderContrib,
+ type PluginManifest,
} from "./index.js";
const base = { schemaVersion: 1, id: "demo.x", name: "X", version: "0.1.0", main: "main.js" };
@@ -649,6 +650,25 @@ describe("contributes.globalShortcuts", () => {
});
});
+describe("contributes.launcherTriggers", () => {
+ it("types a declared trigger and keeps it on the parsed manifest", () => {
+ const contributes: NonNullable<PluginManifest["contributes"]> = {
+ launcherTriggers: [
+ {
+ id: "calculator",
+ pattern: "^[0-9+\\-*/(). ]+$",
+ title: { en: "Calculator", "zh-CN": "计算器" },
+ },
+ { id: "kilometres", pattern: "^\\d+\\s*km$", flags: "iu", title: "Kilometres" },
+ ],
+ };
+ expect(validateContributions(contributes)).toBeUndefined();
+ const result = validateManifest({ ...base, permissions: ["ui.panel"], contributes });
+ expect(result.ok).toBe(true);
+ expect(result.manifest?.contributes?.launcherTriggers).toEqual(contributes.launcherTriggers);
+ });
+});
+
describe("PLUGIN_PERMISSIONS", () => {
it("declares the capability permissions and stays unique", () => {
for (const permission of [
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 1d70c45a9..ad9ad8c4e 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -185,6 +185,20 @@ export type PluginManifest = {
globalShortcuts?: PluginGlobalShortcutContrib[];
/** User-invoked text actions beside the Composer controls. */
composerTransforms?: PluginComposerTransformContrib[];
+ /**
+ * Launcher triggers: the plugin claims launcher input that matches its
+ * pattern. Each `pattern` is matched against the *whole* trimmed launcher
+ * input, so a character class never competes with a one-character query;
+ * patterns that could backtrack catastrophically are refused at manifest
+ * load. Requires the `ui.panel` permission, because a match opens this
+ * plugin's panel.
+ */
+ launcherTriggers?: Array<{
+ id: string;
+ pattern: string;
+ flags?: string;
+ title?: string | { en: string; "zh-CN": string };
+ }>;
};
permissions?: string[];
/**