Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(plugins): reproduce the seven finalized UI demos in the example plugin
Tioit-Wang406ee5c8edac
diff --git a/apps/desktop/index.html b/apps/desktop/index.htmlindex 9267565ff..60d7fed57 100644--- a/apps/desktop/index.html+++ b/apps/desktop/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8" /><metahttp-equiv="Content-Security-Policy"- content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset: 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:;"+ content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:;"/><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>PI-Desktop</title>diff --git a/apps/desktop/test/plugin-self-dialog.test.mjs b/apps/desktop/test/plugin-self-dialog.test.mjsindex e73a0a75d..c419d5e6a 100644--- a/apps/desktop/test/plugin-self-dialog.test.mjs+++ b/apps/desktop/test/plugin-self-dialog.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";+ import { readdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import test from "node:test";@@ -10,10 +10,14 @@ 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",-);+ // The renderer is split into small modules; aggregate them so both the+ // positive assertions and the "no Esc wiring" negative scan cover all files.+ const rendererDir = join(root("examples/plugins/ui-slots-demo"), "renderer");+ const demoSource = readdirSync(rendererDir)+ .filter((name) => name.endsWith(".mjs"))+ .sort()+ .map((name) => readFileSync(join(rendererDir, name), "utf8"))+ .join("\n");test("self-dialog tool classes and the 600..899 / 900 z ladder exist", () => {// Tool classes from the finalized page.diff --git a/apps/desktop/test/plugin-ui-slots-demo.test.mjs b/apps/desktop/test/plugin-ui-slots-demo.test.mjsindex e4f08b9f7..b1560e0d8 100644--- a/apps/desktop/test/plugin-ui-slots-demo.test.mjs+++ b/apps/desktop/test/plugin-ui-slots-demo.test.mjs@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { execFileSync } from "node:child_process";-import { readFileSync } from "node:fs";+ import { readdirSync, readFileSync } from "node:fs";import { createRequire } from "node:module";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";@@ -12,7 +12,20 @@ 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");+ // The renderer is split into small ES modules; aggregate every file so+ // assertions cover the full registration + dispatch surface.+ const rendererDir = join(demoDir, "renderer");+ const rendererFiles = readdirSync(rendererDir)+ .filter((name) => name.endsWith(".mjs"))+ .sort();+ const rendererSource = rendererFiles+ .map((name) => readFileSync(join(rendererDir, name), "utf8"))+ .join("\n");+ const checkRendererSyntax = () => {+ for (const name of rendererFiles) {+ execFileSync(process.execPath, ["--check", join(rendererDir, name)]);+ }+ };const sdkSource = readFileSync(root("packages/plugin-sdk/src/renderer.ts"),"utf8",@@ -37,9 +50,17 @@ test("the demo manifest declares the full renderer action vocabulary", () => {assert.ok(manifest.renderer.endsWith("renderer/index.mjs"));});-test("the demo renderer stays valid ESM with every registration", () => {- execFileSync(process.execPath, ["--check", join(demoDir, "renderer/index.mjs")]);- assert.match(rendererSource, /import \{ createElement as h, useState \} from "react"/);+ test("the demo renderer stays valid ESM with every component on shared react", () => {+ checkRendererSyntax();+ // Every component module binds the host's single React through the+ // document import map.+ // document import map; index.mjs only wires siblings together.+ for (const name of rendererFiles) {+ // styles.mjs is CSS-only; index.mjs only wires siblings together.+ if (name === "index.mjs" || name === "styles.mjs") continue;+ const source = readFileSync(join(rendererDir, name), "utf8");+ assert.match(source, /from "react"/, `${name} must import react via the import map`);+ }});test("the page CSP lets the import map's blob shims load", () => {@@ -68,13 +89,13 @@ test("the headless entry answers the declared renderer method", async () => {});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")]);+ // Syntax gate: the host imports every renderer module as ESM.+ checkRendererSyntax();const registrations = [...rendererSource.matchAll(/pi\.slots\.register\(\s*"([^"]+)"/g)].map((match) => match[1],);- // 7 slots + the self-dialog sample riding in entryExtra.+ // 7 slots + three entryExtra registrations (runner, spark, self-dialog).assert.deepEqual(registrations,[@@ -86,7 +107,8 @@ test("the renderer entry registers every slot with valid keys", () => {"composerControl","composerTrigger","composerToken",- "entryExtra",+ "entryExtra",+ "entryExtra",],);diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjsindex b3a1a1de5..fb007f02e 100644--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@ -45,10 +45,12 @@ function loadComponent(name, extras = {}) {"../../../components/ui": { TooltipButton },"./shared": shared,"./menu-items": { userMessageMenuItems: () => [] },- "./TranscriptMenu": {- useTranscriptMenu: () => () => {},- useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),- },+ "./TranscriptMenu": {+ useTranscriptMenu: () => () => {},+ useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),+ },+ "./ActionBarSlots": { ActionBarSlots: ({ children }) => children },+ "../../../plugins/renderer-slots/use-slots": { useSlotEntries: () => [] },...extras,};const module = { exports: {} };diff --git a/examples/plugins/ui-slots-demo/renderer/actions.mjs b/examples/plugins/ui-slots-demo/renderer/actions.mjsnew file mode 100644index 000000000..dd4831225--- /dev/null+++ b/examples/plugins/ui-slots-demo/renderer/actions.mjs@@ -0,0 +1,42 @@+/**+ * Action-gutter demos (docs/plugin-plan/ui/user-action, /assistant-action,+ * demo.html scenario 2): the user card gets 标星 / 转工单, the assistant card+ * gets 一键复现 / 存为知识库. Both draw around the host keys; neither can+ * move, hide, or restyle them.+ */+import { createElement as h, useState } from "react";++export function UserActionButton({ position, dispatch }) {+ const [starred, setStarred] = useState(false);+ if (position === "left") {+ return h("button", {+ className: "slot-demo-plugin-btn",+ title: "demo.ui-slots · userAction left",+ onClick: () => setStarred((value) => !value),+ }, starred ? "★ 已标星" : "★ 标星");+ }+ return h("button", {+ className: "slot-demo-plugin-btn",+ title: "demo.ui-slots · userAction right",+ onClick: () => dispatch("composer.insertText", "请把这个对话整理成工单:"),+ }, "转工单");+}++export function AssistantActionButton({ position, dispatch }) {+ const [saved, setSaved] = useState(false);+ if (position === "left") {+ return h("button", {+ className: "slot-demo-plugin-btn",+ title: "demo.ui-slots · assistantAction left",+ onClick: () => dispatch("composer.insertText", "一键复现:"),+ }, "一键复现");+ }+ return h("button", {+ className: "slot-demo-plugin-btn",+ title: "demo.ui-slots · assistantAction right",+ onClick: () => {+ setSaved(true);+ dispatch("composer.insertText", "已存为知识库条目:");+ },+ }, saved ? "✓ 已存知识库" : "存为知识库");+}diff --git a/examples/plugins/ui-slots-demo/renderer/cards.mjs b/examples/plugins/ui-slots-demo/renderer/cards.mjsnew file mode 100644index 000000000..e4b5717e9--- /dev/null+++ b/examples/plugins/ui-slots-demo/renderer/cards.mjs@@ -0,0 +1,92 @@+/**+ * toolCard + blockRenderer demos (docs/plugin-plan/ui/tool-card and+ * /block-renderer, demo.html): the db-query card draws the plugin's own+ * tool only (no-claim), and the chart block takes over a whole code fence+ * for the pluginId:lang key, falling back to the raw source on parse errors.+ */+import { createElement as h } from "react";++const BAR_COLORS = ["#c27aff", "#a78bff", "#8f7dff", "#7b9bff", "#6cb2ff"];+const DEFAULT_SQL = "SELECT customer, COUNT(*) AS orders\nFROM orders WHERE created_at >= '2026-08-01'\nGROUP BY customer ORDER BY orders DESC LIMIT 5;";++export function StatsCard({ toolName, toolStatus, toolArgs, toolResult, toolError, durationMs }) {+ const head = h("div", { className: "slot-demo-title-row" },+ h("h4", null, "toolCard · " + toolName),+ h("span", { className: "slot-demo-own" }, "只画自己的工具"));+ if (toolStatus === "running") {+ return h("div", { className: "slot-demo-card" }, head, h("div", null, "running…"));+ }+ if (toolStatus === "error") {+ // 失败是数据,不是抛错。+ return h("div", { className: "slot-demo-card" }, head,+ h("div", { className: "slot-demo-error" },+ "failed: " + String(toolError?.message ?? toolError ?? "unknown error")));+ }+ const entries = toolResult && typeof toolResult === "object" ? Object.entries(toolResult) : [];+ return h("div", { className: "slot-demo-card" },+ head,+ h("div", { className: "slot-demo-sql" }, String(toolArgs?.sql ?? DEFAULT_SQL)),+ h("table", { className: "slot-demo-table" },+ h("thead", null, h("tr", null,+ h("th", null, "field"),+ h("th", { style: { textAlign: "right" } }, "value"))),+ h("tbody", null,+ (entries.length ? entries : [["demo", "no result yet"]]).map(([key, value]) =>+ h("tr", { key: String(key) },+ h("td", null, String(key)),+ h("td", { className: "num" }, String(value)))))),+ typeof durationMs === "number"+ ? h("div", { className: "slot-demo-legend" }, durationMs + "ms")+ : null);+}++export 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,+ }));+ if (!bars.length) throw new Error("empty data");+ } catch (cause) {+ error = cause;+ }+ const max = bars ? Math.max(...bars.map((bar) => bar.value), 1) : 1;+ return h("div", { className: "slot-demo-card" },+ h("div", { className: "slot-demo-title-row" },+ h("h4", null, "blockRenderer · " + language),+ h("span", { className: "slot-demo-own" }, "整块接管")),+ error+ ? h("div", null,+ h("div", { className: "slot-demo-error" }, "render failed: " + error.message),+ h("pre", { className: "slot-demo-sql" }, source))+ : h("div", null,+ h("svg", {+ viewBox: "0 0 420 140",+ style: { display: "block", width: "100%" },+ "aria-hidden": "true",+ },+ bars.map((bar, index) => {+ const height = Math.max(6, Math.round((bar.value / max) * 110));+ return h("rect", {+ key: bar.label,+ x: 30 + index * 80,+ y: 130 - height,+ width: 48,+ height,+ rx: 6,+ fill: BAR_COLORS[index % BAR_COLORS.length],+ });+ })),+ h("div", { className: "slot-demo-legend" },+ bars.map((bar, index) =>+ h("span", { key: bar.label },+ h("span", {+ className: "dot",+ style: { background: BAR_COLORS[index % BAR_COLORS.length] },+ }),+ bar.label + " " + bar.value)))));+}diff --git a/examples/plugins/ui-slots-demo/renderer/composer.mjs b/examples/plugins/ui-slots-demo/renderer/composer.mjsnew file mode 100644index 000000000..6519d4538--- /dev/null+++ b/examples/plugins/ui-slots-demo/renderer/composer.mjs@@ -0,0 +1,47 @@+/**+ * Composer slot demos (docs/plugin-plan/ui/composer/demo.html): the 知识库+ * left control and the 草稿统计 right counter, the self-drawn # trigger+ * candidate list whose picks flow back through composer.acceptTriggerItem,+ * and the composerToken face (the host owns the ✕ so fold records survive).+ */+import { createElement as h } from "react";++export function ComposerControl({ position, dispatch }) {+ if (position === "left") {+ return h("button", {+ className: "slot-demo-bar-btn",+ title: "demo.ui-slots · composerControl left",+ onClick: () => dispatch("composer.insertText", "从知识库选择:"),+ }, "知识库");+ }+ return h("span", {+ className: "slot-demo-bar-btn",+ title: "demo.ui-slots · composerControl right (demo counter)",+ }, "1,284");+}++export 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-trigger" },+ h("div", { className: "slot-demo-notice-msg" }, "#" + query),+ items.length+ ? items.map((item) =>+ h("button", {+ key: item.label,+ className: "slot-demo-bar-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", { className: "slot-demo-notice-msg" }, "no match"));+}++export function ComposerToken({ label }) {+ return h("span", { className: "slot-demo-token" },+ h("span", { className: "tok" }, "#"),+ label);+}diff --git a/examples/plugins/ui-slots-demo/renderer/extras.mjs b/examples/plugins/ui-slots-demo/renderer/extras.mjsnew file mode 100644index 000000000..5f98a3384--- /dev/null+++ b/examples/plugins/ui-slots-demo/renderer/extras.mjs@@ -0,0 +1,96 @@+/**+ * entryExtra demos (docs/plugin-plan/ui/entry-extra/demo.html): the runnable+ * panel and the metric sparkline stack additively under the reply. The+ * self-dialog launcher (docs/plugin-plan/ui/self-dialog/demo.html) rides in+ * this slot too — the modal and the corner notice draw inside this+ * component's own tree, disappear on unload, stay under the host safety+ * layer, and close only through explicit UI actions.+ */+import { createElement as h, useState } from "react";++export function RunnerPanel({ message, dispatch }) {+ const [result, setResult] = useState("no call yet");+ return h("div", { className: "slot-demo-card" },+ h("div", { className: "slot-demo-title-row" },+ h("h4", null, "plugin_demo_runner · 可运行面板"),+ h("span", { className: "slot-demo-own" }, "additive")),+ h("div", { className: "slot-demo-run-row" },+ h("code", null, "pnpm test -- filter retry"),+ h("button", {+ className: "slot-demo-btn",+ onClick: () =>+ dispatch("plugin.call", { method: "stats.summary", args: { scale: 1 } })+ .then((answer) => setResult("ok total=" + answer.total + " average=" + answer.average))+ .catch((error) => setResult((error.code ?? "ERROR") + ": " + error.message)),+ }, "运行")),+ h("div", { className: "slot-demo-rows" }, result));+}++export function SparkPanel() {+ const points = "0,40 40,36 80,28 120,30 160,18 200,22 240,10 280,14";+ return h("div", { className: "slot-demo-card" },+ h("div", { className: "slot-demo-title-row" },+ h("h4", null, "plugin_demo_spark · 指标缩略图"),+ h("span", { className: "slot-demo-own" }, "additive")),+ h("svg", {+ className: "slot-demo-spark",+ viewBox: "0 0 280 54",+ preserveAspectRatio: "none",+ "aria-hidden": "true",+ },+ h("polyline", { fill: "none", stroke: "#c27aff", "stroke-width": "2", points }),+ h("polyline", {+ fill: "rgb(194 122 255 / 0.18)",+ stroke: "none",+ points: points + " 280,54 0,54",+ })));+}++export function SelfDialogLauncher() {+ const [open, setOpen] = useState(false);+ const [notice, setNotice] = useState(false);+ return h("div", { className: "slot-demo-card" },+ h("div", { className: "slot-demo-title-row" },+ h("h4", null, "self-dialog · 自理弹层"),+ h("span", { className: "slot-demo-own" }, "no slot")),+ h("div", { className: "slot-demo-run-row" },+ h("button", { className: "slot-demo-btn", onClick: () => setOpen(true) }, "翻译助手弹窗"),+ h("button", { className: "slot-demo-btn", onClick: () => setNotice(true) }, "翻译队列浮层")),+ // 模态: p-overlay + p-dialog, z 600..899, Esc 不关安全层, 关闭只走明确动作;+ // 宿主安全层 (z 900) always wins — 插件层之间不做仲裁, 后注册者自然叠在上。+ open+ ? h("div", { className: "p-overlay" },+ h("div", { className: "p-dialog", role: "dialog", "aria-label": "翻译助手" },+ h("div", { className: "p-dialog-head" },+ h("span", null, "翻译助手"),+ h("button", {+ className: "p-notice__dismiss",+ "aria-label": "关闭",+ onClick: () => setOpen(false),+ }, "✕")),+ h("div", { className: "p-dialog__body" },+ h("div", { className: "slot-demo-term-row" },+ h("span", null, "术语表"),+ h("span", { className: "slot-demo-term" }, "发版 → release"),+ h("span", { className: "slot-demo-term" }, "插槽 → slot")),+ h("div", { className: "slot-demo-translation" },+ "译文中…: The plugin slot boundary for the composer was agreed this week…")),+ h("div", { className: "p-dialog__foot" },+ h("button", { className: "slot-demo-btn", onClick: () => setOpen(false) }, "暂停"),+ h("button", { className: "slot-demo-btn", onClick: () => setOpen(false) }, "应用到原文"))))+ : null,+ // 角落浮层: p-overlay__corner 非阻塞, p-notice, ✕ 收起。+ notice+ ? h("div", { className: "p-overlay p-overlay__corner" },+ h("div", { className: "p-notice" },+ h("span", { className: "p-notice-icon", "aria-hidden": "true" }, "✚"),+ h("span", { className: "slot-demo-notice-body" },+ h("span", { className: "slot-demo-notice-title" }, "翻译队列"),+ h("span", { className: "slot-demo-notice-msg" }, "进行中 2 / 5 · 已交付 14")),+ h("button", {+ className: "p-notice__dismiss",+ "aria-label": "收起",+ onClick: () => setNotice(false),+ }, "✕")))+ : null);+}diff --git a/examples/plugins/ui-slots-demo/renderer/index.mjs b/examples/plugins/ui-slots-demo/renderer/index.mjsindex 6ac667873..6d2580be6 100644--- a/examples/plugins/ui-slots-demo/renderer/index.mjs+++ b/examples/plugins/ui-slots-demo/renderer/index.mjs@@ -1,258 +1,39 @@/**- * UI Slots Demo — renderer entry (`demo.ui-slots`).+ * 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.+ * Reproduces every finalized demo in docs/plugin-plan/ui/ as a real running+ * plugin. Plain ES module, no build step: the "react" specifier resolves to+ * the host's single React through the document import map.*/-import { createElement as h, useState } from "react";+import { applyDemoStyles } from "./styles.mjs";+import { UserActionButton, AssistantActionButton } from "./actions.mjs";+import { RunnerPanel, SparkPanel, SelfDialogLauncher } from "./extras.mjs";+import { StatsCard, ChartBlock } from "./cards.mjs";+import { ComposerControl, ComposerTrigger, ComposerToken } from "./composer.mjs";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;+ applyDemoStyles(pi);- 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.+ // entryExtra 的三块叠加演示 additive(按注册顺序堆放)。+ pi.slots.register("entryExtra", RunnerPanel);+ pi.slots.register("userAction", UserActionButton);+ pi.slots.register("assistantAction", AssistantActionButton);+ // toolCard no-claim: 只画 manifest 里自己声明的工具。pi.slots.register("toolCard", StatsCard, { toolName: TOOL_NAME });pi.slots.register("blockRenderer", ChartBlock, { language: CHART_LANGUAGE });- pi.slots.register("composerControl", ComposerControl, { positions: ["left"] });+ // composerControl 双侧一个组件,按 position 分形态。+ pi.slots.register("composerControl", ComposerControl);pi.slots.register("composerTrigger", ComposerTrigger, { trigger: "#" });pi.slots.register("composerToken", ComposerToken);-- // The self-dialog sample rides inside the entryExtra card.+ pi.slots.register("entryExtra", SparkPanel);+ // self-dialog 无槽无注册:弹层画在组件自己的树里(卸载即消失)。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.+ // Registrations and injected styles are torn down by the host (卸载摘注册);+ // the self-dialog layers disappear with this module's components.}diff --git a/examples/plugins/ui-slots-demo/renderer/styles.mjs b/examples/plugins/ui-slots-demo/renderer/styles.mjsnew file mode 100644index 000000000..bfb57e66e--- /dev/null+++ b/examples/plugins/ui-slots-demo/renderer/styles.mjs@@ -0,0 +1,206 @@+/**+ * Demo styles for the ui-slots example plugin. Injected once at load and+ * torn down by the host on unload. Scoped under this plugin's slot chrome.+ */+export function applyDemoStyles(pi) {+ const cssId = pi.plugin.id.replace(/[^A-Za-z0-9_-]/g, "-");+ const scope = `.pi-plugin-slot.${cssId}`;+ pi.ui.injectStyle(`+${scope} .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;+}+${scope} .slot-demo-card h4 {+ margin: 0 0 6px;+ font-size: 11px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ opacity: 0.75;+}+${scope} .slot-demo-title-row {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0 0 6px;+}+${scope} .slot-demo-title-row h4 {+ margin: 0;+}+${scope} .slot-demo-own {+ padding: 0 7px;+ border-radius: 99px;+ background: rgb(64 201 119 / 0.14);+ color: #40c977;+ font-size: 10px;+ letter-spacing: 0.04em;+}+${scope} .slot-demo-btn {+ 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;+}+${scope} .slot-demo-btn:hover {+ background: rgb(255 255 255 / 0.08);+}+${scope} .slot-demo-plugin-btn {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 3px 9px;+ border: 0;+ border-radius: 99px;+ font: inherit;+ font-size: 11.5px;+ color: var(--ds-accent, #c27aff);+ background: color-mix(in oklab, var(--ds-accent, #c27aff) 12%, transparent);+ cursor: pointer;+}+${scope} .slot-demo-plugin-btn:hover {+ background: color-mix(in oklab, var(--ds-accent, #c27aff) 20%, transparent);+}+${scope} .slot-demo-bar-btn {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px 9px;+ border: 1px solid rgb(255 255 255 / 0.14);+ border-radius: 99px;+ background: transparent;+ color: var(--ds-text-secondary, #b0b0b0);+ font: inherit;+ font-size: 11.5px;+ cursor: pointer;+}+${scope} .slot-demo-bar-btn:hover {+ background: rgb(255 255 255 / 0.06);+}+${scope} .slot-demo-run-row {+ display: flex;+ align-items: center;+ gap: 8px;+}+${scope} .slot-demo-run-row code {+ flex: 1;+ font-family: ui-monospace, Consolas, monospace;+ font-size: 11.5px;+}+${scope} .slot-demo-rows {+ display: grid;+ gap: 2px;+ margin-top: 6px;+ font-family: ui-monospace, Consolas, monospace;+ font-size: 11.5px;+ white-space: pre-wrap;+}+${scope} .slot-demo-spark {+ display: block;+ width: 100%;+ height: 54px;+}+${scope} .slot-demo-sql {+ padding: 8px 10px;+ border-radius: 6px;+ background: rgb(0 0 0 / 0.28);+ font-family: ui-monospace, Consolas, monospace;+ font-size: 11.5px;+ white-space: pre-wrap;+}+${scope} .slot-demo-error {+ color: #ff6764;+}+${scope} .slot-demo-table {+ width: 100%;+ margin-top: 8px;+ border-collapse: collapse;+ font-size: 11.5px;+}+${scope} .slot-demo-table th {+ padding: 3px 8px;+ border-bottom: 1px solid rgb(255 255 255 / 0.1);+ color: var(--ds-text-muted, #7d7d7d);+ font-weight: 500;+ text-align: left;+}+${scope} .slot-demo-table td {+ padding: 3px 8px;+ border-bottom: 1px solid rgb(255 255 255 / 0.05);+}+${scope} .slot-demo-table .num {+ text-align: right;+ font-family: ui-monospace, Consolas, monospace;+}+${scope} .slot-demo-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ margin-top: 6px;+ font-size: 11px;+ color: var(--ds-text-secondary, #b0b0b0);+}+${scope} .slot-demo-legend .dot {+ display: inline-block;+ width: 8px;+ height: 8px;+ margin-right: 4px;+ border-radius: 50%;+}+${scope} .slot-demo-term-row {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-bottom: 10px;+}+${scope} .slot-demo-term {+ padding: 2px 7px;+ border-radius: 6px;+ background: rgb(255 255 255 / 0.07);+ font-family: ui-monospace, Consolas, monospace;+ font-size: 11.5px;+}+${scope} .slot-demo-translation {+ padding: 9px 11px;+ border-radius: 8px;+ background: rgb(255 255 255 / 0.05);+ font-size: 12px;+ line-height: 1.55;+}+${scope} .slot-demo-notice-body {+ flex: 1;+ display: grid;+ gap: 1px;+ text-align: left;+}+${scope} .slot-demo-notice-title {+ font-size: 12.5px;+ font-weight: 600;+}+${scope} .slot-demo-notice-msg {+ font-size: 11.5px;+ color: var(--ds-text-secondary, #b0b0b0);+}+${scope} .slot-demo-trigger {+ display: grid;+ gap: 4px;+}+${scope} .slot-demo-token {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}+${scope} .slot-demo-token .tok {+ color: var(--ds-accent, #c27aff);+ font-weight: 600;+}+`);+}