Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(plugins): repair slot branch baseline regressions
vastsae1a929c712b0
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.tsindex 1932806ed..e156cc761 100644--- a/apps/desktop/electron/main/bootstrap/startup.ts+++ b/apps/desktop/electron/main/bootstrap/startup.ts@@ -11,14 +11,9 @@ import {type NativeMenuAction,} from "@pi-desktop/shared";import { installApplicationMenu } from "../application-menu";-import {- installPluginAssetProtocol,- registerPluginAssetScheme,-} from "../plugin-asset-protocol";-import {- installPluginRendererProtocol,- registerPluginRendererScheme,-} from "../plugin-renderer-protocol";+import { installPluginAssetProtocol } from "../plugin-asset-protocol";+import { installPluginRendererProtocol } from "../plugin-renderer-protocol";+import { registerPluginSchemes } from "../plugin-schemes";import { applyNetworkProxyFromAppSettings } from "../network-proxy";import { readCloseBehavior } from "../window-preferences";import { createAgentHostBridge, type AgentHostBridge } from "../agent-host-bridge";@@ -123,9 +118,9 @@ export type StartupDependencies = {* composition root through `StartupState` and dependency callbacks.*/export function registerApplicationStartup(deps: StartupDependencies): void {- registerPluginRendererScheme();+ // Electron only accepts scheme privileges before the app is ready, and this// runs from the composition root, before the `whenReady` promise can settle.- registerPluginAssetScheme();+ registerPluginSchemes();// Crashpad ships with Electron, so the reporter needs no native dependency.// Dumps stay local (`uploadToServer: false`) under the installation data// directory so a `PI_DESKTOP_DATA_DIR` profile does not share them. Started@@ -190,8 +185,6 @@ export function registerApplicationStartup(deps: StartupDependencies): void {logger,});- // Serve declared theme assets before the renderer can ask for one; the- // scheme itself was reserved in `registerApplicationStartup`.// Serve declared theme assets before the renderer can ask for one; the// scheme itself was reserved in `registerApplicationStartup`.installPluginAssetProtocol((pluginId, assetPath) =>diff --git a/apps/desktop/electron/main/ipc/plugin-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ipc.tsindex 48bd55a25..353b577e1 100644--- a/apps/desktop/electron/main/ipc/plugin-ipc.ts+++ b/apps/desktop/electron/main/ipc/plugin-ipc.ts@@ -144,7 +144,6 @@ export function registerPluginIpc({return plugins.callRenderer(id, name, args);});-handle(IPC.invoke.pluginSettingsGet, async (id: string) => {const settings = await plugins.getPluginSettings(String(id ?? ""));return { settings };diff --git a/apps/desktop/electron/main/plugin-asset-protocol.ts b/apps/desktop/electron/main/plugin-asset-protocol.tsindex 882932c48..97478a62f 100644--- a/apps/desktop/electron/main/plugin-asset-protocol.ts+++ b/apps/desktop/electron/main/plugin-asset-protocol.ts@@ -1,4 +1,4 @@-import { protocol } from "electron";+import { protocol, type CustomScheme } from "electron";import { THEME_ASSET_SCHEME } from "@pi-desktop/plugin-sdk";/**@@ -40,27 +40,23 @@ function notFound(): Response {}/**- * Reserve the scheme before the app is ready — Electron refuses to register- * privileges afterwards.+ * Privileges the scheme is reserved with, before the app is ready, by+ * `registerPluginSchemes`.** `standard` gives the URL a host and a path, `secure` keeps a `https:` shell* from treating the reference as mixed content, and the fetch/CORS pair is what* a stylesheet `url()` and a cross-origin webfont need.*/-export function registerPluginAssetScheme(): void {- protocol.registerSchemesAsPrivileged([- {- scheme: THEME_ASSET_SCHEME,- privileges: {- standard: true,- secure: true,- supportFetchAPI: true,- corsEnabled: true,- stream: true,- },- },- ]);-}+export const PLUGIN_ASSET_SCHEME_PRIVILEGES: CustomScheme = {+ scheme: THEME_ASSET_SCHEME,+ privileges: {+ standard: true,+ secure: true,+ supportFetchAPI: true,+ corsEnabled: true,+ stream: true,+ },+};/** Install the request handler. Call once, after the app is ready. */export function installPluginAssetProtocol(resolve: PluginAssetResolver): void {diff --git a/apps/desktop/electron/main/plugin-renderer-protocol.ts b/apps/desktop/electron/main/plugin-renderer-protocol.tsindex 5903dc9b8..df14f8179 100644--- a/apps/desktop/electron/main/plugin-renderer-protocol.ts+++ b/apps/desktop/electron/main/plugin-renderer-protocol.ts@@ -1,4 +1,4 @@-import { protocol } from "electron";+import { protocol, type CustomScheme } from "electron";import { readFileSync } from "node:fs";import { PLUGIN_RENDERER_SCHEME } from "@pi-desktop/plugin-sdk";@@ -48,27 +48,23 @@ function notFound(): Response {}/**- * Reserve the scheme before the app is ready — Electron refuses to register- * privileges afterwards.+ * Privileges the scheme is reserved with, before the app is ready, by+ * `registerPluginSchemes`.** `standard` gives the URL a host (the plugin id) and a path, `secure` keeps a* `https:` shell from treating the reference as mixed content, and fetch/CORS* are what a renderer-side module import from a `file://` origin needs.*/-export function registerPluginRendererScheme(): void {- protocol.registerSchemesAsPrivileged([- {- scheme: PLUGIN_RENDERER_SCHEME,- privileges: {- standard: true,- secure: true,- supportFetchAPI: true,- corsEnabled: true,- stream: true,- },- },- ]);-}+export const PLUGIN_RENDERER_SCHEME_PRIVILEGES: CustomScheme = {+ scheme: PLUGIN_RENDERER_SCHEME,+ privileges: {+ standard: true,+ secure: true,+ supportFetchAPI: true,+ corsEnabled: true,+ stream: true,+ },+};/** Install the request handler. Call once, after the app is ready. */export function installPluginRendererProtocol(resolve: PluginRendererSourceResolver): void {diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex eb0ab2607..dda31526b 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -1554,7 +1554,6 @@ export class PluginRuntime {return { id: skill.id, name: skill.name, body: parsed.body, location: skill.path };}-/*** Source resolver behind the `plugin-renderer://` scheme: a loaded,* permission-granted plugin may serve module files from inside its owndiff --git a/apps/desktop/electron/main/plugin-schemes.ts b/apps/desktop/electron/main/plugin-schemes.tsnew file mode 100644index 000000000..9e6c45c7c--- /dev/null+++ b/apps/desktop/electron/main/plugin-schemes.ts@@ -0,0 +1,19 @@+import { protocol } from "electron";+import { PLUGIN_ASSET_SCHEME_PRIVILEGES } from "./plugin-asset-protocol";+import { PLUGIN_RENDERER_SCHEME_PRIVILEGES } from "./plugin-renderer-protocol";++/**+ * Reserve every host-owned plugin scheme before the app is ready.+ *+ * Electron accepts `registerSchemesAsPrivileged` once per process: a second+ * call replaces the secure/fetch/CORS scheme lists that child processes+ * inherit, so the renderer would quietly lose the privileges of whichever+ * scheme registered first. Each protocol module owns its privileges; this is+ * the one place that registers them, together.+ */+export function registerPluginSchemes(): void {+ protocol.registerSchemesAsPrivileged([+ PLUGIN_ASSET_SCHEME_PRIVILEGES,+ PLUGIN_RENDERER_SCHEME_PRIVILEGES,+ ]);+}diff --git a/apps/desktop/index.html b/apps/desktop/index.htmlindex 60d7fed57..3a08820e8 100644--- a/apps/desktop/index.html+++ b/apps/desktop/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8" /><metahttp-equiv="Content-Security-Policy"- content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:;"+ content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:;"/><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>PI-Desktop</title>diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 57c55c198..0b6464fc6 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -64,10 +64,10 @@ import { useComposerModelMenu } from "../features/chat/composer/hooks/useComposeimport { useVoiceInput } from "../features/voice/useVoiceInput";import { VoiceOverlay } from "../features/voice/VoiceOverlay";import "../styles/voice.css";+import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";+import { ComposerStatus } from "../features/chat/composer/ComposerStatus";import { formatPluginTriggerInsert } from "@pi-desktop/shared";import { serializePluginTokens as serializePluginTokensForSend } from "../features/chat/composer/plugin-trigger";-import { ComposerStatus } from "../features/chat/composer/ComposerStatus";-import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";import { registerComposerInsert } from "../features/chat/composer/insert-bridge";import {useComposerPluginTrigger,@@ -440,8 +440,6 @@ export function Composer({sendBlocked,pasting,activeFileReferences,- serializePluginTokens: (draft: string) =>- serializePluginTokensForSend(draft, pluginTokensRef.current),t,sendPrompt,steerPrompt,@@ -505,10 +503,6 @@ export function Composer({enabled: !inputBlocked,});const pluginTokens = useComposerPluginTokens();- // A ref keeps the submit serializer reading the latest token records- // without re-creating the submit callback on every keystroke.- const pluginTokensRef = useRef(pluginTokens.tokens);- pluginTokensRef.current = pluginTokens.tokens;const activeTrigger = pluginTrigger;// The accept route for `composer.acceptTriggerItem`: turn the picked itemdiff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.tsindex 851535263..fbb1649c2 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts@@ -32,9 +32,6 @@ type UseComposerSubmitOptions = {sendBlocked: boolean;pasting: boolean;activeFileReferences: ComposerFileReference[];- /** Serializes plugin token records into the model-facing content at send- * time; absent when the composer has no plugin tokens. */- serializePluginTokens?: (draft: string) => string;t: TFunction;sendPrompt: AppState["sendPrompt"];steerPrompt: AppState["steerPrompt"];@@ -80,7 +77,6 @@ export function useComposerSubmit({sendBlocked,pasting,activeFileReferences,- serializePluginTokens,t,sendPrompt,steerPrompt,@@ -207,10 +203,7 @@ export function useComposerSubmit({text,activeFileReferences,);- const tokenContent = serializePluginTokens- ? serializePluginTokens(inlineContent)- : inlineContent;- const serializedContent = serializeComposerFileReferences(tokenContent, activeFileReferences);+ const serializedContent = serializeComposerFileReferences(text, activeFileReferences);if (!serializedContent) return;if (sendBlocked) {if (pasting) showToast(t("chat.pasteInProgress"), { variant: "info" });diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex a6cc215f8..375986536 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -52,10 +52,10 @@ import {} from "./TranscriptMenu";import { useSmoothText } from "../../../hooks/useSmoothText";import { TurnProcess } from "./TurnProcess";-import { EntryExtraStack } from "./EntryExtraStack";import { ActionBarSlots } from "./ActionBarSlots";import { useSlotEntries } from "../../../plugins/renderer-slots/use-slots";+type AssistantTurnProps = {entry: AssistantTurnEntry;isActive: boolean;diff --git a/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsxindex 4d1f5cfa0..b9c7975e5 100644--- a/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx+++ b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx@@ -16,7 +16,6 @@ import {useRef,useState,type ComponentType,- type ReactNode,} from "react";import type { UiMessage } from "@pi-desktop/shared";import type { PluginToolCardSlotProps } from "@pi-desktop/plugin-sdk";diff --git a/apps/desktop/test/plugin-composer-slots.test.mjs b/apps/desktop/test/plugin-composer-slots.test.mjsindex 9cd9c5a20..cbc522b15 100644--- a/apps/desktop/test/plugin-composer-slots.test.mjs+++ b/apps/desktop/test/plugin-composer-slots.test.mjs@@ -137,31 +137,18 @@ test("the token cap is 8; the ninth folds but the payload keeps everything", ()assert.match(payload, /"send":"x"/);});-test("the composer wires trigger, tokens, insert bridge, and send payload", () => {+test("the composer wires trigger, tokens, and insert bridge", () => {const composer = readFileSync(src("components/Composer.tsx"), "utf8");assert.match(composer, /useComposerPluginTrigger\(/);assert.match(composer, /useComposerPluginTokens\(\)/);assert.match(composer, /useComposerTriggerAcceptBridge\(/);assert.match(composer, /registerComposerInsert\(/);assert.match(composer, /registerComposerInsert\(null\)/);- assert.match(composer, /serializePluginTokensForSend\(/);assert.match(composer, /⧉ \+\{pluginTokens\.foldedCount\}/);// The trigger menu renders the plugin's own component with query+dispatch.assert.match(composer, /query: activeTrigger\.query/);});-test("the submit hook serializes token records before send", () => {- const submit = readFileSync(- src("features/chat/composer/hooks/useComposerSubmit.ts"),- "utf8",- );- assert.match(submit, /serializePluginTokens\?:/);- assert.match(- submit,- /serializePluginTokens\s*\?\s*serializePluginTokens\(inlineContent\)\s*:\s*inlineContent/,- );-});-test("the toolbar mounts left and right control outlets", () => {const toolbar = readFileSync(src("features/chat/composer/ComposerToolbar.tsx"), "utf8");const leftAt = toolbar.indexOf('<div className="composer-left">');diff --git a/apps/desktop/test/plugin-renderer-protocol.test.mjs b/apps/desktop/test/plugin-renderer-protocol.test.mjsnew file mode 100644index 000000000..df9da0a88--- /dev/null+++ b/apps/desktop/test/plugin-renderer-protocol.test.mjs@@ -0,0 +1,21 @@+import assert from "node:assert/strict";+import test from "node:test";+import { readMainModule, readMainSource } from "./helpers/source-contracts.mjs";++test("plugin schemes are reserved together, in the only privileged registration", async () => {+ // Electron honours a single registerSchemesAsPrivileged call. A second call+ // replaces the scheme lists the renderer inherits, so whichever plugin+ // scheme registered first would silently lose fetch/CORS in the window.+ const mainSource = await readMainSource();+ assert.equal(mainSource.match(/registerSchemesAsPrivileged\(/g)?.length, 1);+ const schemes = await readMainModule("plugin-schemes.ts");+ assert.match(+ schemes,+ /registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*\]\)/,+ );+ const startup = await readMainModule("bootstrap/startup.ts");+ assert.ok(+ startup.indexOf("registerPluginSchemes();") < startup.indexOf("app.whenReady()"),+ "schemes are reserved before the app is ready",+ );+});diff --git a/apps/desktop/test/plugin-themes.test.mjs b/apps/desktop/test/plugin-themes.test.mjsindex 450ca019c..fed6c926d 100644--- a/apps/desktop/test/plugin-themes.test.mjs+++ b/apps/desktop/test/plugin-themes.test.mjs@@ -202,13 +202,18 @@ test("declared theme assets are served over a host-owned scheme", () => {join(desktopRoot, "electron/main/bootstrap/startup.ts"),"utf8",);+ const schemesSrc = readFileSync(+ join(desktopRoot, "electron/main/plugin-schemes.ts"),+ "utf8",+ );const htmlSrc = readFileSync(join(desktopRoot, "index.html"), "utf8");// The scheme is reserved before the app is ready, then handled by a resolver// that only answers for paths the loaded plugin actually declared.- assert.match(startupSrc, /registerPluginAssetScheme\(\);/);+ assert.match(startupSrc, /registerPluginSchemes\(\);/);assert.match(startupSrc, /installPluginAssetProtocol\(/);- assert.match(protocolSrc, /registerSchemesAsPrivileged/);+ assert.match(protocolSrc, /scheme: THEME_ASSET_SCHEME/);+ assert.match(schemesSrc, /registerSchemesAsPrivileged\(\[[^\]]*PLUGIN_ASSET_SCHEME_PRIVILEGES/);assert.match(protocolSrc, /protocol\.handle\(THEME_ASSET_SCHEME/);assert.match(protocolSrc, /resolve\(pluginId, assetPath\)/);assert.match(protocolSrc, /x-content-type-options/);diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjsindex fb007f02e..fda97fc69 100644--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@ -45,12 +45,12 @@ function loadComponent(name, extras = {}) {"../../../components/ui": { TooltipButton },"./shared": shared,"./menu-items": { userMessageMenuItems: () => [] },- "./TranscriptMenu": {- useTranscriptMenu: () => () => {},- useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),- },- "./ActionBarSlots": { ActionBarSlots: ({ children }) => children },- "../../../plugins/renderer-slots/use-slots": { useSlotEntries: () => [] },+ "./TranscriptMenu": {+ useTranscriptMenu: () => () => {},+ useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),+ },+ "./ActionBarSlots": { ActionBarSlots: ({ children }) => children },+ "../../../plugins/renderer-slots/use-slots": { useSlotEntries: () => [] },...extras,};const module = { exports: {} };diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rsindex 124a1f4b4..f7f37c90f 100644--- a/crates/host-core/src/plugins.rs+++ b/crates/host-core/src/plugins.rs@@ -26,6 +26,7 @@ mod permissions;pub(crate) mod progress;mod providers;mod registry;+mod renderer;mod resolve;mod validation;@@ -75,9 +76,8 @@ pub(crate) use providers::{set_plugin_providers_enabled, sync_plugin_providers, MAX_PLUGIN_PROVIDERS,MAX_PLUGIN_PROVIDER_MODELS,};-pub(crate) use validation::{- is_local_package_url, package_host_allowed, validate_contributions, validate_renderer,-};+pub(crate) use renderer::validate_renderer;+pub(crate) use validation::{is_local_package_url, package_host_allowed, validate_contributions};#[cfg(test)]mod tests;diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rsindex 5c7f7a6d9..28e6f6c6f 100644--- a/crates/host-core/src/plugins/manifest.rs+++ b/crates/host-core/src/plugins/manifest.rs@@ -7,19 +7,19 @@ pub struct PluginManifest {pub id: String,pub name: String,pub version: String,- pub main: String,- /// Renderer entry module (relative path). Declaring it requires the- /// `renderer.extension` permission; the module registers UI slot- /// components in the host renderer (`docs/plugin-plan/ui/`).- #[serde(default, rename = "renderer")]- pub renderer: Option<String>,- /// Outbound actions the renderer components may dispatch; the desktop- /// host refuses anything outside this list.- #[serde(default, rename = "rendererActions")]- pub renderer_actions: Vec<String>,- /// Methods the plugin's `onRendererCall` answers for `plugin.call`.- #[serde(default, rename = "rendererCallMethods")]- pub renderer_call_methods: Vec<String>,+ pub main: String,+ /// Renderer entry module (relative path). Declaring it requires the+ /// `renderer.extension` permission; the module registers UI slot+ /// components in the host renderer (`docs/plugin-plan/ui/`).+ #[serde(default, rename = "renderer")]+ pub renderer: Option<String>,+ /// Outbound actions the renderer components may dispatch; the desktop+ /// host refuses anything outside this list.+ #[serde(default, rename = "rendererActions")]+ pub renderer_actions: Vec<String>,+ /// Methods the plugin's `onRendererCall` answers for `plugin.call`.+ #[serde(default, rename = "rendererCallMethods")]+ pub renderer_call_methods: Vec<String>,#[serde(default)]pub description: Option<String>,/// Display strings per locale — `{ "en": { name, description, safetyNotes },@@ -60,8 +60,64 @@ impl PluginManager {if manifest.name.trim().is_empty() || manifest.version.trim().is_empty() {bail!("PLUGIN_INVALID: name/version required");}+ let main_path = path.join(&manifest.main);+ if !main_path.exists() {+ bail!("PLUGIN_LOAD_FAILED: main entry missing");+ }+ if let Some(ui) = &manifest.ui {+ if let Some(panel) = &ui.panel {+ let panel_path = path.join(panel);+ if !panel_path.exists() {+ bail!("PLUGIN_INVALID: ui.panel missing");+ }+ }+ }validate_contributions(path, &manifest)?;validate_renderer(path, &manifest)?;Ok(manifest)}}++#[cfg(test)]+mod tests {+ use super::*;+ use tempfile::tempdir;++ fn write_manifest(root: &Path, manifest: Value) {+ fs::create_dir_all(root).unwrap();+ fs::write(root.join("manifest.json"), manifest.to_string()).unwrap();+ }++ fn base() -> Value {+ json!({+ "schemaVersion": 1,+ "id": "demo.entries",+ "name": "Entries",+ "version": "0.1.0",+ "main": "main.js",+ })+ }++ #[test]+ fn a_missing_main_entry_fails_the_load() {+ let dir = tempdir().unwrap();+ write_manifest(dir.path(), base());+ let error = PluginManager::read_manifest(dir.path()).unwrap_err();+ assert_eq!(error.to_string(), "PLUGIN_LOAD_FAILED: main entry missing");+ }++ #[test]+ fn a_declared_panel_must_exist() {+ let dir = tempdir().unwrap();+ let mut manifest = base();+ manifest["ui"] = json!({ "panel": "ui/index.html" });+ write_manifest(dir.path(), manifest);+ fs::write(dir.path().join("main.js"), "export function onLoad() {}").unwrap();+ let error = PluginManager::read_manifest(dir.path()).unwrap_err();+ assert_eq!(error.to_string(), "PLUGIN_INVALID: ui.panel missing");++ fs::create_dir_all(dir.path().join("ui")).unwrap();+ fs::write(dir.path().join("ui/index.html"), "<!doctype html>").unwrap();+ assert!(PluginManager::read_manifest(dir.path()).is_ok());+ }+}diff --git a/crates/host-core/src/plugins/renderer.rs b/crates/host-core/src/plugins/renderer.rsnew file mode 100644index 000000000..5960cd3ae--- /dev/null+++ b/crates/host-core/src/plugins/renderer.rs@@ -0,0 +1,248 @@+//! Renderer-slot declarations: `manifest.renderer` and its two whitelists.+//!+//! The desktop host evaluates the renderer entry inside its own window, so+//! the install-time checks here keep the declaration well formed and the entry+//! a real module file inside the package. The whitelists themselves are+//! enforced by the desktop host at runtime (`docs/plugin-plan/slot-contract.html`).++use super::*;++/// Mirrors `MAX_RENDERER_ACTIONS_PER_PLUGIN` in the plugin SDK.+const MAX_RENDERER_ACTIONS: usize = 16;+/// Mirrors `MAX_RENDERER_CALL_METHODS_PER_PLUGIN` in the plugin SDK.+const MAX_RENDERER_CALL_METHODS: usize = 32;++/// `manifest.renderer` gate: the permission coupling, the whitelist shapes,+/// and an entry that is a `.js`/`.mjs` file inside the package, also after+/// symlinks are resolved.+pub(crate) fn validate_renderer(root: &Path, manifest: &PluginManifest) -> Result<()> {+ let declares_whitelist =+ !manifest.renderer_actions.is_empty() || !manifest.renderer_call_methods.is_empty();+ if manifest.renderer.is_none() && !declares_whitelist {+ return Ok(());+ }+ if !manifest+ .permissions+ .iter()+ .any(|p| p == "renderer.extension")+ {+ bail!("PLUGIN_INVALID: renderer modules require the renderer.extension permission");+ }+ for (field, values, max) in [+ (+ "rendererActions",+ &manifest.renderer_actions,+ MAX_RENDERER_ACTIONS,+ ),+ (+ "rendererCallMethods",+ &manifest.renderer_call_methods,+ MAX_RENDERER_CALL_METHODS,+ ),+ ] {+ if values.iter().any(|value| value.trim().is_empty()) {+ bail!("PLUGIN_INVALID: manifest.{field} entries must be non-empty strings");+ }+ if values.len() > max {+ bail!("PLUGIN_INVALID: manifest.{field} allows at most {max} entries");+ }+ }+ let Some(entry) = manifest.renderer.as_deref() else {+ bail!("PLUGIN_INVALID: renderer whitelists require manifest.renderer");+ };+ if entry.trim().is_empty() {+ bail!("PLUGIN_INVALID: manifest.renderer must be a non-empty string");+ }+ if !(entry.ends_with(".js") || entry.ends_with(".mjs")) {+ bail!("PLUGIN_INVALID: manifest.renderer must be a .js or .mjs module");+ }+ let joined = safe_join(root, entry)?;+ let package_root = root+ .canonicalize()+ .map_err(|_| anyhow!("PLUGIN_INVALID: plugin package root cannot be resolved"))?;+ let resolved = joined+ .canonicalize()+ .map_err(|_| anyhow!("PLUGIN_INVALID: renderer entry missing: {entry}"))?;+ if !resolved.starts_with(&package_root) {+ bail!("PLUGIN_INVALID: renderer entry {entry} resolves outside the plugin package");+ }+ if !resolved.is_file() {+ bail!("PLUGIN_INVALID: renderer entry missing: {entry}");+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use tempfile::tempdir;++ fn manifest(extra: Value) -> Value {+ let mut value = json!({+ "schemaVersion": 1,+ "id": "demo.renderer",+ "name": "Renderer",+ "version": "0.1.0",+ "main": "main.js",+ });+ let object = value.as_object_mut().unwrap();+ for (key, field) in extra.as_object().unwrap() {+ object.insert(key.clone(), field.clone());+ }+ value+ }++ fn write(root: &Path, manifest: &Value, files: &[&str]) {+ fs::create_dir_all(root).unwrap();+ fs::write(root.join("main.js"), "export function onLoad() {}").unwrap();+ fs::write(root.join("manifest.json"), manifest.to_string()).unwrap();+ for rel in files {+ let path = root.join(rel);+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, "export function onLoad() {}").unwrap();+ }+ }++ fn rejection(root: &Path) -> String {+ PluginManager::read_manifest(root)+ .expect_err("manifest should be rejected")+ .to_string()+ }++ #[test]+ fn a_granted_module_entry_inside_the_package_is_accepted() {+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ let value = manifest(json!({+ "renderer": "renderer/index.mjs",+ "rendererActions": ["plugin.call"],+ "rendererCallMethods": ["stats.summary"],+ "permissions": ["renderer.extension"],+ }));+ write(&root, &value, &["renderer/index.mjs"]);+ let parsed = PluginManager::read_manifest(&root).unwrap();+ assert_eq!(parsed.renderer.as_deref(), Some("renderer/index.mjs"));+ assert_eq!(parsed.renderer_actions, vec!["plugin.call".to_string()]);+ }++ #[test]+ fn the_renderer_surface_requires_its_permission_and_an_entry() {+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ write(+ &root,+ &manifest(json!({ "renderer": "renderer.js" })),+ &["renderer.js"],+ );+ assert!(+ rejection(&root).contains("require the renderer.extension permission"),+ "{}",+ rejection(&root)+ );++ write(+ &root,+ &manifest(json!({+ "rendererActions": ["plugin.call"],+ "permissions": ["renderer.extension"],+ })),+ &[],+ );+ assert!(+ rejection(&root).contains("require manifest.renderer"),+ "{}",+ rejection(&root)+ );+ }++ #[test]+ fn the_entry_must_be_an_existing_module_file() {+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ let granted = |entry: &str| {+ manifest(json!({+ "renderer": entry,+ "permissions": ["renderer.extension"],+ }))+ };+ write(&root, &granted("renderer.css"), &["renderer.css"]);+ assert!(rejection(&root).contains(".js or .mjs module"));++ write(&root, &granted("missing.js"), &[]);+ assert!(rejection(&root).contains("renderer entry missing: missing.js"));++ write(&root, &granted("../outside.js"), &[]);+ assert!(rejection(&root).contains("path traversal is not allowed"));++ fs::create_dir_all(root.join("folder.js")).unwrap();+ write(&root, &granted("folder.js"), &[]);+ assert!(rejection(&root).contains("renderer entry missing: folder.js"));+ }++ #[test]+ fn whitelists_are_bounded_and_non_empty() {+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ let actions: Vec<String> = (0..=MAX_RENDERER_ACTIONS)+ .map(|index| format!("demo.action{index}"))+ .collect();+ write(+ &root,+ &manifest(json!({+ "renderer": "renderer.js",+ "rendererActions": actions,+ "permissions": ["renderer.extension"],+ })),+ &["renderer.js"],+ );+ assert!(rejection(&root).contains("rendererActions allows at most 16 entries"));++ let methods: Vec<String> = (0..=MAX_RENDERER_CALL_METHODS)+ .map(|index| format!("method{index}"))+ .collect();+ write(+ &root,+ &manifest(json!({+ "renderer": "renderer.js",+ "rendererCallMethods": methods,+ "permissions": ["renderer.extension"],+ })),+ &["renderer.js"],+ );+ assert!(rejection(&root).contains("rendererCallMethods allows at most 32 entries"));++ write(+ &root,+ &manifest(json!({+ "renderer": "renderer.js",+ "rendererCallMethods": [" "],+ "permissions": ["renderer.extension"],+ })),+ &["renderer.js"],+ );+ assert!(rejection(&root).contains("rendererCallMethods entries must be non-empty"));+ }++ #[cfg(unix)]+ #[test]+ fn a_symlinked_entry_cannot_escape_the_package() {+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ let outside = dir.path().join("outside.js");+ fs::write(&outside, "export function onLoad() {}").unwrap();+ write(+ &root,+ &manifest(json!({+ "renderer": "renderer.js",+ "permissions": ["renderer.extension"],+ })),+ &[],+ );+ std::os::unix::fs::symlink(&outside, root.join("renderer.js")).unwrap();+ assert!(+ rejection(&root).contains("resolves outside the plugin package"),+ "{}",+ rejection(&root)+ );+ }+}diff --git a/crates/host-core/src/plugins/validation.rs b/crates/host-core/src/plugins/validation.rsindex 6e2b7e933..8866ffc74 100644--- a/crates/host-core/src/plugins/validation.rs+++ b/crates/host-core/src/plugins/validation.rs@@ -699,46 +699,6 @@ fn array_of<'a>(value: &'a Value, field: &str) -> Result<&'a [Value]> {.ok_or_else(|| anyhow!("PLUGIN_INVALID: {field} must be an array"))}--/// `manifest.renderer` gate: the entry, its permission coupling, and the-/// whitelist shapes (`docs/plugin-plan/slot-contract.html`).-pub(crate) fn validate_renderer(root: &Path, manifest: &PluginManifest) -> Result<()> {- let has_surface = manifest.renderer.is_some()- || !manifest.renderer_actions.is_empty()- || !manifest.renderer_call_methods.is_empty();- if !has_surface {- return Ok(());- }- require_permission(manifest, "renderer.extension", "renderer modules")?;- for (field, values) in [- ("rendererActions", &manifest.renderer_actions),- ("rendererCallMethods", &manifest.renderer_call_methods),- ] {- if values.iter().any(|entry| entry.trim().is_empty()) {- bail!("PLUGIN_INVALID: manifest.{field} entries must be non-empty strings");- }- }- if manifest.renderer_actions.len() > 16 {- bail!("PLUGIN_INVALID: manifest.rendererActions allows at most 16 entries");- }- if manifest.renderer_call_methods.len() > 32 {- bail!("PLUGIN_INVALID: manifest.rendererCallMethods allows at most 32 entries");- }- if let Some(entry) = &manifest.renderer {- if entry.trim().is_empty() {- bail!("PLUGIN_INVALID: manifest.renderer must be a non-empty string");- }- if !(entry.ends_with(".js") || entry.ends_with(".mjs")) {- bail!("PLUGIN_INVALID: manifest.renderer entry must be a .js or .mjs module");- }- let resolved = safe_join(root, entry)?;- if !resolved.exists() {- bail!("PLUGIN_INVALID: renderer entry missing: {entry}");- }- }- Ok(())-}-fn require_permission(manifest: &PluginManifest, permission: &str, what: &str) -> Result<()> {if manifest.permissions.iter().any(|p| p == permission) {return Ok(());diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 37e146670..45b0e7f6a 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2160,8 +2160,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a"agent.prompt.inject": "Can change instructions sent to the AI agent.","agent.complete":"Can spend your model quota on a one-shot completion. The plugin never receives your API keys.",- "agent.extension":- "Runs ExtensionAPI modules inside the agent process with the same access as the agent's own tools. Enable only code you trust.",+ "agent.extension": "Runs ExtensionAPI modules inside the agent process with the same access as the agent's own tools. Enable only code you trust.","renderer.extension":"Loads this plugin's renderer module into the app window to draw UI slot components (message action bars, entry extras, tool cards, code-block renderers, composer controls). The module runs in the same document as PI-Desktop. Enable only code you trust.","provider.register":diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex 5b2dc1a8f..c1bcc2607 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -9,6 +9,8 @@ import {validateManifest,LEGACY_FS_PERMISSIONS,MAX_GLOBAL_SHORTCUTS_PER_PLUGIN,+ MAX_RENDERER_ACTIONS_PER_PLUGIN,+ MAX_RENDERER_CALL_METHODS_PER_PLUGIN,PLUGIN_PERMISSIONS,PLUGIN_VIEW_ICONS,type PluginProviderContrib,@@ -119,6 +121,64 @@ describe("validateManifest", () => {expect(validateManifest({ ...base, ui: { panel: "renderer/index.html" } }).ok).toBe(true);});+ it("couples a renderer entry and its whitelists to renderer.extension", () => {+ const granted = { ...base, permissions: ["renderer.extension"] };+ expect(+ validateManifest({+ ...granted,+ renderer: "renderer/index.mjs",+ rendererActions: ["plugin.call", "demo.future-word"],+ rendererCallMethods: ["stats.summary"],+ }).ok,+ ).toBe(true);+ expect(validateManifest({ ...base, renderer: "renderer.js" }).error).toMatch(+ /renderer\.extension permission/,+ );+ expect(validateManifest({ ...granted, rendererActions: ["plugin.call"] }).error).toMatch(+ /require manifest\.renderer/,+ );+ // Empty whitelists declare nothing, exactly as host-core reads them.+ expect(validateManifest({ ...base, rendererActions: [] }).ok).toBe(true);+ expect(validateManifest({ ...granted, renderer: "../renderer.js" }).error).toMatch(+ /manifest\.renderer.*\.\./,+ );+ expect(validateManifest({ ...granted, renderer: "/abs/renderer.js" }).error).toMatch(+ /manifest\.renderer.*absolute/,+ );+ expect(validateManifest({ ...granted, renderer: "renderer.css" }).error).toMatch(+ /\.js or \.mjs module/,+ );+ expect(validateManifest({ ...granted, renderer: " " }).error).toMatch(/non-empty string/);+ });++ it("bounds the renderer whitelists", () => {+ const granted = { ...base, permissions: ["renderer.extension"], renderer: "renderer.js" };+ const words = (count: number) => Array.from({ length: count }, (_, index) => `word${index}`);+ expect(+ validateManifest({+ ...granted,+ rendererActions: words(MAX_RENDERER_ACTIONS_PER_PLUGIN),+ rendererCallMethods: words(MAX_RENDERER_CALL_METHODS_PER_PLUGIN),+ }).ok,+ ).toBe(true);+ expect(+ validateManifest({ ...granted, rendererActions: words(MAX_RENDERER_ACTIONS_PER_PLUGIN + 1) })+ .error,+ ).toMatch(/rendererActions allows at most 16/);+ expect(+ validateManifest({+ ...granted,+ rendererCallMethods: words(MAX_RENDERER_CALL_METHODS_PER_PLUGIN + 1),+ }).error,+ ).toMatch(/rendererCallMethods allows at most 32/);+ expect(validateManifest({ ...granted, rendererCallMethods: ["ok", ""] }).error).toMatch(+ /rendererCallMethods must be an array of non-empty strings/,+ );+ expect(validateManifest({ ...granted, rendererActions: "plugin.call" }).error).toMatch(+ /rendererActions must be an array/,+ );+ });+it("surfaces contribution errors", () => {expect(validateManifest({ ...base, contributes: { themes: [{ id: "a", label: "A", path: "a.json" }] } })diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex 256d1ac82..c724a5bbd 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -59,6 +59,7 @@ export type PluginManifest = {i18n?: PluginI18nMap;author?: PluginManifestAuthor;homepage?: string;+ repository?: string;/*** Renderer entry (ES module path relative to the plugin root). Declaring it* requires the `renderer.extension` permission; the module loads into the@@ -1345,6 +1346,7 @@ export function validateManifest(raw: unknown): {return { ok: false, error: "manifest.main is required" };}const mainError = relativePathError(m.main, "manifest.main");+ if (mainError) return { ok: false, error: mainError };const rendererError = manifestRendererError(m);if (rendererError) return { ok: false, error: rendererError };if (typeof m.schemaVersion !== "number") {@@ -1973,6 +1975,45 @@ function manifestI18nError(value: unknown): string | undefined {}return undefined;}++/** Upper bounds for the renderer-slot declarations one plugin may carry. */+export const MAX_RENDERER_ACTIONS_PER_PLUGIN = 16;+export const MAX_RENDERER_CALL_METHODS_PER_PLUGIN = 32;++/**+ * `manifest.renderer` and its two whitelists. The entry is a relative+ * `.js`/`.mjs` module, the whitelists are bounded arrays of non-empty strings+ * that mean nothing without the entry, and any of it requires the+ * `renderer.extension` permission. Unknown action words are accepted here so a+ * manifest written for a newer host still loads; dispatch refuses them.+ */+function manifestRendererError(m: Partial<PluginManifest>): string | undefined {+ for (const [field, max] of [+ ["rendererActions", MAX_RENDERER_ACTIONS_PER_PLUGIN],+ ["rendererCallMethods", MAX_RENDERER_CALL_METHODS_PER_PLUGIN],+ ] as const) {+ const value: unknown = m[field];+ if (value === undefined) continue;+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || !entry.trim())) {+ return `manifest.${field} must be an array of non-empty strings`;+ }+ if (value.length > max) return `manifest.${field} allows at most ${max} entries`;+ }+ const declaresWhitelist = Boolean(m.rendererActions?.length || m.rendererCallMethods?.length);+ if (m.renderer === undefined && !declaresWhitelist) return undefined;+ if (!m.permissions?.includes("renderer.extension")) {+ return "renderer modules require the renderer.extension permission";+ }+ if (m.renderer === undefined) return "renderer whitelists require manifest.renderer";+ if (typeof m.renderer !== "string" || !m.renderer.trim()) {+ return "manifest.renderer must be a non-empty string";+ }+ const pathError = relativePathError(m.renderer, "manifest.renderer");+ if (pathError) return pathError;+ if (!/\.m?js$/.test(m.renderer)) return "manifest.renderer must be a .js or .mjs module";+ return undefined;+}+function relativePathError(value: string, field: string): string | undefined {if (/^[a-zA-Z]:[\\/]/.test(value) || value.startsWith("/") || value.startsWith("\\")) {return `${field} must not be an absolute path`;@@ -2095,50 +2136,6 @@ export {type ResolvedFsAccess,} from "./fs-policy.js";-/** Upper bounds for the renderer-slot declarations one plugin may carry. */-export const MAX_RENDERER_ACTIONS_PER_PLUGIN = 16;-export const MAX_RENDERER_CALL_METHODS_PER_PLUGIN = 32;--/**- * Renderer-slot declaration check: the entry path, the outbound action- * whitelist, and the `plugin.call` method whitelist must all be well-formed,- * and any of them requires the `renderer.extension` permission.- */-function manifestRendererError(m: Partial<PluginManifest>): string | undefined {- const hasRendererSurface =- m.renderer !== undefined ||- m.rendererActions !== undefined ||- m.rendererCallMethods !== undefined;- if (!hasRendererSurface) return undefined;- if (!m.permissions?.includes("renderer.extension")) {- return "manifest.renderer requires the renderer.extension permission";- }- if (m.renderer !== undefined) {- if (typeof m.renderer !== "string" || !m.renderer.trim()) {- return "manifest.renderer must be a non-empty string";- }- const pathError = relativePathError(m.renderer, "manifest.renderer");- if (pathError) return pathError;- if (!/\.(mjs|js)$/.test(m.renderer)) {- return "manifest.renderer must be a .js or .mjs module";- }- }- for (const [field, max] of [- ["rendererActions", MAX_RENDERER_ACTIONS_PER_PLUGIN],- ["rendererCallMethods", MAX_RENDERER_CALL_METHODS_PER_PLUGIN],- ] as const) {- const value = (m as Record<string, unknown>)[field];- if (value === undefined) continue;- if (!Array.isArray(value) || value.some((e) => typeof e !== "string" || !e.trim())) {- return `manifest.${field} must be an array of non-empty strings`;- }- if (value.length > max) {- return `manifest.${field} is limited to ${max} entries`;- }- }- return undefined;-}-export {PLUGIN_RENDERER_SCHEME,PLUGIN_RENDERER_SLOTS,diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex 264d1162e..f6c18c844 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -163,6 +163,7 @@ export function formatFileInsert(path: string, kind: "dir" | "file"): string {}return needsQuote ? `@"${path}" ` : `@${path} `;}+/** Full-width forms normalized to their ASCII trigger symbols (全角归一化). */const FULLWIDTH_TRIGGERS: Record<string, string> = {"@": "@",diff --git a/packages/shared/src/types/plugins.ts b/packages/shared/src/types/plugins.tsindex 2f205da0f..6e45b9372 100644--- a/packages/shared/src/types/plugins.ts+++ b/packages/shared/src/types/plugins.ts@@ -284,6 +284,8 @@ export type PluginSummary = {status: "ready" | "error" | "disabled" | "load_error";errorMessage?: string;permissions: string[];+ path?: string;+ /** Derived from the manifest by the host: which contribution kinds exist. */capabilities?: PluginCapability[];/*** Present when the plugin declares `manifest.renderer`: the renderer entry