Skip to content

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

feat(plugins): implement all seven finalized UI slots

Tioit-Wang9df8ee471f3a
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index d91209bee..1932806ed 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -15,6 +15,10 @@ import {
installPluginAssetProtocol,
registerPluginAssetScheme,
} from "../plugin-asset-protocol";
+import {
+ installPluginRendererProtocol,
+ registerPluginRendererScheme,
+} from "../plugin-renderer-protocol";
import { applyNetworkProxyFromAppSettings } from "../network-proxy";
import { readCloseBehavior } from "../window-preferences";
import { createAgentHostBridge, type AgentHostBridge } from "../agent-host-bridge";
@@ -119,7 +123,7 @@ export type StartupDependencies = {
* composition root through `StartupState` and dependency callbacks.
*/
export function registerApplicationStartup(deps: StartupDependencies): void {
- // Electron only accepts scheme privileges before the app is ready, and this
+ registerPluginRendererScheme();
// runs from the composition root, before the `whenReady` promise can settle.
registerPluginAssetScheme();
// Crashpad ships with Electron, so the reporter needs no native dependency.
@@ -186,11 +190,18 @@ 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) =>
plugins.resolveThemeAsset(pluginId, assetPath),
);
+ // Serve renderer entry modules the same way — a loaded plugin that
+ // declared `manifest.renderer` and holds `renderer.extension`.
+ installPluginRendererProtocol((pluginId, requestPath) =>
+ plugins.resolveRendererSource(pluginId, requestPath),
+ );
// Load the close-behavior preference before the first window exists: the
// close handler reads `closeBehavior` synchronously, and a window created
// while it still held the "ask" default would prompt a user who already
diff --git a/apps/desktop/electron/main/ipc/plugin-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ipc.ts
index f0f217186..48bd55a25 100644
--- a/apps/desktop/electron/main/ipc/plugin-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ipc.ts
@@ -137,6 +137,14 @@ export function registerPluginIpc({
return { ...result, plugins: pluginsWithSettings };
});
+ handle(IPC.invoke.pluginRendererCall, async (pluginId: unknown, method: unknown, args: unknown) => {
+ const id = String(pluginId ?? "");
+ const name = String(method ?? "");
+ if (!id || !name) throw new Error("INVALID_ARGUMENT: pluginId and method are required");
+ 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-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 1ed4f3db3..3e0dcf493 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -578,7 +578,15 @@ async function handleParentCall(method, payload, invocationId) {
if (entry.stop) await entry.stop();
return { ok: true };
}
- case "lifecycle.unload": {
+ case "renderer.call": {
+ const handler = pluginModule?.onRendererCall;
+ if (typeof handler !== "function") {
+ const error = new Error("plugin does not implement onRendererCall");
+ error.code = "PLUGIN_CALL_NO_HANDLER";
+ throw error;
+ }
+ return handler(String(payload?.method ?? ""), payload?.args ?? {});
+ }
for (const id of invocations.keys()) cancelInvocation(id, "Plugin unloaded");
// Best effort: a throwing onUnload must not block teardown.
try {
diff --git a/apps/desktop/electron/main/plugin-renderer-protocol.ts b/apps/desktop/electron/main/plugin-renderer-protocol.ts
new file mode 100644
index 000000000..5903dc9b8
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-renderer-protocol.ts
@@ -0,0 +1,125 @@
+import { protocol } from "electron";
+import { readFileSync } from "node:fs";
+import { PLUGIN_RENDERER_SCHEME } from "@pi-desktop/plugin-sdk";
+
+/**
+ * Serve a plugin's renderer entry modules over a host-owned scheme.
+ *
+ * The renderer host evaluates plugin code inside the app's own window, so the
+ * bytes have to come from somewhere the host controls: `plugin-renderer://`
+ * answers only for plugins the runtime has already loaded AND that declared
+ * `manifest.renderer` AND that hold the `renderer.extension` permission. The
+ * allowlist is not computed here — `resolve` owns it, exactly as it does for
+ * theme assets — so a path that escapes the package, or a plugin that never
+ * declared the entry, has no URL to begin with.
+ *
+ * This is why the scheme is separate from `plugin-asset`: that allowlist is
+ * images and webfonts on purpose, and adding `js` to it would turn every theme
+ * asset URL into a script URL.
+ */
+export type PluginRendererSourceResolver = (
+ pluginId: string,
+ requestPath: string,
+) => string | null;
+
+/**
+ * Only files a module graph can consume. `json` and `map` are here so a plugin
+ * may ship data and source maps; everything else is answered with 404 rather
+ * than an empty body a loader would have to interpret.
+ */
+const MIME_TYPES: Record<string, string> = {
+ js: "text/javascript",
+ mjs: "text/javascript",
+ css: "text/css",
+ json: "application/json",
+ map: "application/json",
+};
+
+function mimeTypeFor(requestPath: string): string | null {
+ const extension = requestPath.split(".").pop()?.toLowerCase() ?? "";
+ return MIME_TYPES[extension] ?? null;
+}
+
+function notFound(): Response {
+ return new Response("not found", {
+ status: 404,
+ headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
+ });
+}
+
+/**
+ * Reserve the scheme before the app is ready — Electron refuses to register
+ * privileges afterwards.
+ *
+ * `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,
+ },
+ },
+ ]);
+}
+
+/** Install the request handler. Call once, after the app is ready. */
+export function installPluginRendererProtocol(resolve: PluginRendererSourceResolver): void {
+ protocol.handle(PLUGIN_RENDERER_SCHEME, (request) => {
+ // A renderer module is fetched, never posted to; anything but a read is a
+ // caller that has gone wrong rather than a plugin that needs the verb.
+ if (request.method !== "GET") return notFound();
+ let url: URL;
+ try {
+ url = new URL(request.url);
+ } catch {
+ return notFound();
+ }
+ // Plugin ids are `[a-z0-9]` dotted namespaces, so the host survives the URL
+ // parser's lowercasing unchanged.
+ const pluginId = url.hostname;
+ let requestPath: string;
+ try {
+ requestPath = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
+ } catch {
+ return notFound();
+ }
+ if (!pluginId || !requestPath) return notFound();
+ const mime = mimeTypeFor(requestPath);
+ if (!mime) return notFound();
+ const absolute = resolve(pluginId, requestPath);
+ if (!absolute) return notFound();
+ let body: Buffer;
+ try {
+ body = readFileSync(absolute);
+ } catch {
+ return notFound();
+ }
+ // Copy into a plain view: `Buffer` is a `Uint8Array` subtype that the DOM
+ // `BodyInit` union does not accept, and this tsconfig loads both libs.
+ const bytes = new Uint8Array(body);
+ return new Response(bytes, {
+ status: 200,
+ headers: {
+ "content-type": mime,
+ "content-length": String(body.byteLength),
+ // A plugin module is replaced whenever the plugin reloads, so caching
+ // it would outlive the code that produced it.
+ "cache-control": "no-store",
+ // A renderer module must never be sniffed into an executable type.
+ "x-content-type-options": "nosniff",
+ // The requesting origin is the app's own document, which is
+ // cross-origin to any scheme; the resolver above, not this header, is
+ // what keeps other plugins' files out of reach.
+ "access-control-allow-origin": "*",
+ },
+ });
+ });
+}
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index ce2fa5d50..eb0ab2607 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -1270,6 +1270,24 @@ function parseSpeechAdapterReply(value: unknown): {
throw apiError("INVALID_ARGUMENT", "speech adapter reply kind is invalid");
}
+/** `plugin.call` relay limits (`docs/plugin-plan/render/plugin-call/`). */
+export const RENDERER_CALL_QPS = 10;
+export const RENDERER_CALL_MAX_BYTES = 64 * 1024;
+export const RENDERER_CALL_TIMEOUT_MS = 2_000;
+export const RENDERER_CALL_BREAKER_THRESHOLD = 5;
+export const RENDERER_CALL_BREAKER_COOLDOWN_MS = 30_000;
+
+/**
+ * Per-plugin relay bookkeeping, keyed weakly so an unloaded plugin's state
+ * goes with it. `calls` are the timestamps inside the current 1s QPS window.
+ */
+type RendererCallState = {
+ calls: number[];
+ failures: number;
+ disabledUntil: number;
+};
+const rendererCallStates = new WeakMap<object, RendererCallState>();
+
export class PluginRuntime {
private commands = new Map<string, RegisteredCommand>();
private tools = new Map<string, RegisteredPluginTool>();
@@ -1536,6 +1554,95 @@ 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 own
+ * package, and nothing else (`docs/plugin-plan/ui/`).
+ */
+ resolveRendererSource(pluginId: string, requestPath: string): string | null {
+ const loaded = this.loaded.get(pluginId);
+ if (!loaded || loaded.disposing) return null;
+ if (!loaded.permissions.has("renderer.extension")) return null;
+ if (!loaded.manifest.renderer) return null;
+ const base = resolve(loaded.path);
+ const target = resolve(base, requestPath);
+ if (target !== base && !target.startsWith(base + sep)) return null;
+ return target;
+ }
+
+ /**
+ * The `plugin.call` relay: a renderer slot component asks its own plugin
+ * for one JSON answer. Whitelist, size ceiling, QPS brake, 2s timeout, and
+ * the failure breaker are all enforced here — the renderer only ever sees
+ * coded refusals, never the raw failure modes.
+ */
+ async callRenderer(pluginId: string, method: string, args: unknown): Promise<unknown> {
+ const loaded = this.loaded.get(pluginId);
+ if (!loaded || loaded.disposing || !loaded.child) {
+ throw apiError("PLUGIN_NOT_FOUND", `renderer plugin not loaded: ${pluginId}`);
+ }
+ if (!loaded.permissions.has("renderer.extension")) {
+ throw apiError("PLUGIN_PERMISSION_DENIED", "renderer.extension is not granted");
+ }
+ if (!loaded.manifest.renderer) {
+ throw apiError("PLUGIN_SLOT_NOT_DECLARED", "plugin declares no renderer entry");
+ }
+ if (!loaded.manifest.rendererCallMethods?.includes(method)) {
+ throw apiError("PLUGIN_CALL_NO_HANDLER", `method not declared: ${method}`);
+ }
+ let state = rendererCallStates.get(loaded);
+ if (!state) {
+ state = { calls: [], failures: 0, disabledUntil: 0 };
+ rendererCallStates.set(loaded, state);
+ }
+ const now = Date.now();
+ if (now < state.disabledUntil) {
+ throw apiError("PLUGIN_CALL_DISABLED", "plugin.call is cooling down after repeated failures");
+ }
+ state.calls = state.calls.filter((t) => now - t < 1000);
+ if (state.calls.length >= RENDERER_CALL_QPS) {
+ throw apiError("PLUGIN_CALL_RATE_LIMITED", `plugin.call exceeds ${RENDERER_CALL_QPS} calls/s`);
+ }
+ try {
+ if ((JSON.stringify({ method, args }) ?? "").length > RENDERER_CALL_MAX_BYTES) {
+ throw apiError("PLUGIN_CALL_TOO_LARGE", "plugin.call payload exceeds 64KB");
+ }
+ } catch (error) {
+ if ((error as PluginApiError)?.code) throw error;
+ throw apiError("PLUGIN_CALL_UNSERIALIZABLE", "plugin.call args must be JSON");
+ }
+ state.calls.push(now);
+ try {
+ const value = await this.sendToChild(
+ loaded,
+ { t: "call", method: "renderer.call", payload: { method, args } },
+ RENDERER_CALL_TIMEOUT_MS,
+ );
+ let answer: string;
+ try {
+ answer = JSON.stringify(value ?? null) ?? "";
+ } catch {
+ throw apiError("PLUGIN_CALL_UNSERIALIZABLE", "plugin.call answer must be JSON");
+ }
+ if (answer.length > RENDERER_CALL_MAX_BYTES) {
+ throw apiError("PLUGIN_CALL_TOO_LARGE", "plugin.call answer exceeds 64KB");
+ }
+ state.failures = 0;
+ return value ?? null;
+ } catch (error) {
+ if ((error as PluginApiError)?.code === "TIMEOUT") {
+ state.failures += 1;
+ if (state.failures >= RENDERER_CALL_BREAKER_THRESHOLD) {
+ state.disabledUntil = Date.now() + RENDERER_CALL_BREAKER_COOLDOWN_MS;
+ state.failures = 0;
+ }
+ throw apiError("PLUGIN_CALL_TIMEOUT", `plugin ${pluginId} did not answer ${method} within ${RENDERER_CALL_TIMEOUT_MS}ms`);
+ }
+ throw error;
+ }
+ }
+
getLoaded(pluginId: string): LoadedPlugin | undefined {
return this.loaded.get(pluginId);
}
diff --git a/apps/desktop/index.html b/apps/desktop/index.html
index 73358c18a..b5e890034 100644
--- a/apps/desktop/index.html
+++ b/apps/desktop/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: plugin-asset:; 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:*;"
+ content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' 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: plugin-renderer:; 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.tsx
index 5da4c2699..901b61c4e 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -47,6 +47,8 @@ import {
import {
createFileReference,
editorSelectionRange,
+ readEditorValue,
+ setEditorCaret,
isImageFilePath,
nextChipToken,
} from "../features/chat/composer/editor";
@@ -57,11 +59,21 @@ import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSu
import { ComposerImageAttachments } from "../features/chat/composer/ComposerImageAttachments";
import { ComposerInput } from "../features/chat/composer/ComposerInput";
import { useComposerModelMenu } from "../features/chat/composer/hooks/useComposerModelMenu";
-import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";
import { useVoiceInput } from "../features/voice/useVoiceInput";
import { VoiceOverlay } from "../features/voice/VoiceOverlay";
import "../styles/voice.css";
+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,
+ useComposerPluginTokens,
+ useComposerTriggerAcceptBridge,
+} from "../features/chat/composer/use-plugin-composer-slots";
+import { SlotBoundary } from "../plugins/renderer-slots/use-slots";
+import { dispatchFor } from "../plugins/renderer-host/dispatch";
const EMPTY_QUEUED_PROMPTS: QueuedPrompt[] = [];
@@ -425,6 +437,8 @@ export function Composer({
sendBlocked,
pasting,
activeFileReferences,
+ serializePluginTokens: (draft: string) =>
+ serializePluginTokensForSend(draft, pluginTokensRef.current),
t,
sendPrompt,
steerPrompt,
@@ -479,6 +493,44 @@ export function Composer({
enabled: !inputBlocked,
});
+ // Plugin composer slots (# trigger + token records). The trigger state
+ // freezes during IME composition inside the hook; 程序写入 never fires it.
+ const pluginTrigger = useComposerPluginTrigger({
+ value,
+ cursor,
+ composing,
+ 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 item
+ // into a recorded token plus a `#label ` chip in the draft.
+ const pluginAcceptRef = useRef<(item: { label: string; value?: unknown }) => void>(
+ () => {},
+ );
+ useComposerTriggerAcceptBridge({
+ active: Boolean(activeTrigger),
+ onAccept: (item) => pluginAcceptRef.current(item),
+ });
+ pluginAcceptRef.current = (item) => {
+ if (!activeTrigger) return;
+ const folded = pluginTokens.addToken({
+ pluginId: activeTrigger.entry.pluginId,
+ label: item.label,
+ send: item.value,
+ });
+ const insert = formatPluginTriggerInsert(item.label);
+ const before = value.slice(0, activeTrigger.tokenStart);
+ const after = value.slice(activeTrigger.tokenEnd);
+ const nextText = `${before}${insert}${after}`;
+ applyEditorDraft(nextText, fileReferencesRef.current, before.length + insert.length);
+ };
+
const acceptCompletion = (index: number) => {
const result = composerAc.accept(index);
if (!result) return;
@@ -516,6 +568,24 @@ export function Composer({
// height (it grows with multi-line input) so the last message sits just
// above the box instead of far below it.
useEffect(() => {
+ // The insert bridge: plugin slot components reach the draft through
+ // `composer.insertText`; this composer instance owns the live route while
+ // it is mounted and clears it on unmount (last-writer-wins is the docked
+ // composer, which is the one the user sees).
+ useEffect(() => {
+ registerComposerInsert((text) => {
+ const element = draft.ref.current;
+ if (!element) return;
+ const current = readEditorValue(element);
+ const selection = editorSelectionRange(element);
+ const nextText = current.slice(0, selection.start) + text + current.slice(selection.end);
+ applyEditorDraft(nextText, fileReferencesRef.current, selection.start + text.length);
+ element.focus();
+ setEditorCaret(element, selection.start + text.length);
+ });
+ return () => registerComposerInsert(null);
+ }, [draft, fileReferencesRef]);
+
const el = dockRef.current;
if (!el) return;
// Setting a custom property on documentElement invalidates style for the
@@ -587,6 +657,53 @@ export function Composer({
onAccept={acceptCompletion}
/>
) : null}
+ {activeTrigger ? (
+ <div
+ className="pi-plugin-trigger-menu"
+ data-pi-plugin={activeTrigger.entry.pluginId}
+ >
+ <SlotBoundary entry={activeTrigger.entry} slot="composerTrigger">
+ {activeTrigger.entry.component({
+ query: activeTrigger.query,
+ dispatch: dispatchFor(activeTrigger.entry.pluginId),
+ }) as React.ReactNode}
+ </SlotBoundary>
+ </div>
+ ) : null}
+ {pluginTokens.tokens.length ? (
+ <div className="pi-plugin-token-chips" role="list">
+ {pluginTokens.tokens
+ .slice(0, 8)
+ .map((token) => (
+ <span
+ key={`${token.pluginId}:${token.label}`}
+ className="pi-plugin-token-chip"
+ role="listitem"
+ >
+ #{token.label}
+ <button
+ type="button"
+ className="pi-plugin-token-chip-remove"
+ aria-label={`remove #${token.label}`}
+ onClick={() => pluginTokens.removeToken(token.label)}
+ >
+ ×
+ </button>
+ </span>
+ ))}
+ {pluginTokens.foldedCount > 0 ? (
+ <span
+ className="pi-plugin-token-chip is-fold"
+ title={pluginTokens.tokens
+ .slice(8)
+ .map((token) => `#${token.label} (${token.pluginId})`)
+ .join("\n")}
+ >
+ ⧉ +{pluginTokens.foldedCount}
+ </span>
+ ) : null}
+ </div>
+ ) : null}
<ComposerInput
imagePreview={draft.imagePreview}
inputRef={ref}
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsx
index d21389b67..46488f718 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -42,6 +42,9 @@ import { TooltipButton } from "./ui";
import { ContextMenu, useContextMenu } from "./ContextMenu";
import { MarkdownTable } from "./MarkdownTable";
import { markdownTableData } from "../lib/markdown-table";
+import { PluginBlockRenderer } from "./PluginBlockRenderer";
+import { blockRendererCandidate } from "../lib/block-renderer";
+import { useSlotEntryForKey } from "../plugins/renderer-slots/use-slots";
import { api } from "../lib/api";
import { openHttpUrl } from "../lib/open-http-url";
import {
@@ -454,6 +457,12 @@ function PreBlock({
}: ComponentProps<"pre"> & SourcePositionProps & { node?: unknown }) {
const { closedFence, renderDiagrams } = useContext(MarkdownBlockContext);
const info = extractCode(children);
+ // Hooks stay unconditional: the fence language and closed-ness can flip
+ // between streaming renders, so the lookup must run on every render.
+ const blockEntry = useSlotEntryForKey(
+ "blockRenderer",
+ closedFence ? blockRendererCandidate(info?.lang ?? "") : undefined,
+ );
if (!info) return <pre {...rest}>{children}</pre>;
if (
renderDiagrams &&
@@ -462,6 +471,18 @@ function PreBlock({
) {
return <MermaidBlock code={info.code} {...sourcePositionProps(rest)} />;
}
+ if (blockEntry) {
+ return (
+ <PluginBlockRenderer
+ entry={blockEntry}
+ language={info.lang}
+ source={info.code}
+ fallback={
+ <CodeBlock code={info.code} lang={info.lang} {...sourcePositionProps(rest)} />
+ }
+ />
+ );
+ }
return <CodeBlock code={info.code} lang={info.lang} {...sourcePositionProps(rest)} />;
}
diff --git a/apps/desktop/src/components/PluginBlockRenderer.tsx b/apps/desktop/src/components/PluginBlockRenderer.tsx
new file mode 100644
index 000000000..fc53eca8b
--- /dev/null
+++ b/apps/desktop/src/components/PluginBlockRenderer.tsx
@@ -0,0 +1,57 @@
+/**
+ * The `blockRenderer` slot host (`docs/plugin-plan/ui/block-renderer/`).
+ *
+ * A claimed fence hands `{ language, source }` to the plugin once (props-once)
+ * and the plugin owns the whole block — head, copy button, error display.
+ * The host keeps exactly one guarantee: content taller than 4000px counts as
+ * a render failure and falls back to the host code block, and so does a
+ * component that throws (via the boundary's fallback) — the source code must
+ * always stay visible to the user.
+ */
+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import type { PluginBlockRendererSlotProps } from "@pi-desktop/plugin-sdk";
+import { SlotBoundary } from "../plugins/renderer-slots/use-slots";
+import type { SlotEntry } from "../plugins/renderer-slots/registry";
+import {
+ BLOCK_RENDERER_MAX_HEIGHT_PX,
+ blockRendererOverflow,
+} from "../lib/block-renderer";
+
+export function PluginBlockRenderer({
+ entry,
+ language,
+ source,
+ fallback,
+}: {
+ entry: SlotEntry;
+ language: string;
+ source: string;
+ /** The host default block, shown when the plugin fails the contract. */
+ fallback: ReactNode;
+}) {
+ // props-once: the first mount's projection is the only one there is.
+ const onceRef = useRef<PluginBlockRendererSlotProps>({ language, source });
+ const contentRef = useRef<HTMLDivElement>(null);
+ const [overflowed, setOverflowed] = useState(false);
+
+ useLayoutEffect(() => {
+ const el = contentRef.current;
+ if (el && blockRendererOverflow(el.scrollHeight)) {
+ setOverflowed(true);
+ }
+ }, []);
+
+ if (overflowed) return fallback;
+ return (
+ <SlotBoundary entry={entry} slot="blockRenderer" fallback={fallback}>
+ <div
+ ref={contentRef}
+ className="pi-plugin-block-renderer"
+ data-pi-language={onceRef.current.language}
+ style={{ maxHeight: BLOCK_RENDERER_MAX_HEIGHT_PX }}
+ >
+ {entry.component(onceRef.current) as ReactNode}
+ </div>
+ </SlotBoundary>
+ );
+}
diff --git a/apps/desktop/src/features/app/AppShell.tsx b/apps/desktop/src/features/app/AppShell.tsx
index e6a693a2d..a211e8f63 100644
--- a/apps/desktop/src/features/app/AppShell.tsx
+++ b/apps/desktop/src/features/app/AppShell.tsx
@@ -2,6 +2,7 @@ import { type CSSProperties, lazy, type ReactNode, Suspense } from "react";
import { ChatSurface } from "../../components/ChatSurface";
import { ConversationTopbar } from "../../components/ConversationTopbar";
import { ExtensionPromptHost } from "../../components/ExtensionPromptDialog";
+import { PluginRendererHost } from "../../plugins/renderer-host/PluginRendererHost";
import {
IconNewSession,
IconPanel,
@@ -294,6 +295,7 @@ export function AppShell() {
) : null}
<SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />
<ToastHost />
+ <PluginRendererHost />
<ExtensionPromptHost />
{page === "settings" ? <UpdateBanner /> : null}
</>
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 09b4315cf..30ceccdcb 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -10,6 +10,13 @@ import {
import type { AppState } from "../../../stores/app-store";
import { ComposerPermissionPicker } from "./ComposerPermissionPicker";
import { ContextUsageInspector } from "../../../components/ContextUsageInspector";
+import { useAppStore } from "../../../stores/app-store";
+import {
+ useComposerControlEntries,
+ useComposerTriggerEntry,
+} from "./use-plugin-composer-slots";
+import { SlotBoundary } from "../../../plugins/renderer-slots/use-slots";
+import { dispatchFor } from "../../../plugins/renderer-host/dispatch";
import { TooltipButton } from "../../../components/ui";
import {
IconArrowUp,
@@ -105,6 +112,8 @@ export function ComposerToolbar({
onVoiceToggle,
onVoiceCancel,
}: ComposerToolbarProps) {
+ const leftControls = useComposerControlEntries("left");
+ const rightControls = useComposerControlEntries("right");
const platform = (window.piDesktop?.platform ?? "darwin") as ShortcutPlatform;
const steeringShortcut = keybindingDisplayParts("Alt+Enter", platform).join("+");
return (
@@ -186,9 +195,11 @@ export function ComposerToolbar({
});
}
}} />
+ <PluginControlGroup entries={leftControls} side="left" />
</div>
<div className="composer-right">
+ <PluginControlGroup entries={rightControls} side="right" />
{contextUsage ? <ContextUsageInspector {...contextUsage} /> : null}
<ComposerModelPicker
t={t}
@@ -273,3 +284,32 @@ export function ComposerToolbar({
</div>
);
}
+
+/**
+ * The `composerControl` outlet for one side: each registration renders its
+ * component inside its own boundary. Props are the position and the plugin's
+ * own dispatch relay — a rendering position, no draft data.
+ */
+function PluginControlGroup({
+ entries,
+ side,
+}: {
+ entries: ReturnType<typeof useComposerControlEntries>;
+ side: "left" | "right";
+}) {
+ if (entries.length === 0) return null;
+ return (
+ <>
+ {entries.map((entry) => (
+ <SlotBoundary key={entry.id} entry={entry} slot="composerControl">
+ <span className="pi-plugin-control" data-pi-plugin={entry.pluginId}>
+ {entry.component({
+ position: side,
+ dispatch: dispatchFor(entry.pluginId),
+ }) as React.ReactNode}
+ </span>
+ </SlotBoundary>
+ ))}
+ </>
+ );
+}
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
index fbb1649c2..851535263 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
@@ -32,6 +32,9 @@ 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"];
@@ -77,6 +80,7 @@ export function useComposerSubmit({
sendBlocked,
pasting,
activeFileReferences,
+ serializePluginTokens,
t,
sendPrompt,
steerPrompt,
@@ -203,7 +207,10 @@ export function useComposerSubmit({
text,
activeFileReferences,
);
- const serializedContent = serializeComposerFileReferences(text, activeFileReferences);
+ const tokenContent = serializePluginTokens
+ ? serializePluginTokens(inlineContent)
+ : inlineContent;
+ const serializedContent = serializeComposerFileReferences(tokenContent, activeFileReferences);
if (!serializedContent) return;
if (sendBlocked) {
if (pasting) showToast(t("chat.pasteInProgress"), { variant: "info" });
diff --git a/apps/desktop/src/features/chat/composer/insert-bridge.ts b/apps/desktop/src/features/chat/composer/insert-bridge.ts
new file mode 100644
index 000000000..a046620ab
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/insert-bridge.ts
@@ -0,0 +1,29 @@
+/**
+ * Renderer-internal bridge for the `composer.insertText` outbound action.
+ *
+ * The composer is renderer-local, so the dispatch relay routes that action
+ * here instead of through the main process. The composer registers its
+ * insertion implementation on mount and clears it on unmount; with no
+ * composer mounted the relay answers `PLUGIN_ACTION_UNROUTED`.
+ */
+
+type ComposerInsert = (text: string) => void;
+
+let handler: ComposerInsert | null = null;
+
+/** Called by the composer when it can accept draft insertions. */
+export function registerComposerInsert(fn: ComposerInsert | null): void {
+ handler = fn;
+}
+
+/** Returns false when no composer is mounted to receive the text. */
+export function insertComposerText(text: string): boolean {
+ if (!handler) return false;
+ handler(text);
+ return true;
+}
+
+/** Test seam. */
+export function resetComposerInsertBridge(): void {
+ handler = null;
+}
diff --git a/apps/desktop/src/features/chat/composer/plugin-trigger.ts b/apps/desktop/src/features/chat/composer/plugin-trigger.ts
new file mode 100644
index 000000000..6d8030dc4
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/plugin-trigger.ts
@@ -0,0 +1,79 @@
+/**
+ * Pure helpers for the composer's plugin trigger slot
+ * (`docs/plugin-plan/ui/composer/`).
+ *
+ * Triggers are fixed to `@` `#` `/` (one symbol per plugin, duplicates
+ * refuse with PLUGIN_SLOT_DUPLICATE). `@` and `/` stay host-owned for file
+ * references and slash commands; a plugin claim of either is refused at
+ * registration. A `#` token fires only from line start or after whitespace,
+ * never mid-word, and the host resolves candidates with `query`.
+ */
+
+/** Detect a `#plugin` token at the cursor; null when none is active. */
+export function detectPluginHashTrigger(
+ value: string,
+ cursor: number,
+): { query: string; tokenStart: number; tokenEnd: number } | null {
+ if (cursor < 0 || cursor > value.length) return null;
+ // Scan back to the nearest delimiter; the token must start with "#".
+ let start = cursor;
+ while (start > 0 && !isTriggerDelimiter(value[start - 1])) start -= 1;
+ const token = value.slice(start, cursor);
+ if (!token.startsWith("#") || token.length < 1) return null;
+ // 行首或空白后: the character before "#" must be a boundary. The scan-back
+ // already guarantees the token has no delimiter inside, so this only
+ // rejects tokens that begin mid-word ("abc#def").
+ if (start > 0 && !isTriggerDelimiter(value[start - 1])) return null;
+ // A quoted or markdown-ish prefix ("#tag" inside emphasis, headings) is out
+ // of scope: any "#" that starts a boundary token is the plugin trigger.
+ return { query: token.slice(1), tokenStart: start, tokenEnd: cursor };
+}
+
+function isTriggerDelimiter(ch: string): boolean {
+ return ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
+}
+
+/**
+ * In-draft token records for the composerToken slot: label shown in the
+ * draft chip, send data serialized into the submit payload.
+ */
+export type ComposerPluginToken = {
+ readonly pluginId: string;
+ readonly label: string;
+ readonly send: unknown;
+};
+
+/**
+ * The single-draft cap: tokens up to this many stay individual; the 9th
+ * onward folds into the host ⧉ +N chip. Data is never dropped — the
+ * overflow chips keep their records and serialize at send time.
+ */
+export const COMPOSER_PLUGIN_TOKEN_LIMIT = 8;
+
+/** True when the draft already holds the cap and a new token must fold. */
+export function pluginTokenAtLimit(count: number): boolean {
+ return count >= COMPOSER_PLUGIN_TOKEN_LIMIT;
+}
+
+/**
+ * Serialized `#token` payload for the model prompt: visible labels plus a
+ * fenced data block carrying every token's `send` value (folded overflow
+ * included), so 发送 payload 不丢.
+ */
+export function serializePluginTokens(
+ draft: string,
+ tokens: readonly ComposerPluginToken[],
+): string {
+ if (tokens.length === 0) return draft;
+ const dataLines = tokens
+ .map((token) =>
+ JSON.stringify({
+ pluginId: token.pluginId,
+ label: token.label,
+ send: token.send,
+ }),
+ )
+ .join("\n");
+ const visible = tokens.map((token) => `#${token.label}`).join(" ");
+ return `${draft}\n\n${visible}\n\`\`\`pi-plugin-tokens\n${dataLines}\n\`\`\``;
+}
diff --git a/apps/desktop/src/features/chat/composer/trigger-bridge.ts b/apps/desktop/src/features/chat/composer/trigger-bridge.ts
new file mode 100644
index 000000000..eeac484e8
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/trigger-bridge.ts
@@ -0,0 +1,40 @@
+/**
+ * Renderer-internal bridge for the `composer.acceptTriggerItem` outbound
+ * action.
+ *
+ * The trigger menu lives in the composer, so the dispatch relay routes that
+ * action here. The trigger host registers its accept implementation while a
+ * plugin trigger menu is open and clears it on close; with no menu open the
+ * relay answers `PLUGIN_ACTION_UNROUTED` — never a silent drop.
+ */
+
+import type { PluginComposerTriggerItem } from "@pi-desktop/plugin-sdk";
+
+type TriggerItemAccept = (item: PluginComposerTriggerItem) => void;
+
+let handler: TriggerItemAccept | null = null;
+
+/** Called by the trigger host while a plugin trigger menu is open. */
+export function registerComposerTriggerAccept(fn: TriggerItemAccept | null): void {
+ handler = fn;
+}
+
+export function acceptComposerTriggerItem(payload: unknown): boolean {
+ if (!handler) return false;
+ if (!payload || typeof payload !== "object") return false;
+ const candidate = payload as { label?: unknown; value?: unknown };
+ if (typeof candidate.label !== "string" || candidate.label.length === 0) {
+ return false;
+ }
+ const item: PluginComposerTriggerItem = {
+ label: candidate.label,
+ value: candidate.value,
+ };
+ handler(item);
+ return true;
+}
+
+/** Test seam. */
+export function resetComposerTriggerBridge(): void {
+ handler = null;
+}
diff --git a/apps/desktop/src/features/chat/composer/use-plugin-composer-slots.ts b/apps/desktop/src/features/chat/composer/use-plugin-composer-slots.ts
new file mode 100644
index 000000000..459232bff
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/use-plugin-composer-slots.ts
@@ -0,0 +1,138 @@
+/**
+ * React glue for the composer's plugin slots
+ * (`docs/plugin-plan/ui/composer/`): toolbar controls (left/right), the `#`
+ * trigger dropdown, and token records with the host ⧉ +N fold.
+ *
+ * The trigger list is plugin-drawn: the host detects the `#token` at the
+ * cursor and renders the plugin's component with `{ query, dispatch }`; the
+ * plugin answers per keystroke by rendering candidates, and a picked item
+ * flows back through `dispatch("composer.acceptTriggerItem", { label,
+ * value })` — routed by the trigger bridge to the composer.
+ */
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { normalizeFullWidthTrigger } from "@pi-desktop/shared";
+import { slotRegistry, type SlotEntry } from "../../../plugins/renderer-slots/registry";
+import { registerComposerTriggerAccept } from "./trigger-bridge";
+import {
+ COMPOSER_PLUGIN_TOKEN_LIMIT,
+ detectPluginHashTrigger,
+ pluginTokenAtLimit,
+ type ComposerPluginToken,
+} from "./plugin-trigger";
+
+/** Left / right control registrations, subscription-live. */
+export function useComposerControlEntries(side: "left" | "right"): SlotEntry[] {
+ const snapshot = useSyncExternalStore(slotRegistry.subscribe, slotRegistry.getSnapshot);
+ return useMemo(
+ () => slotRegistry.entriesForSide("composerControl", side),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal
+ [snapshot.version, side],
+ );
+}
+
+/** The one plugin trigger registration (a keyed slot, symbol `#`). */
+export function useComposerTriggerEntry(): SlotEntry | undefined {
+ const snapshot = useSyncExternalStore(slotRegistry.subscribe, slotRegistry.getSnapshot);
+ return useMemo(
+ () => slotRegistry.entryForKey("composerTrigger", "#"),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal
+ [snapshot.version],
+ );
+}
+
+/** An active `#plugin` token at the cursor. */
+export type PluginTriggerState = {
+ query: string;
+ tokenStart: number;
+ tokenEnd: number;
+ entry: SlotEntry;
+};
+
+/**
+ * The `#` trigger detector: locate the token at the cursor and expose the
+ * matched registration. During IME composition the state freezes (the same
+ * rule as the host autocomplete); a programmatic insert never moves the
+ * caret into a `#token`, so it can not fire the trigger.
+ */
+export function useComposerPluginTrigger({
+ value,
+ cursor,
+ composing,
+ enabled,
+}: {
+ value: string;
+ cursor: number;
+ composing: boolean;
+ enabled: boolean;
+}): PluginTriggerState | null {
+ const entry = useComposerTriggerEntry();
+ const frozenRef = useRef<PluginTriggerState | null>(null);
+ const live = useMemo<PluginTriggerState | null>(() => {
+ if (!enabled || !entry) return null;
+ // 全角归一化: @#/ rewrite to @#/ before detection. Every replacement
+ // is one code unit for one, so cursor offsets stay valid against the
+ // raw draft the accept path slices.
+ const normalized = normalizeFullWidthTrigger(value);
+ const hit = detectPluginHashTrigger(normalized, cursor);
+ return hit ? { ...hit, entry } : null;
+ }, [enabled, entry, value, cursor]);
+ const trigger = composing ? frozenRef.current : live;
+ useEffect(() => {
+ if (!composing) frozenRef.current = live;
+ }, [composing, live]);
+ return trigger;
+}
+
+/**
+ * Token records for the draft with the finalized cap: up to eight tokens
+ * stay individual; the ninth onward folds into the host ⧉ +N chip. Folded
+ * tokens keep their records — 发送 payload 不丢.
+ */
+export function useComposerPluginTokens(): {
+ tokens: ComposerPluginToken[];
+ /** Records one accept; `folded` reports whether it went into the fold. */
+ addToken: (token: ComposerPluginToken) => { folded: boolean };
+ removeToken: (label: string) => void;
+ foldedCount: number;
+} {
+ const [tokens, setTokens] = useState<ComposerPluginToken[]>([]);
+ const addToken = useCallback(
+ (token: ComposerPluginToken) => {
+ // 折叠不丢弃: every accept is recorded; `folded` only reports that
+ // this token renders inside the host ⧉ +N chip instead of its own.
+ const folded = pluginTokenAtLimit(tokens.length);
+ setTokens((current) => [...current, token]);
+ return { folded };
+ },
+ [tokens.length],
+ );
+ const removeToken = useCallback((label: string) => {
+ setTokens((current) => current.filter((token) => token.label !== label));
+ }, []);
+ const foldedCount = Math.max(0, tokens.length - COMPOSER_PLUGIN_TOKEN_LIMIT);
+ return { tokens, addToken, removeToken, foldedCount };
+}
+
+/**
+ * Bridges the trigger menu's accept route: while a menu is open the dispatch
+ * relay hands `composer.acceptTriggerItem` payloads here; with no menu open
+ * the bridge answers UNROUTED.
+ */
+export function useComposerTriggerAcceptBridge({
+ active,
+ onAccept,
+}: {
+ active: boolean;
+ onAccept: (item: { label: string; value?: unknown }) => void;
+}): void {
+ const acceptRef = useRef(onAccept);
+ acceptRef.current = onAccept;
+ useEffect(() => {
+ if (!active) {
+ registerComposerTriggerAccept(null);
+ return;
+ }
+ registerComposerTriggerAccept((item) => acceptRef.current(item));
+ return () => registerComposerTriggerAccept(null);
+ }, [active]);
+}
diff --git a/apps/desktop/src/features/chat/transcript/ActionBarSlots.tsx b/apps/desktop/src/features/chat/transcript/ActionBarSlots.tsx
new file mode 100644
index 000000000..d2fe6dd5c
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/ActionBarSlots.tsx
@@ -0,0 +1,172 @@
+/**
+ * The shared action-bar gutters for `userAction` / `assistantAction`
+ * (`docs/plugin-plan/ui/user-action/`, `docs/plugin-plan/ui/assistant-action/`).
+ *
+ * The finalized shape is 【left slots】【host keys】【right slots】: the host
+ * keys render through `children` and can never be changed, hidden, removed,
+ * or folded by a plugin. Each side shows at most three visible items; the
+ * fourth onward folds into the host "⋯" menu on that side (left ⋯ before
+ * the host keys, right ⋯ last). 装卸插件时 the registry recompute re-renders
+ * the gutters, so install/uninstall reflows immediately. 出错隔离 and the
+ * `.pi-plugin-slot` chrome live in `SlotBoundary`.
+ */
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import type { UiMessage } from "@pi-desktop/shared";
+import type { PluginActionSlotProps } from "@pi-desktop/plugin-sdk";
+import { SlotBoundary, useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
+import type { SlotEntry, SlotSide } from "../../../plugins/renderer-slots/registry";
+import { dispatchFor } from "../../../plugins/renderer-host/dispatch";
+import {
+ actionSlotPropsFor,
+ splitActionSide,
+} from "./action-slot-props";
+
+type ActionBarSlotsProps = {
+ slot: "userAction" | "assistantAction";
+ message: UiMessage;
+ left: SlotEntry[];
+ right: SlotEntry[];
+ /** The host keys, rendered between the two sides; plugins never own them. */
+ children: ReactNode;
+};
+
+function ActionSlotItem({
+ entry,
+ slot,
+ message,
+ side,
+ sessionId,
+}: {
+ entry: SlotEntry;
+ slot: "userAction" | "assistantAction";
+ message: UiMessage;
+ side: SlotSide;
+ sessionId: string;
+}) {
+ // Rebuilt every render: the contract is props-push, the whole projection.
+ const props: PluginActionSlotProps = actionSlotPropsFor(
+ message,
+ side,
+ sessionId,
+ dispatchFor(entry.pluginId),
+ );
+ return (
+ <SlotBoundary entry={entry} slot={slot}>
+ {entry.component(props) as ReactNode}
+ </SlotBoundary>
+ );
+}
+
+/** One side's "⋯" menu for the folded registrations. */
+function ActionOverflowMenu({
+ slot,
+ message,
+ entries,
+ side,
+ sessionId,
+}: {
+ slot: "userAction" | "assistantAction";
+ message: UiMessage;
+ entries: SlotEntry[];
+ side: SlotSide;
+ sessionId: string;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ // Close on any click outside the menu; the folded items must not trap
+ // the pointer the way a stray popover would.
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (event: PointerEvent) => {
+ if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
+ };
+ document.addEventListener("pointerdown", onPointerDown, true);
+ return () => document.removeEventListener("pointerdown", onPointerDown, true);
+ }, [open]);
+
+ if (entries.length === 0) return null;
+ return (
+ <div ref={rootRef} className="pi-action-overflow" data-side={side}>
+ <button
+ type="button"
+ className="copy-btn icon pi-action-overflow-btn"
+ aria-label={t("chat.actionSlotMore")}
+ title={t("chat.actionSlotMore")}
+ aria-expanded={open ? "true" : "false"}
+ onClick={() => setOpen((value) => !value)}
+ >
+ ⋯
+ </button>
+ {open ? (
+ <div className="pi-action-overflow-panel" role="menu">
+ {entries.map((entry) => (
+ <ActionSlotItem
+ key={entry.id}
+ entry={entry}
+ slot={slot}
+ message={message}
+ side={side}
+ sessionId={sessionId}
+ />
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * Both plugin sides of one action bar around the host keys. With no
+ * registrations it renders exactly the children — a plugin-free bar keeps
+ * its exact current DOM.
+ */
+export function ActionBarSlots({
+ slot,
+ message,
+ left,
+ right,
+ children,
+}: ActionBarSlotsProps) {
+ const sessionId = useSlotSessionId();
+ if (left.length === 0 && right.length === 0) return <>{children}</>;
+ const leftSplit = splitActionSide(left);
+ const rightSplit = splitActionSide(right);
+ const renderItem = (entry: SlotEntry, side: SlotSide) => (
+ <ActionSlotItem
+ key={entry.id}
+ entry={entry}
+ slot={slot}
+ message={message}
+ side={side}
+ sessionId={sessionId}
+ />
+ );
+ return (
+ <>
+ {leftSplit.overflow.length ? (
+ <ActionOverflowMenu
+ slot={slot}
+ message={message}
+ entries={leftSplit.overflow}
+ side="left"
+ sessionId={sessionId}
+ />
+ ) : null}
+ {leftSplit.visible.map((entry) => renderItem(entry, "left"))}
+ {children}
+ {rightSplit.visible.map((entry) => renderItem(entry, "right"))}
+ {rightSplit.overflow.length ? (
+ <ActionOverflowMenu
+ slot={slot}
+ message={message}
+ entries={rightSplit.overflow}
+ side="right"
+ sessionId={sessionId}
+ />
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index 974448401..a6cc215f8 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -53,6 +53,9 @@ import {
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;
@@ -295,6 +298,8 @@ export const AssistantTurn = memo(function AssistantTurn({
const responseOutputTokens = assistantTurnResponseOutputTokens(entry);
const modelId = metaMessage?.modelId ?? latestUsageMessage?.modelId;
const hasError = messages.some((message) => Boolean(message.error));
+ const assistantActionLeft = useSlotEntries("assistantAction", "left");
+ const assistantActionRight = useSlotEntries("assistantAction", "right");
const complete =
!isActive && !hasError && Boolean(content) && Boolean(actionMessage);
const streaming =
@@ -422,6 +427,7 @@ export const AssistantTurn = memo(function AssistantTurn({
) : null}
{complete && actionMessage ? (
<div className="message-actions">
+ <ActionBarSlots slot="assistantAction" message={actionMessage} left={assistantActionLeft} right={assistantActionRight}>
<MessageTimestamp createdAt={actionMessage.createdAt} />
<CopyButton text={content} label={t("chat.copy")} />
<TooltipButton
@@ -440,8 +446,12 @@ export const AssistantTurn = memo(function AssistantTurn({
>
<IconReview size={13} />
</TooltipButton>
+ </ActionBarSlots>
</div>
) : null}
+ {complete && actionMessage ? (
+ <EntryExtraStack message={actionMessage} />
+ ) : null}
</div>
</div>
);
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index 00f71bec2..a8398de83 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -29,6 +29,7 @@ import {
useTranscriptMenu,
} from "./TranscriptMenu";
import { conversationMenuItems } from "./menu-items";
+import { SlotSessionProvider } from "../../../plugins/renderer-slots/use-slots";
type ChatTranscriptProps = {
sessionId: string | undefined;
@@ -221,6 +222,7 @@ function TranscriptBody({
return (
<TranscriptSearchContext.Provider value={searchTarget}>
<DisclosureAnchorContext.Provider value={disclosureAnchorNotifier}>
+ <SlotSessionProvider sessionId={sessionId ?? ""}>
<div
className="thread-wrap"
ref={wrapRef}
@@ -357,6 +359,7 @@ function TranscriptBody({
</TooltipButton>
) : null}
</div>
+ </SlotSessionProvider>
</DisclosureAnchorContext.Provider>
</TranscriptSearchContext.Provider>
);
diff --git a/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx b/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx
new file mode 100644
index 000000000..eb083e0dc
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx
@@ -0,0 +1,129 @@
+/**
+ * The `entryExtra` slot mount (`docs/plugin-plan/ui/entry-extra/`).
+ *
+ * Additive blocks under the assistant reply body, stacked in registration
+ * order. The host owns the height contract: a collapsed block clamps at
+ * 320px with an edge fade and the host expand toggle; expanded it scrolls
+ * internally up to 600px. Blocks appear with the finished reply (the same
+ * internally up to 600px. Blocks appear with the finished reply, and the
+ * whole stack re-renders per reply the way props-push would rebuild it.
+ *
+ * 出错隔离 lives in `SlotBoundary`: a throwing block collapses only itself.
+ */
+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import type { UiMessage } from "@pi-desktop/shared";
+import type { PluginEntryExtraSlotProps } from "@pi-desktop/plugin-sdk";
+import {
+ SlotBoundary,
+ useSlotEntries,
+ useSlotSessionId,
+} from "../../../plugins/renderer-slots/use-slots";
+import type { SlotEntry } from "../../../plugins/renderer-slots/registry";
+import { dispatchFor } from "../../../plugins/renderer-host/dispatch";
+import {
+ ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT,
+ ENTRY_EXTRA_EXPANDED_MAX_HEIGHT,
+ entryExtraPropsFor,
+} from "./entry-extra-props";
+
+export { ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT, ENTRY_EXTRA_EXPANDED_MAX_HEIGHT };
+
+/** One registration's clamped viewport plus the host expand toggle. */
+function EntryExtraBlock({
+ entry,
+ message,
+ sessionId,
+}: {
+ entry: SlotEntry;
+ message: UiMessage;
+ sessionId: string;
+}) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const contentRef = useRef<HTMLDivElement>(null);
+ const [overflows, setOverflows] = useState(false);
+
+ // The toggle exists only when content actually exceeds the collapsed clamp;
+ // ResizeObserver keeps that honest when a block loads data asynchronously.
+ useLayoutEffect(() => {
+ const viewport = viewportRef.current;
+ const content = contentRef.current;
+ if (!viewport || !content || typeof ResizeObserver === "undefined") {
+ setOverflows(false);
+ return;
+ }
+ const measure = () => {
+ setOverflows(content.scrollHeight > viewport.clientHeight + 1);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(content);
+ observer.observe(viewport);
+ return () => observer.disconnect();
+ }, []);
+
+ // Rebuilt every render: the contract is props-push, the whole projection.
+ const props: PluginEntryExtraSlotProps = entryExtraPropsFor(
+ message,
+ sessionId,
+ dispatchFor(entry.pluginId),
+ );
+ const showToggle = expanded || overflows;
+ return (
+ <SlotBoundary entry={entry} slot="entryExtra">
+ <div
+ className="pi-entry-extra-block"
+ data-expanded={expanded ? "true" : undefined}
+ >
+ <div
+ ref={viewportRef}
+ className="pi-entry-extra-viewport"
+ data-clipped={!expanded && overflows ? "true" : undefined}
+ style={{
+ maxHeight: expanded
+ ? ENTRY_EXTRA_EXPANDED_MAX_HEIGHT
+ : ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT,
+ }}
+ >
+ <div ref={contentRef}>{entry.component(props) as ReactNode}</div>
+ </div>
+ {showToggle ? (
+ <button
+ type="button"
+ className="pi-entry-extra-toggle"
+ data-state={expanded ? "expanded" : "collapsed"}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {expanded
+ ? t("chat.entryExtraCollapse")
+ : t("chat.entryExtraExpand")}
+ </button>
+ ) : null}
+ </div>
+ </SlotBoundary>
+ );
+}
+
+/**
+ * The whole slot region for one assistant reply: zero or more blocks in
+ * registration order. Renders nothing when no plugin registered the slot.
+ */
+export function EntryExtraStack({ message }: { message: UiMessage }) {
+ const entries = useSlotEntries("entryExtra");
+ const sessionId = useSlotSessionId();
+ if (entries.length === 0) return null;
+ return (
+ <div className="pi-entry-extra-stack" data-pi-slot="entryExtra">
+ {entries.map((entry) => (
+ <EntryExtraBlock
+ key={entry.id}
+ entry={entry}
+ message={message}
+ sessionId={sessionId}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index 7b69b7445..7b6466f2a 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -21,6 +21,8 @@ import {
} from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
import { userMessageMenuItems } from "./menu-items";
+import { ActionBarSlots } from "./ActionBarSlots";
+import { useSlotEntries } from "../../../plugins/renderer-slots/use-slots";
import { SessionMessageOrigin } from "./SessionMessageOrigin";
import {
CopyButton,
@@ -84,6 +86,11 @@ export const MessageRow = memo(function MessageRow({
const editableUserMessage = isUser && !isSessionMessage;
const workspaceRoot = useAppStore((s) => s.workspace?.path);
const openFileRef = useOpenChatFileRef();
+ const userActionLeftEntries = useSlotEntries("userAction", "left");
+ const userActionRightEntries = useSlotEntries("userAction", "right");
+ // Only the user card carries userAction; system rows keep a plugin-free bar.
+ const userActionLeft = isUser ? userActionLeftEntries : [];
+ const userActionRight = isUser ? userActionRightEntries : [];
// Slash prompts are stored expanded; editing works on the typed form so the
// resent turn re-expands the template (D123).
const editSeed =
@@ -308,6 +315,7 @@ export const MessageRow = memo(function MessageRow({
) : null}
{!editing && (hasAnswer || showRevisionPager) ? (
<div className="message-actions">
+ <ActionBarSlots slot="userAction" message={message} left={userActionLeft} right={userActionRight}>
<MessageTimestamp createdAt={message.createdAt} />
{showRevisionPager ? (
<div className="message-revision-pager" role="group" aria-label={t("chat.revisions")}>
@@ -367,6 +375,7 @@ export const MessageRow = memo(function MessageRow({
<IconTrash size={13} />
</TooltipButton>
) : null}
+ </ActionBarSlots>
</div>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx
new file mode 100644
index 000000000..02b92a998
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx
@@ -0,0 +1,68 @@
+/**
+ * The `toolCard` slot host (`docs/plugin-plan/ui/tool-card/`).
+ *
+ * One plugin card replaces the host default card entirely for a claimed
+ * tool call; the plugin draws the whole card and failure stays data. The
+ * host owns the push cadence: running updates merge onto a 500ms beat so a
+ * chatty stream cannot re-render the card per token, while a status
+ * transition and the final result push immediately. 出错隔离 lives in
+ * `SlotBoundary` — a throwing card collapses only itself, and the host
+ * default card is gone for this row, so the failure is a collapsed region,
+ * not a missing tool call.
+ */
+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import type { UiMessage } from "@pi-desktop/shared";
+import type { PluginToolCardSlotProps } from "@pi-desktop/plugin-sdk";
+import { SlotBoundary, useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
+import type { SlotEntry } from "../../../plugins/renderer-slots/registry";
+import { dispatchFor } from "../../../plugins/renderer-host/dispatch";
+import {
+ TOOL_CARD_RUNNING_INTERVAL_MS,
+ shouldEmitToolCard,
+ toolCardPropsFor,
+} from "./tool-card-props";
+
+export function PluginToolCard({
+ entry,
+ message,
+}: {
+ entry: SlotEntry;
+ message: UiMessage;
+}) {
+ const sessionId = useSlotSessionId();
+ // The committed projection only advances on the cadence, never per tick.
+ const [committed, setCommitted] = useState<PluginToolCardSlotProps>(() =>
+ toolCardPropsFor(message, sessionId, dispatchFor(entry.pluginId)),
+ );
+ const lastEmitRef = useRef({ at: Date.now(), status: committed.toolStatus });
+
+ useLayoutEffect(() => {
+ const status = message.toolStatus === "running" || message.toolStatus === "error"
+ ? message.toolStatus
+ : "success";
+ const emit = () => {
+ lastEmitRef.current = { at: Date.now(), status };
+ setCommitted(toolCardPropsFor(message, sessionId, dispatchFor(entry.pluginId)));
+ };
+ if (shouldEmitToolCard(lastEmitRef.current.at, lastEmitRef.current.status, status, Date.now())) {
+ emit();
+ return;
+ }
+ // Still running before the beat: commit with the latest data at the
+ // next boundary, so the merged push never drops the newest snapshot.
+ const remaining = Math.max(
+ 0,
+ TOOL_CARD_RUNNING_INTERVAL_MS - (Date.now() - lastEmitRef.current.at),
+ );
+ const timer = window.setTimeout(emit, remaining);
+ return () => window.clearTimeout(timer);
+ }, [message, sessionId, entry]);
+
+ return (
+ <SlotBoundary entry={entry} slot="toolCard">
+ <div className="pi-plugin-tool-card" data-pi-tool={message.toolName}>
+ {entry.component(committed) as ReactNode}
+ </div>
+ </SlotBoundary>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
index 205aad94f..e9c2017c1 100644
--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
@@ -80,6 +80,8 @@ import {
delegateModelId,
delegateThinkingLevel,
} from "./model";
+import { PluginToolCard } from "./PluginToolCard";
+import { useSlotEntryForKey } from "../../../plugins/renderer-slots/use-slots";
type ToolRowProps = {
message: UiMessage;
@@ -361,6 +363,16 @@ export const ToolRow = memo(function ToolRow({
: "is-done";
const caret = hasDetails ? <IconChevronRight size={12} /> : null;
+ // The toolCard slot: one plugin card replaces the host card entirely for a
+ // tool the plugin itself registered (the no-claim gate lives in the
+ // loader). Topology nodes and denied rows keep the host card.
+ const pluginCardEntry = useSlotEntryForKey(
+ "toolCard",
+ variant === "default" && status !== "denied" ? message.toolName : undefined,
+ );
+ if (pluginCardEntry) {
+ return <PluginToolCard entry={pluginCardEntry} message={message} />;
+ }
return (
<div
className={`tool-row ${variant === "topology" ? "subagent-topology-node" : ""} ${
diff --git a/apps/desktop/src/features/chat/transcript/action-slot-props.ts b/apps/desktop/src/features/chat/transcript/action-slot-props.ts
new file mode 100644
index 000000000..e15b86bfa
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/action-slot-props.ts
@@ -0,0 +1,58 @@
+/**
+ * Props projection and pagination for the additive action slots
+ * (`docs/plugin-plan/ui/user-action/`, `docs/plugin-plan/ui/assistant-action/`).
+ *
+ * The finalized shape is 【left slots】【host keys】【right slots】: plugins
+ * may only add around the host keys, which never collapse. Each side shows
+ * at most three items; the fourth onward folds into the host "⋯" menu on
+ * that side (left ⋯ before the host keys, right ⋯ last). JSX-free so logic
+ * tests can drive it directly.
+ */
+import type {
+ PluginActionSlotProps,
+ PluginRendererDispatch,
+ PluginSlotPosition,
+} from "@pi-desktop/plugin-sdk";
+import type { UiMessage } from "@pi-desktop/shared";
+
+/** Visible items per side; the rest fold into the host ⋯ menu. */
+export const ACTION_SLOT_VISIBLE_LIMIT = 3;
+
+/** The data projection the contract hands to an action item. */
+export function actionSlotMessage(
+ message: UiMessage,
+): PluginActionSlotProps["message"] {
+ return {
+ id: message.id,
+ role: message.role,
+ content: message.content,
+ createdAt: message.createdAt,
+ };
+}
+
+/** Full props for one action item; rebuilt per render (props-push). */
+export function actionSlotPropsFor(
+ message: UiMessage,
+ position: PluginSlotPosition,
+ sessionId: string,
+ dispatch: PluginRendererDispatch,
+): PluginActionSlotProps {
+ return {
+ message: actionSlotMessage(message),
+ messageId: message.id,
+ sessionId,
+ position,
+ dispatch,
+ };
+}
+
+/** Split one side's registrations into visible items and ⋯ overflow. */
+export function splitActionSide<T>(
+ entries: readonly T[],
+ limit: number = ACTION_SLOT_VISIBLE_LIMIT,
+): { visible: T[]; overflow: T[] } {
+ return {
+ visible: entries.slice(0, limit),
+ overflow: entries.slice(limit),
+ };
+}
diff --git a/apps/desktop/src/features/chat/transcript/entry-extra-props.ts b/apps/desktop/src/features/chat/transcript/entry-extra-props.ts
new file mode 100644
index 000000000..ca43120a1
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/entry-extra-props.ts
@@ -0,0 +1,44 @@
+/**
+ * Props projection for the `entryExtra` slot (`docs/plugin-plan/ui/entry-extra/`).
+ *
+ * The contract fixes the shape: the assistant message data, the ids, and the
+ * plugin's own dispatch relay — no host functions, no extra data. Kept
+ * JSX-free so logic tests can drive it directly.
+ */
+import type {
+ PluginEntryExtraSlotProps,
+ PluginRendererDispatch,
+} from "@pi-desktop/plugin-sdk";
+import type { UiMessage } from "@pi-desktop/shared";
+
+/** The data projection the contract hands to an entryExtra block. */
+export function entryExtraMessage(
+ message: UiMessage,
+): PluginEntryExtraSlotProps["message"] {
+ return {
+ id: message.id,
+ role: "assistant",
+ content: message.content,
+ createdAt: message.createdAt,
+ };
+}
+
+/** Full props for one entryExtra block; rebuilt per render (props-push). */
+export function entryExtraPropsFor(
+ message: UiMessage,
+ sessionId: string,
+ dispatch: PluginRendererDispatch,
+): PluginEntryExtraSlotProps {
+ return {
+ message: entryExtraMessage(message),
+ messageId: message.id,
+ sessionId,
+ dispatch,
+ };
+}
+
+/** Collapsed-state clamp: taller content fades and shows the host toggle. */
+export const ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT = 320;
+
+/** Expanded state scrolls internally up to this height. */
+export const ENTRY_EXTRA_EXPANDED_MAX_HEIGHT = 600;
diff --git a/apps/desktop/src/features/chat/transcript/tool-card-props.ts b/apps/desktop/src/features/chat/transcript/tool-card-props.ts
new file mode 100644
index 000000000..0fa178130
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/tool-card-props.ts
@@ -0,0 +1,67 @@
+/**
+ * Props projection and push cadence for the `toolCard` slot
+ * (`docs/plugin-plan/ui/tool-card/`).
+ *
+ * The contract fixes the fields (toolName / toolCallId / toolArgs? /
+ * toolStatus / toolResult? / toolError? / durationMs? + ids + dispatch) and
+ * the cadence: while the tool runs, the whole projection is pushed on a
+ * 500ms merged beat; a status transition and the final result push
+ * immediately. Failure is data (`toolError`), never a throw. JSX-free so
+ * logic tests can drive it directly.
+ */
+import type {
+ PluginRendererDispatch,
+ PluginToolCardSlotProps,
+} from "@pi-desktop/plugin-sdk";
+import type { UiMessage } from "@pi-desktop/shared";
+
+/** Merged-push beat while a call is still running. */
+export const TOOL_CARD_RUNNING_INTERVAL_MS = 500;
+
+/**
+ * The props vocabulary carries three statuses; `denied` is host vocabulary,
+ * so a denied row keeps the host default card and never reaches a plugin.
+ */
+export function toolCardStatusOf(
+ message: UiMessage,
+): PluginToolCardSlotProps["toolStatus"] {
+ return message.toolStatus === "running" || message.toolStatus === "error"
+ ? message.toolStatus
+ : "success";
+}
+
+/** Full props for one card; rebuilt per render (props-push). */
+export function toolCardPropsFor(
+ message: UiMessage,
+ sessionId: string,
+ dispatch: PluginRendererDispatch,
+): PluginToolCardSlotProps {
+ return {
+ toolName: message.toolName ?? "",
+ toolCallId: message.toolCallId ?? message.id,
+ toolArgs: message.toolArgs,
+ toolStatus: toolCardStatusOf(message),
+ toolResult: message.toolResult,
+ toolError: message.isError ? message.error : undefined,
+ durationMs: message.toolDurationMs,
+ messageId: message.id,
+ sessionId,
+ dispatch,
+ };
+}
+
+/**
+ * The push decision: a status transition or a finished result is immediate;
+ * running-tick updates merge onto the 500ms beat.
+ */
+export function shouldEmitToolCard(
+ lastEmittedAt: number,
+ lastStatus: PluginToolCardSlotProps["toolStatus"],
+ nextStatus: PluginToolCardSlotProps["toolStatus"],
+ now: number,
+ interval: number = TOOL_CARD_RUNNING_INTERVAL_MS,
+): boolean {
+ if (nextStatus !== lastStatus) return true;
+ if (nextStatus !== "running") return true;
+ return now - lastEmittedAt >= interval;
+}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 7b871d2d1..a20090b4a 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -966,6 +966,9 @@ export const api = {
invoke<PlanResolutionResult>(IPC.invoke.plansResolve, resolution),
listPlugins: () =>
invoke<{ plugins: PluginSummary[] }>(IPC.invoke.pluginList),
+ /** One renderer slot component asking its own plugin for one JSON answer. */
+ pluginRendererCall: (pluginId: string, method: string, args?: unknown) =>
+ invoke(IPC.invoke.pluginRendererCall, pluginId, method, args),
/**
* Picking a folder only reports what it declares; the load happens in
* `confirmLoadDevPlugin` once the user has seen that.
diff --git a/apps/desktop/src/lib/block-renderer.ts b/apps/desktop/src/lib/block-renderer.ts
new file mode 100644
index 000000000..b592f8b91
--- /dev/null
+++ b/apps/desktop/src/lib/block-renderer.ts
@@ -0,0 +1,27 @@
+/**
+ * Pure helpers for the `blockRenderer` slot (`docs/plugin-plan/ui/block-renderer/`).
+ *
+ * The contract: a plugin claims the whole code block for a fence language
+ * registered as `<pluginId>:lang`; the host hands `{ language, source }`
+ * once when the fence closes (props-once), and the plugin owns the chrome.
+ * The host keeps exactly one guarantee — a block taller than 4000px counts
+ * as a render failure and falls back to the host code block.
+ */
+
+/** The one host-side clamp on a plugin-drawn block. */
+export const BLOCK_RENDERER_MAX_HEIGHT_PX = 4000;
+
+/** True when a block's drawn content exceeds the host clamp. */
+export function blockRendererOverflow(contentHeight: number): boolean {
+ return contentHeight > BLOCK_RENDERER_MAX_HEIGHT_PX;
+}
+
+/**
+ * Fast path for the render loop: only a label that carries the
+ * `<pluginId>:` prefix shape can hit a registration, so plain languages
+ * (`json`, `ts`, `mermaid`, …) never touch the slot registry.
+ */
+export function blockRendererCandidate(lang: string): string | undefined {
+ const trimmed = lang.trim();
+ return trimmed.includes(":") ? trimmed : undefined;
+}
diff --git a/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
new file mode 100644
index 000000000..d0b141c0e
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
@@ -0,0 +1,58 @@
+/**
+ * Mounts once per app window and keeps the set of loaded renderer modules in
+ * step with the plugin list: load on enable, unload on disable/uninstall —
+ * 卸载摘注册, exactly as the slot contract promises.
+ */
+import { useEffect } from "react";
+import { useAppStore } from "../../stores/app-store";
+import {
+ loadedRendererPluginIds,
+ loadRendererModule,
+ unloadRendererModule,
+} from "./loader";
+import { installRendererImportMap } from "./import-map";
+import "../renderer-slots/slot-shell.css";
+
+function eligible(summary: {
+ enabled: boolean;
+ status: string;
+ permissions: string[];
+ renderer?: { entry: string; actions: string[]; callMethods: string[] } | null;
+}): boolean {
+ if (!summary.renderer) return false;
+ if (!summary.enabled) return false;
+ if (summary.status === "disabled" || summary.status === "load_error") return false;
+ return summary.permissions.includes("renderer.extension");
+}
+
+export function PluginRendererHost(): null {
+ const plugins = useAppStore((state) => state.plugins);
+
+ useEffect(() => {
+ // Must run before the first plugin import resolves bare `react`.
+ installRendererImportMap();
+ }, []);
+
+ useEffect(() => {
+ const wanted = new Set<string>();
+ for (const summary of plugins) {
+ if (!eligible(summary)) continue;
+ wanted.add(summary.id);
+ void loadRendererModule(
+ summary.id,
+ summary.renderer?.entry,
+ summary.version,
+ { actions: summary.renderer?.actions ?? [], tools: summary.tools },
+ ).catch((error: unknown) => {
+ const code = (error as { code?: string } | null)?.code ?? "PLUGIN_SLOT_LOAD_FAILED";
+ console.warn(`[plugin-renderer] ${code}:`, error instanceof Error ? error.message : error);
+ });
+ }
+ for (const id of loadedRendererPluginIds()) {
+ if (!wanted.has(id)) void unloadRendererModule(id);
+ }
+ }, [plugins]);
+
+ return null;
+}
+
diff --git a/apps/desktop/src/plugins/renderer-host/dispatch.ts b/apps/desktop/src/plugins/renderer-host/dispatch.ts
new file mode 100644
index 000000000..7d9545a00
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-host/dispatch.ts
@@ -0,0 +1,121 @@
+/**
+ * Outbound dispatch gate (`slot-contract.html` §3).
+ *
+ * A slot component's only way out is `dispatch(action, payload)`. The relay
+ * is bound to one plugin id, so a component can never act as another plugin,
+ * and every action must be in that plugin's `manifest.rendererActions`
+ * whitelist (`PLUGIN_ACTION_UNDECLARED` otherwise). `plugin.call` is
+ * forwarded to the plugin's own headless entry over the main-process relay;
+ * `composer.insertText` is renderer-local and routes through the insert
+ * bridge.
+ */
+import { api } from "../../lib/api";
+import { insertComposerText } from "../../features/chat/composer/insert-bridge";
+import { acceptComposerTriggerItem } from "../../features/chat/composer/trigger-bridge";
+import type { PluginRendererDispatch } from "@pi-desktop/plugin-sdk";
+
+export type DispatchErrorCode =
+ | "PLUGIN_ACTION_UNDECLARED"
+ | "PLUGIN_ACTION_UNROUTED"
+ | "PLUGIN_ACTION_INVALID_PAYLOAD";
+
+/** A coded refusal from the dispatch path; rejects rather than throws. */
+export class DispatchError extends Error {
+ readonly code: DispatchErrorCode;
+ constructor(code: DispatchErrorCode, message: string) {
+ super(message);
+ this.name = "DispatchError";
+ this.code = code;
+ }
+}
+
+export type RendererDispatchContext = {
+ /** The whitelists from `manifest.rendererActions`, via PluginSummary. */
+ actions: readonly string[];
+ /** The plugin's own tool names, for the toolCard no-claim gate. */
+ tools?: readonly string[];
+};
+
+export function createDispatch(
+ pluginId: string,
+ context: RendererDispatchContext,
+): PluginRendererDispatch {
+ const dispatch: PluginRendererDispatch = async (action, payload) => {
+ if (!context.actions.includes(action)) {
+ throw new DispatchError(
+ "PLUGIN_ACTION_UNDECLARED",
+ `action ${String(action)} is not in ${pluginId}'s rendererActions`,
+ );
+ }
+ if (action === "plugin.call") {
+ const call = (payload ?? {}) as { method?: unknown; args?: unknown };
+ if (typeof call.method !== "string" || call.method.length === 0) {
+ throw new DispatchError(
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ "plugin.call requires { method, args? }",
+ );
+ }
+ return api.pluginRendererCall(pluginId, call.method, call.args);
+ }
+ if (action === "composer.insertText") {
+ if (typeof payload !== "string" || payload.length === 0) {
+ throw new DispatchError(
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ "composer.insertText requires a non-empty string",
+ );
+ }
+ if (!insertComposerText(payload)) {
+ throw new DispatchError(
+ "PLUGIN_ACTION_UNROUTED",
+ "no composer is mounted to receive text",
+ );
+ }
+ return { ok: true };
+ }
+ if (action === "composer.acceptTriggerItem") {
+ // Routed by the composer trigger host; without a live listener the
+ // answer is UNROUTED, never a silent drop.
+ if (!acceptComposerTriggerItem(payload)) {
+ throw new DispatchError(
+ "PLUGIN_ACTION_UNROUTED",
+ "no trigger menu is open to accept the item",
+ );
+ }
+ return { ok: true };
+ }
+ throw new DispatchError("PLUGIN_ACTION_UNROUTED", `no route for action ${String(action)}`);
+ };
+ return dispatch;
+}
+
+
+/**
+ * One dispatch per loaded plugin, bound when its module loads. Slot outlets
+ * hand the bound relay to components as the `dispatch` prop.
+ */
+const dispatchCache = new Map<string, PluginRendererDispatch>();
+
+export function bindDispatch(pluginId: string, actions: readonly string[]): void {
+ dispatchCache.set(pluginId, createDispatch(pluginId, { actions }));
+}
+
+export function unbindDispatch(pluginId: string): void {
+ dispatchCache.delete(pluginId);
+}
+
+/**
+ * The relay for one plugin's components. Falls back to a gate with an empty
+ * whitelist when the plugin has no live binding — every call then refuses
+ * with `PLUGIN_ACTION_UNDECLARED` instead of leaking a route.
+ */
+export function dispatchFor(pluginId: string): PluginRendererDispatch {
+ return (
+ dispatchCache.get(pluginId) ??
+ createDispatch(pluginId, { actions: [] })
+ );
+}
+
+/** Test seam: drop cached dispatches. */
+export function resetDispatchForTests(): void {
+ dispatchCache.clear();
+}
diff --git a/apps/desktop/src/plugins/renderer-host/import-map.ts b/apps/desktop/src/plugins/renderer-host/import-map.ts
new file mode 100644
index 000000000..f304c362c
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-host/import-map.ts
@@ -0,0 +1,87 @@
+/**
+ * The one React the host renderer and every plugin renderer module share.
+ *
+ * A plugin that brought its own React would break hooks and context in the
+ * first component that mixed the two, and the failure looks like a plugin bug
+ * rather than a duplicate module. The host therefore answers the bare
+ * specifiers `react`, `react-dom` and `react-dom/client` from here, through a
+ * document import map pointing at generated blob modules.
+ *
+ * The shims are generated from the live namespaces rather than a hand-written
+ * list, so a hook the host can use is a hook a plugin can import; there is no
+ * second surface to keep in step.
+ */
+import * as ReactDom from "react-dom";
+import * as ReactDomClient from "react-dom/client";
+import * as React from "react";
+
+/** Where the generated shims read their modules from. Not a plugin API. */
+export const RENDERER_HOST_KEY = "__PI_RENDERER_HOST__";
+
+type RendererHostModules = {
+ react: typeof React;
+ reactDom: typeof ReactDom;
+ reactDomClient: typeof ReactDomClient;
+};
+
+export const REACT_IMPORT_MAP: Readonly<Record<string, keyof RendererHostModules>> = {
+ react: "react",
+ "react-dom": "reactDom",
+ "react-dom/client": "reactDomClient",
+};
+
+let installed = false;
+
+/**
+ * A module that re-exports the host's namespace. One `export const x = host.x`
+ * per key is what makes this work without a bundler: a bare `export *` has
+ * nothing to point at, because the host's copy lives in a closure, not at a URL.
+ */
+function shimSource(key: keyof RendererHostModules, namespace: Record<string, unknown>): string {
+ const lines = [`const host = globalThis.${RENDERER_HOST_KEY}[${JSON.stringify(key)}];`];
+ if ("default" in namespace) lines.push("export default host.default;");
+ for (const name of Object.keys(namespace)) {
+ if (name === "default") continue;
+ // Only legal binding names; React's namespace has nothing else, and a key
+ // that is not one would fail the whole module rather than quietly vanish.
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) continue;
+ lines.push(`export const ${name} = host[${JSON.stringify(name)}];`);
+ }
+ return lines.join("\n");
+}
+
+function blobModuleUrl(modules: RendererHostModules, key: keyof RendererHostModules): string {
+ const namespace = modules[key] as unknown as Record<string, unknown>;
+ return URL.createObjectURL(
+ new Blob([shimSource(key, namespace)], { type: "text/javascript" }),
+ );
+}
+
+/**
+ * Publish the host's React and map the three bare specifiers onto it. Called
+ * once, before the first plugin module is evaluated — a plugin imported first
+ * would otherwise fail to resolve `react` at all.
+ */
+export function installRendererImportMap(): void {
+ if (installed) return;
+ installed = true;
+ const modules: RendererHostModules = {
+ react: React,
+ reactDom: ReactDom,
+ reactDomClient: ReactDomClient,
+ };
+ (globalThis as Record<string, unknown>)[RENDERER_HOST_KEY] = modules;
+ const imports: Record<string, string> = {};
+ for (const [specifier, key] of Object.entries(REACT_IMPORT_MAP)) {
+ imports[specifier] = blobModuleUrl(modules, key);
+ }
+ const script = document.createElement("script");
+ script.type = "importmap";
+ script.textContent = JSON.stringify({ imports });
+ document.head.appendChild(script);
+}
+
+/** Test seam: allow a second install in a fresh document. */
+export function resetRendererImportMap(): void {
+ installed = false;
+}
diff --git a/apps/desktop/src/plugins/renderer-host/loader.ts b/apps/desktop/src/plugins/renderer-host/loader.ts
new file mode 100644
index 000000000..336efe47e
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-host/loader.ts
@@ -0,0 +1,188 @@
+/**
+ * Loads one plugin's renderer entry into the app document and hands it the
+ * `pi` API (`PiRendererApi` in @pi-desktop/plugin-sdk).
+ *
+ * The entry is a plain ES module served from `plugin-renderer://<id>/...`.
+ * Loads are single-flight per plugin: the first caller starts the fetch and
+ * everyone else awaits the same promise. A module without `onLoad` is
+ * refused with `PLUGIN_SLOT_LOAD_FAILED`; a module that throws during
+ * registration leaves the registrations it already made behind, so the
+ * unload path still tears them down.
+ */
+import {
+ PLUGIN_RENDERER_SCHEME,
+ type PiRendererApi,
+ type PiRendererModule,
+ type PluginRendererSlotOptions,
+ toolCardOwnershipError,
+} from "@pi-desktop/plugin-sdk";
+import { slotRegistry, type SlotRegistrationHandle } from "../renderer-slots/registry";
+import {
+ injectStyle,
+ removePluginStyles,
+ type PluginStyleHandle,
+} from "../renderer-slots/style-injection";
+import {
+ bindDispatch,
+ createDispatch,
+ unbindDispatch,
+ type RendererDispatchContext,
+} from "./dispatch";
+
+export type RendererModuleRecord = {
+ pluginId: string;
+ module: PiRendererModule;
+};
+
+const loaded = new Map<string, Promise<RendererModuleRecord | null>>();
+
+function rendererModuleUrl(pluginId: string, entry: string): string {
+ return `${PLUGIN_RENDERER_SCHEME}://${encodeURIComponent(pluginId)}/${entry.replace(/^\//, "")}`;
+}
+
+function codedError(code: string, message: string): Error {
+ const error = new Error(message) as Error & { code?: string };
+ error.code = code;
+ return error;
+}
+
+function buildPiApi(
+ pluginId: string,
+ version: string,
+ context: RendererDispatchContext,
+): PiRendererApi {
+ const handles: (SlotRegistrationHandle | PluginStyleHandle)[] = [];
+ const api: PiRendererApi = {
+ plugin: { id: pluginId, version },
+ slots: {
+ register<Props>(
+ slot: Parameters<PiRendererApi["slots"]["register"]>[0],
+ component: (props: Props) => unknown,
+ options?: PluginRendererSlotOptions,
+ ) {
+ // The toolCard no-claim gate: a card may only serve a tool the
+ // plugin's own manifest declares (`contributes.agentTools`).
+ if (slot === "toolCard") {
+ const ownershipError = toolCardOwnershipError(
+ options?.toolName ?? "",
+ context.tools,
+ );
+ if (ownershipError) {
+ throw codedError("PLUGIN_SLOT_INVALID_KEY", ownershipError);
+ }
+ }
+ const handle = slotRegistry.register(
+ pluginId,
+ slot,
+ component as unknown,
+ options,
+ );
+ handles.push(handle);
+ return handle;
+ },
+ },
+ ui: {
+ injectStyle(css: string) {
+ const handle = injectStyle(pluginId, css);
+ handles.push(handle);
+ return handle;
+ },
+ },
+ };
+ // Keeps the handles reachable for host-side teardown even if the plugin
+ // drops its own registration handles.
+ handlesAtLoad.set(api, handles);
+ return api;
+}
+
+const handlesAtLoad = new WeakMap<object, (SlotRegistrationHandle | PluginStyleHandle)[]>();
+
+/**
+ * Load and `onLoad` one renderer module. Resolves `null` when the plugin
+ * declares no renderer entry. Single-flight per plugin. `context.tools` is
+ * the plugin's own declared tool names (the no-claim gate for `toolCard`).
+ */
+export function loadRendererModule(
+ pluginId: string,
+ entry: string | undefined,
+ version: string,
+ context: RendererDispatchContext,
+): Promise<RendererModuleRecord | null> {
+ if (!entry) return Promise.resolve(null);
+ const existing = loaded.get(pluginId);
+ if (existing) return existing;
+ const promise = (async () => {
+ const url = rendererModuleUrl(pluginId, entry);
+ let namespace: unknown;
+ try {
+ namespace = await import(/* @vite-ignore */ url);
+ } catch (error) {
+ throw codedError(
+ "PLUGIN_SLOT_LOAD_FAILED",
+ `renderer entry for ${pluginId} failed to load: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ const candidate = namespace as { default?: unknown } & Record<string, unknown>;
+ const mod = ((candidate.default ?? candidate) ?? {}) as Partial<PiRendererModule>;
+ if (typeof mod.onLoad !== "function") {
+ throw codedError(
+ "PLUGIN_SLOT_LOAD_FAILED",
+ `renderer entry for ${pluginId} must export onLoad`,
+ );
+ }
+ bindDispatch(pluginId, context.actions);
+ try {
+ await mod.onLoad(buildPiApi(pluginId, version, context));
+ } catch (error) {
+ // A throwing onLoad still leaves the registrations it already made;
+ // surface the failure but keep the host consistent.
+ unbindDispatch(pluginId);
+ slotRegistry.unregisterPlugin(pluginId);
+ removePluginStyles(pluginId);
+ throw codedError(
+ "PLUGIN_SLOT_LOAD_FAILED",
+ `onLoad for ${pluginId} failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ return { pluginId, module: mod as PiRendererModule };
+ })();
+ loaded.set(pluginId, promise);
+ promise.catch(() => {
+ // Failed loads are retryable: drop the memo so a fixed plugin can reload.
+ loaded.delete(pluginId);
+ });
+ return promise;
+}
+
+/** Plugin ids with a live renderer module (host teardown diffing). */
+export function loadedRendererPluginIds(): string[] {
+ return [...loaded.keys()];
+}
+
+/**
+ * 卸载摘注册: registrations, injected styles, the dispatch binding, then the
+ * plugin's own onUnload. Teardown never blocks on a plugin's own failure.
+ */
+export async function unloadRendererModule(pluginId: string): Promise<void> {
+ const record = loaded.get(pluginId);
+ loaded.delete(pluginId);
+ slotRegistry.unregisterPlugin(pluginId);
+ removePluginStyles(pluginId);
+ unbindDispatch(pluginId);
+ if (!record) return;
+ try {
+ const settled = await record;
+ if (settled && typeof settled.module.onUnload === "function") {
+ await settled.module.onUnload();
+ }
+ } catch {
+ // Ignored by design: the plugin is going away regardless.
+ }
+}
+
+/** Test seam. */
+export function resetRendererModulesForTests(): void {
+ for (const id of loaded.keys()) {
+ void unloadRendererModule(id);
+ }
+}
diff --git a/apps/desktop/src/plugins/renderer-slots/registry.ts b/apps/desktop/src/plugins/renderer-slots/registry.ts
new file mode 100644
index 000000000..2168a184b
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-slots/registry.ts
@@ -0,0 +1,182 @@
+import {
+ PLUGIN_RENDERER_SLOTS,
+ slotKeyError,
+ slotPositionsError,
+ type PluginRendererSlot,
+ type PluginRendererSlotOptions,
+} from "@pi-desktop/plugin-sdk";
+
+/**
+ * The renderer-side slot registry (`docs/plugin-plan/slot-contract.html`).
+ *
+ * A plugin's renderer entry registers components through `pi.slots.register`;
+ * this store owns the resulting catalog. It is deliberately React-free so
+ * logic tests can drive it directly — the React glue lives in `use-slots.ts`.
+ *
+ * Conflict semantics follow the contract: additive slots stack in
+ * registration order and never clash; keyed slots (`toolCard` by tool name,
+ * `blockRenderer` by `<pluginId>:lang`, `composerTrigger` by symbol) refuse a
+ * second claim of the same key with `PLUGIN_SLOT_DUPLICATE`. Uninstalling a
+ * plugin drops every registration it held, in one call.
+ */
+
+export type SlotErrorCode =
+ | "PLUGIN_SLOT_UNKNOWN"
+ | "PLUGIN_SLOT_DUPLICATE"
+ | "PLUGIN_SLOT_INVALID_COMPONENT"
+ | "PLUGIN_SLOT_INVALID_KEY"
+ | "PLUGIN_SLOT_INVALID_POSITION";
+
+/** A coded refusal from the registration path; surfaces verbatim to the plugin. */
+export class SlotError extends Error {
+ readonly code: SlotErrorCode;
+ constructor(code: SlotErrorCode, message: string) {
+ super(message);
+ this.name = "SlotError";
+ this.code = code;
+ }
+}
+
+export type SlotSide = "left" | "right";
+
+export type SlotEntry = {
+ readonly id: string;
+ readonly pluginId: string;
+ readonly slot: PluginRendererSlot;
+ readonly component: (props: Record<string, unknown>) => unknown;
+ readonly options: PluginRendererSlotOptions;
+ /** Resolved sides for additive slots; empty for the rest. */
+ readonly sides: readonly SlotSide[];
+ /** Keyed slots carry their key (`toolName`, `<pluginId>:lang`, trigger). */
+ readonly key?: string;
+};
+
+export type SlotRegistrationHandle = {
+ readonly slot: PluginRendererSlot;
+ remove(): void;
+};
+
+type RegistryState = {
+ /** Bumped on every mutation; the useSyncExternalStore snapshot key. */
+ version: number;
+ /** Insertion order across plugins is the presentation order. */
+ entries: SlotEntry[];
+};
+
+function slotKeyFor(
+ slot: PluginRendererSlot,
+ options: PluginRendererSlotOptions | undefined,
+): string | undefined {
+ if (slot === "toolCard") return options?.toolName;
+ if (slot === "blockRenderer") return options?.language;
+ if (slot === "composerTrigger") return options?.trigger;
+ return undefined;
+}
+
+export class SlotRegistry {
+ private state: RegistryState = { version: 0, entries: [] };
+ private listeners = new Set<() => void>();
+ private nextId = 0;
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ };
+
+ getSnapshot = (): RegistryState => this.state;
+
+ private commit(entries: SlotEntry[]): void {
+ this.state = { version: this.state.version + 1, entries };
+ for (const listener of this.listeners) listener();
+ }
+
+ /**
+ * Register one slot component. Throws `SlotError` with a documented code
+ * when the host refuses the registration.
+ */
+ register(
+ pluginId: string,
+ slot: unknown,
+ component: unknown,
+ options: PluginRendererSlotOptions | undefined,
+ ): SlotRegistrationHandle {
+ const slotName =
+ typeof slot === "string" && (PLUGIN_RENDERER_SLOTS as readonly string[]).includes(slot)
+ ? (slot as PluginRendererSlot)
+ : null;
+ if (!slotName) {
+ throw new SlotError("PLUGIN_SLOT_UNKNOWN", `unknown slot: ${String(slot)}`);
+ }
+ if (typeof component !== "function") {
+ throw new SlotError(
+ "PLUGIN_SLOT_INVALID_COMPONENT",
+ `slot ${slot} requires a function component`,
+ );
+ }
+ const keyError = slotKeyError(slotName, pluginId, options);
+ if (keyError) throw new SlotError("PLUGIN_SLOT_INVALID_KEY", keyError);
+ const positionsError = slotPositionsError(slotName, options);
+ if (positionsError) throw new SlotError("PLUGIN_SLOT_INVALID_POSITION", positionsError);
+ const key = slotKeyFor(slotName, options);
+ if (key !== undefined) {
+ const clash = this.state.entries.find(
+ (entry) => entry.slot === slotName && entry.key === key,
+ );
+ if (clash) {
+ throw new SlotError(
+ "PLUGIN_SLOT_DUPLICATE",
+ `slot ${slot} key ${key} is already taken by ${clash.pluginId}`,
+ );
+ }
+ }
+
+ const sides: readonly SlotSide[] =
+ slotName === "userAction" || slotName === "assistantAction" || slotName === "composerControl"
+ ? (options?.positions ?? ["left", "right"])
+ : [];
+ const entry: SlotEntry = {
+ id: `s${this.nextId++}`,
+ pluginId,
+ slot: slotName,
+ component: component as SlotEntry["component"],
+ options: options ?? {},
+ sides,
+ key,
+ };
+ this.commit([...this.state.entries, entry]);
+ return {
+ slot: slotName,
+ remove: () => {
+ this.commit(this.state.entries.filter((candidate) => candidate.id !== entry.id));
+ },
+ };
+ }
+
+ /** 卸载摘注册: drop every registration one plugin held. */
+ unregisterPlugin(pluginId: string): void {
+ const kept = this.state.entries.filter((entry) => entry.pluginId !== pluginId);
+ if (kept.length !== this.state.entries.length) this.commit(kept);
+ }
+
+ /** Additive slots, in registration order, filtered to one side. */
+ entriesForSide(slot: PluginRendererSlot, side: SlotSide): SlotEntry[] {
+ return this.state.entries.filter(
+ (entry) => entry.slot === slot && entry.sides.includes(side),
+ );
+ }
+
+ /** Every registration of an additive slot, both sides, registration order. */
+ entriesFor(slot: PluginRendererSlot): SlotEntry[] {
+ return this.state.entries.filter((entry) => entry.slot === slot);
+ }
+
+ /** Keyed lookup: the one card for a tool, the one renderer for a language. */
+ entryForKey(slot: PluginRendererSlot, key: string): SlotEntry | undefined {
+ return this.state.entries.find((entry) => entry.slot === slot && entry.key === key);
+ }
+}
+
+/** The app-wide singleton. Renderer host modules register through it. */
+export const slotRegistry = new SlotRegistry();
diff --git a/apps/desktop/src/plugins/renderer-slots/slot-shell.css b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
new file mode 100644
index 000000000..739baf070
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
@@ -0,0 +1,268 @@
+/**
+ * Host chrome styles for plugin slot regions plus the self-dialog tool
+ * classes (`docs/plugin-plan/ui/self-dialog/`): p-overlay / p-dialog /
+ * p-notice with the --ds-scrim / --ds-shadow-dialog tokens.
+ *
+ * Plugin self layers own z 600..899 (first 600, +1 per layer); the host
+ * safety layer (permission approvals, confirms) pins to 900; the existing
+ * 1000+ ladder is untouched.
+ */
+
+.pi-plugin-slot {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+}
+
+.pi-plugin-slot[data-pi-slot="entryExtra"] {
+ display: block;
+ width: 100%;
+}
+
+/* ---- self-dialog tool classes ---------------------------------------- */
+
+:root {
+ --ds-scrim: rgb(0 0 0 / 0.55);
+ --ds-shadow-dialog: 0 24px 64px rgb(0 0 0 / 0.4), 0 4px 16px rgb(0 0 0 / 0.3);
+ --ds-z-plugin-layer: 600;
+ --ds-z-safety-layer: 900;
+}
+
+.p-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: var(--ds-z-plugin-layer);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--ds-scrim);
+}
+
+.p-overlay__corner {
+ align-items: flex-end;
+ justify-content: flex-end;
+ background: transparent;
+ pointer-events: none;
+ padding: 16px;
+}
+
+.p-overlay__corner > * {
+ pointer-events: auto;
+}
+
+.p-dialog {
+ display: flex;
+ flex-direction: column;
+ min-width: 320px;
+ max-width: min(560px, calc(100vw - 48px));
+ max-height: min(70vh, 640px);
+ border-radius: var(--radius-md);
+ border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ background: var(--ds-bg-elevated, #1b1b1b);
+ color: var(--ds-text-primary, #ededed);
+ box-shadow: var(--ds-shadow-dialog);
+ overflow: hidden;
+}
+
+.p-dialog-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 16px;
+ font-weight: var(--font-weight-semibold);
+ border-bottom: 1px solid var(--ds-border, rgb(255 255 255 / 0.08));
+}
+
+.p-dialog__body {
+ padding: 14px 16px;
+ overflow: auto;
+}
+
+.p-dialog__foot {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 16px;
+ border-top: 1px solid var(--ds-border, rgb(255 255 255 / 0.08));
+}
+
+.p-notice {
+ position: relative;
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ width: 320px;
+ padding: 12px 14px;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ background: var(--ds-bg-elevated, #1b1b1b);
+ color: var(--ds-text-primary, #ededed);
+ box-shadow: var(--ds-shadow-dialog);
+}
+
+.p-notice__msg {
+ flex: 1;
+ font-size: var(--text-md);
+ line-height: var(--leading-body);
+}
+.p-notice-icon {
+ flex: none;
+ width: 18px;
+ height: 18px;
+}
+
+.p-notice__dismiss {
+ cursor: pointer;
+ border: 0;
+ background: transparent;
+ color: var(--ds-text-secondary, #b0b0b0);
+ font: inherit;
+ padding: 0 2px;
+}
+
+.p-notice__dismiss:hover {
+ color: var(--ds-text-primary, #ededed);
+}
+/* ---- entryExtra clamp (docs/plugin-plan/ui/entry-extra) --------------- */
+
+.pi-entry-extra-stack {
+ display: block;
+ width: 100%;
+}
+
+.pi-entry-extra-block {
+ display: block;
+ width: 100%;
+ margin-top: 8px;
+}
+
+.pi-entry-extra-viewport {
+ overflow: hidden;
+}
+
+.pi-entry-extra-viewport[data-clipped="true"] {
+ -webkit-mask-image: linear-gradient(to bottom, #000 92%, transparent 100%);
+ mask-image: linear-gradient(to bottom, #000 92%, transparent 100%);
+}
+
+.pi-entry-extra-viewport[data-expanded="true"] {
+ overflow-y: auto;
+ overscroll-behavior: contain;
+}
+
+.pi-entry-extra-toggle {
+ margin-top: 4px;
+ padding: 2px 8px;
+ border: 0;
+ border-radius: var(--radius-2xs);
+ background: transparent;
+ color: var(--ds-text-secondary, rgb(255 255 255 / 0.6));
+ font: inherit;
+ font-size: var(--text-sm);
+ cursor: pointer;
+}
+
+.pi-entry-extra-toggle:hover {
+ color: var(--ds-text-primary, rgb(255 255 255 / 0.9));
+ background: var(--ds-bg-hover, rgb(255 255 255 / 0.06));
+}
+.pi-action-overflow {
+ position: relative;
+ display: inline-flex;
+}
+
+.pi-action-overflow-panel {
+ position: absolute;
+ bottom: calc(100% + 6px);
+ z-index: 30;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 120px;
+ padding: 6px;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ background: var(--ds-bg-elevated, #1b1b1b);
+ color: var(--ds-text-primary, #ededed);
+ box-shadow: var(--ds-shadow-dialog);
+}
+
+.pi-action-overflow[data-side="left"] .pi-action-overflow-panel {
+ left: 0;
+}
+
+.pi-action-overflow[data-side="right"] .pi-action-overflow-panel {
+ right: 0;
+}
+
+.pi-plugin-slot[data-pi-slot="toolCard"] {
+ display: block;
+ width: 100%;
+}
+
+.pi-plugin-tool-card {
+ display: block;
+ width: 100%;
+}
+
+.pi-plugin-block-renderer {
+ display: block;
+ width: 100%;
+ overflow: hidden;
+}
+
+/* ---- composer trigger menu + token chips (docs/plugin-plan/ui/composer) -- */
+
+.pi-plugin-trigger-menu {
+ position: absolute;
+ top: 8px;
+ left: 12px;
+ right: 12px;
+ z-index: 30;
+ max-height: 240px;
+ overflow-y: auto;
+ padding: 6px;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ background: var(--ds-bg-elevated, #1b1b1b);
+ color: var(--ds-text-primary, #ededed);
+ box-shadow: var(--ds-shadow-dialog);
+}
+
+.pi-plugin-token-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 0 12px 6px;
+}
+
+.pi-plugin-token-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 1px 8px;
+ border-radius: var(--radius-full);
+ border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ background: var(--ds-bg-hover, rgb(255 255 255 / 0.06));
+ font-size: var(--text-xs);
+ line-height: var(--leading-tighter);
+}
+
+.pi-plugin-token-chip.is-fold {
+ cursor: default;
+}
+
+.pi-plugin-token-chip-remove {
+ cursor: pointer;
+ border: 0;
+ padding: 0 2px;
+ background: transparent;
+ color: var(--ds-text-secondary, rgb(255 255 255 / 0.6));
+ font: inherit;
+ font-size: var(--text-xs);
+}
+
+.pi-plugin-token-chip-remove:hover {
+ color: var(--ds-text-primary, #ededed);
+}
diff --git a/apps/desktop/src/plugins/renderer-slots/style-injection.ts b/apps/desktop/src/plugins/renderer-slots/style-injection.ts
new file mode 100644
index 000000000..76a7ee21e
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-slots/style-injection.ts
@@ -0,0 +1,47 @@
+/**
+ * Style injection for renderer slot plugins (`slot-contract.html` §4).
+ *
+ * The host's promise is: a sheet a plugin injects is removed when the plugin
+ * unloads, with nothing left behind. Scoping is best-effort — the contract
+ * records "样式重写可被绕过" as an accepted cost, so the host does not police
+ * selectors; it tags every sheet with the plugin that owns it.
+ */
+
+type InjectedSheet = {
+ pluginId: string;
+ element: HTMLStyleElement;
+};
+
+const sheets: InjectedSheet[] = [];
+
+export type PluginStyleHandle = {
+ remove(): void;
+};
+
+function removeSheet(sheet: InjectedSheet): void {
+ sheet.element.remove();
+ const index = sheets.indexOf(sheet);
+ if (index >= 0) sheets.splice(index, 1);
+}
+
+/** Inject one stylesheet owned by `pluginId`. Returns a removal handle. */
+export function injectStyle(pluginId: string, css: string): PluginStyleHandle {
+ const element = document.createElement("style");
+ element.setAttribute("data-pi-plugin", pluginId);
+ element.textContent = css;
+ document.head.appendChild(element);
+ const sheet: InjectedSheet = { pluginId, element };
+ sheets.push(sheet);
+ return {
+ remove: () => {
+ removeSheet(sheet);
+ },
+ };
+}
+
+/** 卸载摘样式: drop every sheet one plugin injected. */
+export function removePluginStyles(pluginId: string): void {
+ for (const sheet of [...sheets]) {
+ if (sheet.pluginId === pluginId) removeSheet(sheet);
+ }
+}
diff --git a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
new file mode 100644
index 000000000..ca5314e44
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
@@ -0,0 +1,123 @@
+/**
+ * React glue over the slot registry: subscriptions + the per-registration
+ * error boundary that realizes 出错隔离 (a throwing component collapses only
+ * its own region).
+ */
+import {
+ Component,
+ type ReactNode,
+ createContext,
+ useContext,
+ useMemo,
+ useSyncExternalStore,
+} from "react";
+import type { PluginRendererSlot } from "@pi-desktop/plugin-sdk";
+import {
+ slotRegistry,
+ type SlotEntry,
+ type SlotSide,
+} from "./registry";
+
+export function useSlotEntries(slot: PluginRendererSlot, side?: SlotSide): SlotEntry[] {
+ const snapshot = useSyncExternalStore(
+ slotRegistry.subscribe,
+ slotRegistry.getSnapshot,
+ slotRegistry.getSnapshot,
+ );
+ return useMemo(
+ () => (side ? slotRegistry.entriesForSide(slot, side) : slotRegistry.entriesFor(slot)),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal
+ [snapshot.version, slot, side],
+ );
+}
+
+export function useSlotEntryForKey(
+ slot: PluginRendererSlot,
+ key: string | undefined,
+): SlotEntry | undefined {
+ const snapshot = useSyncExternalStore(
+ slotRegistry.subscribe,
+ slotRegistry.getSnapshot,
+ slotRegistry.getSnapshot,
+ );
+ return useMemo(
+ () => (key ? slotRegistry.entryForKey(slot, key) : undefined),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal
+ [snapshot.version, slot, key],
+ );
+}
+
+/**
+ * Host chrome around one plugin registration. Every rendered slot component
+ * sits inside `.pi-plugin-slot` with `data-pi-plugin`, and inside its own
+ * boundary: a render failure removes exactly that registration's region.
+ */
+export function SlotBoundary({
+ entry,
+ slot,
+ children,
+ fallback,
+}: {
+ entry: SlotEntry;
+ slot: PluginRendererSlot;
+ children: ReactNode;
+ /** Rendered when the registration's component throws (blockRenderer's
+ * contract hands back the host code block instead of collapsing). */
+ fallback?: ReactNode;
+}) {
+ return (
+ <SlotErrorBoundary entry={entry} fallback={fallback}>
+ <div className="pi-plugin-slot" data-pi-plugin={entry.pluginId} data-pi-slot={slot}>
+ {children}
+ </div>
+ </SlotErrorBoundary>
+ );
+}
+
+type BoundaryProps = { entry: SlotEntry; fallback?: ReactNode; children: ReactNode };
+
+type BoundaryState = { failed: boolean };
+
+class SlotErrorBoundary extends Component<BoundaryProps, BoundaryState> {
+ state: BoundaryState = { failed: false };
+
+ static getDerivedStateFromError(): BoundaryState {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown): void {
+ const pluginId = this.props.entry.pluginId;
+ // Isolated by design; the console line is the diagnosability surface.
+ console.warn(
+ `[plugin-slot] ${pluginId} component failed; collapsing its own region only`,
+ error,
+ );
+ }
+
+ render(): ReactNode {
+ return this.state.failed ? (this.props.fallback ?? null) : this.props.children;
+ }
+}
+
+/**
+ * Session identity for slot props. The transcript knows the session a
+ * message belongs to; slot hosts pass it down through this context so the
+ * props skeleton (`message/messageId/sessionId`) stays uniform.
+ */
+const SlotSessionContext = createContext<string>("");
+
+export function SlotSessionProvider({
+ sessionId,
+ children,
+}: {
+ sessionId: string;
+ children: ReactNode;
+}) {
+ return (
+ <SlotSessionContext.Provider value={sessionId}>{children}</SlotSessionContext.Provider>
+ );
+}
+
+export function useSlotSessionId(): string {
+ return useContext(SlotSessionContext);
+}
diff --git a/apps/desktop/test/plugin-action-slots.test.mjs b/apps/desktop/test/plugin-action-slots.test.mjs
new file mode 100644
index 000000000..847f7193e
--- /dev/null
+++ b/apps/desktop/test/plugin-action-slots.test.mjs
@@ -0,0 +1,141 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+
+const { SlotRegistry } = await import(
+ "../src/plugins/renderer-slots/registry.ts"
+);
+const {
+ actionSlotPropsFor,
+ actionSlotMessage,
+ splitActionSide,
+ ACTION_SLOT_VISIBLE_LIMIT,
+} = await import("../src/features/chat/transcript/action-slot-props.ts");
+const { en, zhCN, zhTW, de, es, fr, ko, tr } = await import("@pi-desktop/i18n");
+
+const message = (role, extra = {}) => ({
+ id: "m1",
+ role,
+ content: "hello",
+ createdAt: "2026-09-17T00:00:00.000Z",
+ ...extra,
+});
+
+test("action slot props projection carries message, ids, position, dispatch", () => {
+ const dispatch = async () => ({});
+ const props = actionSlotPropsFor(message("user"), "left", "sess-1", dispatch);
+ assert.deepEqual(props.message, {
+ id: "m1",
+ role: "user",
+ content: "hello",
+ createdAt: "2026-09-17T00:00:00.000Z",
+ });
+ assert.equal(props.messageId, "m1");
+ assert.equal(props.sessionId, "sess-1");
+ assert.equal(props.position, "left");
+ assert.equal(props.dispatch, dispatch);
+});
+
+test("the action projection keeps the row's real role", () => {
+ assert.equal(actionSlotMessage(message("assistant")).role, "assistant");
+ assert.equal(actionSlotMessage(message("user")).role, "user");
+});
+
+test("each side shows three items and folds the rest into the host menu", () => {
+ assert.equal(ACTION_SLOT_VISIBLE_LIMIT, 3);
+ const items = ["a", "b", "c", "d", "e"];
+ const split = splitActionSide(items);
+ assert.deepEqual(split.visible, ["a", "b", "c"]);
+ assert.deepEqual(split.overflow, ["d", "e"]);
+ assert.deepEqual(splitActionSide(["a"]), { visible: ["a"], overflow: [] });
+});
+
+test("positions subsets filter per side and default to both sides", () => {
+ const registry = new SlotRegistry();
+ const component = () => null;
+ registry.register("plugin-a", "userAction", component, undefined);
+ registry.register("plugin-b", "userAction", component, { positions: ["left"] });
+ registry.register("plugin-c", "assistantAction", component, {
+ positions: ["right"],
+ });
+ assert.equal(registry.entriesForSide("userAction", "left").length, 2);
+ assert.equal(registry.entriesForSide("userAction", "right").length, 1);
+ assert.equal(registry.entriesForSide("assistantAction", "left").length, 0);
+ assert.equal(registry.entriesForSide("assistantAction", "right").length, 1);
+ // Uninstall recomputes the sides immediately.
+ registry.unregisterPlugin("plugin-b");
+ assert.equal(registry.entriesForSide("userAction", "left").length, 1);
+});
+
+test("MessageRow wraps its host keys in the userAction bar slots", () => {
+ const source = readFileSync(src("features/chat/transcript/MessageRow.tsx"), "utf8");
+ const slotsAt = source.indexOf("<ActionBarSlots slot=\"userAction\"");
+ const barAt = source.indexOf('<div className="message-actions">');
+ assert.ok(slotsAt > 0, "userAction bar slots mounted");
+ // The slot wrapper sits inside the action-bar div, around the host keys.
+ assert.ok(slotsAt > barAt);
+ assert.match(
+ source,
+ /isUser \? userActionLeftEntries : \[\]/,
+ "system rows keep a plugin-free bar",
+ );
+ assert.match(source, /<\/ActionBarSlots>/);
+});
+
+test("AssistantTurn wraps its host keys in the assistantAction bar slots", () => {
+ const source = readFileSync(
+ src("features/chat/transcript/AssistantTurn.tsx"),
+ "utf8",
+ );
+ const slotsAt = source.indexOf('<ActionBarSlots slot="assistantAction"');
+ const copyAt = source.indexOf("<CopyButton text={content}");
+ const closeAt = source.indexOf("</ActionBarSlots>");
+ assert.ok(slotsAt > 0 && slotsAt < copyAt && closeAt > copyAt,
+ "host keys render inside the slot wrapper");
+});
+
+test("ActionBarSlots keeps the finalized 【left】【host】【right】 shape", () => {
+ const source = readFileSync(
+ src("features/chat/transcript/ActionBarSlots.tsx"),
+ "utf8",
+ );
+ // Host keys (children) render between the left and right visible items.
+ const leftVisible = source.indexOf("leftSplit.visible.map");
+ const children = source.lastIndexOf("{children}");
+ const rightVisible = source.indexOf("rightSplit.visible.map");
+ assert.ok(leftVisible > 0 && leftVisible < children && children < rightVisible);
+ // Left ⋯ before the host keys, right ⋯ last.
+ const leftOverflow = source.indexOf("leftSplit.overflow.length");
+ const rightOverflow = source.indexOf("rightSplit.overflow.length");
+ assert.ok(leftOverflow > 0 && leftOverflow < children);
+ assert.ok(rightOverflow > children);
+ // Plugin-free bars keep their exact DOM.
+ assert.match(source, /left\.length === 0 && right\.length === 0\) return <>\{children\}<\/>/);
+ // Each item gets its own plugin's relay and boundary.
+ assert.match(source, /dispatchFor\(entry\.pluginId\)/);
+ assert.match(source, /<SlotBoundary entry=\{entry\} slot=\{slot\}>/);
+});
+
+test("every shipped locale labels the host ⋯ overflow menu", () => {
+ const catalogs = { en, zhCN, zhTW, de, es, fr, ko, tr };
+ for (const [name, catalog] of Object.entries(catalogs)) {
+ assert.ok(
+ typeof catalog.chat?.actionSlotMore === "string" &&
+ catalog.chat.actionSlotMore.length > 0,
+ `${name} is missing chat.actionSlotMore`,
+ );
+ }
+});
+
+test("slot shell styles carry the ⋯ overflow menu chrome", () => {
+ const css = readFileSync(src("plugins/renderer-slots/slot-shell.css"), "utf8");
+ assert.match(css, /\.pi-action-overflow-panel/);
+ assert.match(css, /data-side="right"/);
+});
diff --git a/apps/desktop/test/plugin-block-renderer-slot.test.mjs b/apps/desktop/test/plugin-block-renderer-slot.test.mjs
new file mode 100644
index 000000000..ffbd39642
--- /dev/null
+++ b/apps/desktop/test/plugin-block-renderer-slot.test.mjs
@@ -0,0 +1,100 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+
+const { blockRendererOverflow, blockRendererCandidate, BLOCK_RENDERER_MAX_HEIGHT_PX } =
+ await import("../src/lib/block-renderer.ts");
+const { SlotRegistry } = await import("../src/plugins/renderer-slots/registry.ts");
+
+test("only prefixed languages can reach the slot registry", () => {
+ assert.equal(blockRendererCandidate("json"), undefined);
+ assert.equal(blockRendererCandidate("ts"), undefined);
+ assert.equal(blockRendererCandidate("mermaid"), undefined);
+ assert.equal(blockRendererCandidate("demo:chart"), "demo:chart");
+ assert.equal(blockRendererCandidate(" demo:csv "), "demo:csv");
+});
+
+test("the host clamp is 4000px and overflow means render failure", () => {
+ assert.equal(BLOCK_RENDERER_MAX_HEIGHT_PX, 4000);
+ assert.equal(blockRendererOverflow(3999), false);
+ assert.equal(blockRendererOverflow(4000), false);
+ assert.equal(blockRendererOverflow(4001), true);
+});
+
+test("blockRenderer keys stay plugin-prefixed and additive per language", () => {
+ const registry = new SlotRegistry();
+ const component = () => null;
+ registry.register("demo.chart", "blockRenderer", component, { language: "demo.chart:chart" });
+ registry.register("demo.chart", "blockRenderer", component, { language: "demo.chart:csv" });
+ assert.equal(registry.entryForKey("blockRenderer", "demo.chart:chart")?.pluginId, "demo.chart");
+ assert.equal(registry.entryForKey("blockRenderer", "demo.chart:csv")?.pluginId, "demo.chart");
+ assert.equal(registry.entryForKey("blockRenderer", "json"), undefined);
+ // A second claim of the same language — even by the same plugin — is refused.
+ assert.throws(
+ () =>
+ registry.register("demo.chart", "blockRenderer", component, {
+ language: "demo.chart:chart",
+ }),
+ (error) => error.code === "PLUGIN_SLOT_DUPLICATE",
+ );
+ // A different plugin cannot even express that key: the language is
+ // namespaced by the registering plugin's own id, so cross-plugin claims
+ // are structurally impossible (INVALID_KEY, not DUPLICATE).
+ assert.throws(
+ () =>
+ registry.register("demo.other", "blockRenderer", component, {
+ language: "demo.chart:chart",
+ }),
+ (error) => error.code === "PLUGIN_SLOT_INVALID_KEY",
+ );
+});
+test("unclosed fences fall back to the host block; closed fences hand over", () => {
+ const source = readFileSync(src("components/Markdown.tsx"), "utf8");
+ const preAt = source.indexOf("function PreBlock(");
+ const hookAt = source.indexOf('useSlotEntryForKey(\n "blockRenderer"');
+ const guardAt = source.indexOf("if (!info) return <pre");
+ assert.ok(preAt > 0 && hookAt > preAt && guardAt > hookAt,
+ "the slot lookup runs before every early return");
+ assert.match(
+ source,
+ /closedFence \? blockRendererCandidate\(info\?\.lang \?\? ""\) : undefined/,
+ "an unclosed fence never resolves a registration",
+ );
+ assert.match(source, /<PluginBlockRenderer/);
+ assert.match(
+ source,
+ /fallback=\{\s*<CodeBlock code=\{info\.code\} lang=\{info\.lang\}/,
+ "failure and no-claim both land on the host code block",
+ );
+});
+
+test("claimed blocks mount props-once with the 4000px clamp and a fallback", () => {
+ const source = readFileSync(src("components/PluginBlockRenderer.tsx"), "utf8");
+ assert.match(source, /useRef<PluginBlockRendererSlotProps>\(\{ language, source \}\)/,
+ "props-once: the first projection is the only one");
+ assert.match(source, /BLOCK_RENDERER_MAX_HEIGHT_PX/);
+ assert.match(source, /blockRendererOverflow\(/);
+ assert.match(
+ source,
+ /<SlotBoundary entry=\{entry\} slot="blockRenderer" fallback=\{fallback\}>/,
+ "a throwing renderer hands back the host block",
+ );
+ assert.equal(source.includes("dispatchFor("), false,
+ "blockRenderer has no dispatch: no further data exchange after handover");
+});
+
+test("the boundary fallback keeps the host region visible on failure", () => {
+ const source = readFileSync(src("plugins/renderer-slots/use-slots.tsx"), "utf8");
+ assert.match(source, /fallback\?: ReactNode/);
+ assert.match(
+ source,
+ /this\.state\.failed \? \(this\.props\.fallback \?\? null\) : this\.props\.children/,
+ );
+});
diff --git a/apps/desktop/test/plugin-composer-slots.test.mjs b/apps/desktop/test/plugin-composer-slots.test.mjs
new file mode 100644
index 000000000..d81cc6042
--- /dev/null
+++ b/apps/desktop/test/plugin-composer-slots.test.mjs
@@ -0,0 +1,211 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+
+const {
+ detectPluginHashTrigger,
+ pluginTokenAtLimit,
+ serializePluginTokens,
+ COMPOSER_PLUGIN_TOKEN_LIMIT,
+} = await import("../src/features/chat/composer/plugin-trigger.ts");
+const { normalizeFullWidthTrigger, formatPluginTriggerInsert } = await import(
+ "@pi-desktop/shared"
+);
+const {
+ registerComposerTriggerAccept,
+ acceptComposerTriggerItem,
+ resetComposerTriggerBridge,
+} = await import("../src/features/chat/composer/trigger-bridge.ts");
+const {
+ insertComposerText,
+ registerComposerInsert,
+ resetComposerInsertBridge,
+} = await import("../src/features/chat/composer/insert-bridge.ts");
+const { SlotRegistry } = await import("../src/plugins/renderer-slots/registry.ts");
+
+test.afterEach(() => {
+ resetComposerTriggerBridge();
+ resetComposerInsertBridge();
+});
+
+test("full-width trigger symbols normalize to ASCII", () => {
+ assert.equal(normalizeFullWidthTrigger("@file"), "@file");
+ assert.equal(normalizeFullWidthTrigger("#tag"), "#tag");
+ assert.equal(normalizeFullWidthTrigger("/cmd"), "/cmd");
+ assert.equal(normalizeFullWidthTrigger("plain"), "plain");
+});
+
+test("the # token fires only from line start or after whitespace", () => {
+ // Line start.
+ assert.deepEqual(detectPluginHashTrigger("#ta", 3), {
+ query: "ta",
+ tokenStart: 0,
+ tokenEnd: 3,
+ });
+ // After whitespace.
+ assert.deepEqual(detectPluginHashTrigger("hi #ta", 6), {
+ query: "ta",
+ tokenStart: 3,
+ tokenEnd: 6,
+ });
+ // Mid-word never fires.
+ assert.equal(detectPluginHashTrigger("abc#de", 6), null);
+ // A bare # with no query still fires (empty query is valid).
+ assert.deepEqual(detectPluginHashTrigger("#", 1), {
+ query: "",
+ tokenStart: 0,
+ tokenEnd: 1,
+ });
+ // Not a # token at all.
+ assert.equal(detectPluginHashTrigger("plain", 5), null);
+});
+
+test("plugin trigger items insert as #label chips", () => {
+ assert.equal(formatPluginTriggerInsert("alpha"), "#alpha ");
+});
+
+test("the trigger bridge routes accept only while a menu is open", () => {
+ // No listener: refused (UNROUTED upstream), never a silent drop.
+ assert.equal(acceptComposerTriggerItem({ label: "x", value: 1 }), false);
+ const received = [];
+ registerComposerTriggerAccept((item) => received.push(item));
+ assert.equal(acceptComposerTriggerItem({ label: "alpha", value: { a: 1 } }), true);
+ assert.deepEqual(received, [{ label: "alpha", value: { a: 1 } }]);
+ // Malformed payloads are refused.
+ assert.equal(acceptComposerTriggerItem({ value: 1 }), false);
+ assert.equal(acceptComposerTriggerItem(null), false);
+ assert.equal(acceptComposerTriggerItem("nope"), false);
+});
+
+test("the insert bridge routes text into the mounted composer", () => {
+ assert.equal(insertComposerText("hi"), false);
+ const inserted = [];
+ registerComposerInsert((text) => inserted.push(text));
+ assert.equal(insertComposerText("hi"), true);
+ assert.deepEqual(inserted, ["hi"]);
+});
+
+test("composerTrigger claims are keyed by symbol and @ / / stay host-owned", () => {
+ const registry = new SlotRegistry();
+ const component = () => null;
+ registry.register("demo.ui-slots", "composerTrigger", component, { trigger: "#" });
+ assert.equal(registry.entryForKey("composerTrigger", "#")?.pluginId, "demo.ui-slots");
+ assert.throws(
+ () =>
+ registry.register("demo.other", "composerTrigger", component, { trigger: "#" }),
+ (error) => error.code === "PLUGIN_SLOT_DUPLICATE",
+ );
+ // SDK vocabulary: only @ # / exist.
+ const sdk = readFileSync(
+ join(here, "../../../packages/plugin-sdk/src/renderer.ts"),
+ "utf8",
+ );
+ assert.match(sdk, /PLUGIN_COMPOSER_TRIGGERS = \["@", "#", "\/"\] as const/);
+ // 宿主先占: @ and / are host-owned; a plugin claim of either is refused
+ // at registration (docs/plugin-plan/ui/composer/requirements.html:139).
+ assert.match(sdk, /plugins claim "#"/);
+ const registry2 = new SlotRegistry();
+ assert.throws(
+ () => registry2.register("demo.other", "composerTrigger", component, { trigger: "@" }),
+ (error) => error.code === "PLUGIN_SLOT_INVALID_KEY",
+ );
+ assert.throws(
+ () => registry2.register("demo.other", "composerTrigger", component, { trigger: "/" }),
+ (error) => error.code === "PLUGIN_SLOT_INVALID_KEY",
+ );
+});
+test("the token cap is 8; the ninth folds but the payload keeps everything", () => {
+ assert.equal(COMPOSER_PLUGIN_TOKEN_LIMIT, 8);
+ assert.equal(pluginTokenAtLimit(7), false);
+ assert.equal(pluginTokenAtLimit(8), true);
+ const payload = serializePluginTokens("draft text", [
+ { pluginId: "p1", label: "one", send: { n: 1 } },
+ { pluginId: "p2", label: "two", send: "x" },
+ ]);
+ assert.match(payload, /^draft text/);
+ assert.match(payload, /#one #two/);
+ assert.match(payload, /```pi-plugin-tokens\n/);
+ assert.match(payload, /"pluginId":"p1"/);
+ assert.match(payload, /"send":\{"n":1\}/);
+ assert.match(payload, /"send":"x"/);
+});
+
+test("the composer wires trigger, tokens, insert bridge, and send payload", () => {
+ 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">');
+ const rightAt = toolbar.indexOf('<div className="composer-right">');
+ const leftGroup = toolbar.indexOf('<PluginControlGroup entries={leftControls} side="left" />');
+ const rightGroup = toolbar.indexOf('<PluginControlGroup entries={rightControls} side="right" />');
+ // 左槽=左排固定件右边;右槽=模型选择左边 (ui/composer/requirements.html:89-90).
+ assert.ok(
+ leftGroup > toolbar.indexOf("ComposerPermissionPicker") && leftGroup < rightAt,
+ "left outlet sits after the host fixed controls, before composer-right",
+ );
+ assert.ok(
+ rightGroup > rightAt && rightGroup < toolbar.indexOf("<ComposerModelPicker"),
+ "right outlet sits before the model picker",
+ );
+ assert.match(toolbar, /useComposerControlEntries\("left"\)/);
+ assert.match(toolbar, /useComposerControlEntries\("right"\)/);
+ // Each control gets the position prop and its own relay.
+ assert.match(toolbar, /position: side/);
+ assert.match(toolbar, /dispatchFor\(entry\.pluginId\)/);
+});
+
+test("the trigger hook normalizes full-width symbols before detection", () => {
+ // 全角归一化 wiring: the hook rewrites @#/ to @#/ before running the
+ // detector, so a full-width # fires the plugin trigger (data-flow:145).
+ const hookSource = readFileSync(
+ src("features/chat/composer/use-plugin-composer-slots.ts"),
+ "utf8",
+ );
+ const normalizeAt = hookSource.indexOf("normalizeFullWidthTrigger(value)");
+ const detectAt = hookSource.indexOf("detectPluginHashTrigger(normalized, cursor)");
+ assert.ok(normalizeAt > -1, "hook must call normalizeFullWidthTrigger");
+ assert.ok(detectAt > normalizeAt, "normalization must precede detection");
+ assert.match(hookSource, /import \{ normalizeFullWidthTrigger \} from "@pi-desktop\/shared"/);
+});
+
+test("the trigger menu and token chips have host chrome styles", () => {
+ // Without these the menu paints unpositioned inside the composer flow
+ // and chips render as bare text (slot-shell.css).
+ const shell = readFileSync(src("plugins/renderer-slots/slot-shell.css"), "utf8");
+ assert.match(shell, /\.pi-plugin-trigger-menu \{[\s\S]*?position: absolute/);
+ assert.match(shell, /\.pi-plugin-trigger-menu \{[\s\S]*?z-index: 30/);
+ assert.match(shell, /\.pi-plugin-token-chips \{/);
+ assert.match(shell, /\.pi-plugin-token-chip \{/);
+ assert.match(shell, /\.pi-plugin-token-chip-remove \{/);
+ assert.match(shell, /\.pi-plugin-token-chip\.is-fold \{/);
+});
diff --git a/apps/desktop/test/plugin-entry-extra-slot.test.mjs b/apps/desktop/test/plugin-entry-extra-slot.test.mjs
new file mode 100644
index 000000000..153f3a64c
--- /dev/null
+++ b/apps/desktop/test/plugin-entry-extra-slot.test.mjs
@@ -0,0 +1,205 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+
+const {
+ SlotRegistry,
+ SlotError,
+} = await import("../src/plugins/renderer-slots/registry.ts");
+const {
+ entryExtraPropsFor,
+ entryExtraMessage,
+ ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT,
+ ENTRY_EXTRA_EXPANDED_MAX_HEIGHT,
+} = await import("../src/features/chat/transcript/entry-extra-props.ts");
+const {
+ en,
+ zhCN,
+ zhTW,
+ de,
+ es,
+ fr,
+ ko,
+ tr,
+} = await import("@pi-desktop/i18n");
+
+const message = (extra = {}) => ({
+ id: "m1",
+ role: "assistant",
+ content: "answer",
+ createdAt: "2026-09-17T00:00:00.000Z",
+ ...extra,
+});
+
+test("entryExtra props projection carries the fixed contract fields", () => {
+ const dispatch = async () => ({});
+ const props = entryExtraPropsFor(message(), "sess-1", dispatch);
+ assert.deepEqual(props.message, {
+ id: "m1",
+ role: "assistant",
+ content: "answer",
+ createdAt: "2026-09-17T00:00:00.000Z",
+ });
+ assert.equal(props.messageId, "m1");
+ assert.equal(props.sessionId, "sess-1");
+ assert.equal(props.dispatch, dispatch);
+ // No position field: only the action bars are two-sided.
+ assert.equal("position" in props, false);
+});
+
+test("entryExtra projection pins the role to assistant", () => {
+ const projected = entryExtraMessage(message({ role: "tool" }));
+ assert.equal(projected.role, "assistant");
+});
+
+test("entryExtra clamp heights match the finalized contract", () => {
+ assert.equal(ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT, 320);
+ assert.equal(ENTRY_EXTRA_EXPANDED_MAX_HEIGHT, 600);
+});
+
+test("entryExtra is additive: registrations stack in order and never clash", () => {
+ const registry = new SlotRegistry();
+ const component = () => null;
+ registry.register("plugin-a", "entryExtra", component, undefined);
+ registry.register("plugin-b", "entryExtra", component, undefined);
+ const entries = registry.entriesFor("entryExtra");
+ assert.deepEqual(
+ entries.map((entry) => entry.pluginId),
+ ["plugin-a", "plugin-b"],
+ );
+ registry.unregisterPlugin("plugin-a");
+ assert.deepEqual(
+ registry.entriesFor("entryExtra").map((entry) => entry.pluginId),
+ ["plugin-b"],
+ );
+});
+
+test("a throwing onLoad leaving registrations behind still unregisters cleanly", () => {
+ // The unload path (loader.unloadRendererModule) owns this guarantee; the
+ // registry half of it is that unregisterPlugin drops every entry in one call.
+ const registry = new SlotRegistry();
+ const component = () => null;
+ registry.register("plugin-a", "entryExtra", component, undefined);
+ registry.register("plugin-a", "assistantAction", component, undefined);
+ registry.unregisterPlugin("plugin-a");
+ assert.equal(registry.entriesFor("entryExtra").length, 0);
+ assert.equal(registry.entriesFor("assistantAction").length, 0);
+});
+
+test("entryExtra registrations still validate slot name and component", () => {
+ const registry = new SlotRegistry();
+ assert.throws(
+ () => registry.register("plugin-a", "notASlot", () => null, undefined),
+ (error) =>
+ error instanceof SlotError && error.code === "PLUGIN_SLOT_UNKNOWN",
+ );
+ assert.throws(
+ () => registry.register("plugin-a", "entryExtra", "not-a-function", undefined),
+ (error) =>
+ error instanceof SlotError &&
+ error.code === "PLUGIN_SLOT_INVALID_COMPONENT",
+ );
+});
+
+test("the assistant turn mounts the stack after the action bar, gated on completion", () => {
+ const source = readFileSync(
+ src("features/chat/transcript/AssistantTurn.tsx"),
+ "utf8",
+ );
+ const actionsAt = source.indexOf('<div className="message-actions">');
+ const stackAt = source.lastIndexOf("{complete && actionMessage ? (");
+ assert.ok(actionsAt > 0, "host action bar must stay");
+ assert.ok(stackAt > actionsAt, "entryExtra mounts below the action bar");
+ assert.match(
+ source,
+ /complete && actionMessage \? \(\s*\n\s*<EntryExtraStack message=\{actionMessage\} \/>/,
+ "blocks ride the same completion gate as the action bar",
+ );
+ assert.ok(
+ !source.includes('useSlotEntries("entryExtra")'),
+ "AssistantTurn stays slot-free; EntryExtraStack owns the lookup",
+ );
+});
+
+test("EntryExtraStack renders registry entries inside per-plugin boundaries", () => {
+ const source = readFileSync(
+ src("features/chat/transcript/EntryExtraStack.tsx"),
+ "utf8",
+ );
+ assert.match(source, /useSlotEntries\("entryExtra"\)/);
+ assert.match(source, /useSlotSessionId\(\)/);
+ assert.match(source, /<SlotBoundary entry=\{entry\} slot="entryExtra">/);
+ assert.match(source, /entryExtraPropsFor\(/);
+ assert.match(
+ source,
+ /dispatchFor\(entry\.pluginId\)/,
+ "each block gets its own plugin's relay",
+ );
+ assert.match(
+ source,
+ /entries\.length === 0\) return null/,
+ "no blocks means no DOM",
+ );
+ // The host owns the clamp: collapsed 320, expanded 600, toggle only when
+ // content actually overflows or the block is expanded.
+ assert.match(source, /ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT/);
+ assert.match(source, /ENTRY_EXTRA_EXPANDED_MAX_HEIGHT/);
+ assert.match(source, /data-clipped/);
+ assert.match(source, /entryExtraExpand/);
+ assert.match(source, /entryExtraCollapse/);
+});
+
+test("the transcript provides session identity to slot props", () => {
+ const source = readFileSync(
+ src("features/chat/transcript/ChatTranscript.tsx"),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /<SlotSessionProvider sessionId=\{sessionId \?\? ""\}>/,
+ );
+ // Wraps the scroller so every message row (history and tail) is covered.
+ const providerAt = source.indexOf("<SlotSessionProvider");
+ const scrollerAt = source.indexOf('className="thread-scroll"');
+ const closeAt = source.indexOf("</SlotSessionProvider>");
+ assert.ok(providerAt > 0 && providerAt < scrollerAt && closeAt > scrollerAt);
+});
+
+test("slot shell styles carry the clamp viewport, edge fade, and toggle", () => {
+ const css = readFileSync(
+ src("plugins/renderer-slots/slot-shell.css"),
+ "utf8",
+ );
+ assert.match(css, /\.pi-entry-extra-stack/);
+ assert.match(css, /\.pi-entry-extra-viewport/);
+ assert.match(
+ css,
+ /data-clipped="true"[^\{]*\{[^}]*mask-image/,
+ "collapsed overflow fades at the 8% edge",
+ );
+ assert.match(css, /\.pi-entry-extra-toggle/);
+});
+
+test("every shipped locale has the host expand/collapse labels", () => {
+ const catalogs = { en, zhCN, zhTW, de, es, fr, ko, tr };
+ for (const [name, catalog] of Object.entries(catalogs)) {
+ const chat = catalog.chat ?? {};
+ assert.ok(
+ typeof chat.entryExtraExpand === "string" &&
+ chat.entryExtraExpand.length > 0,
+ `${name} is missing chat.entryExtraExpand`,
+ );
+ assert.ok(
+ typeof chat.entryExtraCollapse === "string" &&
+ chat.entryExtraCollapse.length > 0,
+ `${name} is missing chat.entryExtraCollapse`,
+ );
+ }
+});
diff --git a/apps/desktop/test/plugin-self-dialog.test.mjs b/apps/desktop/test/plugin-self-dialog.test.mjs
new file mode 100644
index 000000000..e73a0a75d
--- /dev/null
+++ b/apps/desktop/test/plugin-self-dialog.test.mjs
@@ -0,0 +1,79 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+const root = (relative) => join(here, "..", "..", "..", relative);
+
+const css = readFileSync(src("plugins/renderer-slots/slot-shell.css"), "utf8");
+const loader = readFileSync(src("plugins/renderer-host/loader.ts"), "utf8");
+const demoSource = readFileSync(
+ root("examples/plugins/ui-slots-demo/renderer/index.mjs"),
+ "utf8",
+);
+
+test("self-dialog tool classes and the 600..899 / 900 z ladder exist", () => {
+ // Tool classes from the finalized page.
+ for (const cls of [
+ ".p-overlay",
+ ".p-overlay__corner",
+ ".p-dialog",
+ ".p-dialog-head",
+ ".p-dialog__body",
+ ".p-dialog__foot",
+ ".p-notice",
+ ".p-notice-icon",
+ ".p-notice__msg",
+ ".p-notice__dismiss",
+ ".p-notice__msg",
+ ".p-notice__dismiss",
+ ]) {
+ assert.ok(css.includes(cls), `missing tool class ${cls}`);
+ }
+ // Recommended tokens.
+ assert.match(css, /--ds-scrim:/);
+ assert.match(css, /--ds-shadow-dialog:/);
+ // Ladder: plugin layers start at 600, the host safety layer pins 900.
+ assert.match(css, /--ds-z-plugin-layer: 600;/);
+ assert.match(css, /--ds-z-safety-layer: 900;/);
+ assert.match(css, /\.p-overlay \{[\s\S]*?z-index: var\(--ds-z-plugin-layer\)/);
+});
+
+test("the demo self-dialog draws inside its own component, closes via explicit UI only", () => {
+ // Drawn inside the plugin's own launcher component — no host slot, no
+ // registry call for it.
+ assert.match(demoSource, /function SelfDialogLauncher/);
+ assert.match(demoSource, /h\("div", \{ className: "p-overlay"/);
+ assert.match(demoSource, /className: "p-dialog"/);
+ assert.match(demoSource, /"p-dialog-head"/);
+ assert.match(demoSource, /"p-dialog__body"/);
+ assert.match(demoSource, /"p-dialog__foot"/);
+ // Close only through explicit UI actions (✕ / buttons).
+ assert.match(demoSource, /"p-notice__dismiss"/);
+ // Esc must not close it — no host Escape wiring in the sample.
+ assert.doesNotMatch(demoSource, /onKeyDown|key === "Escape"/);
+});
+
+test("unload makes the layer disappear because the host tears the module down", () => {
+ // The overlay is conditional JSX in the plugin component: gone with the
+ // component tree, no host cleanup needed for the sample itself.
+ assert.match(demoSource, /open\s*\?\s*h\("div", \{ className: "p-overlay"/);
+ // Host teardown strips registrations, injected styles, and dispatch
+ // before calling the plugin's own onUnload (loader contract).
+ assert.match(loader, /slotRegistry\.unregisterPlugin\(pluginId\)/);
+ assert.match(loader, /removePluginStyles\(pluginId\)/);
+ assert.match(loader, /unbindDispatch\(pluginId\)/);
+});
+
+test("the host runs no stacking arbitration between plugin layers", () => {
+ // One fixed mount for every self layer; the host never computes or
+ // increments plugin z values, so later plugins simply stack above.
+ assert.doesNotMatch(css, /z-index:\s*calc\(/);
+ assert.doesNotMatch(css, /counter\(|z-index:\s*var\(--pi-plugin-z/);
+ // The demo copy documents the ladder rule in place.
+ assert.match(demoSource, /z 600\.\.899/);
+ assert.match(demoSource, /900\) always wins/);
+});
diff --git a/apps/desktop/test/plugin-tool-card-slot.test.mjs b/apps/desktop/test/plugin-tool-card-slot.test.mjs
new file mode 100644
index 000000000..5d049a826
--- /dev/null
+++ b/apps/desktop/test/plugin-tool-card-slot.test.mjs
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const src = (relative) => join(here, "..", "src", relative);
+
+const { toolCardOwnershipError } = await import("@pi-desktop/plugin-sdk");
+const {
+ shouldEmitToolCard,
+ toolCardPropsFor,
+ toolCardStatusOf,
+ TOOL_CARD_RUNNING_INTERVAL_MS,
+} = await import("../src/features/chat/transcript/tool-card-props.ts");
+
+const message = (extra = {}) => ({
+ id: "m1",
+ role: "tool",
+ content: "",
+ createdAt: "2026-09-17T00:00:00.000Z",
+ toolName: "query_db",
+ toolCallId: "call-1",
+ toolStatus: "success",
+ ...extra,
+});
+
+test("the no-claim gate refuses cards for tools the plugin does not own", () => {
+ assert.match(
+ toolCardOwnershipError("query_db", undefined) ?? "",
+ /contributes\.agentTools/,
+ );
+ assert.match(
+ toolCardOwnershipError("query_db", []) ?? "",
+ /contributes\.agentTools/,
+ );
+ assert.match(
+ toolCardOwnershipError("other_tool", ["query_db"]) ?? "",
+ /not in the plugin's own/,
+ );
+ assert.equal(toolCardOwnershipError("query_db", ["query_db", "other"]), null);
+});
+
+test("card props carry the finalized fields, failure as data", () => {
+ const dispatch = async () => ({});
+ const failing = message({
+ toolStatus: "error",
+ isError: true,
+ error: { code: "TOOL_FAILED", message: "boom" },
+ });
+ const props = toolCardPropsFor(failing, "sess-1", dispatch);
+ assert.equal(props.toolName, "query_db");
+ assert.equal(props.toolCallId, "call-1");
+ assert.equal(props.toolStatus, "error");
+ assert.deepEqual(props.toolError, { code: "TOOL_FAILED", message: "boom" });
+ assert.equal(props.messageId, "m1");
+ assert.equal(props.sessionId, "sess-1");
+ assert.equal(props.dispatch, dispatch);
+ const ok = toolCardPropsFor(message({ toolDurationMs: 42 }), "s", dispatch);
+ assert.equal(ok.durationMs, 42);
+ assert.equal(ok.toolError, undefined);
+});
+
+test("denied rows never reach a plugin card", () => {
+ assert.equal(toolCardStatusOf(message({ toolStatus: "denied" })), "success");
+ assert.equal(toolCardStatusOf(message({ toolStatus: "running" })), "running");
+});
+
+test("running pushes merge on the 500ms beat; transitions are immediate", () => {
+ assert.equal(TOOL_CARD_RUNNING_INTERVAL_MS, 500);
+ // Same status inside the beat: no push.
+ assert.equal(shouldEmitToolCard(1_000, "running", "running", 1_200), false);
+ // Same status after the beat: push.
+ assert.equal(shouldEmitToolCard(1_000, "running", "running", 1_500), true);
+ // Status transition: immediate regardless of the beat.
+ assert.equal(shouldEmitToolCard(1_000, "running", "success", 1_100), true);
+ // A finished call always pushes.
+ assert.equal(shouldEmitToolCard(1_000, "success", "success", 1_050), true);
+});
+
+test("ToolRow swaps in the plugin card before rendering the host card", () => {
+ const source = readFileSync(src("features/chat/transcript/ToolRow.tsx"), "utf8");
+ assert.match(
+ source,
+ /useSlotEntryForKey\(\s*"toolCard",\s*variant === "default" && status !== "denied" \? message\.toolName : undefined,?\s*\)/,
+ );
+ assert.match(source, /if \(pluginCardEntry\) \{/);
+ assert.match(
+ source,
+ /return <PluginToolCard entry=\{pluginCardEntry\} message=\{message\} \/>;/,
+ );
+ // Topology nodes keep the host card: the lookup is skipped for them.
+ const lookupAt = source.indexOf('useSlotEntryForKey(\n "toolCard"');
+ assert.ok(lookupAt > source.indexOf("export const ToolRow"));
+ assert.ok(lookupAt < source.indexOf("export const SubagentRunRows"));
+});
+
+test("the card renders inside its own boundary with the 500ms cadence", () => {
+ const source = readFileSync(src("features/chat/transcript/PluginToolCard.tsx"), "utf8");
+ assert.match(source, /<SlotBoundary entry=\{entry\} slot="toolCard">/);
+ assert.match(source, /toolCardPropsFor\(/);
+ assert.match(source, /dispatchFor\(entry\.pluginId\)/);
+ assert.match(source, /shouldEmitToolCard\(/);
+ assert.match(source, /TOOL_CARD_RUNNING_INTERVAL_MS/);
+});
+
+test("the host passes each plugin's own tool list to the loader context", () => {
+ const host = readFileSync(src("plugins/renderer-host/PluginRendererHost.tsx"), "utf8");
+ assert.match(host, /tools: summary\.tools/);
+ const loader = readFileSync(src("plugins/renderer-host/loader.ts"), "utf8");
+ assert.match(loader, /toolCardOwnershipError\(/);
+ assert.match(loader, /PLUGIN_SLOT_INVALID_KEY/);
+ const context = readFileSync(src("plugins/renderer-host/dispatch.ts"), "utf8");
+ assert.match(context, /tools\?: readonly string\[\]/);
+});
diff --git a/apps/desktop/test/plugin-ui-slots-demo.test.mjs b/apps/desktop/test/plugin-ui-slots-demo.test.mjs
new file mode 100644
index 000000000..4e1028f24
--- /dev/null
+++ b/apps/desktop/test/plugin-ui-slots-demo.test.mjs
@@ -0,0 +1,128 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = (relative) => join(here, "..", "..", "..", relative);
+
+const demoDir = root("examples/plugins/ui-slots-demo");
+const manifest = JSON.parse(readFileSync(join(demoDir, "manifest.json"), "utf8"));
+const mainSource = readFileSync(join(demoDir, "main.js"), "utf8");
+const rendererSource = readFileSync(join(demoDir, "renderer/index.mjs"), "utf8");
+const sdkSource = readFileSync(
+ root("packages/plugin-sdk/src/renderer.ts"),
+ "utf8",
+);
+
+test("the demo manifest declares the full renderer action vocabulary", () => {
+ assert.equal(manifest.id, "demo.ui-slots");
+ // The three dispatched actions this milestone shipped.
+ assert.deepEqual(
+ [...manifest.rendererActions].sort(),
+ ["composer.acceptTriggerItem", "composer.insertText", "plugin.call"],
+ );
+ assert.ok(manifest.rendererCallMethods.includes("stats.summary"));
+ assert.ok(manifest.permissions.includes("renderer.extension"));
+ assert.ok(manifest.permissions.includes("agent.tool.register"));
+ // toolCard ownership premise: the claimed tool is declared here.
+ assert.equal(
+ manifest.contributes?.agentTools?.[0]?.name,
+ "slot_demo_stats",
+ );
+ // Entry files exist.
+ assert.ok(manifest.main.endsWith("main.js"));
+ assert.ok(manifest.renderer.endsWith("renderer/index.mjs"));
+});
+
+test("the headless entry answers the declared renderer method", async () => {
+ const entry = createRequire(import.meta.url)(join(demoDir, "main.js"));
+ assert.equal(typeof entry.onLoad, "function");
+ assert.equal(typeof entry.onUnload, "function");
+ assert.equal(typeof entry.onRendererCall, "function");
+
+ const answer = await entry.onRendererCall("stats.summary", { scale: 2 });
+ assert.equal(answer.total, 2400);
+ // Relay payloads must stay serializable JSON.
+ JSON.stringify(answer);
+
+ await assert.rejects(
+ () => entry.onRendererCall("unknown.method", {}),
+ /unknown renderer method/,
+ );
+});
+
+test("the renderer entry registers every slot with valid keys", () => {
+ // Syntax gate: the host imports this file as ESM through the import map.
+ execFileSync(process.execPath, ["--check", join(demoDir, "renderer/index.mjs")]);
+
+ const registrations = [...rendererSource.matchAll(/pi\.slots\.register\(\s*"([^"]+)"/g)].map(
+ (match) => match[1],
+ );
+ // 7 slots + the self-dialog sample riding in entryExtra.
+ assert.deepEqual(
+ registrations,
+ [
+ "entryExtra",
+ "userAction",
+ "assistantAction",
+ "toolCard",
+ "blockRenderer",
+ "composerControl",
+ "composerTrigger",
+ "composerToken",
+ "entryExtra",
+ ],
+ );
+
+ // toolCard claim matches the manifest-declared tool.
+ assert.match(rendererSource, /pi\.slots\.register\("toolCard", StatsCard, \{ toolName: TOOL_NAME \}\)/);
+ assert.match(mainSource, /name: "slot_demo_stats"/);
+
+ // blockRenderer key keeps the `<pluginId>:` ownership prefix.
+ assert.match(
+ rendererSource,
+ /pi\.slots\.register\("blockRenderer", ChartBlock, \{ language: CHART_LANGUAGE \}\)/,
+ );
+ assert.match(rendererSource, /CHART_LANGUAGE = "demo\.ui-slots:chart"/);
+
+ // composerTrigger uses an SDK-vocabulary symbol.
+ assert.match(
+ rendererSource,
+ /pi\.slots\.register\("composerTrigger", ComposerTrigger, \{ trigger: "#" \}\)/,
+ );
+});
+
+test("every renderer dispatch stays inside the manifest whitelist", () => {
+ const sdkActions = [...sdkSource.matchAll(/"(plugin\.call|composer\.insertText|composer\.acceptTriggerItem)"/g)].map(
+ (match) => match[1],
+ );
+ const dispatched = [
+ ...rendererSource.matchAll(/dispatch\(\s*"([^"]+)"/g),
+ ].map((match) => match[1]);
+
+ assert.ok(dispatched.length >= 3, "demo should exercise the vocabulary");
+ for (const action of new Set(dispatched)) {
+ assert.ok(
+ manifest.rendererActions.includes(action),
+ `${action} is dispatched but not declared in manifest.rendererActions`,
+ );
+ assert.ok(
+ sdkActions.includes(action),
+ `${action} is not in the SDK PluginRendererActionName vocabulary`,
+ );
+ }
+ for (const required of [
+ "plugin.call",
+ "composer.insertText",
+ "composer.acceptTriggerItem",
+ ]) {
+ assert.ok(
+ dispatched.includes(required),
+ `demo never exercises ${required}`,
+ );
+ }
+});
diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rs
index ae0dd435a..124a1f4b4 100644
--- a/crates/host-core/src/plugins.rs
+++ b/crates/host-core/src/plugins.rs
@@ -66,14 +66,18 @@ pub(crate) use marketplace::{
built_in_catalog_at, bundled_package_bytes, has_package_metadata, host_supports_version,
latest_market_version,
};
-pub(crate) use permissions::{derive_capabilities, derive_settings, permission_diff, sanitize_id};
+pub(crate) use permissions::{
+ derive_capabilities, derive_settings, permission_diff, renderer_row, sanitize_id, tools_row,
+};
pub(crate) use providers::{
declared_providers, is_known_api_style, is_known_auth_kind, owned_provider_ids,
plugin_provider_row_id, reconcile_all, reconcile_plugin, remove_plugin_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};
+pub(crate) use validation::{
+ is_local_package_url, package_host_allowed, validate_contributions, validate_renderer,
+};
#[cfg(test)]
mod tests;
diff --git a/crates/host-core/src/plugins/install.rs b/crates/host-core/src/plugins/install.rs
index 8ec766dc0..38e30787d 100644
--- a/crates/host-core/src/plugins/install.rs
+++ b/crates/host-core/src/plugins/install.rs
@@ -133,6 +133,8 @@ impl PluginManager {
update_available: None,
yanked: None,
ui: manifest.ui.clone(),
+ renderer: renderer_row(&manifest),
+ tools: tools_row(&manifest),
fs: manifest.fs.clone(),
settings: derive_settings(&manifest),
i18n: manifest.i18n.clone(),
diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rs
index 4f9a1377f..5c7f7a6d9 100644
--- a/crates/host-core/src/plugins/manifest.rs
+++ b/crates/host-core/src/plugins/manifest.rs
@@ -7,7 +7,19 @@ pub struct PluginManifest {
pub id: String,
pub name: String,
pub version: String,
- pub main: 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 },
@@ -48,19 +60,8 @@ 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)
}
}
diff --git a/crates/host-core/src/plugins/model.rs b/crates/host-core/src/plugins/model.rs
index 43a03d2f2..acaecceec 100644
--- a/crates/host-core/src/plugins/model.rs
+++ b/crates/host-core/src/plugins/model.rs
@@ -81,6 +81,19 @@ pub struct PluginSummary {
pub yanked: Option<PluginYankNotice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ui: Option<PluginUiMeta>,
+ /// Present when the plugin declares `manifest.renderer`
+ /// (`docs/plugin-plan/ui/`): the renderer entry plus the outbound
+ /// action / `plugin.call` method whitelists the desktop host enforces
+ /// for its slot components.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub renderer: Option<Value>,
+ /// `contributes.agentTools` names for the toolCard slot's no-claim gate
+ /// (`docs/plugin-plan/ui/tool-card/`): a plugin card may only render calls
+ /// of tools it registers itself. Held as raw JSON like `renderer`, so the
+ /// row schema stays decoupled from the manifest struct. Absent in records
+ /// written before the renderer milestone, which the host reads as empty.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tools: Option<Value>,
/// `manifest.fs`, passed through verbatim: which files each mode may touch.
/// The desktop host enforces it; the registry carries it so the Plugins
/// page can show the user what they granted. Absent in records written
diff --git a/crates/host-core/src/plugins/permissions.rs b/crates/host-core/src/plugins/permissions.rs
index c8127d9ae..90dfe2e80 100644
--- a/crates/host-core/src/plugins/permissions.rs
+++ b/crates/host-core/src/plugins/permissions.rs
@@ -60,6 +60,9 @@ pub(crate) fn derive_capabilities(manifest: &PluginManifest) -> Vec<String> {
{
out.push("panel".into());
}
+ if manifest.renderer.is_some() {
+ out.push("rendererUi".into());
+ }
let map = manifest.contributes.as_ref().and_then(Value::as_object);
let has = |key: &str| -> bool {
map.and_then(|m| m.get(key))
@@ -112,6 +115,41 @@ pub(crate) fn derive_capabilities(manifest: &PluginManifest) -> Vec<String> {
out
}
+/// `PluginSummary.renderer` payload: the entry plus the whitelists, present
+/// only when the manifest declares a renderer surface. Held as raw JSON so
+/// the row schema stays decoupled from the manifest struct.
+pub(crate) fn renderer_row(manifest: &PluginManifest) -> Option<Value> {
+ manifest.renderer.as_ref().map(|entry| {
+ json!({
+ "entry": entry,
+ "actions": manifest.renderer_actions,
+ "callMethods": manifest.renderer_call_methods,
+ })
+ })
+}
+
+/// `PluginSummary.tools` payload: the plugin's own `contributes.agentTools`
+/// names, present when the manifest declares any. The toolCard slot uses it
+/// for the no-claim gate: a plugin card only renders its own tool's calls.
+pub(crate) fn tools_row(manifest: &PluginManifest) -> Option<Value> {
+ let names: Vec<&str> = manifest
+ .contributes
+ .as_ref()
+ .and_then(|c| c.get("agentTools"))
+ .and_then(|t| t.as_array())
+ .map(|tools| {
+ tools
+ .iter()
+ .filter_map(|tool| tool.get("name").and_then(|n| n.as_str()))
+ })
+ .map(|names| names.collect())
+ .unwrap_or_default();
+ if names.is_empty() {
+ return None;
+ }
+ Some(json!(names))
+}
+
pub(crate) fn permission_diff(old: &[String], new: &[String]) -> Vec<String> {
new.iter()
.filter(|p| !old.iter().any(|o| o == *p))
diff --git a/crates/host-core/src/plugins/registry.rs b/crates/host-core/src/plugins/registry.rs
index 75c057e36..edf4e1565 100644
--- a/crates/host-core/src/plugins/registry.rs
+++ b/crates/host-core/src/plugins/registry.rs
@@ -143,6 +143,8 @@ impl PluginManager {
// lifecycle is the application's own release cycle.
yanked: None,
ui: manifest.ui.clone(),
+ renderer: renderer_row(&manifest),
+ tools: tools_row(&manifest),
fs: manifest.fs.clone(),
settings: derive_settings(&manifest),
i18n: manifest.i18n.clone(),
@@ -327,6 +329,8 @@ impl PluginManager {
update_available: None,
yanked: None,
ui: manifest.ui.clone(),
+ renderer: renderer_row(&manifest),
+ tools: tools_row(&manifest),
fs: manifest.fs.clone(),
settings: derive_settings(&manifest),
i18n: manifest.i18n.clone(),
diff --git a/crates/host-core/src/plugins/validation.rs b/crates/host-core/src/plugins/validation.rs
index 8866ffc74..6e2b7e933 100644
--- a/crates/host-core/src/plugins/validation.rs
+++ b/crates/host-core/src/plugins/validation.rs
@@ -699,6 +699,46 @@ 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/docs/plugin-plan/index.html b/docs/plugin-plan/index.html
index 2acb5af4f..844a76793 100644
--- a/docs/plugin-plan/index.html
+++ b/docs/plugin-plan/index.html
@@ -41,7 +41,7 @@
.pill.rt{color:var(--rt);background:var(--rt-bg)}
.pill.api{color:var(--api);background:var(--api-bg)}
.pill.draft{color:var(--warn);background:var(--warn-bg)}
- .pill.none{color:var(--faint);background:rgba(255,255,255,.04)}
+ .pill.done{color:var(--api);background:var(--api-bg)}
td a{color:var(--text);text-decoration:none;border-bottom:1px solid var(--line-2)}
td a:hover{border-bottom-color:var(--ui)}
.note{margin:16px 0 0;padding:12px 14px;border-radius:10px;background:var(--surface);color:var(--text-2);font-size:13px}
@@ -95,57 +95,58 @@
<table>
<thead><tr><th>id</th><th>插槽</th><th>形态</th><th>文件夹</th><th>状态</th></tr></thead>
<tbody>
- <tr class="open">
+ <tr class="done">
<td class="id">user-action</td>
<td>用户消息操作栏<br /><span style="color:var(--muted);font-size:12.5px">左右只许新增;不改正文、不动三键</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/user-action/index.html">ui/user-action/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">assistant-action</td>
<td>AI 回复操作栏<br /><span style="color:var(--muted);font-size:12.5px">与用户卡同形</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/assistant-action/index.html">ui/assistant-action/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">entry-extra</td>
<td>AI 回复追加区<br /><span style="color:var(--muted);font-size:12.5px">正文下方,可叠加</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/entry-extra/index.html">ui/entry-extra/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">tool-card</td>
<td>工具调用卡<br /><span style="color:var(--muted);font-size:12.5px">只画自己注册的工具;无认领</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/tool-card/index.html">ui/tool-card/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">block-renderer</td>
<td>块渲染器<br /><span style="color:var(--muted);font-size:12.5px"><code>前缀:语言</code>;不得注册已有语言</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/block-renderer/index.html">ui/block-renderer/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">composer</td>
<td>输入区<br /><span style="color:var(--muted);font-size:12.5px">左右控件 · 触发符 · 记号;固定件不可动</span></td>
<td><span class="pill ui">组件</span></td>
<td><a href="ui/composer/index.html">ui/composer/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
- <tr class="open">
+ <tr class="done">
<td class="id">self-dialog</td>
<td>弹窗 / 悬浮层 · 自理<br /><span style="color:var(--muted);font-size:12.5px">无槽无注册;四条底线</span></td>
<td><span class="pill ui">指导</span></td>
<td><a href="ui/self-dialog/index.html">ui/self-dialog/</a></td>
- <td><span class="pill draft">draft</span></td>
+ <td><span class="pill done">done</span></td>
</tr>
</tbody>
</table>
+ <p class="note"><b>落地状态:</b>以上 7 项已实现(SDK + 宿主挂载 + 契约测试 + 示例插件 <code>examples/plugins/ui-slots-demo</code>);契约与词表详见 <a href="../slot-contract.html">slot-contract.html</a>。</p>
</section>
<section>
diff --git a/docs/plugin-plan/slot-contract.html b/docs/plugin-plan/slot-contract.html
index f9e413e21..e8080c671 100644
--- a/docs/plugin-plan/slot-contract.html
+++ b/docs/plugin-plan/slot-contract.html
@@ -100,10 +100,11 @@
<table>
<thead><tr><th>模型</th><th>契约</th><th>用在哪</th></tr></thead>
<tbody>
+ <tr><td>props-once</td><td>一次给全;重挂载才更新</td><td>块渲染(闭合后)</td></tr>
+ <tr><td><span class="pill core">核心 H</span></td><td><code>composer.acceptTriggerItem</code></td><td>触发符候选选中项回流(<code>label</code> + <code>value</code>);宿主写入 <code>#label</code> 记号;菜单未开拒绝 <code>PLUGIN_ACTION_UNROUTED</code></td></tr>
<tr><td>props-once</td><td>一次给全;重挂载才更新</td><td>块渲染(闭合后)</td></tr>
<tr><td>props-push</td><td>宿主推整份,插件不订阅</td><td>action · entryExtra · 工具卡</td></tr>
<tr><td>request</td><td>问几次答几次</td><td>触发符候选</td></tr>
- </tbody>
</table>
<table>
<thead><tr><th>层</th><th>词</th><th>约束</th></tr></thead>
@@ -144,7 +145,7 @@
<li>左右位(userAction / assistantAction)每侧最多 3 个可见项,第 4 个起进宿主「⋯」折叠菜单;entryExtra 单块折叠态 320px / 展开态 600px 内部滚动</li>
<li>composer 触发符固定 <code>@</code> / <code>#</code> / <code>/</code>;记号单草稿上限 8 个;tool-card 运行中 500ms 节拍合并推送(状态跃迁立即推)</li>
<li><code>ui.ask</code> 定名不变:与 agent 侧布尔确认同名不同物,消歧表述以 render/ask 为准</li>
- <li>SDK 尚未实现:以上为文档定稿;落地时按根 AGENTS.md §13/§10 同步 spec/ADR 与契约测试</li>
+ <li>SDK 与宿主已实现(7 槽 + self-dialog 指导项;dispatch 词表 <code>plugin.call</code> / <code>composer.insertText</code> / <code>composer.acceptTriggerItem</code>);示例见 <code>examples/plugins/ui-slots-demo</code>,契约测试见 <code>apps/desktop/test/plugin-*.test.mjs</code></li>
</ul>
</section>
diff --git a/docs/plugin-plan/ui/assistant-action/data-flow.html b/docs/plugin-plan/ui/assistant-action/data-flow.html
index 286d63641..f331f4962 100644
--- a/docs/plugin-plan/ui/assistant-action/data-flow.html
+++ b/docs/plugin-plan/ui/assistant-action/data-flow.html
@@ -70,7 +70,7 @@
<header class="top">
<h1>AI 回复操作栏 · 数据流</h1>
<p>与用户消息操作栏同一套:props 一次给全,插件只渲染,不回调宿主。</p>
- <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 尚未实现</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
</header>
<main>
diff --git a/docs/plugin-plan/ui/composer/data-flow.html b/docs/plugin-plan/ui/composer/data-flow.html
index f91aee27e..4493885f3 100644
--- a/docs/plugin-plan/ui/composer/data-flow.html
+++ b/docs/plugin-plan/ui/composer/data-flow.html
@@ -70,7 +70,7 @@
<header class="top">
<h1>输入区 · 数据流</h1>
<p>组件槽的数据怎么走。草稿读写 / 附件方法不在本夹。</p>
- <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 尚未实现</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
</header>
<main>
diff --git a/docs/plugin-plan/ui/entry-extra/data-flow.html b/docs/plugin-plan/ui/entry-extra/data-flow.html
index f217a08cf..7617eab84 100644
--- a/docs/plugin-plan/ui/entry-extra/data-flow.html
+++ b/docs/plugin-plan/ui/entry-extra/data-flow.html
@@ -70,7 +70,7 @@
<header class="top">
<h1>AI 回复追加区 · 数据流</h1>
<p>宿主把这条 AI 回复的数据推给追加块;插件只渲染,不回调宿主。</p>
- <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 尚未实现</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
</header>
<main>
diff --git a/docs/plugin-plan/ui/tool-card/data-flow.html b/docs/plugin-plan/ui/tool-card/data-flow.html
index 34b6d6361..ec8bb82e8 100644
--- a/docs/plugin-plan/ui/tool-card/data-flow.html
+++ b/docs/plugin-plan/ui/tool-card/data-flow.html
@@ -70,7 +70,7 @@
<header class="top">
<h1>工具调用卡 · 数据流</h1>
<p>自己注册的工具:调用数据推给卡片组件;失败是数据。宿主 / 他人工具不进插件。</p>
- <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 尚未实现</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
</header>
<main>
diff --git a/docs/plugin-plan/ui/user-action/data-flow.html b/docs/plugin-plan/ui/user-action/data-flow.html
index edb0306db..21c7193d5 100644
--- a/docs/plugin-plan/ui/user-action/data-flow.html
+++ b/docs/plugin-plan/ui/user-action/data-flow.html
@@ -71,7 +71,7 @@
<header class="top">
<h1>用户消息操作栏 · 数据流</h1>
<p>插件能拿到什么、自己画什么、出错时发生什么。</p>
- <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 尚未实现</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
</header>
<main>
diff --git a/examples/plugins/ui-slots-demo/main.js b/examples/plugins/ui-slots-demo/main.js
new file mode 100644
index 000000000..4371564b3
--- /dev/null
+++ b/examples/plugins/ui-slots-demo/main.js
@@ -0,0 +1,63 @@
+/**
+ * UI Slots Demo — headless entry (`demo.ui-slots`).
+ *
+ * Registers one low-risk tool (the toolCard no-claim gate only accepts cards
+ * for tools the plugin itself declares) and answers one `plugin.call` method
+ * so the slot components have something real to fetch across the relay.
+ */
+
+async function onLoad() {
+ await pi.agent.registerTool({
+ name: "slot_demo_stats",
+ description: "Return fake usage stats for the toolCard demo",
+ risk: "low",
+ schema: {
+ type: "object",
+ properties: {
+ query: { type: "string" },
+ },
+ },
+ execute: async (args) => {
+ const query = String(args?.query ?? "");
+ let calls = 0;
+ try {
+ calls = parseInt(query.replace(/\D+/g, ""), 10) || 0;
+ } catch {
+ calls = 0;
+ }
+ return {
+ ok: true,
+ query,
+ total: 1200 + calls * 37,
+ average: 42.5,
+ label: "slot-demo stats",
+ };
+ },
+ });
+}
+
+async function onUnload() {
+ await pi.agent.unregisterTool("slot_demo_stats");
+}
+
+/**
+ * The `plugin.call` relay target (`stats.summary`). Args come from the
+ * renderer slot components; the answer must stay serializable JSON.
+ */
+async function onRendererCall(method, args) {
+ if (method === "stats.summary") {
+ const scale = Number(args?.scale) || 1;
+ return {
+ total: Math.round(1200 * scale),
+ average: 42.5,
+ generatedAt: new Date().toISOString(),
+ };
+ }
+ throw new Error(`unknown renderer method: ${method}`);
+}
+
+module.exports = {
+ onLoad,
+ onUnload,
+ onRendererCall,
+};
diff --git a/examples/plugins/ui-slots-demo/manifest.json b/examples/plugins/ui-slots-demo/manifest.json
new file mode 100644
index 000000000..dc98cfd07
--- /dev/null
+++ b/examples/plugins/ui-slots-demo/manifest.json
@@ -0,0 +1,37 @@
+{
+ "schemaVersion": 1,
+ "id": "demo.ui-slots",
+ "name": "UI Slots Demo",
+ "version": "0.1.0",
+ "description": "PI-Desktop 示例插件:一次性注册全部 UI 插槽(动作栏 / 回复追加区 / 工具卡 / 代码块渲染器 / 输入区)+ 自绘弹窗样本",
+ "author": "PI-Desktop",
+ "main": "main.js",
+ "renderer": "renderer/index.mjs",
+ "rendererActions": ["plugin.call", "composer.insertText", "composer.acceptTriggerItem"],
+ "rendererCallMethods": ["stats.summary"],
+ "contributes": {
+ "agentTools": [
+ {
+ "name": "slot_demo_stats",
+ "description": "Return fake usage stats for the toolCard demo",
+ "risk": "low",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string" }
+ }
+ }
+ }
+ ]
+ },
+ "permissions": [
+ "renderer.extension",
+ "agent.tool.register"
+ ],
+ "engines": {
+ "piDesktop": ">=0.1.0"
+ },
+ "activationEvents": [
+ "onStartup"
+ ]
+}
diff --git a/examples/plugins/ui-slots-demo/renderer/index.mjs b/examples/plugins/ui-slots-demo/renderer/index.mjs
new file mode 100644
index 000000000..6ac667873
--- /dev/null
+++ b/examples/plugins/ui-slots-demo/renderer/index.mjs
@@ -0,0 +1,258 @@
+/**
+ * UI Slots Demo — renderer entry (`demo.ui-slots`).
+ *
+ * Registers every finalized UI slot in one plugin, plus the self-dialog
+ * sample (`docs/plugin-plan/ui/self-dialog/`): a plugin-drawn modal using
+ * the host's p-overlay/p-dialog tool classes, honoring the four ground
+ * rules — drawn inside its own component, gone on unload, never above the
+ * host safety layer (z 600..899 < 900), later plugins stack above earlier
+ * ones with no host arbitration.
+ *
+ * Plain ES module, no build step: `react` resolves to the host's single
+ * React through the document import map.
+ */
+import { createElement as h, useState } from "react";
+
+const TOOL_NAME = "slot_demo_stats";
+const CHART_LANGUAGE = "demo.ui-slots:chart";
+
+/* ---------- shared bits ------------------------------------------------- */
+
+function useDemoStyles(pi) {
+ const cssId = pi.plugin.id.replace(/[^A-Za-z0-9_-]/g, "-");
+ pi.ui.injectStyle(`
+.pi-plugin-slot.${cssId} .slot-demo-card {
+ display: block;
+ width: 100%;
+ padding: 10px 12px;
+ border: 1px solid rgb(255 255 255 / 0.08);
+ border-radius: 10px;
+ background: rgb(255 255 255 / 0.04);
+ font-size: 12.5px;
+ line-height: 1.55;
+}
+.pi-plugin-slot.${cssId} .slot-demo-card h4 {
+ margin: 0 0 6px;
+ font-size: 12px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ opacity: 0.75;
+}
+.pi-plugin-slot.${cssId} .slot-demo-btn {
+ margin: 4px 6px 0 0;
+ padding: 2px 10px;
+ border: 1px solid rgb(255 255 255 / 0.16);
+ border-radius: 7px;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+.pi-plugin-slot.${cssId} .slot-demo-btn:hover {
+ background: rgb(255 255 255 / 0.08);
+}
+.pi-plugin-slot.${cssId} .slot-demo-bar {
+ height: 10px;
+ margin: 3px 0;
+ border-radius: 4px;
+ background: rgb(124 92 255 / 0.55);
+}
+.pi-plugin-slot.${cssId} .slot-demo-mono {
+ font-family: ui-monospace, "Cascadia Code", Consolas, monospace;
+ font-size: 11.5px;
+ white-space: pre-wrap;
+}
+`);
+ return cssId;
+}
+
+/* ---------- entryExtra -------------------------------------------------- */
+
+function EntryExtraCard({ message, dispatch }) {
+ const [result, setResult] = useState("no call yet");
+ const rows = Array.from({ length: 18 }, (_, i) => `metric-${i + 1}`);
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `entryExtra · reply ${message.id.slice(0, 8)}`),
+ h("div", { className: "slot-demo-mono" },
+ rows.map((row) => `${row.padEnd(12, " ")} ██████ 42.5\n`).join("")),
+ h("button", {
+ className: "slot-demo-btn",
+ onClick: () => {
+ dispatch("plugin.call", { method: "stats.summary", args: { scale: 2 } })
+ .then((answer) => setResult(JSON.stringify(answer)))
+ .catch((error) => setResult(`${error.code ?? "ERROR"}: ${error.message}`));
+ },
+ }, "plugin.call → stats.summary"),
+ h("button", {
+ className: "slot-demo-btn",
+ onClick: () => dispatch("composer.insertText", "Inserted by demo.ui-slots"),
+ }, "composer.insertText"),
+ h("div", { className: "slot-demo-mono" }, result),
+ );
+}
+
+/* ---------- user / assistant actions ------------------------------------ */
+
+function ActionButton({ position, dispatch }) {
+ const [clicked, setClicked] = useState(0);
+ return h("button", {
+ className: "slot-demo-btn",
+ title: `plugin action (${position})`,
+ onClick: () => {
+ setClicked((n) => n + 1);
+ dispatch("composer.insertText", `demo action (${position}) #${clicked + 1} `);
+ },
+ }, clicked > 0 ? `demo ×${clicked}` : "demo");
+}
+
+/* ---------- toolCard ---------------------------------------------------- */
+
+function StatsCard({ toolName, toolCallId, toolStatus, toolArgs, toolResult, toolError, durationMs }) {
+ if (toolStatus === "running") {
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `toolCard · ${toolName} · call ${toolCallId.slice(0, 8)}`),
+ h("div", null, "running…"));
+ }
+ if (toolStatus === "error") {
+ // Failure is data, drawn by the card.
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `toolCard · ${toolName}`),
+ h("div", { style: { color: "#ff6764" } },
+ `failed: ${String(toolError?.message ?? toolError ?? "unknown error")}`));
+ }
+ const rows = toolResult && typeof toolResult === "object" ? Object.entries(toolResult) : [];
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `toolCard · ${toolName}${typeof durationMs === "number" ? ` · ${durationMs}ms` : ""}`),
+ h("div", { className: "slot-demo-mono" },
+ rows.map(([key, value]) => `${key}: ${String(value)}\n`).join("") ||
+ `args: ${JSON.stringify(toolArgs ?? null)}`));
+}
+
+/* ---------- blockRenderer ------------------------------------------------ */
+
+function ChartBlock({ language, source }) {
+ let bars = null;
+ let error = null;
+ try {
+ const parsed = JSON.parse(source);
+ if (!Array.isArray(parsed)) throw new Error("expected a JSON array");
+ bars = parsed.map((entry) => ({
+ label: String(entry.label ?? "?"),
+ value: Number(entry.value) || 0,
+ }));
+ } catch (cause) {
+ error = cause;
+ }
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `blockRenderer · ${language}`),
+ error
+ ? h("div", null,
+ h("div", { style: { color: "#ff6764" } }, `render failed: ${error.message}`),
+ h("pre", { className: "slot-demo-mono" }, source))
+ : h("div", null,
+ bars.map((bar) =>
+ h("div", { key: bar.label, style: { display: "flex", alignItems: "center", gap: 6 } },
+ h("span", { style: { width: 64 } }, bar.label),
+ h("div", {
+ className: "slot-demo-bar",
+ style: { width: Math.min(220, bar.value) },
+ }),
+ h("span", { className: "slot-demo-mono" }, String(bar.value)))),
+ h("div", { className: "slot-demo-mono" }, source)));
+}
+
+/* ---------- composer slots ---------------------------------------------- */
+
+function ComposerControl({ position, dispatch }) {
+ return h("button", {
+ className: "slot-demo-btn",
+ title: `composer control (${position})`,
+ onClick: () => dispatch("composer.insertText", "[demo token] "),
+ }, "+demo");
+}
+
+function ComposerTrigger({ query, dispatch }) {
+ const items = ["alpha", "beta", "gamma"]
+ .filter((name) => name.toLowerCase().startsWith(query.toLowerCase()))
+ .map((name) => ({ label: name, value: { intent: "demo", name } }));
+ return h("div", { className: "slot-demo-card" },
+ h("h4", null, `composerTrigger "#${query}" — click to accept`),
+ items.length
+ ? items.map((item) =>
+ h("button", {
+ key: item.label,
+ className: "slot-demo-btn",
+ style: { display: "block", width: "100%", textAlign: "left" },
+ onClick: () =>
+ dispatch("composer.acceptTriggerItem", {
+ label: item.label,
+ value: item.value,
+ }).catch((error) =>
+ console.warn("[ui-slots-demo] accept rejected", error.code ?? error)),
+ }, `#${item.label}`))
+ : h("div", null, "no match"));
+}
+
+function ComposerToken({ label }) {
+ return h("span", {
+ style: {
+ display: "inline-flex",
+ alignItems: "center",
+ padding: "0 6px",
+ borderRadius: 6,
+ border: "1px solid rgb(124 92 255 / 0.5)",
+ fontSize: 11,
+ },
+ }, `#${label}`);
+}
+
+/* ---------- self-dialog sample ------------------------------------------ */
+
+function SelfDialogLauncher() {
+ const [open, setOpen] = useState(false);
+ return h("div", null,
+ h("button", {
+ className: "slot-demo-btn",
+ onClick: () => setOpen(true),
+ }, "open self-dialog"),
+ open
+ ? h("div", { className: "p-overlay", onClick: (event) => {
+ if (event.target === event.currentTarget) setOpen(false);
+ } },
+ h("div", { className: "p-dialog", role: "dialog", "aria-label": "UI Slots Demo dialog" },
+ h("div", { className: "p-dialog-head" },
+ h("span", null, "UI Slots Demo"),
+ h("button", { className: "p-notice__dismiss", onClick: () => setOpen(false) }, "✕")),
+ h("div", { className: "p-dialog__body" },
+ h("p", null, "Plugin-drawn modal. z 600..899 — the host safety layer (900) always wins; Esc does not close it, only this ✕ does.")),
+ h("div", { className: "p-dialog__foot" },
+ h("button", { className: "slot-demo-btn", onClick: () => setOpen(false) }, "close"))))
+ : null);
+}
+
+/* ---------- registration ------------------------------------------------ */
+
+export function onLoad(pi) {
+ const cssId = useDemoStyles(pi);
+ void cssId;
+
+ pi.slots.register("entryExtra", EntryExtraCard);
+ pi.slots.register("userAction", ActionButton);
+ // positions subset demo: only the right side of the assistant bar.
+ pi.slots.register("assistantAction", ActionButton, { positions: ["right"] });
+ // toolCard no-claim: this tool is declared in this plugin's manifest.
+ pi.slots.register("toolCard", StatsCard, { toolName: TOOL_NAME });
+ pi.slots.register("blockRenderer", ChartBlock, { language: CHART_LANGUAGE });
+ pi.slots.register("composerControl", ComposerControl, { positions: ["left"] });
+ pi.slots.register("composerTrigger", ComposerTrigger, { trigger: "#" });
+ pi.slots.register("composerToken", ComposerToken);
+
+ // The self-dialog sample rides inside the entryExtra card.
+ pi.slots.register("entryExtra", SelfDialogLauncher);
+}
+
+export function onUnload() {
+ // Registrations and injected styles are torn down by the host
+ // (卸载摘注册); the self-dialog disappears with this module's components.
+}
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index cb867c419..601ca7d11 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -374,6 +374,9 @@ export const de = {
"compactionRowSummary": "Zusammenfassung ≈{{tokens}} Token",
"compactionRowNoSummary": "keine Zusammenfassung generiert",
"compactionRowSummaryFailed": "Zusammenfassung fehlgeschlagen · aktueller Kontext beibehalten",
+ "entryExtraExpand": "Block vollständig anzeigen",
+ "entryExtraCollapse": "Block einklappen",
+ "actionSlotMore": "Weitere Aktionen",
"scrollToBottom": "Zum Neuesten springen",
"minimap": "Gesprächsübersicht",
"resultNeedsAttention": "Diese Aufgabe erfordert Aufmerksamkeit",
@@ -2093,6 +2096,7 @@ sklm: {
"agent.prompt.inject": "Agentenanweisungen anpassen",
"agent.complete": "One-Shot-Vervollständigung mit Ihren Modellen durchführen",
"agent.extension": "Code im Agenten ausführen",
+ "renderer.extension": "Oberfläche in Chat-Slots zeichnen",
"provider.register": "Anbieter zur Modellliste hinzufügen",
"desktop.control": "Desktop steuern",
"models.list": "Authentifizierte Modelle auflisten",
@@ -2130,6 +2134,7 @@ sklm: {
"agent.prompt.inject": "Kann Anweisungen ändern, die an den KI-Agenten gesendet werden.",
"agent.complete": "Kann Ihr Modellkontingent für eine einmalige Fertigstellung ausgeben. Das Plugin erhält niemals Ihre API-Schlüssel.",
"agent.extension": "Führt ExtensionAPI-Module im Agentenprozess mit denselben Rechten wie die Tools des Agenten aus. Aktiviere nur Code, dem du vertraust.",
+ "renderer.extension": "Lädt das Renderer-Modul dieses Plugins in das App-Fenster, um UI-Slot-Komponenten zu zeichnen (Nachrichten-Aktionsleisten, Antwort-Anhänge, Tool-Karten, Codeblock-Renderer, Eingabebereich). Das Modul läuft im selben Dokument wie PI-Desktop. Aktiviere nur Code, dem du vertraust.",
"provider.register": "Fügt die Anbieter, die dieses Plugin definiert, zur Anbieterliste in den Einstellungen hinzu. Das Plugin liefert den Endpunkt und die Modelle; Ihr API-Schlüssel bleibt in PI-Desktop.",
"desktop.control": "Erlaubt den Aufruf des geprüften PI-Desktop-Katalogs; destruktive Vorgänge benötigen weiterhin confirm=true, und das MCP-Bearer-Token wird nicht offengelegt.",
"models.list": "Kann sehen, für welche Modelle Sie sich angemeldet haben. Es erhält keine Schlüssel.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index bdaf1bc7d..37e146670 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -331,6 +331,9 @@ export const en = {
hideErrorDetails: "Hide details",
dismissError: "Dismiss error message",
copyErrorDetails: "Copy details",
+ entryExtraExpand: "Show full block",
+ entryExtraCollapse: "Collapse block",
+ actionSlotMore: "More actions",
errorProvider: "AI provider",
errorModel: "Model",
previewFile: "Preview in the side panel",
@@ -2112,6 +2115,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a
"agent.prompt.inject": "Adjust agent instructions",
"agent.complete": "Run a one-shot completion with your models",
"agent.extension": "Run code inside the agent",
+ "renderer.extension": "Draw UI in chat slots",
"provider.register": "Add providers to the model list",
"desktop.control": "Control the desktop",
"models.list": "List authenticated models",
@@ -2156,7 +2160,10 @@ 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":
"Adds the providers this plugin defines to Settings' provider list. The plugin supplies the endpoint and models; your API key stays in PI-Desktop.",
"desktop.control":
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 7d9acfe17..89a9e6e68 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -374,6 +374,9 @@ export const es = {
"compactionRowSummary": "resumen ≈{{tokens}} tokens",
"compactionRowNoSummary": "no se generó ningún resumen",
"compactionRowSummaryFailed": "falló la generación del resumen · se conservó el contexto reciente",
+ "entryExtraExpand": "Mostrar el bloque completo",
+ "entryExtraCollapse": "Contraer el bloque",
+ "actionSlotMore": "Más acciones",
"scrollToBottom": "Saltar a la última",
"minimap": "Esquema de la conversación",
"resultNeedsAttention": "Esta tarea necesita atención",
@@ -2093,6 +2096,7 @@ sklm: {
"agent.prompt.inject": "Ajustar instrucciones del agente",
"agent.complete": "Ejecutar una finalización de una sola vez con sus modelos",
"agent.extension": "Ejecutar código dentro del agente",
+ "renderer.extension": "Dibujar interfaz en los slots del chat",
"provider.register": "Agregar proveedores a la lista de modelos",
"desktop.control": "Controlar el escritorio",
"models.list": "Listar modelos autenticados",
@@ -2130,6 +2134,7 @@ sklm: {
"agent.prompt.inject": "Puede cambiar las instrucciones enviadas al agente de IA.",
"agent.complete": "Puede gastar su cuota de modelo en una finalización única. El complemento nunca recibe sus claves API.",
"agent.extension": "Ejecuta módulos ExtensionAPI dentro del proceso del agente con el mismo acceso que sus propias herramientas. Activa solo código en el que confíes.",
+ "renderer.extension": "Carga el módulo de renderizado de este complemento en la ventana de la app para dibujar componentes en los slots de la interfaz (barras de acción de mensajes, extras de respuesta, tarjetas de herramientas, renderizadores de bloques de código, controles del compositor). El módulo se ejecuta en el mismo documento que PI-Desktop. Activa solo código de confianza.",
"provider.register": "Agregue los proveedores que define este complemento a la lista de proveedores de Configuración. El complemento aporta el punto final y los modelos; su clave API permanece en PI-Desktop.",
"desktop.control": "Permite invocar el catálogo de control de PI-Desktop revisado; las operaciones destructivas siguen requiriendo confirm=true y el token bearer de MCP no se expone.",
"models.list": "Puede ver en qué modelos se ha registrado. No recibe llaves.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 724e751a3..923382924 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -374,6 +374,9 @@ export const fr = {
"compactionRowSummary": "résumé ≈{{tokens}} jetons",
"compactionRowNoSummary": "aucun résumé généré",
"compactionRowSummaryFailed": "échec de la génération du résumé · contexte récent conservé",
+ "entryExtraExpand": "Afficher tout le bloc",
+ "entryExtraCollapse": "Replier le bloc",
+ "actionSlotMore": "Plus d'actions",
"scrollToBottom": "Passer au dernier",
"minimap": "Aperçu de la conversation",
"resultNeedsAttention": "Cette tâche nécessite une attention particulière",
@@ -2093,6 +2096,7 @@ sklm: {
"agent.prompt.inject": "Ajuster les instructions de l'agent",
"agent.complete": "Exécuter une complétion unique avec vos modèles",
"agent.extension": "Exécuter du code dans l'agent",
+ "renderer.extension": "Dessiner l'interface dans les emplacements du chat",
"provider.register": "Ajouter des fournisseurs à la liste de modèles",
"desktop.control": "Contrôler le bureau",
"models.list": "Liste des modèles authentifiés",
@@ -2130,6 +2134,7 @@ sklm: {
"agent.prompt.inject": "Peut modifier les instructions envoyées à l'agent IA.",
"agent.complete": "Peut dépenser votre quota de modèle pour une réalisation unique. Le plugin ne reçoit jamais vos clés API.",
"agent.extension": "Exécute des modules ExtensionAPI dans le processus de l'agent avec le même accès que ses propres outils. N'activez que du code auquel vous faites confiance.",
+ "renderer.extension": "Charge le module de rendu de ce plugin dans la fenêtre de l'app pour dessiner des composants d'interface (barres d'actions des messages, extras de réponse, cartes d'outils, rendus de blocs de code, contrôles du composeur). Le module s'exécute dans le même document que PI-Desktop. N'activez que du code de confiance.",
"provider.register": "Ajoute les fournisseurs définis par ce plugin à la liste des fournisseurs des Paramètres. Le plugin fournit le point de terminaison et les modèles ; votre clé API reste dans PI-Desktop.",
"desktop.control": "Permet d'appeler le catalogue PI-Desktop contrôlé ; les opérations destructrices exigent toujours confirm=true et le bearer token MCP n'est pas exposé.",
"models.list": "Peut voir pour quels modèles vous vous êtes connecté. Il ne reçoit pas de clés.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index f4d96e985..a078ed812 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -313,6 +313,9 @@ export const ko = {
copied: "복사됨",
copyFailed: "클립보드에 복사하지 못했습니다",
messageMenu: "메시지 작업",
+ entryExtraExpand: "전체 콘텐츠 보기",
+ entryExtraCollapse: "콘텐츠 접기",
+ actionSlotMore: "더 많은 작업",
conversationMenu: "대화 작업",
selectMessageText: "메시지 텍스트 선택",
copyConversation: "대화 복사",
@@ -2109,6 +2112,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"agent.prompt.inject": "에이전트 지침 조정",
"agent.complete": "모델로 일회성 완성 실행",
"agent.extension": "에이전트 안에서 코드 실행",
+ "renderer.extension": "채팅 슬롯에 UI 그리기",
"provider.register": "모델 목록에 프로바이더 추가",
"desktop.control": "데스크톱 제어",
"models.list": "인증된 모델 목록 표시",
@@ -2153,6 +2157,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"agent.complete":
"모델 할당량을 사용해 일회성 완성을 실행할 수 있습니다. 플러그인은 API 키를 받지 않습니다.",
"agent.extension": "ExtensionAPI 모듈을 에이전트 프로세스 안에서 에이전트 자체 도구와 같은 권한으로 실행합니다. 신뢰하는 코드만 켜세요.",
+ "renderer.extension": "이 플러그인의 렌더러 모듈을 앱 창에 로드하여 메시지 작업 표시줄, 응답 추가 영역, 도구 카드, 코드 블록 렌더러, 작성기 컨트롤 등 UI 슬롯 구성 요소를 그립니다. 모듈은 PI-Desktop과 같은 문서에서 실행됩니다. 신뢰하는 코드만 활성화하세요.",
"provider.register":
"이 플러그인이 정의한 프로바이더를 설정의 프로바이더 목록에 추가합니다. 플러그인은 엔드포인트와 모델을 제공하며, API 키는 PI-Desktop에 남습니다.",
"desktop.control":
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 35f54ab25..d2ca693c0 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -312,6 +312,9 @@ export const tr = {
copy: "Kopyala",
copied: "Kopyalandı",
copyFailed: "Panoya kopyalanamadı",
+ entryExtraExpand: "Bloğun tamamını göster",
+ entryExtraCollapse: "Bloğu daralt",
+ actionSlotMore: "Diğer işlemler",
messageMenu: "Mesaj işlemleri",
conversationMenu: "Konuşma işlemleri",
selectMessageText: "Mesaj metnini seç",
@@ -2099,6 +2102,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"agent.prompt.inject": "Ajan yönergelerini ayarla",
"agent.complete": "Modellerinizle tek seferlik tamamlatma çalıştır",
"agent.extension": "Ajanın içinde kod çalıştır",
+ "renderer.extension": "Sohbet yuvalarında arayüz çiz",
"provider.register": "Model listesine servis ekle",
"desktop.control": "Masaüstünü kontrol et",
"models.list": "Kimliği doğrulanmış modelleri listele",
@@ -2143,6 +2147,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"agent.complete":
"Model kotanızı tek seferlik bir tamamlatma için harcayabilir. Eklenti API anahtarlarınızı almaz.",
"agent.extension": "ExtensionAPI modüllerini ajan sürecinde, ajanın kendi araçlarıyla aynı erişimle çalıştırır. Yalnızca güvendiğiniz kodu etkinleştirin.",
+ "renderer.extension": "Bu eklentinin işleyici modülünü uygulama penceresine yükler; mesaj eylem çubukları, yanıt ek alanları, araç kartları, kod bloğu işleyicileri ve besteleyici kontrolleri gibi arayüz yuvası bileşenleri çizer. Modül PI-Desktop ile aynı belgede çalışır. Yalnızca güvendiğiniz kodu etkinleştirin.",
"provider.register":
"Bu eklentinin tanımladığı servisleri Ayarlar’daki servis listesine ekler. Uç noktayı ve modelleri eklenti sağlar; API anahtarınız PI-Desktop’ta kalır.",
"desktop.control":
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index ec16c49a1..ab558b90e 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -305,6 +305,9 @@ export const zhCN = {
copied: "已复制",
copyFailed: "复制到剪贴板失败",
messageMenu: "消息操作",
+ entryExtraExpand: "展开完整内容",
+ entryExtraCollapse: "收起内容",
+ actionSlotMore: "更多操作",
conversationMenu: "对话操作",
selectMessageText: "选中消息文本",
copyConversation: "复制整个对话",
@@ -2078,6 +2081,7 @@ sklm: {
"agent.prompt.inject": "调整智能体指令",
"agent.complete": "用你的模型发起一次补全",
"agent.extension": "在 agent 内运行代码",
+ "renderer.extension": "在聊天插槽绘制界面",
"provider.register": "将服务添加到模型列表",
"desktop.control": "控制桌面操作",
"models.list": "列出已登录的模型",
@@ -2116,6 +2120,7 @@ sklm: {
"agent.prompt.inject": "可能修改发送给智能体的指令。",
"agent.complete": "会消耗你的模型额度发起一次补全。插件拿不到 API 密钥。",
"agent.extension": "在 agent 进程内运行 ExtensionAPI 模块,拥有与 agent 自身工具相同的权限。只启用你信任的代码。",
+ "renderer.extension": "把该插件的渲染模块加载进应用窗口,在消息操作栏、回复追加区、工具卡、代码块、输入区等插槽绘制界面。模块与 PI-Desktop 同文档运行,只启用你信任的代码。",
"provider.register": "把此插件定义的服务添加到设置的服务列表。接口地址和模型由插件提供,API 密钥则留在 PI-Desktop 中。",
"desktop.control":
"允许插件调用经过审查的 PI-Desktop 操作目录;破坏性操作仍需 confirm=true,插件永远拿不到 MCP bearer token。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index b3b055ddb..075dd4f55 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -305,6 +305,9 @@ export const zhTW = {
copied: "已複製",
copyFailed: "複製到剪貼簿失敗",
messageMenu: "訊息操作",
+ entryExtraExpand: "展開完整內容",
+ entryExtraCollapse: "收起內容",
+ actionSlotMore: "更多操作",
conversationMenu: "對話操作",
selectMessageText: "選取訊息文字",
copyConversation: "複製整段對話",
@@ -2078,6 +2081,7 @@ sklm: {
"agent.prompt.inject": "調整智慧體指令",
"agent.complete": "用你的模型發起一次補全",
"agent.extension": "在 agent 內執行程式碼",
+ "renderer.extension": "在聊天插槽繪製介面",
"provider.register": "將服務新增到模型列表",
"desktop.control": "控制桌面操作",
"models.list": "列出已登入的模型",
@@ -2116,6 +2120,7 @@ sklm: {
"agent.prompt.inject": "可能修改傳送給智慧體的指令。",
"agent.complete": "會消耗你的模型額度發起一次補全。外掛拿不到 API 金鑰。",
"agent.extension": "在 agent 程序內執行 ExtensionAPI 模組,擁有與 agent 自身工具相同的權限。只啟用你信任的程式碼。",
+ "renderer.extension": "把該外掛的渲染模組載入應用視窗,在訊息操作列、回覆追加區、工具卡、程式碼區塊、輸入區等插槽繪製介面。模組與 PI-Desktop 同文件執行,只啟用你信任的程式碼。",
"provider.register": "把此外掛定義的服務新增到設定的服務列表。介面地址和模型由外掛提供,API 金鑰則留在 PI-Desktop 中。",
"desktop.control": "允許外掛呼叫經過審查的 PI-Desktop 操作目錄;破壞性操作仍需 confirm=true,外掛永遠拿不到 MCP bearer token。",
"models.list": "可以看到你已登入的模型,但拿不到金鑰。",
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 3483a13b7..256d1ac82 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -59,7 +59,24 @@ 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
+ * host renderer and registers UI slot components through `pi.slots`.
+ */
+ renderer?: string;
+ /**
+ * Outbound actions the renderer components may dispatch. Declaring fewer
+ * is safe; an action outside this list is refused with
+ * `PLUGIN_ACTION_UNDECLARED`. Requires `renderer.extension`.
+ */
+ rendererActions?: string[];
+ /**
+ * Methods the plugin's `onRendererCall` answers for `plugin.call`.
+ * Whitelist: an undeclared method is refused with `PLUGIN_CALL_NO_HANDLER`.
+ * Requires `renderer.extension`.
+ */
+ rendererCallMethods?: string[];
main: string;
icon?: string;
/**
@@ -1271,6 +1288,10 @@ export const PLUGIN_PERMISSIONS = [
"agent.prompt.inject",
"agent.complete",
"agent.extension",
+ // Renderer slots (`docs/plugin-plan/ui/`): the entry module loads into the
+ // host renderer's own document, so the surface it can touch is the
+ // renderer itself. One umbrella permission, like `agent.extension`.
+ "renderer.extension",
"provider.register",
"desktop.control",
"models.list",
@@ -1324,7 +1345,8 @@ 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") {
return { ok: false, error: "manifest.schemaVersion is required" };
}
@@ -2072,3 +2094,81 @@ export {
type PluginFsRule,
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,
+ PLUGIN_SLOT_POSITIONS,
+ PLUGIN_COMPOSER_TRIGGERS,
+ PLUGIN_COMPOSER_TOKEN_LIMIT,
+ slotKeyError,
+ slotPositionsError,
+ toolCardOwnershipError,
+ type PiRendererApi,
+ type PiRendererModule,
+ type PluginRendererSlot,
+ type PluginRendererSlotOptions,
+ type PluginRendererSlotDiagnosticCode,
+ type PluginRendererDiagnostic,
+ type PluginRendererRegistration,
+ type PluginRendererStyleHandle,
+ type PluginRendererDispatch,
+ type PluginRendererActionName,
+ type PluginCallPayload,
+ type PluginSlotMessage,
+ type PluginSlotPosition,
+ type PluginActionSlotProps,
+ type PluginEntryExtraSlotProps,
+ type PluginToolCardSlotProps,
+ type PluginBlockRendererSlotProps,
+ type PluginComposerControlSlotProps,
+ type PluginComposerTriggerProps,
+ type PluginComposerTrigger,
+ type PluginComposerTriggerItem,
+ type PluginComposerTokenProps,
+ type PluginRendererCall,
+} from "./renderer.js";
diff --git a/packages/plugin-sdk/src/renderer.ts b/packages/plugin-sdk/src/renderer.ts
new file mode 100644
index 000000000..7b7c3b93e
--- /dev/null
+++ b/packages/plugin-sdk/src/renderer.ts
@@ -0,0 +1,353 @@
+/**
+ * UI slot contract shared by all renderer slots (`docs/plugin-plan/ui/`).
+ *
+ * A plugin ships a **renderer entry** — an ES module loaded into the host
+ * renderer process — and registers slot components through the `pi.slots`
+ * API handed to `onLoad`. The slot vocabulary below is the finalized
+ * catalog (`docs/plugin-plan/slot-contract.html`):
+ *
+ * - `userAction` / `assistantAction` — additive left/right positions on the
+ * user / assistant message card action bars.
+ * - `entryExtra` — additive block below the assistant reply body.
+ * - `toolCard` — no-claim card for the plugin's **own** registered tool.
+ * - `blockRenderer` — keyed `<pluginId>:lang` code-block takeover.
+ * - `composerControl` — additive left/right controls in the composer toolbar.
+ * - `composerTrigger` — one trigger symbol per plugin (`@`, `#`, `/`).
+ * - `composerToken` — how a selected item is written into the draft.
+ *
+ * Self-dialog (modal/overlay) is deliberately **not** a slot: plugins draw
+ * it themselves inside their own components (`docs/plugin-plan/ui/self-dialog/`).
+ */
+
+/** Privileged scheme that serves renderer entry modules. */
+export const PLUGIN_RENDERER_SCHEME = "plugin-renderer";
+
+/** Every renderer slot the host mounts. */
+export const PLUGIN_RENDERER_SLOTS = [
+ "userAction",
+ "assistantAction",
+ "entryExtra",
+ "toolCard",
+ "blockRenderer",
+ "composerControl",
+ "composerTrigger",
+ "composerToken",
+] as const;
+
+export type PluginRendererSlot = (typeof PLUGIN_RENDERER_SLOTS)[number];
+
+/** Positions of the additive action bars and composer controls. */
+export type PluginSlotPosition = "left" | "right";
+
+/** Position vocabulary, used by `validateSlotOptions`. */
+export const PLUGIN_SLOT_POSITIONS = ["left", "right"] as const;
+
+/** Trigger symbols fixed by contract — one plugin per symbol. */
+export const PLUGIN_COMPOSER_TRIGGERS = ["@", "#", "/"] as const;
+
+export type PluginComposerTrigger = (typeof PLUGIN_COMPOSER_TRIGGERS)[number];
+
+/** In-draft token cap: the 9th token onward collapses into a host `⧉ +N` chip. */
+export const PLUGIN_COMPOSER_TOKEN_LIMIT = 8;
+
+/** Message shape the host hands to message-anchored slots. */
+export type PluginSlotMessage = {
+ readonly id: string;
+ readonly role: "user" | "assistant" | "system" | "tool";
+ readonly content: string;
+ readonly createdAt?: string;
+};
+
+/**
+ * Props skeleton for the additive message slots (`slot-contract.html` §2):
+ * `message` + ids + `position`. No host functions, no extra data.
+ */
+export type PluginActionSlotProps = {
+ readonly message: PluginSlotMessage;
+ readonly messageId: string;
+ readonly sessionId: string;
+ readonly position: PluginSlotPosition;
+ /** Bound per plugin; the only outbound channel for slot components. */
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** Props for `entryExtra` — assistant messages only, no `position` field. */
+export type PluginEntryExtraSlotProps = {
+ readonly message: PluginSlotMessage & { readonly role: "assistant" };
+ readonly messageId: string;
+ readonly sessionId: string;
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** Props for `toolCard` — keyed to one of the plugin's own tools.
+ * Failure is data (`toolError`), never a throw. */
+export type PluginToolCardSlotProps = {
+ readonly toolName: string;
+ readonly toolCallId: string;
+ readonly toolArgs?: unknown;
+ readonly toolStatus: "running" | "success" | "error";
+ readonly toolResult?: unknown;
+ readonly toolError?: unknown;
+ readonly durationMs?: number;
+ readonly messageId: string;
+ readonly sessionId: string;
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** Props for `blockRenderer` — the raw fence content, once, on close. */
+export type PluginBlockRendererSlotProps = {
+ readonly language: string;
+ readonly source: string;
+};
+
+/** Props for the composer control slot — a rendering position, no data. */
+export type PluginComposerControlSlotProps = {
+ readonly position: PluginSlotPosition;
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** Filter text the user typed after a trigger symbol; plugin answers candidates. */
+export type PluginComposerTriggerProps = {
+ readonly query: string;
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** One selectable item a trigger plugin contributes. */
+export type PluginComposerTriggerItem = {
+ readonly label: string;
+ readonly detail?: string;
+ /** Data carried into the draft token when this item is picked. */
+ readonly value: unknown;
+};
+
+/** Token props — label for display, send data preserved into the submit payload. */
+export type PluginComposerTokenProps = {
+ readonly label: string;
+ readonly send: unknown;
+ readonly dispatch: PluginRendererDispatch;
+};
+
+/** Host → plugin, once per `plugin.call`. Plugin answers with a JSON value. */
+export type PluginRendererCall = {
+ readonly pluginId: string;
+ readonly method: string;
+ readonly args?: unknown;
+};
+
+/** Plugin → host, the only outbound channel for slot components. */
+export type PluginRendererDispatch = (
+ action: PluginRendererActionName,
+ payload?: unknown,
+) => Promise<unknown>;
+
+/**
+ * Actions a slot component may dispatch. Declared per plugin in
+ * `manifest.rendererActions`; an undeclared action is refused with
+ * `PLUGIN_ACTION_UNDECLARED`. The wider vocabulary in
+ * `slot-contract.html` §3 (entry.copy, message.mutate, …) lands with the
+ * rounds that consume it; the gate below is real from day one.
+ */
+export type PluginRendererActionName =
+ | "plugin.call"
+ | "composer.insertText"
+ | "composer.acceptTriggerItem";
+
+/** `plugin.call` payload — `pluginId` is host-injected, never plugin-supplied. */
+export type PluginCallPayload = {
+ readonly method: string;
+ readonly args?: unknown;
+};
+
+/** A registration handle; `remove()` unregisters (卸载摘注册). */
+export type PluginRendererRegistration = {
+ readonly slot: PluginRendererSlot;
+ remove(): void;
+};
+
+/** A style handle; `remove()` drops the injected sheet. */
+export type PluginRendererStyleHandle = {
+ remove(): void;
+};
+
+/**
+ * The `pi` object handed to a renderer entry's `onLoad`.
+ *
+ * `pi.functions` (the F layer: `measureHeight` / `deriveSummary`) is
+ * deliberately absent from this milestone — no finalized ui/ slot consumes
+ * it yet; the vocabulary stays reserved in `slot-contract.html` §3.
+ */
+export type PiRendererApi = {
+ readonly plugin: {
+ readonly id: string;
+ readonly version: string;
+ };
+ readonly slots: {
+ /**
+ * Register a slot component. Throws a coded error when the host refuses:
+ * `PLUGIN_SLOT_DUPLICATE` (keyed slot already taken),
+ * `PLUGIN_SLOT_INVALID_COMPONENT` (component not a function),
+ * `PLUGIN_SLOT_INVALID_KEY` (malformed key), or
+ * `PLUGIN_SLOT_UNKNOWN` (slot not in the vocabulary).
+ */
+ register<Props>(
+ slot: PluginRendererSlot,
+ component: (props: Props) => unknown,
+ options?: PluginRendererSlotOptions,
+ ): PluginRendererRegistration;
+ };
+ readonly ui: {
+ /** Inject a style sheet scoped under `.pi-plugin-slot.<pluginId>`. */
+ injectStyle(css: string): PluginRendererStyleHandle;
+ };
+};
+
+/** Renderer entry module shape — plain ES module, no build step required. */
+export type PiRendererModule = {
+ onLoad(pi: PiRendererApi): void | Promise<void>;
+ onUnload?(): void | Promise<void>;
+};
+
+/** Options accepted by `pi.slots.register` per slot. Keyed slots carry
+ * their key here (`language`, `toolName`, `trigger`); additive slots take
+ * optional position subsets. */
+export type PluginRendererSlotOptions = {
+ /**
+ * `userAction` / `assistantAction` / `composerControl` — which sides to
+ * occupy; omit for both.
+ */
+ readonly positions?: readonly PluginSlotPosition[];
+ /** `toolCard` — must match one of the plugin's own `contributes.agentTools[].name`. */
+ readonly toolName?: string;
+ /** `blockRenderer` — must be `<pluginId>:lang`. */
+ readonly language?: string;
+ /** `composerTrigger` — exactly one of `@` `#` `/`; one plugin per symbol. */
+ readonly trigger?: PluginComposerTrigger;
+};
+
+/** Diagnostic codes the slot subsystem reports (also surfaced as thrown errors). */
+export type PluginRendererSlotDiagnosticCode =
+ | "PLUGIN_SLOT_UNKNOWN"
+ | "PLUGIN_SLOT_DUPLICATE"
+ | "PLUGIN_SLOT_INVALID_COMPONENT"
+ | "PLUGIN_SLOT_INVALID_KEY"
+ | "PLUGIN_SLOT_INVALID_POSITION"
+ | "PLUGIN_SLOT_NOT_DECLARED"
+ | "PLUGIN_SLOT_RENDER_FAILED"
+ | "PLUGIN_SLOT_LOAD_FAILED"
+ | "PLUGIN_ACTION_UNDECLARED"
+ | "PLUGIN_ACTION_UNROUTED"
+ | "PLUGIN_ACTION_INVALID_PAYLOAD"
+ | "PLUGIN_CALL_NO_HANDLER"
+ | "PLUGIN_CALL_UNSERIALIZABLE"
+ | "PLUGIN_CALL_TIMEOUT"
+ | "PLUGIN_CALL_TOO_LARGE"
+ | "PLUGIN_CALL_RATE_LIMITED"
+ | "PLUGIN_CALL_DISABLED";
+
+/** A refusal the host reports for a renderer plugin, for the plugin row UI. */
+export type PluginRendererDiagnostic = {
+ readonly pluginId: string;
+ readonly code: PluginRendererSlotDiagnosticCode;
+ readonly detail?: string;
+};
+
+/**
+ * Guard used by keyed registration: `blockRenderer` keys must be
+ * `<pluginId>:lang`; `toolCard` keys are the tool name; `composerTrigger`
+ * keys are the single symbol. Returns an error message or `null`.
+ */
+export function slotKeyError(
+ slot: PluginRendererSlot,
+ pluginId: string,
+ options: PluginRendererSlotOptions | undefined,
+): string | null {
+ if (slot === "blockRenderer") {
+ const language = options?.language;
+ if (typeof language !== "string" || language.length === 0) {
+ return "blockRenderer requires options.language";
+ }
+ const prefix = `${pluginId}:`;
+ if (
+ language === prefix ||
+ !language.startsWith(prefix) ||
+ language.slice(prefix.length).trim().length === 0
+ ) {
+ return `blockRenderer language must be "<pluginId>:lang" (got ${JSON.stringify(language)})`;
+ }
+ const lang = language.slice(prefix.length);
+ if (!/^[A-Za-z0-9_-]+$/.test(lang)) {
+ return `blockRenderer language suffix must match [A-Za-z0-9_-]+ (got ${JSON.stringify(lang)})`;
+ }
+ return null;
+ }
+ if (slot === "toolCard") {
+ const toolName = options?.toolName;
+ if (typeof toolName !== "string" || toolName.trim().length === 0) {
+ return "toolCard requires options.toolName";
+ }
+ return null;
+ }
+ if (slot === "composerTrigger") {
+ const trigger = options?.trigger;
+ if (
+ typeof trigger !== "string" ||
+ !(PLUGIN_COMPOSER_TRIGGERS as readonly string[]).includes(trigger)
+ ) {
+ return `composerTrigger requires options.trigger to be one of ${PLUGIN_COMPOSER_TRIGGERS.join(" ")}`;
+ }
+ // 宿主先占: `@` drives file references and `/` drives slash commands;
+ // plugins claim only `#` this round (docs/plugin-plan/ui/composer/).
+ if (trigger !== "#") {
+ return `composerTrigger trigger "${trigger}" is host-owned; plugins claim "#"`;
+ }
+ return null;
+ }
+ return null;
+}
+
+/**
+ * The no-claim gate for `toolCard` (`docs/plugin-plan/ui/tool-card/`):
+ * a plugin may only register a card for a tool its own manifest declares
+ * in `contributes.agentTools`. Returns an error message or `null`.
+ *
+ * `declaredTools` comes from the plugin's `PluginSummary.tools` row; an
+ * absent row means the registry predates the renderer milestone, so the
+ * declaration is unprovable and the registration is refused.
+ */
+export function toolCardOwnershipError(
+ toolName: string,
+ declaredTools: readonly string[] | undefined,
+): string | null {
+ if (!declaredTools || declaredTools.length === 0) {
+ return `toolCard requires the manifest to declare contributes.agentTools (no tools found for this plugin)`;
+ }
+ if (!declaredTools.includes(toolName)) {
+ return `toolCard toolName ${JSON.stringify(toolName)} is not in the plugin's own contributes.agentTools`;
+ }
+ return null;
+}
+
+/**
+ * Position-subset validation for the additive slots (`userAction`,
+ * `assistantAction`, `composerControl`). Entries must come from the
+ * vocabulary; an empty array registers nothing and is refused.
+ */
+export function slotPositionsError(
+ slot: PluginRendererSlot,
+ options: PluginRendererSlotOptions | undefined,
+): string | null {
+ if (slot !== "userAction" && slot !== "assistantAction" && slot !== "composerControl") {
+ return null;
+ }
+ const raw = options?.positions;
+ if (raw === undefined) return null;
+ if (!Array.isArray(raw) || raw.length === 0) {
+ return `${slot} options.positions must be a non-empty array`;
+ }
+ for (const entry of raw) {
+ if (entry !== "left" && entry !== "right") {
+ return `${slot} options.positions entries must be "left" or "right"`;
+ }
+ }
+ return null;
+}
diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.ts
index a3f6d8917..264d1162e 100644
--- a/packages/shared/src/composer-trigger.ts
+++ b/packages/shared/src/composer-trigger.ts
@@ -163,6 +163,25 @@ 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> = {
+ "@": "@",
+ "#": "#",
+ "/": "/",
+};
+
+export function normalizeFullWidthTrigger(value: string): string {
+ let out = value;
+ for (const [wide, ascii] of Object.entries(FULLWIDTH_TRIGGERS)) {
+ out = out.replaceAll(wide, ascii);
+ }
+ return out;
+}
+
+/** Insertion text for an accepted plugin trigger item: `#label `. */
+export function formatPluginTriggerInsert(label: string): string {
+ return `#${label} `;
+}
/** Return a compact leaf label without changing the canonical reference path. */
export function fileReferenceLabel(path: string, preferredName?: string): string {
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index fd67a2c1e..a965eb721 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -229,6 +229,8 @@ export const IPC = {
providersOauthCancel: "pi-desktop/providers/oauth/cancel",
providersOauthDelete: "pi-desktop/providers/oauth/delete",
pluginList: "pi-desktop/plugin/list",
+ /** A renderer slot component asking its own plugin for one JSON answer. */
+ pluginRendererCall: "pi-desktop/plugin/rendererCall",
/** Plugin-contributed agent extensions (D387/D388, ADR 0214). */
pluginImportExtension: "pi-desktop/plugin/importExtension",
extensionsCommandRun: "pi-desktop/extensions/commands/run",
diff --git a/packages/shared/src/types/plugins.ts b/packages/shared/src/types/plugins.ts
index 1078fb4b7..2f205da0f 100644
--- a/packages/shared/src/types/plugins.ts
+++ b/packages/shared/src/types/plugins.ts
@@ -199,7 +199,9 @@ export type PluginCapability =
| "services"
| "bus"
/** `contributes.agentExtensions`: ExtensionAPI modules in the agent process. */
- | "agentExtension";
+ | "agentExtension"
+ /** `manifest.renderer`: the plugin ships a renderer slot entry (`docs/plugin-plan/ui/`). */
+ | "rendererUi";
export type PluginSettingType =
| "string"
@@ -282,9 +284,22 @@ 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
+ * plus the outbound action / `plugin.call` method whitelists the host
+ * enforces for its slot components.
+ */
+ renderer?: {
+ entry: string;
+ actions: string[];
+ callMethods: string[];
+ };
+ /** The plugin's own `contributes.agentTools` tool names (`tools` row from
+ * the host registry). The toolCard slot's no-claim gate reads this: a
+ * plugin card may only render calls of a tool this list names. Absent in
+ * registry rows written before the renderer milestone. */
+ tools?: string[];
description?: string;
author?: string;
installedAt?: string;