Skip to content

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

feat(plugins): harden renderer slots and add the UI Slots Lab

vastsa674513d7d308
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index e156cc761..6460cacf7 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -190,10 +190,10 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
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),
+ // Serve renderer entry modules the same way — the current load of a
+ // plugin that declared `manifest.renderer` and holds `renderer.extension`.
+ installPluginRendererProtocol((pluginId, generation, requestPath) =>
+ plugins.resolveRendererSource(pluginId, generation, requestPath),
);
// Load the close-behavior preference before the first window exists: the
// close handler reads `closeBehavior` synchronously, and a window created
diff --git a/apps/desktop/electron/main/ipc/plugin-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ipc.ts
index 353b577e1..40e58d01e 100644
--- a/apps/desktop/electron/main/ipc/plugin-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ipc.ts
@@ -12,6 +12,7 @@ import {
type PluginRuntime,
} from "../plugin-runtime";
import { PluginViewHost } from "../plugin-view-host";
+import { rendererCallError } from "../plugin-renderer-extension";
import type { IpcRegistrar } from "./types";
export type PluginIpcDependencies = {
@@ -125,24 +126,34 @@ export function registerPluginIpc({
const withExtension = extensionIds.length
? { ...plugin, agentExtension: agentExtensions.statusForPlugin(extensionIds) }
: plugin;
- if (!plugin?.settings?.length || !plugins.getLoaded(plugin.id)) return withExtension;
+ // The renderer host loads from the live load, never from the registry
+ // row: a plugin that is not running has nothing to load.
+ const renderer = plugin?.id ? plugins.rendererDescriptor(plugin.id) : undefined;
+ const withRenderer = renderer ? { ...withExtension, renderer } : withExtension;
+ if (!plugin?.settings?.length || !plugins.getLoaded(plugin.id)) return withRenderer;
try {
const settings = await plugins.getPluginSettings(plugin.id);
- return { ...withExtension, settings };
+ return { ...withRenderer, settings };
} catch {
- return withExtension;
+ return withRenderer;
}
}),
);
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);
- });
+ // Renderer extensions run in the main window only (`PluginRendererHost`),
+ // so no other window may relay into a plugin's headless entry.
+ registrar.handleWithEvent(
+ IPC.invoke.pluginRendererCall,
+ async (event, pluginId: unknown, method: unknown, args: unknown) => {
+ registrar.assertMainWindowSender(event);
+ if (typeof pluginId !== "string" || !pluginId || typeof method !== "string" || !method) {
+ throw rendererCallError("INVALID_ARGUMENT", "pluginId and method are required");
+ }
+ return plugins.callRenderer(pluginId, method, args);
+ },
+ );
handle(IPC.invoke.pluginSettingsGet, async (id: string) => {
const settings = await plugins.getPluginSettings(String(id ?? ""));
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 0ea635860..717c4e70b 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -585,7 +585,22 @@ async function handleParentCall(method, payload, invocationId) {
error.code = "PLUGIN_CALL_NO_HANDLER";
throw error;
}
- return handler(String(payload?.method ?? ""), payload?.args ?? {});
+ const answer = await handler(String(payload?.method ?? ""), payload?.args ?? {});
+ // The relay answers JSON only. A cycle, a BigInt or a bare function is
+ // the plugin's bug and is reported as one, instead of surfacing as a
+ // structured-clone failure without a code.
+ let text;
+ try {
+ text = JSON.stringify(answer ?? null);
+ } catch {
+ text = undefined;
+ }
+ if (text === undefined) {
+ const error = new Error("onRendererCall answer is not JSON");
+ error.code = "PLUGIN_CALL_UNSERIALIZABLE";
+ throw error;
+ }
+ return JSON.parse(text);
}
case "lifecycle.unload": {
for (const id of invocations.keys()) cancelInvocation(id, "Plugin unloaded");
diff --git a/apps/desktop/electron/main/plugin-renderer-extension.ts b/apps/desktop/electron/main/plugin-renderer-extension.ts
new file mode 100644
index 000000000..a59e291dd
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-renderer-extension.ts
@@ -0,0 +1,262 @@
+/**
+ * The main-process half of a plugin's renderer extension
+ * (`docs/plugin-plan/ui/`, `docs/plugin-plan/render/plugin-call/`).
+ *
+ * `PluginRuntime` owns which plugins are loaded; this module owns what a
+ * loaded plugin's renderer extension may reach, so the runtime only delegates:
+ *
+ * - the descriptor the renderer host loads from, stamped with a per-load
+ * generation so a reload evaluates fresh modules;
+ * - the `plugin-renderer://` source resolver: current generation only, real
+ * paths inside the package only, regular files only;
+ * - the `plugin.call` relay: method whitelist, UTF-8 size ceiling, QPS brake,
+ * 2s timeout and a failure breaker, answering the renderer only in coded
+ * errors.
+ */
+import { realpathSync, statSync } from "node:fs";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import type { PluginManifest } from "@pi-desktop/plugin-sdk";
+import type { PluginRendererDescriptor } from "@pi-desktop/shared";
+
+export const RENDERER_EXTENSION_PERMISSION = "renderer.extension";
+
+/** `plugin.call` relay limits (`docs/plugin-plan/render/plugin-call/`). */
+export const RENDERER_CALL_QPS = 10;
+/** Args and answer together, counted in UTF-8 bytes of their JSON text. */
+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;
+
+/** What of a loaded plugin the renderer extension reads. */
+export type RendererExtensionPlugin = {
+ readonly manifest: PluginManifest;
+ readonly path: string;
+ readonly permissions: ReadonlySet<string>;
+ readonly disposing: boolean;
+};
+
+/**
+ * A refusal the renderer can branch on. `errorCode` is what the IPC layer
+ * forwards as the result's code; `code` keeps main-side callers uniform with
+ * the runtime's other API errors.
+ */
+export type RendererCallError = Error & { code: string; errorCode: string };
+
+export function rendererCallError(code: string, message: string): RendererCallError {
+ const error = new Error(message) as RendererCallError;
+ error.code = code;
+ error.errorCode = code;
+ return error;
+}
+
+function servesRenderer(plugin: RendererExtensionPlugin | undefined): plugin is RendererExtensionPlugin {
+ return Boolean(
+ plugin &&
+ !plugin.disposing &&
+ plugin.permissions.has(RENDERER_EXTENSION_PERMISSION) &&
+ plugin.manifest.renderer,
+ );
+}
+
+/**
+ * Load generations, keyed by the runtime's per-load record: a reload builds a
+ * new record, so it can never inherit the previous load's generation, and an
+ * unloaded record takes its entry with it.
+ */
+let generationCounter = 0;
+const generations = new WeakMap<object, number>();
+
+export function rendererGeneration(plugin: object): number {
+ let generation = generations.get(plugin);
+ if (generation === undefined) {
+ generation = ++generationCounter;
+ generations.set(plugin, generation);
+ }
+ return generation;
+}
+
+/** The renderer host's view of a loaded plugin, or nothing to load. */
+export function rendererDescriptorFor(
+ plugin: RendererExtensionPlugin | undefined,
+): PluginRendererDescriptor | undefined {
+ if (!servesRenderer(plugin)) return undefined;
+ const { manifest } = plugin;
+ return {
+ entry: manifest.renderer as string,
+ generation: rendererGeneration(plugin),
+ actions: [...(manifest.rendererActions ?? [])],
+ callMethods: [...(manifest.rendererCallMethods ?? [])],
+ tools: (manifest.contributes?.agentTools ?? []).map((tool) => tool.name),
+ };
+}
+
+/**
+ * The file behind `plugin-renderer://<id>/g<generation>/<requestPath>`, or
+ * null. The generation must be the one the current load handed out, so a
+ * module URL from before a reload stops resolving; containment is checked on
+ * real paths, so a symlink inside the package cannot point out of it.
+ */
+export function resolveRendererSourcePath(
+ plugin: RendererExtensionPlugin | undefined,
+ generation: number,
+ requestPath: string,
+): string | null {
+ if (!servesRenderer(plugin)) return null;
+ // Peek, never assign: only a descriptor hands a generation out.
+ if (generations.get(plugin) !== generation) return null;
+ try {
+ const base = realpathSync(resolve(plugin.path));
+ const target = realpathSync(resolve(base, requestPath));
+ const inside = relative(base, target);
+ if (!inside || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
+ return null;
+ }
+ return statSync(target).isFile() ? target : null;
+ } catch {
+ return null;
+ }
+}
+
+export type RendererCallPayload = { method: string; args: unknown };
+
+/** Relays one call into the plugin's host process. */
+export type RendererCallSend<T> = (
+ plugin: T,
+ payload: RendererCallPayload,
+ timeoutMs: number,
+) => Promise<unknown>;
+
+type RelayState = {
+ /** Relayed call timestamps inside the current 1s window. */
+ calls: number[];
+ /** Consecutive relayed failures. */
+ failures: number;
+ disabledUntil: number;
+};
+
+/** JSON text of a value, or undefined when it has none (function, cycle, BigInt). */
+function jsonText(value: unknown): string | undefined {
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return undefined;
+ }
+}
+
+function errorCodeOf(error: unknown): string | undefined {
+ const code = (error as { code?: unknown } | null)?.code;
+ return typeof code === "string" && code ? code : undefined;
+}
+
+/**
+ * The `plugin.call` relay. Refusals before the relay (not loaded, undeclared
+ * method, cooling down, over the rate, unserializable or oversize args) are
+ * the caller's problem and never count against the plugin. Everything after
+ * the relay (timeout, a thrown error, a missing `onRendererCall`, an answer
+ * that is not JSON or too large) is the plugin's, and five in a row close the
+ * relay for 30s; one success reopens the count.
+ */
+export class RendererCallRelay {
+ private readonly states = new WeakMap<object, RelayState>();
+ private readonly now: () => number;
+
+ constructor(now: () => number = Date.now) {
+ this.now = now;
+ }
+
+ async call<T extends RendererExtensionPlugin>(
+ pluginId: string,
+ plugin: T | undefined,
+ method: string,
+ args: unknown,
+ send: RendererCallSend<T>,
+ ): Promise<unknown> {
+ if (!plugin || plugin.disposing) {
+ throw rendererCallError("PLUGIN_NOT_FOUND", `renderer plugin not loaded: ${pluginId}`);
+ }
+ if (!plugin.permissions.has(RENDERER_EXTENSION_PERMISSION)) {
+ throw rendererCallError("PLUGIN_PERMISSION_DENIED", `${RENDERER_EXTENSION_PERMISSION} is not granted`);
+ }
+ if (!plugin.manifest.renderer || !plugin.manifest.rendererCallMethods?.includes(method)) {
+ throw rendererCallError("PLUGIN_CALL_NO_HANDLER", `method not declared: ${method}`);
+ }
+ const state = this.stateFor(plugin);
+ const startedAt = this.now();
+ if (startedAt < state.disabledUntil) {
+ throw rendererCallError(
+ "PLUGIN_CALL_DISABLED",
+ "plugin.call is cooling down after repeated failures",
+ );
+ }
+ state.calls = state.calls.filter((at) => startedAt - at < 1_000);
+ if (state.calls.length >= RENDERER_CALL_QPS) {
+ throw rendererCallError(
+ "PLUGIN_CALL_RATE_LIMITED",
+ `plugin.call exceeds ${RENDERER_CALL_QPS} calls/s`,
+ );
+ }
+ // Omitted args relay as omitted; anything else must be JSON, and the
+ // plugin receives the JSON reading of it rather than the raw value.
+ const argsText = args === undefined ? undefined : jsonText(args);
+ if (args !== undefined && argsText === undefined) {
+ throw rendererCallError("PLUGIN_CALL_UNSERIALIZABLE", "plugin.call args must be JSON");
+ }
+ const argsBytes = argsText === undefined ? 0 : Buffer.byteLength(argsText, "utf8");
+ if (argsBytes > RENDERER_CALL_MAX_BYTES) {
+ throw rendererCallError("PLUGIN_CALL_TOO_LARGE", "plugin.call args exceed 64KB");
+ }
+ state.calls.push(startedAt);
+
+ let answer: unknown;
+ try {
+ answer = await send(
+ plugin,
+ { method, args: argsText === undefined ? undefined : JSON.parse(argsText) },
+ RENDERER_CALL_TIMEOUT_MS,
+ );
+ } catch (error) {
+ this.recordFailure(state);
+ const code = errorCodeOf(error);
+ if (code === "TIMEOUT") {
+ throw rendererCallError(
+ "PLUGIN_CALL_TIMEOUT",
+ `plugin ${pluginId} did not answer ${method} within ${RENDERER_CALL_TIMEOUT_MS}ms`,
+ );
+ }
+ // The plugin's own code passes through so its component can branch on
+ // it; an uncoded failure still reaches the renderer as a coded one.
+ throw rendererCallError(
+ code ?? "PLUGIN_CALL_FAILED",
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ const answerText = jsonText(answer ?? null);
+ if (answerText === undefined) {
+ this.recordFailure(state);
+ throw rendererCallError("PLUGIN_CALL_UNSERIALIZABLE", "plugin.call answer must be JSON");
+ }
+ if (argsBytes + Buffer.byteLength(answerText, "utf8") > RENDERER_CALL_MAX_BYTES) {
+ this.recordFailure(state);
+ throw rendererCallError("PLUGIN_CALL_TOO_LARGE", "plugin.call args and answer exceed 64KB");
+ }
+ state.failures = 0;
+ return JSON.parse(answerText) as unknown;
+ }
+
+ private stateFor(plugin: object): RelayState {
+ let state = this.states.get(plugin);
+ if (!state) {
+ state = { calls: [], failures: 0, disabledUntil: 0 };
+ this.states.set(plugin, state);
+ }
+ return state;
+ }
+
+ private recordFailure(state: RelayState): void {
+ state.failures += 1;
+ if (state.failures < RENDERER_CALL_BREAKER_THRESHOLD) return;
+ state.failures = 0;
+ state.disabledUntil = this.now() + RENDERER_CALL_BREAKER_COOLDOWN_MS;
+ }
+}
diff --git a/apps/desktop/electron/main/plugin-renderer-protocol.ts b/apps/desktop/electron/main/plugin-renderer-protocol.ts
index df14f8179..5daa183b8 100644
--- a/apps/desktop/electron/main/plugin-renderer-protocol.ts
+++ b/apps/desktop/electron/main/plugin-renderer-protocol.ts
@@ -13,15 +13,36 @@ import { PLUGIN_RENDERER_SCHEME } from "@pi-desktop/plugin-sdk";
* theme assets — so a path that escapes the package, or a plugin that never
* declared the entry, has no URL to begin with.
*
+ * URLs are `plugin-renderer://<id>/g<generation>/<path>`. The generation is
+ * the plugin's current load (`PluginRendererDescriptor.generation`): a reload
+ * hands out a new one, so the renderer's ES module cache cannot serve the
+ * previous load's code, and a URL from an old load no longer resolves.
+ * Relative imports inside the module graph keep the prefix automatically.
+ *
* 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,
+ generation: number,
requestPath: string,
) => string | null;
+const GENERATION_SEGMENT = /^g([1-9][0-9]{0,14})\/(.+)$/;
+
+/**
+ * Split a decoded URL path into its load generation and the package-relative
+ * request path, or null when the path does not start with a generation.
+ */
+export function parseRendererRequestPath(
+ pathname: string,
+): { generation: number; requestPath: string } | null {
+ const match = GENERATION_SEGMENT.exec(pathname.replace(/^\/+/, ""));
+ if (!match) return null;
+ return { generation: Number(match[1]), requestPath: match[2] };
+}
+
/**
* 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
@@ -81,16 +102,17 @@ export function installPluginRendererProtocol(resolve: PluginRendererSourceResol
// 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;
+ let pathname: string;
try {
- requestPath = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
+ pathname = decodeURIComponent(url.pathname);
} catch {
return notFound();
}
- if (!pluginId || !requestPath) return notFound();
- const mime = mimeTypeFor(requestPath);
+ const parsed = parseRendererRequestPath(pathname);
+ if (!pluginId || !parsed) return notFound();
+ const mime = mimeTypeFor(parsed.requestPath);
if (!mime) return notFound();
- const absolute = resolve(pluginId, requestPath);
+ const absolute = resolve(pluginId, parsed.generation, parsed.requestPath);
if (!absolute) return notFound();
let body: Buffer;
try {
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index dda31526b..0379931c1 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -67,6 +67,7 @@ import {
isAllowedKeybinding,
isReservedKeybinding,
normalizeKeybinding,
+ type PluginRendererDescriptor,
type PluginServiceStatus,
type PluginSettingDefinition,
type PluginWorkspaceInfo,
@@ -89,6 +90,11 @@ import { desktopDataDir } from "./data-paths";
import { McpServerClient, type McpServerClientOptions } from "./plugin-mcp";
import { PluginToolInvocations, type PluginToolInvocation } from "./plugin-tool-invocations";
import { McpCallRegistry } from "./mcp-call-registry";
+import {
+ RendererCallRelay,
+ rendererDescriptorFor,
+ resolveRendererSourcePath,
+} from "./plugin-renderer-extension";
import { DevPluginWatcher, type DevPluginWatcherDeps } from "./plugin-watcher";
import { parseAllowedExternalUrl } from "./safe-open-external";
import type { PluginAppearance } from "../shared/plugin-panel-chrome";
@@ -1270,24 +1276,6 @@ 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>();
@@ -1314,6 +1302,7 @@ export class PluginRuntime {
private busSubscriptions = new Map<string, BusSubscription>();
private busRate = new Map<string, { windowStart: number; count: number }>();
private readonly toolInvocations = new PluginToolInvocations();
+ private readonly rendererCalls = new RendererCallRelay();
private completeRate = new Map<string, { windowStart: number; count: number }>();
/**
* File accesses the user allowed for the rest of the run, keyed
@@ -1555,91 +1544,33 @@ export class PluginRuntime {
}
/**
- * Source resolver behind the `plugin-renderer://` scheme: a loaded,
- * permission-granted plugin may serve module files from inside its own
+ * Source resolver behind the `plugin-renderer://` scheme: the current load
+ * of a permission-granted plugin serves 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;
+ resolveRendererSource(pluginId: string, generation: number, requestPath: string): string | null {
+ return resolveRendererSourcePath(this.loaded.get(pluginId), generation, requestPath);
+ }
+
+ /** What the renderer host loads for this plugin, while it may load anything. */
+ rendererDescriptor(pluginId: string): PluginRendererDescriptor | undefined {
+ return rendererDescriptorFor(this.loaded.get(pluginId));
}
/**
* 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.
+ * for one JSON answer (`docs/plugin-plan/render/plugin-call/`).
*/
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;
- }
+ return this.rendererCalls.call(
+ pluginId,
+ loaded?.child ? loaded : undefined,
+ method,
+ args,
+ (plugin, payload, timeoutMs) =>
+ this.sendToChild(plugin, { t: "call", method: "renderer.call", payload }, timeoutMs),
+ );
}
getLoaded(pluginId: string): LoadedPlugin | undefined {
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 0b6464fc6..82edf676f 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -1,6 +1,4 @@
import {
- ComponentType,
- createElement,
useEffect,
useLayoutEffect,
useMemo,
@@ -66,17 +64,7 @@ import { VoiceOverlay } from "../features/voice/VoiceOverlay";
import "../styles/voice.css";
import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";
import { ComposerStatus } from "../features/chat/composer/ComposerStatus";
-import { formatPluginTriggerInsert } from "@pi-desktop/shared";
-import { serializePluginTokens as serializePluginTokensForSend } from "../features/chat/composer/plugin-trigger";
import { registerComposerInsert } from "../features/chat/composer/insert-bridge";
-import {
- useComposerPluginTrigger,
- useComposerPluginTokens,
- useComposerTriggerAcceptBridge,
-} from "../features/chat/composer/use-plugin-composer-slots";
-import { ComposerTokenChip } from "../features/chat/composer/ComposerTokenChip";
-import { SlotBoundary } from "../plugins/renderer-slots/use-slots";
-import { dispatchFor } from "../plugins/renderer-host/dispatch";
const EMPTY_QUEUED_PROMPTS: QueuedPrompt[] = [];
@@ -494,40 +482,6 @@ 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();
- 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;
@@ -654,46 +608,6 @@ 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">
- {createElement(
- activeTrigger.entry.component as ComponentType<Record<string, unknown>>,
- {
- query: activeTrigger.query,
- dispatch: dispatchFor(activeTrigger.entry.pluginId),
- },
- )}
- </SlotBoundary>
- </div>
- ) : null}
- {pluginTokens.tokens.length ? (
- <div className="pi-plugin-token-chips" role="list">
- {pluginTokens.tokens
- .slice(0, 8)
- .map((token) => (
- <ComposerTokenChip
- key={`${token.pluginId}:${token.label}`}
- token={token}
- onRemove={pluginTokens.removeToken}
- />
- ))}
- {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 46488f718..6ae986fa3 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -139,7 +139,7 @@ function getThemeSnapshot(): ThemeMode {
}
function useThemeMode(): ThemeMode {
- return useSyncExternalStore(subscribeTheme, getThemeSnapshot);
+ return useSyncExternalStore(subscribeTheme, getThemeSnapshot, getThemeSnapshot);
}
/* ---------- syntax highlighting ---------- */
@@ -174,7 +174,11 @@ function useHighlightedTokens(
): ThemedToken[][] | null {
const resolved = resolveLang(lang);
const mode = useThemeMode();
- const version = useSyncExternalStore(subscribeHighlighter, getHighlightVersion);
+ const version = useSyncExternalStore(
+ subscribeHighlighter,
+ getHighlightVersion,
+ getHighlightVersion,
+ );
useEffect(() => {
if (resolved) ensureLang(resolved);
}, [resolved]);
@@ -474,9 +478,11 @@ function PreBlock({
if (blockEntry) {
return (
<PluginBlockRenderer
+ key={blockEntry.id}
entry={blockEntry}
language={info.lang}
source={info.code}
+ sourcePosition={sourcePositionProps(rest)}
fallback={
<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
index ffcfe1f7a..aa11da695 100644
--- a/apps/desktop/src/components/PluginBlockRenderer.tsx
+++ b/apps/desktop/src/components/PluginBlockRenderer.tsx
@@ -7,18 +7,20 @@
* 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.
+ *
+ * The clamp is host chrome, so it wraps the plugin's mount rather than
+ * sitting inside it, and it carries the fence's source anchor so transcript
+ * search lands on the block as it would on the host code block.
*/
-import {
- createElement,
- useLayoutEffect,
- useRef,
- useState,
- type ComponentType,
- type ReactNode,
-} from "react";
+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 {
+ SlotErrorBoundary,
+ SlotMount,
+ slotElement,
+} from "../plugins/renderer-slots/use-slots";
import type { SlotEntry } from "../plugins/renderer-slots/registry";
+import type { SourcePositionProps } from "../lib/markdown-source";
import {
BLOCK_RENDERER_MAX_HEIGHT_PX,
blockRendererOverflow,
@@ -28,21 +30,24 @@ export function PluginBlockRenderer({
entry,
language,
source,
+ sourcePosition,
fallback,
}: {
entry: SlotEntry;
language: string;
source: string;
+ /** Where the fence sits in the message source. */
+ sourcePosition: SourcePositionProps;
/** 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 clampRef = useRef<HTMLDivElement>(null);
const [overflowed, setOverflowed] = useState(false);
useLayoutEffect(() => {
- const el = contentRef.current;
+ const el = clampRef.current;
if (el && blockRendererOverflow(el.scrollHeight)) {
setOverflowed(true);
}
@@ -50,15 +55,15 @@ export function PluginBlockRenderer({
if (overflowed) return fallback;
return (
- <SlotBoundary entry={entry} slot="blockRenderer" fallback={fallback}>
+ <SlotErrorBoundary entry={entry} fallback={fallback}>
<div
- ref={contentRef}
+ ref={clampRef}
className="pi-plugin-block-renderer"
- data-pi-language={onceRef.current.language}
style={{ maxHeight: BLOCK_RENDERER_MAX_HEIGHT_PX }}
+ {...sourcePosition}
>
- {createElement(entry.component as ComponentType<Record<string, unknown>>, onceRef.current)}
+ <SlotMount entry={entry}>{slotElement(entry, onceRef.current)}</SlotMount>
</div>
- </SlotBoundary>
+ </SlotErrorBoundary>
);
}
diff --git a/apps/desktop/src/features/chat/composer/ComposerControlSlots.tsx b/apps/desktop/src/features/chat/composer/ComposerControlSlots.tsx
new file mode 100644
index 000000000..9a0ba6b41
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/ComposerControlSlots.tsx
@@ -0,0 +1,30 @@
+/**
+ * The `composerControl` outlet of one toolbar side
+ * (`docs/plugin-plan/ui/composer/`). Controls stack in registration order,
+ * each in its own boundary; their only prop is the side they are mounted on,
+ * and they reach the draft through `pi.dispatch`, never through props.
+ */
+import type {
+ PluginComposerControlSlotProps,
+ PluginSlotPosition,
+} from "@pi-desktop/plugin-sdk";
+import {
+ SlotBoundary,
+ slotElement,
+ useSlotEntries,
+} from "../../../plugins/renderer-slots/use-slots";
+
+export function ComposerControlSlots({ side }: { side: PluginSlotPosition }) {
+ const entries = useSlotEntries("composerControl", side);
+ if (entries.length === 0) return null;
+ const props: PluginComposerControlSlotProps = { position: side };
+ return (
+ <>
+ {entries.map((entry) => (
+ <SlotBoundary key={entry.id} entry={entry}>
+ {slotElement(entry, props)}
+ </SlotBoundary>
+ ))}
+ </>
+ );
+}
diff --git a/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsx b/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsx
deleted file mode 100644
index 7b7ec597d..000000000
--- a/apps/desktop/src/features/chat/composer/ComposerTokenChip.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * One draft token chip (`docs/plugin-plan/ui/composer/`).
- *
- * A plugin that registered `composerToken` for this label draws the token's
- * face through its own component; without a registration the host chip
- * renders. The ✕ removal stays host-owned either way so the fold records
- * (折叠不丢弃) can never strand a token inside the draft.
- */
-import { createElement, type ComponentType } from "react";
-import type { PluginComposerTokenProps } from "@pi-desktop/plugin-sdk";
-import {
- SlotBoundary,
- useSlotEntryForKey,
-} from "../../../plugins/renderer-slots/use-slots";
-import { dispatchFor } from "../../../plugins/renderer-host/dispatch";
-import type { ComposerPluginToken } from "./plugin-trigger";
-
-export function ComposerTokenChip({
- token,
- onRemove,
-}: {
- token: ComposerPluginToken;
- onRemove: (label: string) => void;
-}) {
- const entry = useSlotEntryForKey("composerToken", token.label);
- const removeButton = (
- <button
- type="button"
- className="pi-plugin-token-chip-remove"
- aria-label={`remove #${token.label}`}
- onClick={() => onRemove(token.label)}
- >
- ×
- </button>
- );
- if (!entry) {
- return (
- <span className="pi-plugin-token-chip" role="listitem">
- #{token.label}
- {removeButton}
- </span>
- );
- }
- return (
- <span
- className="pi-plugin-token-chip"
- role="listitem"
- data-pi-plugin={entry.pluginId}
- >
- <SlotBoundary entry={entry} slot="composerToken">
- {createElement(
- entry.component as ComponentType<PluginComposerTokenProps>,
- {
- label: token.label,
- send: token.send,
- dispatch: dispatchFor(entry.pluginId),
- },
- )}
- </SlotBoundary>
- {removeButton}
- </span>
- );
-}
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index dd8d9218b..48ccd8079 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -1,4 +1,4 @@
-import { createElement, type ComponentType, type Dispatch, type SetStateAction } from "react";
+import type { Dispatch, SetStateAction } from "react";
import type { TFunction } from "i18next";
import {
keybindingDisplayParts,
@@ -10,13 +10,7 @@ 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 { ComposerControlSlots } from "./ComposerControlSlots";
import { TooltipButton } from "../../../components/ui";
import {
IconArrowUp,
@@ -112,8 +106,6 @@ 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 (
@@ -195,11 +187,11 @@ export function ComposerToolbar({
});
}
}} />
- <PluginControlGroup entries={leftControls} side="left" />
+ <ComposerControlSlots side="left" />
</div>
<div className="composer-right">
- <PluginControlGroup entries={rightControls} side="right" />
+ <ComposerControlSlots side="right" />
{contextUsage ? <ContextUsageInspector {...contextUsage} /> : null}
<ComposerModelPicker
t={t}
@@ -284,32 +276,3 @@ 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}>
- {createElement(entry.component as ComponentType<Record<string, unknown>>, {
- position: side,
- dispatch: dispatchFor(entry.pluginId),
- })}
- </span>
- </SlotBoundary>
- ))}
- </>
- );
-}
diff --git a/apps/desktop/src/features/chat/composer/insert-bridge.ts b/apps/desktop/src/features/chat/composer/insert-bridge.ts
index a046620ab..b302000f4 100644
--- a/apps/desktop/src/features/chat/composer/insert-bridge.ts
+++ b/apps/desktop/src/features/chat/composer/insert-bridge.ts
@@ -4,7 +4,7 @@
* 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`.
+ * composer mounted the relay answers `PLUGIN_ACTION_NO_COMPOSER`.
*/
type ComposerInsert = (text: string) => void;
diff --git a/apps/desktop/src/features/chat/composer/plugin-trigger.ts b/apps/desktop/src/features/chat/composer/plugin-trigger.ts
deleted file mode 100644
index 6d8030dc4..000000000
--- a/apps/desktop/src/features/chat/composer/plugin-trigger.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * 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
deleted file mode 100644
index eeac484e8..000000000
--- a/apps/desktop/src/features/chat/composer/trigger-bridge.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 459232bff..000000000
--- a/apps/desktop/src/features/chat/composer/use-plugin-composer-slots.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * 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
index a7ca00109..ed9354485 100644
--- a/apps/desktop/src/features/chat/transcript/ActionBarSlots.tsx
+++ b/apps/desktop/src/features/chat/transcript/ActionBarSlots.tsx
@@ -1,123 +1,86 @@
/**
- * The shared action-bar gutters for `userAction` / `assistantAction`
+ * The action-bar sides of `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`.
+ * A bar renders its left side, its host keys, then its right side; a plugin
+ * can add around the host keys but never change, hide or fold them. Each side
+ * shows up to three items and folds the rest into its own "⋯" menu
+ * (`splitActionSide`); the registry re-renders the sides when a plugin loads
+ * or unloads, so they reflow at once. Every item sits in its own boundary: a
+ * throwing item disappears alone.
*/
-import {
- createElement,
- useEffect,
- useRef,
- useState,
- type ComponentType,
- type ReactNode,
-} from "react";
+import { useEffect, useRef, useState } 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 type { PluginSlotMessage, PluginSlotPosition } from "@pi-desktop/plugin-sdk";
import {
- actionSlotPropsFor,
- splitActionSide,
-} from "./action-slot-props";
+ SlotBoundary,
+ slotElement,
+ useSlotEntries,
+ useSlotSessionId,
+} from "../../../plugins/renderer-slots/use-slots";
+import type { SlotEntry } from "../../../plugins/renderer-slots/registry";
+import { actionSlotProps, 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;
-};
+type ActionSlot = "userAction" | "assistantAction";
-function ActionSlotItem({
- entry,
- slot,
- message,
- side,
- sessionId,
-}: {
- entry: SlotEntry;
- slot: "userAction" | "assistantAction";
- message: UiMessage;
- side: SlotSide;
+type ItemContext = {
+ message: PluginSlotMessage;
sessionId: string;
-}) {
- // Rebuilt every render: the contract is props-push, the whole projection.
- const props: PluginActionSlotProps = actionSlotPropsFor(
- message,
- side,
- sessionId,
- dispatchFor(entry.pluginId),
- );
+ side: PluginSlotPosition;
+};
+
+function ActionSlotItem({ entry, context }: { entry: SlotEntry; context: ItemContext }) {
return (
- <SlotBoundary entry={entry} slot={slot}>
- {createElement(entry.component as ComponentType<Record<string, unknown>>, props)}
+ <SlotBoundary entry={entry}>
+ {slotElement(entry, actionSlotProps(context.message, context.sessionId, context.side))}
</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;
-}) {
+/** One side's "⋯" menu holding the items past the visible three. */
+function ActionOverflowMenu({ entries, context }: { entries: SlotEntry[]; context: ItemContext }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
+ const buttonRef = useRef<HTMLButtonElement>(null);
- // Close on any click outside the menu; the folded items must not trap
- // the pointer the way a stray popover would.
+ // A pointer press anywhere else closes the menu, and so does Escape, which
+ // hands the focus back to the ⋯ key.
useEffect(() => {
if (!open) return;
const onPointerDown = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
};
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ setOpen(false);
+ buttonRef.current?.focus();
+ };
document.addEventListener("pointerdown", onPointerDown, true);
- return () => document.removeEventListener("pointerdown", onPointerDown, true);
+ document.addEventListener("keydown", onKeyDown);
+ return () => {
+ document.removeEventListener("pointerdown", onPointerDown, true);
+ document.removeEventListener("keydown", onKeyDown);
+ };
}, [open]);
- if (entries.length === 0) return null;
return (
- <div ref={rootRef} className="pi-action-overflow" data-side={side}>
+ <div ref={rootRef} className="pi-action-overflow" data-side={context.side}>
<button
+ ref={buttonRef}
type="button"
className="copy-btn icon pi-action-overflow-btn"
aria-label={t("chat.actionSlotMore")}
title={t("chat.actionSlotMore")}
- aria-expanded={open ? "true" : "false"}
+ aria-expanded={open}
onClick={() => setOpen((value) => !value)}
>
⋯
</button>
{open ? (
- <div className="pi-action-overflow-panel" role="menu">
+ <div className="pi-action-overflow-panel" role="group" aria-label={t("chat.actionSlotMore")}>
{entries.map((entry) => (
- <ActionSlotItem
- key={entry.id}
- entry={entry}
- slot={slot}
- message={message}
- side={side}
- sessionId={sessionId}
- />
+ <ActionSlotItem key={entry.id} entry={entry} context={context} />
))}
</div>
) : null}
@@ -126,54 +89,39 @@ function ActionOverflowMenu({
}
/**
- * 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.
+ * One plugin side of an action bar: its first three items and a ⋯ menu with
+ * the rest. The menu sits at the outer end of the bar, before the items on
+ * the left and after them on the right. Renders nothing without a message or
+ * without registrations on this side.
*/
-export function ActionBarSlots({
+export function ActionSlotSide({
slot,
+ side,
message,
- left,
- right,
- children,
-}: ActionBarSlotsProps) {
+}: {
+ slot: ActionSlot;
+ side: PluginSlotPosition;
+ /** What the items act on; `undefined` keeps the side empty. */
+ message: PluginSlotMessage | undefined;
+}) {
+ const entries = useSlotEntries(slot, side);
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 (
+ if (!message || entries.length === 0) return null;
+ const context: ItemContext = { message, sessionId, side };
+ const { visible, overflow } = splitActionSide(entries);
+ const menu = overflow.length ? <ActionOverflowMenu entries={overflow} context={context} /> : null;
+ const items = visible.map((entry) => (
+ <ActionSlotItem key={entry.id} entry={entry} context={context} />
+ ));
+ return side === "left" ? (
<>
- {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}
+ {menu}
+ {items}
+ </>
+ ) : (
+ <>
+ {items}
+ {menu}
</>
);
}
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index 375986536..717479e83 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -52,9 +52,9 @@ import {
} from "./TranscriptMenu";
import { useSmoothText } from "../../../hooks/useSmoothText";
import { TurnProcess } from "./TurnProcess";
+import { ActionSlotSide } from "./ActionBarSlots";
import { EntryExtraStack } from "./EntryExtraStack";
-import { ActionBarSlots } from "./ActionBarSlots";
-import { useSlotEntries } from "../../../plugins/renderer-slots/use-slots";
+import { slotMessage } from "../../../plugins/renderer-slots/slot-message";
type AssistantTurnProps = {
entry: AssistantTurnEntry;
@@ -298,10 +298,14 @@ 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);
+ // Plugins see a finished reply as the host keys act on it: the id of its
+ // answer message and the text Copy copies.
+ const slotReply =
+ complete && actionMessage
+ ? slotMessage("assistant", { ...actionMessage, content })
+ : undefined;
const streaming =
isActive && messages.some((message) => message.status === "streaming");
/*
@@ -427,8 +431,8 @@ 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} />
+ <ActionSlotSide slot="assistantAction" side="left" message={slotReply} />
<CopyButton text={content} label={t("chat.copy")} />
<TooltipButton
className="copy-btn icon"
@@ -446,12 +450,10 @@ export const AssistantTurn = memo(function AssistantTurn({
>
<IconReview size={13} />
</TooltipButton>
- </ActionBarSlots>
+ <ActionSlotSide slot="assistantAction" side="right" message={slotReply} />
</div>
) : null}
- {complete && actionMessage ? (
- <EntryExtraStack message={actionMessage} />
- ) : null}
+ {slotReply ? <EntryExtraStack message={slotReply} /> : null}
</div>
</div>
);
diff --git a/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx b/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx
index 21314e93f..764cb3eb6 100644
--- a/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx
+++ b/apps/desktop/src/features/chat/transcript/EntryExtraStack.tsx
@@ -1,40 +1,31 @@
/**
* 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.
+ * Additive blocks under a finished assistant reply, stacked in registration
+ * order. The host owns the height: a collapsed block clamps at 320px, fades
+ * out at the edge and offers the host expand toggle; an expanded one scrolls
+ * inside 600px. The toggle is host chrome outside the plugin's mount, so the
+ * plugin's scoped styles never reach it. A block whose component throws
+ * disappears, toggle included; the other blocks stay.
*/
-import {
- createElement,
- useLayoutEffect,
- useRef,
- useState,
- type ComponentType,
- type ReactNode,
-} from "react";
+import { useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { UiMessage } from "@pi-desktop/shared";
import type { PluginEntryExtraSlotProps } from "@pi-desktop/plugin-sdk";
import {
- SlotBoundary,
+ SlotErrorBoundary,
+ SlotMount,
+ slotElement,
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,
+ entryExtraSlotProps,
} from "./entry-extra-props";
-export { ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT, ENTRY_EXTRA_EXPANDED_MAX_HEIGHT };
+type SlotReply = PluginEntryExtraSlotProps["message"];
/** One registration's clamped viewport plus the host expand toggle. */
function EntryExtraBlock({
@@ -43,27 +34,22 @@ function EntryExtraBlock({
sessionId,
}: {
entry: SlotEntry;
- message: UiMessage;
+ message: SlotReply;
sessionId: string;
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
+ const [overflows, setOverflows] = 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.
+ // The toggle exists only while the content is taller than the viewport;
+ // observing both keeps that true when a block loads its data late.
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);
- };
+ if (!viewport || !content || typeof ResizeObserver === "undefined") return;
+ const measure = () => setOverflows(content.scrollHeight > viewport.clientHeight + 1);
measure();
const observer = new ResizeObserver(measure);
observer.observe(content);
@@ -71,65 +57,51 @@ function EntryExtraBlock({
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">
<div
- className="pi-entry-extra-block"
+ ref={viewportRef}
+ className="pi-entry-extra-viewport"
data-expanded={expanded ? "true" : undefined}
+ data-clipped={!expanded && overflows ? "true" : undefined}
+ style={{
+ maxHeight: expanded ? ENTRY_EXTRA_EXPANDED_MAX_HEIGHT : ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT,
+ }}
>
- <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}>{createElement(entry.component as ComponentType<Record<string, unknown>>, props)}</div>
+ <div ref={contentRef}>
+ <SlotMount entry={entry}>
+ {slotElement(entry, entryExtraSlotProps(message, sessionId))}
+ </SlotMount>
</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>
+ {expanded || overflows ? (
+ <button
+ type="button"
+ className="pi-entry-extra-toggle"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {expanded ? t("chat.entryExtraCollapse") : t("chat.entryExtraExpand")}
+ </button>
+ ) : null}
+ </div>
);
}
/**
- * The whole slot region for one assistant reply: zero or more blocks in
- * registration order. Renders nothing when no plugin registered the slot.
+ * The slot region of one finished assistant reply: a block per registration,
+ * in registration order, or nothing when no plugin registered the slot.
*/
-export function EntryExtraStack({ message }: { message: UiMessage }) {
+export function EntryExtraStack({ message }: { message: SlotReply }) {
const entries = useSlotEntries("entryExtra");
const sessionId = useSlotSessionId();
if (entries.length === 0) return null;
return (
- <div className="pi-entry-extra-stack" data-pi-slot="entryExtra">
+ <div className="pi-entry-extra-stack">
{entries.map((entry) => (
- <EntryExtraBlock
- key={entry.id}
- entry={entry}
- message={message}
- sessionId={sessionId}
- />
+ <SlotErrorBoundary key={entry.id} entry={entry}>
+ <EntryExtraBlock entry={entry} message={message} sessionId={sessionId} />
+ </SlotErrorBoundary>
))}
</div>
);
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index 7b6466f2a..145c3f16a 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -21,8 +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 { ActionSlotSide } from "./ActionBarSlots";
+import { slotMessage } from "../../../plugins/renderer-slots/slot-message";
import { SessionMessageOrigin } from "./SessionMessageOrigin";
import {
CopyButton,
@@ -86,11 +86,8 @@ 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 : [];
+ // userAction belongs to user cards; other rows keep a plugin-free bar.
+ const slotUser = isUser ? slotMessage("user", message) : undefined;
// Slash prompts are stored expanded; editing works on the typed form so the
// resent turn re-expands the template (D123).
const editSeed =
@@ -315,8 +312,8 @@ 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} />
+ <ActionSlotSide slot="userAction" side="left" message={slotUser} />
{showRevisionPager ? (
<div className="message-revision-pager" role="group" aria-label={t("chat.revisions")}>
<TooltipButton
@@ -375,7 +372,7 @@ export const MessageRow = memo(function MessageRow({
<IconTrash size={13} />
</TooltipButton>
) : null}
- </ActionBarSlots>
+ <ActionSlotSide slot="userAction" side="right" message={slotUser} />
</div>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx
index b9c7975e5..6cbf2b295 100644
--- a/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx
+++ b/apps/desktop/src/features/chat/transcript/PluginToolCard.tsx
@@ -5,70 +5,73 @@
* 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.
+ * transition and the final result push immediately. A card that throws
+ * collapses alone and the host default card takes its place, so a broken
+ * plugin never hides a tool call from the transcript.
*/
-import {
- createElement,
- useLayoutEffect,
- useRef,
- useState,
- type ComponentType,
-} from "react";
+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 {
+ SlotBoundary,
+ slotElement,
+ 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,
+ toolCardSlotProps,
+ toolCardStatusOf,
} from "./tool-card-props";
export function PluginToolCard({
entry,
message,
+ fallback,
}: {
entry: SlotEntry;
message: UiMessage;
+ /** The host default card, shown instead when the plugin card throws. */
+ fallback: ReactNode;
}) {
const sessionId = useSlotSessionId();
+ const toolName = entry.toolName ?? "";
// The committed projection only advances on the cadence, never per tick.
const [committed, setCommitted] = useState<PluginToolCardSlotProps>(() =>
- toolCardPropsFor(message, sessionId, dispatchFor(entry.pluginId)),
+ toolCardSlotProps(message, toolName, sessionId),
);
- const lastEmitRef = useRef({ at: Date.now(), status: committed.toolStatus });
+ const lastEmitRef = useRef({
+ at: Date.now(),
+ status: committed.toolStatus,
+ message,
+ sessionId,
+ });
useLayoutEffect(() => {
- const status = message.toolStatus === "running" || message.toolStatus === "error"
- ? message.toolStatus
- : "success";
+ const last = lastEmitRef.current;
+ if (last.message === message && last.sessionId === sessionId) return;
+ const status = toolCardStatusOf(message);
const emit = () => {
- lastEmitRef.current = { at: Date.now(), status };
- setCommitted(toolCardPropsFor(message, sessionId, dispatchFor(entry.pluginId)));
+ lastEmitRef.current = { at: Date.now(), status, message, sessionId };
+ setCommitted(toolCardSlotProps(message, toolName, sessionId));
};
- if (shouldEmitToolCard(lastEmitRef.current.at, lastEmitRef.current.status, status, Date.now())) {
+ if (shouldEmitToolCard(last.at, last.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,
+ Math.max(0, TOOL_CARD_RUNNING_INTERVAL_MS - (Date.now() - last.at)),
);
- const timer = window.setTimeout(emit, remaining);
return () => window.clearTimeout(timer);
- }, [message, sessionId, entry]);
+ }, [message, sessionId, toolName]);
return (
- <SlotBoundary entry={entry} slot="toolCard">
- <div className="pi-plugin-tool-card" data-pi-tool={message.toolName}>
- {createElement(entry.component as ComponentType<Record<string, unknown>>, committed)}
- </div>
+ <SlotBoundary entry={entry} fallback={fallback}>
+ {slotElement(entry, committed)}
</SlotBoundary>
);
}
diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
index e9c2017c1..a61600453 100644
--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
@@ -144,7 +144,27 @@ function toolRowPropsEqual(
);
}
-export const ToolRow = memo(function ToolRow({
+/**
+ * One tool call. A call of a plugin's own tool renders the card that plugin
+ * registered for it (the `toolCard` slot); the host card below is its
+ * fallback, and the only card for every other call. Topology nodes and
+ * denied rows always keep the host card.
+ */
+export const ToolRow = memo(function ToolRow(props: ToolRowProps) {
+ const { message, variant = "default" } = props;
+ const cardEntry = useSlotEntryForKey(
+ "toolCard",
+ variant === "default" && message.toolStatus !== "denied" ? message.toolName : undefined,
+ );
+ const hostRow = <HostToolRow {...props} />;
+ return cardEntry ? (
+ <PluginToolCard key={cardEntry.id} entry={cardEntry} message={message} fallback={hostRow} />
+ ) : (
+ hostRow
+ );
+}, toolRowPropsEqual);
+
+function HostToolRow({
message,
delegate,
variant = "default",
@@ -363,16 +383,6 @@ 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" : ""} ${
@@ -583,7 +593,7 @@ export const ToolRow = memo(function ToolRow({
<ContextMenu state={fileMenu} onClose={closeFileMenu} />
</div>
);
-}, toolRowPropsEqual);
+}
/**
* What a delegate did, nested under the `Task` call that spawned it.
diff --git a/apps/desktop/src/features/chat/transcript/action-slot-props.ts b/apps/desktop/src/features/chat/transcript/action-slot-props.ts
index e15b86bfa..011955965 100644
--- a/apps/desktop/src/features/chat/transcript/action-slot-props.ts
+++ b/apps/desktop/src/features/chat/transcript/action-slot-props.ts
@@ -1,49 +1,33 @@
/**
- * Props projection and pagination for the additive action slots
- * (`docs/plugin-plan/ui/user-action/`, `docs/plugin-plan/ui/assistant-action/`).
+ * Props and layout of the additive action slots `userAction` and
+ * `assistantAction` (`docs/plugin-plan/ui/user-action/`,
+ * `docs/plugin-plan/ui/assistant-action/`). React-free so logic tests can
+ * drive it directly.
*
- * 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.
+ * The bar is 【left items】【host keys】【right items】. Each side shows at most
+ * three items; the fourth onward folds into that side's host "⋯" menu, which
+ * sits before the host keys on the left and last on the right. The host keys
+ * never fold.
*/
import type {
PluginActionSlotProps,
- PluginRendererDispatch,
+ PluginSlotMessage,
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,
+/**
+ * One item's props: the message, its ids and the side it is mounted on,
+ * nothing else. Rebuilt on every render of the message (props-push).
+ */
+export function actionSlotProps(
+ message: PluginSlotMessage,
sessionId: string,
- dispatch: PluginRendererDispatch,
+ position: PluginSlotPosition,
): PluginActionSlotProps {
- return {
- message: actionSlotMessage(message),
- messageId: message.id,
- sessionId,
- position,
- dispatch,
- };
+ return { message, messageId: message.id, sessionId, position };
}
/** Split one side's registrations into visible items and ⋯ overflow. */
diff --git a/apps/desktop/src/features/chat/transcript/entry-extra-props.ts b/apps/desktop/src/features/chat/transcript/entry-extra-props.ts
index ca43120a1..41520e002 100644
--- a/apps/desktop/src/features/chat/transcript/entry-extra-props.ts
+++ b/apps/desktop/src/features/chat/transcript/entry-extra-props.ts
@@ -1,40 +1,19 @@
/**
- * 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.
+ * Props and height contract of the `entryExtra` slot
+ * (`docs/plugin-plan/ui/entry-extra/`). React-free so logic tests can drive
+ * it directly.
*/
-import type {
- PluginEntryExtraSlotProps,
- PluginRendererDispatch,
-} from "@pi-desktop/plugin-sdk";
-import type { UiMessage } from "@pi-desktop/shared";
+import type { PluginEntryExtraSlotProps } from "@pi-desktop/plugin-sdk";
-/** 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,
+/**
+ * One block's props: the reply and its ids, nothing else. Rebuilt on every
+ * render of the reply (props-push).
+ */
+export function entryExtraSlotProps(
+ message: PluginEntryExtraSlotProps["message"],
sessionId: string,
- dispatch: PluginRendererDispatch,
): PluginEntryExtraSlotProps {
- return {
- message: entryExtraMessage(message),
- messageId: message.id,
- sessionId,
- dispatch,
- };
+ return { message, messageId: message.id, sessionId };
}
/** Collapsed-state clamp: taller content fades and shows the host toggle. */
diff --git a/apps/desktop/src/features/chat/transcript/tool-card-props.ts b/apps/desktop/src/features/chat/transcript/tool-card-props.ts
index 0fa178130..1d91cbc8c 100644
--- a/apps/desktop/src/features/chat/transcript/tool-card-props.ts
+++ b/apps/desktop/src/features/chat/transcript/tool-card-props.ts
@@ -3,16 +3,14 @@
* (`docs/plugin-plan/ui/tool-card/`).
*
* The contract fixes the fields (toolName / toolCallId / toolArgs? /
- * toolStatus / toolResult? / toolError? / durationMs? + ids + dispatch) and
+ * toolStatus / toolResult? / toolError? / durationMs? + ids) 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.
+ * immediately. Failure is data, never a throw: a failed call carries what the
+ * tool returned as `toolError` instead of `toolResult`. JSX-free so logic
+ * tests can drive it directly.
*/
-import type {
- PluginRendererDispatch,
- PluginToolCardSlotProps,
-} from "@pi-desktop/plugin-sdk";
+import type { PluginToolCardSlotProps } from "@pi-desktop/plugin-sdk";
import type { UiMessage } from "@pi-desktop/shared";
/** Merged-push beat while a call is still running. */
@@ -30,23 +28,27 @@ export function toolCardStatusOf(
: "success";
}
-/** Full props for one card; rebuilt per render (props-push). */
-export function toolCardPropsFor(
+/**
+ * Full props for one card. `toolName` is the bare name the card registered
+ * for; the transcript carries the qualified agent-facing one.
+ */
+export function toolCardSlotProps(
message: UiMessage,
+ toolName: string,
sessionId: string,
- dispatch: PluginRendererDispatch,
): PluginToolCardSlotProps {
+ const toolStatus = toolCardStatusOf(message);
+ const failed = toolStatus === "error";
return {
- toolName: message.toolName ?? "",
+ toolName,
toolCallId: message.toolCallId ?? message.id,
toolArgs: message.toolArgs,
- toolStatus: toolCardStatusOf(message),
- toolResult: message.toolResult,
- toolError: message.isError ? message.error : undefined,
+ toolStatus,
+ toolResult: failed ? undefined : message.toolResult,
+ toolError: failed ? message.toolResult : undefined,
durationMs: message.toolDurationMs,
messageId: message.id,
sessionId,
- dispatch,
};
}
diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.ts
index ba7250f4d..89f75d110 100644
--- a/apps/desktop/src/features/plugins/model.ts
+++ b/apps/desktop/src/features/plugins/model.ts
@@ -80,6 +80,7 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {
export const CAPABILITY_ORDER: PluginCapability[] = [
"panel",
"views",
+ "rendererUi",
"commands",
"tools",
"agentExtension",
diff --git a/apps/desktop/src/lib/block-renderer.ts b/apps/desktop/src/lib/block-renderer.ts
index b592f8b91..081ea6480 100644
--- a/apps/desktop/src/lib/block-renderer.ts
+++ b/apps/desktop/src/lib/block-renderer.ts
@@ -1,3 +1,5 @@
+import { blockRendererLanguageKey } from "@pi-desktop/plugin-sdk";
+
/**
* Pure helpers for the `blockRenderer` slot (`docs/plugin-plan/ui/block-renderer/`).
*
@@ -17,11 +19,10 @@ export function blockRendererOverflow(contentHeight: number): boolean {
}
/**
- * 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.
+ * The registry key a fence language could hit, or `undefined` for a plain
+ * one. Only a label with the `<pluginId>:` prefix shape can match a
+ * registration, so `json`, `ts`, `mermaid`, … never touch the registry.
*/
export function blockRendererCandidate(lang: string): string | undefined {
- const trimmed = lang.trim();
- return trimmed.includes(":") ? trimmed : undefined;
+ return lang.includes(":") ? blockRendererLanguageKey(lang) : undefined;
}
diff --git a/apps/desktop/src/plugins/renderer-error.ts b/apps/desktop/src/plugins/renderer-error.ts
new file mode 100644
index 000000000..2a5bdeea8
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-error.ts
@@ -0,0 +1,15 @@
+import type { PluginRendererErrorCode } from "@pi-desktop/plugin-sdk";
+
+/**
+ * A coded refusal the host hands to plugin renderer code: thrown by
+ * `pi.slots.register` / `pi.ui.injectStyle`, rejected by `pi.dispatch`.
+ * Plugins branch on `code`; the message is for their developer.
+ */
+export class PluginRendererError extends Error {
+ readonly code: PluginRendererErrorCode;
+ constructor(code: PluginRendererErrorCode, message: string) {
+ super(message);
+ this.name = "PluginRendererError";
+ this.code = code;
+ }
+}
diff --git a/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
index d0b141c0e..31d075a55 100644
--- a/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
+++ b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
@@ -1,58 +1,27 @@
/**
- * 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.
+ * Mounts once per app window and keeps its plugin renderer modules in step
+ * with the plugin list and the open project (`rendererLoadSpecs`): a plugin
+ * loads when it becomes eligible, reloads when the main process hands out a
+ * new generation, and unloads — taking its registrations and style sheets
+ * along — when it stops being eligible or the host goes away.
*/
import { useEffect } from "react";
import { useAppStore } from "../../stores/app-store";
-import {
- loadedRendererPluginIds,
- loadRendererModule,
- unloadRendererModule,
-} from "./loader";
import { installRendererImportMap } from "./import-map";
+import { rendererLoadSpecs, rendererModules } from "./loader";
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);
+ const projectPath = useAppStore((state) => state.workspace?.path ?? null);
useEffect(() => {
- // Must run before the first plugin import resolves bare `react`.
+ // Plugin modules import bare `react`: the map must exist before the first.
installRendererImportMap();
- }, []);
+ rendererModules.sync(rendererLoadSpecs(plugins, projectPath));
+ }, [plugins, projectPath]);
- 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]);
+ useEffect(() => () => rendererModules.sync([]), []);
return null;
}
-
diff --git a/apps/desktop/src/plugins/renderer-host/dispatch.ts b/apps/desktop/src/plugins/renderer-host/dispatch.ts
index 7d9545a00..af327faa2 100644
--- a/apps/desktop/src/plugins/renderer-host/dispatch.ts
+++ b/apps/desktop/src/plugins/renderer-host/dispatch.ts
@@ -1,121 +1,156 @@
/**
- * Outbound dispatch gate (`slot-contract.html` §3).
+ * The outbound gate of plugin renderer code (`slot-contract.html` §3,
+ * `docs/plugin-plan/render/plugin-call/`).
*
- * 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.
+ * Every load of a plugin gets its own channel, bound to the plugin's id and
+ * to its `manifest.rendererActions`, so a component can only ever act as its
+ * own plugin and only through the words it declared. `plugin.call` crosses to
+ * the plugin's headless entry through the main-process relay, which owns the
+ * method whitelist, the size and rate limits and the breaker;
+ * `composer.insertText` never leaves the renderer and goes through the
+ * composer's insert bridge. Closing the channel when its load ends refuses
+ * every later dispatch and rejects the calls still in flight, so a late
+ * answer never reaches the components of an unloaded plugin.
*/
-import { api } from "../../lib/api";
+import {
+ PLUGIN_INSERT_TEXT_MAX_BYTES,
+ PLUGIN_RENDERER_ACTIONS,
+ type PluginRendererDispatch,
+} from "@pi-desktop/plugin-sdk";
import { insertComposerText } from "../../features/chat/composer/insert-bridge";
-import { acceptComposerTriggerItem } from "../../features/chat/composer/trigger-bridge";
-import type { PluginRendererDispatch } from "@pi-desktop/plugin-sdk";
+import { api } from "../../lib/api";
+import { PluginRendererError } from "../renderer-error";
-export type DispatchErrorCode =
- | "PLUGIN_ACTION_UNDECLARED"
- | "PLUGIN_ACTION_UNROUTED"
- | "PLUGIN_ACTION_INVALID_PAYLOAD";
+/** Where the implemented words go. The defaults are the live app's. */
+export type DispatchRoutes = {
+ /** The main-process `plugin.call` relay; rejects with its coded errors. */
+ pluginCall(pluginId: string, method: string, args: unknown): Promise<unknown>;
+ /** Inserts at the composer caret; false when no composer is mounted. */
+ insertText(text: string): boolean;
+};
-/** 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;
- }
-}
+const appRoutes: DispatchRoutes = {
+ pluginCall: (pluginId, method, args) => api.pluginRendererCall(pluginId, method, args),
+ insertText: insertComposerText,
+};
-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 type DispatchChannel = {
+ /** The `pi.dispatch` of one load. */
+ readonly dispatch: PluginRendererDispatch;
+ /** End the load: refuse later dispatches and reject the ones in flight. */
+ close(): void;
};
-export function createDispatch(
+const utf8 = new TextEncoder();
+
+function describe(value: unknown): string {
+ return typeof value === "string" ? JSON.stringify(value) : typeof value;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** The JSON reading of `args`, which is exactly what the plugin receives. */
+function jsonArgs(args: unknown): unknown {
+ if (args === undefined) return undefined;
+ let text: string | undefined;
+ try {
+ text = JSON.stringify(args);
+ } catch {
+ text = undefined;
+ }
+ if (text === undefined) {
+ throw new PluginRendererError("PLUGIN_CALL_UNSERIALIZABLE", "plugin.call args must be JSON");
+ }
+ return JSON.parse(text) as unknown;
+}
+
+export function createDispatchChannel(
pluginId: string,
- context: RendererDispatchContext,
-): PluginRendererDispatch {
- const dispatch: PluginRendererDispatch = async (action, payload) => {
- if (!context.actions.includes(action)) {
- throw new DispatchError(
+ declared: readonly string[],
+ routes: DispatchRoutes = appRoutes,
+): DispatchChannel {
+ let closed = false;
+ const inFlight = new Set<(error: unknown) => void>();
+
+ const unloaded = () =>
+ new PluginRendererError("PLUGIN_UNLOADED", `${pluginId} unloaded before the action settled`);
+
+ /** Settle as `work` does, unless the channel closes first. */
+ const untilClosed = <T>(work: Promise<T>): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
+ inFlight.add(reject);
+ work.then(
+ (value) => {
+ if (inFlight.delete(reject)) resolve(value);
+ },
+ (error: unknown) => {
+ if (inFlight.delete(reject)) reject(error);
+ },
+ );
+ });
+
+ const dispatch = async (action: unknown, payload: unknown): Promise<unknown> => {
+ if (closed) throw unloaded();
+ if (
+ typeof action !== "string" ||
+ !(PLUGIN_RENDERER_ACTIONS as readonly string[]).includes(action)
+ ) {
+ throw new PluginRendererError("PLUGIN_ACTION_UNKNOWN", `unknown action ${describe(action)}`);
+ }
+ if (!declared.includes(action)) {
+ throw new PluginRendererError(
"PLUGIN_ACTION_UNDECLARED",
- `action ${String(action)} is not in ${pluginId}'s rendererActions`,
+ `${action} is not in ${pluginId}'s manifest.rendererActions`,
+ );
+ }
+ if (!isRecord(payload)) {
+ throw new PluginRendererError(
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ `${action} takes an object payload`,
);
}
if (action === "plugin.call") {
- const call = (payload ?? {}) as { method?: unknown; args?: unknown };
- if (typeof call.method !== "string" || call.method.length === 0) {
- throw new DispatchError(
+ const method = payload.method;
+ if (typeof method !== "string" || !method) {
+ throw new PluginRendererError(
"PLUGIN_ACTION_INVALID_PAYLOAD",
- "plugin.call requires { method, args? }",
+ "plugin.call requires a method name",
);
}
- return api.pluginRendererCall(pluginId, call.method, call.args);
+ return untilClosed(routes.pluginCall(pluginId, method, jsonArgs(payload.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 };
+ const text = payload.text;
+ if (
+ typeof text !== "string" ||
+ !text ||
+ utf8.encode(text).byteLength > PLUGIN_INSERT_TEXT_MAX_BYTES
+ ) {
+ throw new PluginRendererError(
+ "PLUGIN_ACTION_INVALID_PAYLOAD",
+ `composer.insertText requires non-empty text of at most ${PLUGIN_INSERT_TEXT_MAX_BYTES} UTF-8 bytes`,
+ );
}
- 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 };
+ if (!routes.insertText(text)) {
+ throw new PluginRendererError(
+ "PLUGIN_ACTION_NO_COMPOSER",
+ "no composer is mounted to take the text",
+ );
}
- throw new DispatchError("PLUGIN_ACTION_UNROUTED", `no route for action ${String(action)}`);
+ return { ok: true };
};
- 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();
+ return {
+ // Plugins are untyped JavaScript, so the gate checks every argument at
+ // run time; the SDK's generic signature is the documentation of it.
+ dispatch: dispatch as PluginRendererDispatch,
+ close() {
+ if (closed) return;
+ closed = true;
+ const pending = [...inFlight];
+ inFlight.clear();
+ for (const reject of pending) reject(unloaded());
+ },
+ };
}
diff --git a/apps/desktop/src/plugins/renderer-host/loader.ts b/apps/desktop/src/plugins/renderer-host/loader.ts
index 2e2cbaab9..40c9d008e 100644
--- a/apps/desktop/src/plugins/renderer-host/loader.ts
+++ b/apps/desktop/src/plugins/renderer-host/loader.ts
@@ -1,197 +1,272 @@
/**
- * Loads one plugin's renderer entry into the app document and hands it the
- * `pi` API (`PiRendererApi` in @pi-desktop/plugin-sdk).
+ * Loads plugin renderer entries into the app window and hands each one the
+ * `pi` API (`PiRendererApi`, `docs/plugin-plan/slot-contract.html`).
*
- * 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.
+ * An entry is a plain ES module served from
+ * `plugin-renderer://<id>/g<generation>/<entry>`. The generation is the main
+ * process's load counter: a reload comes with a new one, so the window
+ * evaluates the new code instead of its cached module graph, and the old URLs
+ * stop resolving.
+ *
+ * Each load is its own session. Registrations, style sheets and the dispatch
+ * channel belong to the load that made them, and ending the load disposes all
+ * of them before the plugin's `onUnload` runs, whatever the plugin does or
+ * fails to do. The `pi` of an ended load stays dead: registering or injecting
+ * through it throws `PLUGIN_UNLOADED`, dispatching rejects with it. A load
+ * that fails (the import, a missing `onLoad`, a throwing `onLoad`) is torn
+ * down, reported once, and not retried until the main process hands out a
+ * new generation.
*/
import {
PLUGIN_RENDERER_SCHEME,
type PiRendererApi,
type PiRendererModule,
- type PluginRendererSlotOptions,
- toolCardOwnershipError,
+ type PluginDisposer,
+ type PluginSlotRegistration,
} 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;
+ isActiveInProject,
+ type PluginRendererDescriptor,
+ type PluginSummary,
+} from "@pi-desktop/shared";
+import { PluginRendererError } from "../renderer-error";
+import { slotRegistry, type SlotRegistry } from "../renderer-slots/registry";
+import { injectPluginStyle } from "../renderer-slots/style-injection";
+import { createDispatchChannel, type DispatchChannel } from "./dispatch";
+
+export type RendererLoadSpec = {
+ readonly pluginId: string;
+ readonly version: string;
+ readonly descriptor: PluginRendererDescriptor;
};
-const loaded = new Map<string, Promise<RendererModuleRecord | null>>();
+/** How a load ended up. `cancelled`: it was unloaded before it finished. */
+export type RendererLoadOutcome =
+ | { readonly status: "loaded" }
+ | { readonly status: "failed"; readonly error: unknown }
+ | { readonly status: "cancelled" };
-function rendererModuleUrl(pluginId: string, entry: string): string {
- return `${PLUGIN_RENDERER_SCHEME}://${encodeURIComponent(pluginId)}/${entry.replace(/^\//, "")}`;
+export type RendererLoaderDeps = {
+ importModule(url: string): Promise<unknown>;
+ registry: Pick<SlotRegistry, "register">;
+ injectStyle(pluginId: string, css: string): PluginDisposer;
+ openChannel(pluginId: string, actions: readonly string[]): DispatchChannel;
+ warn(message: string, error: unknown): void;
+};
+
+const LOADED: RendererLoadOutcome = { status: "loaded" };
+const CANCELLED: RendererLoadOutcome = { status: "cancelled" };
+
+/** The module URL of a load's entry; the protocol decodes each segment. */
+export function rendererModuleUrl(
+ pluginId: string,
+ descriptor: Pick<PluginRendererDescriptor, "entry" | "generation">,
+): string {
+ const entry = descriptor.entry
+ .replace(/^\/+/, "")
+ .split("/")
+ .map(encodeURIComponent)
+ .join("/");
+ return `${PLUGIN_RENDERER_SCHEME}://${encodeURIComponent(pluginId)}/g${descriptor.generation}/${entry}`;
}
-function codedError(code: string, message: string): Error {
- const error = new Error(message) as Error & { code?: string };
- error.code = code;
- return error;
+/** Named `onLoad`/`onUnload` exports, or a default export object with them. */
+function rendererModuleOf(namespace: unknown): PiRendererModule | undefined {
+ const exported = namespace as { onLoad?: unknown; default?: unknown } | null;
+ if (typeof exported?.onLoad === "function") return exported as PiRendererModule;
+ const fallback = exported?.default as { onLoad?: unknown } | null | undefined;
+ if (typeof fallback?.onLoad === "function") return fallback as PiRendererModule;
+ return undefined;
}
-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;
+function settled(run: () => unknown): Promise<unknown> {
+ try {
+ return Promise.resolve(run());
+ } catch (error) {
+ return Promise.reject(error);
+ }
}
-const handlesAtLoad = new WeakMap<object, (SlotRegistrationHandle | PluginStyleHandle)[]>();
+/** One load of one plugin: its `pi`, what it registered, and its teardown. */
+class RendererLoad {
+ readonly signature: string;
+ readonly ready: Promise<RendererLoadOutcome>;
+ private readonly spec: RendererLoadSpec;
+ private readonly deps: RendererLoaderDeps;
+ private alive = true;
+ private readonly disposers = new Set<PluginDisposer>();
+ private readonly channel: DispatchChannel;
+ private readonly pi: PiRendererApi;
+ private module: PiRendererModule | undefined;
+ /** Settles once `onLoad` has returned or thrown; never rejects. */
+ private onLoadSettled: Promise<unknown> = Promise.resolve();
+ private ending: Promise<void> | undefined;
-/**
- * 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);
+ constructor(signature: string, spec: RendererLoadSpec, deps: RendererLoaderDeps) {
+ this.signature = signature;
+ this.spec = spec;
+ this.deps = deps;
+ this.channel = deps.openChannel(spec.pluginId, spec.descriptor.actions);
+ this.pi = this.createPi();
+ this.ready = this.run();
+ }
+
+ private createPi(): PiRendererApi {
+ const { pluginId, version, descriptor } = this.spec;
+ return Object.freeze({
+ plugin: Object.freeze({ id: pluginId, version }),
+ slots: Object.freeze({
+ register: (registration: PluginSlotRegistration) => {
+ this.assertAlive();
+ return this.track(this.deps.registry.register(pluginId, registration, descriptor.tools));
+ },
+ }),
+ ui: Object.freeze({
+ injectStyle: (css: string) => {
+ this.assertAlive();
+ return this.track(this.deps.injectStyle(pluginId, css));
+ },
+ }),
+ dispatch: this.channel.dispatch,
+ });
+ }
+
+ private assertAlive(): void {
+ if (!this.alive) {
+ throw new PluginRendererError("PLUGIN_UNLOADED", `${this.spec.pluginId} is unloaded`);
+ }
+ }
+
+ /** Hand the plugin a disposer that the end of this load also runs. */
+ private track(dispose: PluginDisposer): PluginDisposer {
+ const tracked: PluginDisposer = () => {
+ if (this.disposers.delete(tracked)) dispose();
+ };
+ this.disposers.add(tracked);
+ return tracked;
+ }
+
+ private async run(): Promise<RendererLoadOutcome> {
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`,
+ namespace = await this.deps.importModule(
+ rendererModuleUrl(this.spec.pluginId, this.spec.descriptor),
);
+ } catch (error) {
+ return this.alive ? this.fail(error) : CANCELLED;
}
- bindDispatch(pluginId, context.actions);
+ if (!this.alive) return CANCELLED;
+ const module = rendererModuleOf(namespace);
+ if (!module) return this.fail(new Error("the renderer entry does not export onLoad(pi)"));
+ this.module = module;
+ const loading = settled(() => module.onLoad(this.pi));
+ this.onLoadSettled = loading.catch(() => undefined);
try {
- await mod.onLoad(buildPiApi(pluginId, version, context));
+ await loading;
} 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 this.alive ? this.fail(error) : CANCELLED;
}
- // Unload raced the async load: the plugin was torn down while `onLoad`
- // was still running, so its late registrations, styles, and dispatch
- // binding must not survive. The load memo was already deleted by
- // `unloadRendererModule`, which is the lost-race signal here.
- if (!loaded.has(pluginId)) {
- slotRegistry.unregisterPlugin(pluginId);
- removePluginStyles(pluginId);
- unbindDispatch(pluginId);
+ return this.alive ? LOADED : CANCELLED;
+ }
+
+ private fail(error: unknown): RendererLoadOutcome {
+ this.deps.warn(`[plugin-renderer] ${this.spec.pluginId} failed to load`, error);
+ void this.end();
+ return { status: "failed", error };
+ }
+
+ /**
+ * End this load: the host side at once, then the plugin's `onUnload` once
+ * `onLoad` has settled. Idempotent; resolves when `onUnload` has run.
+ */
+ end(): Promise<void> {
+ if (this.ending) return this.ending;
+ this.alive = false;
+ this.channel.close();
+ for (const dispose of [...this.disposers]) dispose();
+ this.ending = this.onLoadSettled.then(() => this.runOnUnload());
+ return this.ending;
+ }
+
+ private async runOnUnload(): Promise<void> {
+ const module = this.module;
+ if (typeof module?.onUnload !== "function") return;
+ try {
+ await module.onUnload();
+ } catch (error) {
+ this.deps.warn(`[plugin-renderer] ${this.spec.pluginId} onUnload failed`, 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()];
-}
+export class RendererModuleLoader {
+ private readonly loads = new Map<string, RendererLoad>();
+ private readonly deps: RendererLoaderDeps;
-/**
- * 卸载摘注册: 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();
+ constructor(deps: RendererLoaderDeps) {
+ this.deps = deps;
+ }
+
+ /**
+ * Bring a plugin to the load `spec` describes. The same generation is one
+ * load, however often it is asked for; a new one ends the previous load
+ * first. Resolves with the load's outcome and never rejects.
+ */
+ load(spec: RendererLoadSpec): Promise<RendererLoadOutcome> {
+ const signature = `${spec.descriptor.generation}:${spec.descriptor.entry}`;
+ const current = this.loads.get(spec.pluginId);
+ if (current?.signature === signature) return current.ready;
+ if (current) void this.unload(spec.pluginId);
+ const next = new RendererLoad(signature, spec, this.deps);
+ this.loads.set(spec.pluginId, next);
+ return next.ready;
+ }
+
+ /** End a plugin's load; resolves once its `onUnload` has run. */
+ unload(pluginId: string): Promise<void> {
+ const current = this.loads.get(pluginId);
+ if (!current) return Promise.resolve();
+ this.loads.delete(pluginId);
+ return current.end();
+ }
+
+ /** Load exactly `specs`: start or keep each of them, end every other load. */
+ sync(specs: readonly RendererLoadSpec[]): void {
+ const wanted = new Set(specs.map((spec) => spec.pluginId));
+ for (const pluginId of this.loadedPluginIds()) {
+ if (!wanted.has(pluginId)) void this.unload(pluginId);
}
- } catch {
- // Ignored by design: the plugin is going away regardless.
+ for (const spec of specs) void this.load(spec);
}
-}
-/** Test seam. */
-export function resetRendererModulesForTests(): void {
- for (const id of loaded.keys()) {
- void unloadRendererModule(id);
+ /** Plugins with a load, failed ones included, so they are not retried. */
+ loadedPluginIds(): string[] {
+ return [...this.loads.keys()];
}
}
+
+/**
+ * The loads a plugin list asks for: every plugin the main process hands a
+ * renderer descriptor (it is running, declares `manifest.renderer` and holds
+ * `renderer.extension`) that is active in the open project. A project-scoped
+ * plugin's slots belong to its projects, like its views and tools.
+ */
+export function rendererLoadSpecs(
+ plugins: readonly PluginSummary[],
+ projectPath: string | null | undefined,
+): RendererLoadSpec[] {
+ return plugins.flatMap((summary) =>
+ summary.renderer && isActiveInProject(summary, projectPath)
+ ? [{ pluginId: summary.id, version: summary.version, descriptor: summary.renderer }]
+ : [],
+ );
+}
+
+/** The app window's loader. */
+export const rendererModules = new RendererModuleLoader({
+ importModule: (url) => import(/* @vite-ignore */ url),
+ registry: slotRegistry,
+ injectStyle: injectPluginStyle,
+ openChannel: (pluginId, actions) => createDispatchChannel(pluginId, actions),
+ warn: (message, error) => console.warn(message, error),
+});
diff --git a/apps/desktop/src/plugins/renderer-slots/registry.ts b/apps/desktop/src/plugins/renderer-slots/registry.ts
index 2168a184b..74954b1d8 100644
--- a/apps/desktop/src/plugins/renderer-slots/registry.ts
+++ b/apps/desktop/src/plugins/renderer-slots/registry.ts
@@ -1,82 +1,91 @@
-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`.
+ * this store owns the resulting catalog. It is React-free so logic tests can
+ * drive it directly; the React glue lives in `use-slots.tsx`.
*
- * 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.
+ * Additive slots stack in registration order and never clash. Keyed slots
+ * (`toolCard` by the plugin's qualified tool name, `blockRenderer` by its
+ * language tag) refuse a second claim of a key with `PLUGIN_SLOT_DUPLICATE`:
+ * the first registration keeps it. Every registration comes back as a
+ * disposer; the loader holds the disposers of one load and runs them all when
+ * the plugin unloads.
*/
-
-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";
+import {
+ PLUGIN_SLOT_POSITIONS,
+ blockRendererLanguageKey,
+ pluginToolName,
+ slotRegistrationRefusal,
+ type PluginDisposer,
+ type PluginRendererSlot,
+ type PluginSlotPosition,
+ type PluginSlotRegistration,
+} from "@pi-desktop/plugin-sdk";
+import { PluginRendererError } from "../renderer-error";
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). */
+ /**
+ * The plugin's function component. Its type admits no call: outlets render
+ * it through `slotElement`, as an element that owns its hooks.
+ */
+ readonly component: (props: never) => unknown;
+ /** Sides a positioned slot occupies, in canonical order; empty otherwise. */
+ readonly sides: readonly PluginSlotPosition[];
+ /**
+ * Keyed slots only: the qualified agent-facing tool name
+ * (`pluginToolName`) for `toolCard`, the normalized language tag for
+ * `blockRenderer`. Outlets look entries up by what the transcript carries.
+ */
readonly key?: string;
+ /** `toolCard` only: the bare tool name the card registered for. */
+ readonly toolName?: string;
};
-export type SlotRegistrationHandle = {
- readonly slot: PluginRendererSlot;
- remove(): void;
+export type SlotRegistrySnapshot = {
+ /** Bumped on every mutation; the `useSyncExternalStore` change signal. */
+ readonly version: number;
+ /** Registration order across plugins is the presentation order. */
+ readonly entries: readonly SlotEntry[];
};
-type RegistryState = {
- /** Bumped on every mutation; the useSyncExternalStore snapshot key. */
- version: number;
- /** Insertion order across plugins is the presentation order. */
- entries: SlotEntry[];
-};
+function sidesOf(registration: PluginSlotRegistration): readonly PluginSlotPosition[] {
+ switch (registration.slot) {
+ case "userAction":
+ case "assistantAction":
+ case "composerControl": {
+ const wanted: readonly PluginSlotPosition[] =
+ registration.positions ?? PLUGIN_SLOT_POSITIONS;
+ return PLUGIN_SLOT_POSITIONS.filter((side) => wanted.includes(side));
+ }
+ default:
+ return [];
+ }
+}
-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;
+function keyOf(
+ pluginId: string,
+ registration: PluginSlotRegistration,
+): Pick<SlotEntry, "key" | "toolName"> {
+ if (registration.slot === "toolCard") {
+ return {
+ key: pluginToolName(pluginId, registration.toolName),
+ toolName: registration.toolName,
+ };
+ }
+ if (registration.slot === "blockRenderer") {
+ return { key: blockRendererLanguageKey(registration.language) };
+ }
+ return {};
}
export class SlotRegistry {
- private state: RegistryState = { version: 0, entries: [] };
- private listeners = new Set<() => void>();
- private nextId = 0;
+ private state: SlotRegistrySnapshot = { version: 0, entries: [] };
+ private readonly listeners = new Set<() => void>();
+ private lastId = 0;
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
@@ -85,98 +94,69 @@ export class SlotRegistry {
};
};
- getSnapshot = (): RegistryState => this.state;
+ getSnapshot = (): SlotRegistrySnapshot => this.state;
- private commit(entries: SlotEntry[]): void {
+ private commit(entries: readonly 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.
+ * Accept one registration of `pluginId` or throw a `PluginRendererError`
+ * with a `PluginSlotErrorCode`. `ownTools` is the plugin's bare
+ * `contributes.agentTools[].name` list. The disposer removes exactly this
+ * registration; calling it again does nothing.
*/
- 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,
+ register(pluginId: string, registration: unknown, ownTools: readonly string[]): PluginDisposer {
+ const refusal = slotRegistrationRefusal(pluginId, registration, ownTools);
+ if (refusal) throw new PluginRendererError(refusal.code, refusal.message);
+ const accepted = registration as PluginSlotRegistration;
+ const keyed = keyOf(pluginId, accepted);
+ if (keyed.key !== undefined) {
+ const holder = this.state.entries.find(
+ (entry) => entry.slot === accepted.slot && entry.key === keyed.key,
);
- if (clash) {
- throw new SlotError(
+ if (holder) {
+ throw new PluginRendererError(
"PLUGIN_SLOT_DUPLICATE",
- `slot ${slot} key ${key} is already taken by ${clash.pluginId}`,
+ `${accepted.slot} ${JSON.stringify(keyed.key)} is already registered by ${holder.pluginId}`,
);
}
}
-
- const sides: readonly SlotSide[] =
- slotName === "userAction" || slotName === "assistantAction" || slotName === "composerControl"
- ? (options?.positions ?? ["left", "right"])
- : [];
const entry: SlotEntry = {
- id: `s${this.nextId++}`,
+ id: `slot-${++this.lastId}`,
pluginId,
- slot: slotName,
- component: component as SlotEntry["component"],
- options: options ?? {},
- sides,
- key,
+ slot: accepted.slot,
+ component: accepted.component as SlotEntry["component"],
+ sides: sidesOf(accepted),
+ ...keyed,
};
this.commit([...this.state.entries, entry]);
- return {
- slot: slotName,
- remove: () => {
- this.commit(this.state.entries.filter((candidate) => candidate.id !== entry.id));
- },
+ let disposed = false;
+ return () => {
+ if (disposed) return;
+ disposed = true;
+ this.commit(this.state.entries.filter((candidate) => candidate !== entry));
};
}
- /** 卸载摘注册: 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);
+ /** Every registration of a slot, in registration order. */
+ entriesFor(slot: PluginRendererSlot): SlotEntry[] {
+ return this.state.entries.filter((entry) => entry.slot === slot);
}
- /** Additive slots, in registration order, filtered to one side. */
- entriesForSide(slot: PluginRendererSlot, side: SlotSide): SlotEntry[] {
+ /** A positioned slot's registrations on one side, in registration order. */
+ entriesForSide(slot: PluginRendererSlot, side: PluginSlotPosition): 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. */
+ /** The one registration holding a key: a tool's card, a language's renderer. */
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. */
+/** The app-wide registry the loader registers into and outlets read from. */
export const slotRegistry = new SlotRegistry();
diff --git a/apps/desktop/src/plugins/renderer-slots/slot-message.ts b/apps/desktop/src/plugins/renderer-slots/slot-message.ts
new file mode 100644
index 000000000..35c1d0b89
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-slots/slot-message.ts
@@ -0,0 +1,20 @@
+/**
+ * The message a message-anchored slot sees (`PluginSlotMessage`,
+ * `docs/plugin-plan/slot-contract.html` §2): its id, the role the slot is
+ * for, its text and its time. Nothing else of the host's message crosses into
+ * plugin code.
+ */
+import type { PluginSlotMessage } from "@pi-desktop/plugin-sdk";
+import type { UiMessage } from "@pi-desktop/shared";
+
+export function slotMessage<Role extends PluginSlotMessage["role"]>(
+ role: Role,
+ message: Pick<UiMessage, "id" | "content" | "createdAt">,
+): PluginSlotMessage & { readonly role: Role } {
+ return {
+ id: message.id,
+ role,
+ content: message.content,
+ createdAt: message.createdAt,
+ };
+}
diff --git a/apps/desktop/src/plugins/renderer-slots/slot-shell.css b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
index 739baf070..512b8b8d9 100644
--- a/apps/desktop/src/plugins/renderer-slots/slot-shell.css
+++ b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
@@ -14,7 +14,10 @@
min-width: 0;
}
-.pi-plugin-slot[data-pi-slot="entryExtra"] {
+/* Slots that own a whole block of the transcript take its full width. */
+.pi-plugin-slot[data-pi-slot="entryExtra"],
+.pi-plugin-slot[data-pi-slot="toolCard"],
+.pi-plugin-slot[data-pi-slot="blockRenderer"] {
display: block;
width: 100%;
}
@@ -22,8 +25,6 @@
/* ---- 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;
}
@@ -57,7 +58,7 @@
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));
+ border: 1px solid var(--ds-border-default);
background: var(--ds-bg-elevated, #1b1b1b);
color: var(--ds-text-primary, #ededed);
box-shadow: var(--ds-shadow-dialog);
@@ -71,7 +72,7 @@
gap: 12px;
padding: 12px 16px;
font-weight: var(--font-weight-semibold);
- border-bottom: 1px solid var(--ds-border, rgb(255 255 255 / 0.08));
+ border-bottom: 1px solid var(--ds-border-subtle);
}
.p-dialog__body {
@@ -84,7 +85,7 @@
justify-content: flex-end;
gap: 8px;
padding: 12px 16px;
- border-top: 1px solid var(--ds-border, rgb(255 255 255 / 0.08));
+ border-top: 1px solid var(--ds-border-subtle);
}
.p-notice {
@@ -95,7 +96,7 @@
width: 320px;
padding: 12px 14px;
border-radius: var(--radius-sm);
- border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ border: 1px solid var(--ds-border-default);
background: var(--ds-bg-elevated, #1b1b1b);
color: var(--ds-text-primary, #ededed);
box-shadow: var(--ds-shadow-dialog);
@@ -182,7 +183,7 @@
min-width: 120px;
padding: 6px;
border-radius: var(--radius-sm);
- border: 1px solid var(--ds-border, rgb(255 255 255 / 0.12));
+ border: 1px solid var(--ds-border-default);
background: var(--ds-bg-elevated, #1b1b1b);
color: var(--ds-text-primary, #ededed);
box-shadow: var(--ds-shadow-dialog);
@@ -196,73 +197,8 @@
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
index 76a7ee21e..f95e60b01 100644
--- a/apps/desktop/src/plugins/renderer-slots/style-injection.ts
+++ b/apps/desktop/src/plugins/renderer-slots/style-injection.ts
@@ -1,47 +1,75 @@
/**
- * Style injection for renderer slot plugins (`slot-contract.html` §4).
+ * `pi.ui.injectStyle` (`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.
+ * A plugin's style sheet applies inside its own mounts only: its style rules
+ * go into `@scope ([data-pi-plugin="<id>"])`, the attribute every
+ * `SlotBoundary` carries. Rules that name things instead of selecting
+ * elements (`@keyframes`, `@font-face`, `@property`, `@layer` statements, ...)
+ * cannot be scoped and stay global, so a plugin's names share the document's
+ * namespace. `@import` is dropped: a sheet brings its rules along rather than
+ * fetching more.
+ *
+ * The browser parses the sheet first (`CSSStyleSheet.replaceSync`), so what
+ * gets scoped is what the CSS engine understood, never a text match. Scoping
+ * keeps well-behaved plugins apart and out of the host's way; it is not a
+ * boundary, since same-realm code can restyle anything (an accepted cost).
*/
+import type { PluginDisposer } from "@pi-desktop/plugin-sdk";
-type InjectedSheet = {
- pluginId: string;
- element: HTMLStyleElement;
+/** What the scoper reads of a parsed rule; a `CSSRule` in the app. */
+export type ParsedCssRule = {
+ readonly cssText: string;
+ readonly constructor: { readonly name: string };
};
-const sheets: InjectedSheet[] = [];
+/** Rules that hold style rules and are valid inside `@scope`. */
+const SCOPED_RULES = new Set([
+ "CSSStyleRule",
+ "CSSMediaRule",
+ "CSSSupportsRule",
+ "CSSContainerRule",
+ "CSSLayerBlockRule",
+ "CSSScopeRule",
+ "CSSStartingStyleRule",
+]);
-export type PluginStyleHandle = {
- remove(): void;
-};
+const DROPPED_RULES = new Set(["CSSImportRule"]);
-function removeSheet(sheet: InjectedSheet): void {
- sheet.element.remove();
- const index = sheets.indexOf(sheet);
- if (index >= 0) sheets.splice(index, 1);
+function cssString(value: string): string {
+ return `"${value.replace(/["\\\n]/g, (char) => (char === "\n" ? "\\a " : `\\${char}`))}"`;
}
-/** Inject one stylesheet owned by `pluginId`. Returns a removal handle. */
-export function injectStyle(pluginId: string, css: string): PluginStyleHandle {
+/**
+ * The text of a plugin's sheet as the host injects it: global at-rules first,
+ * in source order, then every style rule inside the plugin's scope.
+ */
+export function scopedPluginCss(pluginId: string, rules: Iterable<ParsedCssRule>): string {
+ const global: string[] = [];
+ const scoped: string[] = [];
+ for (const rule of rules) {
+ const kind = rule.constructor.name;
+ if (DROPPED_RULES.has(kind)) continue;
+ (SCOPED_RULES.has(kind) ? scoped : global).push(rule.cssText);
+ }
+ if (scoped.length) {
+ global.push(`@scope ([data-pi-plugin=${cssString(pluginId)}]) {\n${scoped.join("\n")}\n}`);
+ }
+ return global.join("\n");
+}
+
+/** Inject one sheet for `pluginId`; the disposer removes it. */
+export function injectPluginStyle(pluginId: string, css: string): PluginDisposer {
+ if (typeof css !== "string") throw new TypeError("injectStyle takes a CSS string");
+ const parsed = new CSSStyleSheet();
+ parsed.replaceSync(css);
const element = document.createElement("style");
- element.setAttribute("data-pi-plugin", pluginId);
- element.textContent = css;
+ element.setAttribute("data-pi-plugin-style", pluginId);
+ element.textContent = scopedPluginCss(pluginId, Array.from(parsed.cssRules));
document.head.appendChild(element);
- const sheet: InjectedSheet = { pluginId, element };
- sheets.push(sheet);
- return {
- remove: () => {
- removeSheet(sheet);
- },
+ let removed = false;
+ return () => {
+ if (removed) return;
+ removed = true;
+ element.remove();
};
}
-
-/** 卸载摘样式: 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
index ca5314e44..a5f42208c 100644
--- a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
+++ b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx
@@ -1,24 +1,34 @@
/**
- * React glue over the slot registry: subscriptions + the per-registration
+ * React glue over the slot registry: subscriptions, the per-registration
* error boundary that realizes 出错隔离 (a throwing component collapses only
- * its own region).
+ * its own region), and the mount element plugin styles are scoped to.
*/
import {
Component,
+ type FunctionComponent,
+ type ReactElement,
type ReactNode,
createContext,
+ createElement,
useContext,
useMemo,
useSyncExternalStore,
} from "react";
-import type { PluginRendererSlot } from "@pi-desktop/plugin-sdk";
-import {
- slotRegistry,
- type SlotEntry,
- type SlotSide,
-} from "./registry";
+import type { PluginRendererSlot, PluginSlotPosition } from "@pi-desktop/plugin-sdk";
+import { slotRegistry, type SlotEntry } from "./registry";
+
+/**
+ * A registration's component as a React element with its slot's props. It is
+ * an element, never a direct call, so the component's hooks belong to it.
+ */
+export function slotElement<Props extends object>(entry: SlotEntry, props: Props): ReactElement {
+ return createElement(entry.component as FunctionComponent<Props>, props);
+}
-export function useSlotEntries(slot: PluginRendererSlot, side?: SlotSide): SlotEntry[] {
+export function useSlotEntries(
+ slot: PluginRendererSlot,
+ side?: PluginSlotPosition,
+): SlotEntry[] {
const snapshot = useSyncExternalStore(
slotRegistry.subscribe,
slotRegistry.getSnapshot,
@@ -48,28 +58,38 @@ export function useSlotEntryForKey(
}
/**
- * 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.
+ * The element a registration's component renders into. `data-pi-plugin` is
+ * what `pi.ui.injectStyle` scopes the plugin's sheets to, so host chrome
+ * around a slot (toggles, menus) stays outside of it.
*/
+export function SlotMount({
+ entry,
+ children,
+}: {
+ entry: SlotEntry;
+ children: ReactNode;
+}) {
+ return (
+ <div className="pi-plugin-slot" data-pi-plugin={entry.pluginId} data-pi-slot={entry.slot}>
+ {children}
+ </div>
+ );
+}
+
+/** A registration's component in its mount, inside its own error boundary. */
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). */
+ /** Rendered instead when the component throws; nothing by default. */
fallback?: ReactNode;
}) {
return (
<SlotErrorBoundary entry={entry} fallback={fallback}>
- <div className="pi-plugin-slot" data-pi-plugin={entry.pluginId} data-pi-slot={slot}>
- {children}
- </div>
+ <SlotMount entry={entry}>{children}</SlotMount>
</SlotErrorBoundary>
);
}
@@ -78,7 +98,12 @@ type BoundaryProps = { entry: SlotEntry; fallback?: ReactNode; children: ReactNo
type BoundaryState = { failed: boolean };
-class SlotErrorBoundary extends Component<BoundaryProps, BoundaryState> {
+/**
+ * Catches what one registration's subtree throws while rendering and renders
+ * `fallback` in its place from then on; outlets key it by `entry.id`, so a new
+ * registration starts over.
+ */
+export class SlotErrorBoundary extends Component<BoundaryProps, BoundaryState> {
state: BoundaryState = { failed: false };
static getDerivedStateFromError(): BoundaryState {
@@ -86,12 +111,9 @@ class SlotErrorBoundary extends Component<BoundaryProps, BoundaryState> {
}
componentDidCatch(error: unknown): void {
- const pluginId = this.props.entry.pluginId;
+ const { pluginId, slot } = this.props.entry;
// Isolated by design; the console line is the diagnosability surface.
- console.warn(
- `[plugin-slot] ${pluginId} component failed; collapsing its own region only`,
- error,
- );
+ console.warn(`[plugin-slot] ${pluginId} ${slot} component failed`, error);
}
render(): ReactNode {
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/README.md b/apps/desktop/test/e2e/plugin-ui-slots/README.md
new file mode 100644
index 000000000..2df171456
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/README.md
@@ -0,0 +1,43 @@
+# Plugin UI slots E2E
+
+Launches the real Electron app with the UI Slots Lab
+(`examples/plugins/ui-slots-lab`) loaded as a development plugin and drives
+every renderer slot end to end. The model is a deterministic in-process
+Chat Completions stub; no real provider or network access is used.
+
+```bash
+pnpm build:js
+cargo build -p host-core # or set PI_DESKTOP_HOST_BIN
+pnpm test:e2e:plugin-ui-slots
+```
+
+| File | Role |
+| --- | --- |
+| `scripts/e2e-plugin-ui-slots.mjs` | Runner: isolated data/home/profile, seed, Electron with MCP control and a CDP port, cleanup |
+| `stub-model.mjs` | Stub model; the prompt names the scenario (`lab: probe <ok\|fail\|crash\|slow>`, `lab: chart <crash\|tall>`) |
+| `seed.mjs` | Provider row for the stub and `plugins.loadDev` of a copy of the lab, through host-core JSON-RPC |
+| `clients.mjs` | MCP control client (sessions, prompts, turn status) and a CDP renderer client |
+| `drive.mjs` | The scenarios and their checks |
+
+Covered behavior (`E2E-PLUGIN-ui-slots-*` in the E2E test plan):
+
+- every slot mounts its sample for the open session: `userAction`,
+ `assistantAction` (fourth right item in the ⋯ menu), stacked `entryExtra`,
+ `toolCard`, `blockRenderer`, `composerControl`
+- the plugin's injected sheet is scoped to its own mounts
+- ⋯ menu opens, closes on Escape (focus returns to ⋯) and on an outside
+ press, stays open on an inside press, and runs the folded item
+- `plugin.call` round trips, a plugin error code passing through, and the
+ 2s `PLUGIN_CALL_TIMEOUT`; `composer.insertText` from every slot
+- `entryExtra` collapsed clamp and the host expand toggle
+- a crashing item, block or control is contained to itself
+- `toolCard`: a failed call as `toolError`, a throwing card falling back to
+ the host row, and `running → success` for a slow call
+- `blockRenderer`: a throwing or over-4000px render falling back to the host
+ code block
+- disabling the plugin removes every mount, menu, block and sheet; enabling
+ it mounts fresh samples
+
+Environment knobs: `E2E_ROOT` (fixed run root, kept), `E2E_KEEP_ARTIFACTS=1`,
+`E2E_TIMEOUT_MS` (drive budget, default 240000), `DEBUG_E2E=1` (Electron
+output). A failed run keeps its root, including `final.png`.
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs b/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs
new file mode 100644
index 000000000..47acb89c1
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/clients.mjs
@@ -0,0 +1,125 @@
+// Clients for the two surfaces the driver works through: the app's MCP
+// control plane (sessions, prompts, turn status) and the real renderer over
+// the Chrome DevTools Protocol (the DOM the slots draw into).
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export async function connectControl(dataDir) {
+ const info = JSON.parse(readFileSync(join(dataDir, "mcp-control.json"), "utf8"));
+ let session;
+ let sequence = 0;
+ async function rpc(method, params) {
+ const res = await fetch(info.url, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${info.token}`,
+ "Content-Type": "application/json",
+ ...(session ? { "Mcp-Session-Id": session } : {}),
+ },
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++sequence, method, params }),
+ });
+ session = res.headers.get("mcp-session-id") ?? session;
+ const body = await res.json();
+ if (body.error) throw new Error(`${method}: ${JSON.stringify(body.error)}`);
+ return body.result;
+ }
+ async function tool(name, args = {}) {
+ const result = await rpc("tools/call", { name, arguments: args });
+ const text = result?.content?.find((part) => part.type === "text")?.text;
+ if (result?.isError) throw new Error(`${name}: ${text}`);
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+ }
+ await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "e2e", version: "0" } });
+ return {
+ tool,
+ async waitForTurn(sessionId, timeoutMs = 60_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const status = await tool("pi_agent_status", { sessionId });
+ if (status?.status?.isRunning === false || status?.isRunning === false) return;
+ await sleep(250);
+ }
+ throw new Error("turn did not finish");
+ },
+ async messages(sessionId) {
+ const detail = await tool("pi_session_get", { id: sessionId, messageLimit: 200 });
+ return detail?.session?.messages ?? [];
+ },
+ };
+}
+
+/**
+ * The main window's page. `run(fn, arg)` evaluates `fn(arg)` in the page and
+ * returns its (awaited, JSON) value; `until` polls `run` until it is truthy.
+ */
+export async function connectRenderer(port) {
+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
+ const target = targets.find((entry) => entry.type === "page" && entry.webSocketDebuggerUrl);
+ if (!target) throw new Error("Missing Electron renderer target");
+ const socket = new WebSocket(target.webSocketDebuggerUrl);
+ await new Promise((resolve, reject) => {
+ socket.addEventListener("open", resolve, { once: true });
+ socket.addEventListener("error", reject, { once: true });
+ });
+ let sequence = 0;
+ const pending = new Map();
+ socket.addEventListener("message", ({ data }) => {
+ const reply = JSON.parse(String(data));
+ const waiter = pending.get(reply.id);
+ if (!waiter) return;
+ pending.delete(reply.id);
+ clearTimeout(waiter.timer);
+ if (reply.error) waiter.reject(new Error(reply.error.message));
+ else waiter.resolve(reply.result);
+ });
+ const call = (method, params) =>
+ new Promise((resolve, reject) => {
+ const id = ++sequence;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ reject(new Error(`${method} timed out`));
+ }, 15_000);
+ pending.set(id, { resolve, reject, timer });
+ socket.send(JSON.stringify({ id, method, params }));
+ });
+ async function run(fn, arg) {
+ const reply = await call("Runtime.evaluate", {
+ expression: `(${fn})(${JSON.stringify(arg ?? null)})`,
+ awaitPromise: true,
+ returnByValue: true,
+ });
+ if (reply.exceptionDetails) {
+ throw new Error(reply.exceptionDetails.exception?.description ?? reply.exceptionDetails.text);
+ }
+ return reply.result?.value;
+ }
+ // The window may sit behind other apps; without page focus Chromium ignores
+ // element.focus(), and the focus-return checks would read the desktop's
+ // window stacking instead of the app.
+ await call("Emulation.setFocusEmulationEnabled", { enabled: true });
+ return {
+ run,
+ async until(fn, arg, label, timeoutMs = 15_000) {
+ const deadline = Date.now() + timeoutMs;
+ let last;
+ while (Date.now() < deadline) {
+ last = await run(fn, arg);
+ if (last) return last;
+ await sleep(50);
+ }
+ throw new Error(`timed out waiting for ${label} (last ${JSON.stringify(last)})`);
+ },
+ async screenshot() {
+ return (await call("Page.captureScreenshot", { format: "png" })).data;
+ },
+ close() {
+ socket.close();
+ },
+ };
+}
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
new file mode 100644
index 000000000..382978682
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
@@ -0,0 +1,424 @@
+// Drives the UI Slots Lab through the real app: prompts go through the MCP
+// control plane, and every assertion reads the renderer DOM the host slots
+// draw into, by the lab's `data-lab="<slot>[:<side>]"` markers.
+import { PROBE_TOOL } from "./stub-model.mjs";
+
+const LAB = "lab.ui-slots";
+/** The host's block clamp (`BLOCK_RENDERER_MAX_HEIGHT_PX`). */
+const BLOCK_MAX_PX = 4_000;
+/** The entryExtra collapsed height (`ENTRY_EXTRA_COLLAPSED_MAX_HEIGHT`). */
+const ENTRY_COLLAPSED_PX = 320;
+
+/* Page-side helpers, installed once; the page is never reloaded. */
+function installPageHelpers() {
+ const turns = () => [...document.querySelectorAll(".message-row.assistant-turn")];
+ // Every read names its root; a missing turn reads as empty, never as the page.
+ const one = (root, lab) => root?.querySelector(`[data-lab="${lab}"]`) ?? null;
+ window.__labE2E = {
+ turn: (index) => turns().at(index) ?? null,
+ userRow: (index) => [...document.querySelectorAll('.message-row[data-row-role="user"]')].at(index) ?? null,
+ labs: (root) => [...(root?.querySelectorAll("[data-lab]") ?? [])].map((node) => node.getAttribute("data-lab")),
+ sessions: (root) => [
+ ...new Set([...(root?.querySelectorAll("[data-lab-session]") ?? [])].map((node) => node.getAttribute("data-lab-session"))),
+ ],
+ one,
+ click(root, lab, button) {
+ const target = one(root, lab)?.querySelector(`[data-lab-button="${button}"]`);
+ target?.click();
+ return Boolean(target);
+ },
+ result(root, lab) {
+ const out = one(root, lab)?.querySelector("[data-lab-result]");
+ return out ? { status: out.getAttribute("data-lab-result"), text: out.textContent } : null;
+ },
+ /** The right-side ⋯ menu of the first reply. */
+ menu() {
+ const turn = turns()[0];
+ const root = turn?.querySelector('.pi-action-overflow[data-side="right"]');
+ const button = root?.querySelector(".pi-action-overflow-btn");
+ return {
+ found: Boolean(root),
+ expanded: button?.getAttribute("aria-expanded") ?? null,
+ folded: Boolean(one(turn, "assistantAction:folded")),
+ focused: Boolean(button) && document.activeElement === button,
+ active: document.activeElement?.className || document.activeElement?.tagName || null,
+ hasFocus: document.hasFocus(),
+ };
+ },
+ composerText() {
+ const input = document.querySelector(".composer-input");
+ return input ? (input.value ?? input.textContent) : null;
+ },
+ };
+ return true;
+}
+
+export async function drive({ control, renderer, check, project }) {
+ const page = renderer.run;
+ const until = renderer.until;
+ const prompt = async (sessionId, content) => {
+ await control.tool("pi_agent_prompt", { sessionId, content });
+ await control.waitForTurn(sessionId);
+ };
+ // A sample's dispatch outcome once it leaves `pending`.
+ const settled = (turnIndex, lab, label, timeoutMs) =>
+ until(
+ ({ turnIndex, lab }) => {
+ const root = turnIndex === null ? document : window.__labE2E.turn(turnIndex);
+ const result = window.__labE2E.result(root, lab);
+ return result && result.status !== "pending" && result.status !== "idle" ? result : null;
+ },
+ { turnIndex, lab },
+ label,
+ timeoutMs,
+ );
+ const clickIn = (turnIndex, lab, button) =>
+ page(({ turnIndex, lab, button }) => {
+ const root = turnIndex === null ? document : window.__labE2E.turn(turnIndex);
+ return window.__labE2E.click(root, lab, button);
+ }, { turnIndex, lab, button });
+
+ await control.tool("pi_project_open", { path: project });
+ const created = await control.tool("pi_session_create", { title: "ui slots lab", projectPath: project, mode: "agent" });
+ const sessionId = created?.session?.id ?? created?.id;
+ check("session created", Boolean(sessionId), sessionId);
+ // The lab's tool is low risk; Auto keeps the run free of approval prompts.
+ await control.tool("pi_session_configure", { id: sessionId, mode: "agent", permissionMode: "auto", confirm: true });
+
+ await until(() => typeof window.__PI_DESKTOP__?.selectSession === "function", null, "renderer automation surface", 30_000);
+ await page(installPageHelpers);
+ await page((id) => window.__PI_DESKTOP__.selectSession(id), sessionId);
+ await until(() => Boolean(document.querySelector('[data-lab="composerControl:left"]')), null, "lab composer controls", 30_000);
+ check("the lab's renderer entry loaded into the open window", true);
+
+ // --- one turn fills every transcript slot -------------------------------
+ await prompt(sessionId, "lab: probe ok");
+ await until(() => Boolean(window.__labE2E.one(window.__labE2E.turn(0), "entryExtra")), null, "entryExtra under the reply");
+
+ const layout = await page(() => {
+ const e2e = window.__labE2E;
+ const turn = e2e.turn(0);
+ return {
+ user: e2e.labs(e2e.userRow(0)),
+ turn: e2e.labs(turn),
+ toolbar: e2e.labs(document).filter((lab) => lab.startsWith("composerControl")),
+ sessions: e2e.sessions(document),
+ mounts: [...new Set([...document.querySelectorAll("[data-pi-plugin]")].map((node) => node.getAttribute("data-pi-plugin")))],
+ };
+ });
+ check("userAction samples sit on both sides of the user bar", sameSet(layout.user, ["userAction:left", "userAction:right"]), layout.user.join(","));
+ check(
+ "the reply carries toolCard, blockRenderer, every visible assistantAction, and both entryExtra blocks",
+ sameSet(layout.turn, [
+ "toolCard",
+ "blockRenderer",
+ "assistantAction:left",
+ "assistantAction:right",
+ "assistantAction:refuse",
+ "assistantAction:crash",
+ "entryExtra",
+ "entryExtra:notes",
+ ]),
+ layout.turn.join(","),
+ );
+ check("composerControl samples sit on both toolbar sides", sameSet(layout.toolbar, ["composerControl:left", "composerControl:right", "composerControl:crash"]), layout.toolbar.join(","));
+ check("every sample was mounted for the open session", layout.sessions.length === 1 && layout.sessions[0] === sessionId, layout.sessions.join(","));
+ check("every mount belongs to the lab", layout.mounts.length === 1 && layout.mounts[0] === LAB, layout.mounts.join(","));
+
+ const blocks = await page(() => {
+ const turn = window.__labE2E.turn(0);
+ const card = window.__labE2E.one(turn, "toolCard");
+ const chart = window.__labE2E.one(turn, "blockRenderer");
+ const clamp = chart?.closest(".pi-plugin-block-renderer");
+ return {
+ status: card?.getAttribute("data-lab-status"),
+ output: card?.querySelector("[data-lab-output]")?.textContent ?? "",
+ call: card?.querySelector("[data-lab-call]")?.getAttribute("data-lab-call") ?? "",
+ language: chart?.getAttribute("data-lab-language"),
+ bars: chart?.querySelectorAll(".lab-bar-row").length ?? 0,
+ clampHeight: clamp?.scrollHeight ?? -1,
+ hostBlocks: turn.querySelectorAll(".code-block").length,
+ };
+ });
+ check("the toolCard draws the finished probe call", blocks.status === "success" && blocks.output.includes('"ok":true') && blocks.call.length > 0, JSON.stringify(blocks));
+ check(
+ "the blockRenderer draws the claimed fence inside the host clamp",
+ blocks.language === `${LAB}:chart` && blocks.bars === 2 && blocks.clampHeight > 0 && blocks.clampHeight <= BLOCK_MAX_PX && blocks.hostBlocks === 0,
+ JSON.stringify(blocks),
+ );
+
+ const styles = await page(() => {
+ const sample = document.querySelector('[data-lab="entryExtra"]');
+ const stray = document.createElement("div");
+ stray.className = "lab-card";
+ document.body.appendChild(stray);
+ const outside = getComputedStyle(stray).borderTopStyle;
+ stray.remove();
+ return {
+ inside: getComputedStyle(sample).borderTopStyle,
+ outside,
+ sheets: document.querySelectorAll('style[data-pi-plugin-style="lab.ui-slots"]').length,
+ };
+ });
+ check("the lab's sheet styles its own mounts and nothing outside them", styles.inside === "dashed" && styles.outside !== "dashed" && styles.sheets === 1, JSON.stringify(styles));
+
+ // --- the ⋯ menu -----------------------------------------------------------
+ // Each step acts in one evaluation and waits for React's commit in the next.
+ const menu = async (action, expanded) => {
+ await page((action) => {
+ const root = window.__labE2E.turn(0).querySelector('.pi-action-overflow[data-side="right"]');
+ if (action === "toggle") root?.querySelector(".pi-action-overflow-btn")?.click();
+ if (action === "escape") document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ if (action === "outside") document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
+ if (action === "inside") {
+ root?.querySelector('[data-lab="assistantAction:folded"]')?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
+ }
+ return true;
+ }, action);
+ // A step that should change nothing gets a moment to prove it.
+ if (action === "inside") await new Promise((done) => setTimeout(done, 200));
+ return until(
+ (expanded) => {
+ const state = window.__labE2E.menu();
+ return state.expanded === expanded ? state : null;
+ },
+ expanded,
+ `⋯ menu aria-expanded=${expanded} after ${action}`,
+ 5_000,
+ ).catch((error) => ({ error: error.message }));
+ };
+ const closed = await page(() => window.__labE2E.menu());
+ check("the fourth right item waits in a closed ⋯ menu", closed.found && closed.expanded === "false" && !closed.folded, JSON.stringify(closed));
+ const opened = await menu("toggle", "true");
+ check("⋯ opens onto the folded item", opened.folded === true, JSON.stringify(opened));
+ const escaped = await menu("escape", "false");
+ check("Escape closes ⋯ and hands focus back to its key", escaped.folded === false && escaped.focused, JSON.stringify(escaped));
+ await menu("toggle", "true");
+ const kept = await menu("inside", "true");
+ check("a press inside the menu keeps it open", kept.folded === true, JSON.stringify(kept));
+ const outside = await menu("outside", "false");
+ check("a press outside closes ⋯", outside.folded === false, JSON.stringify(outside));
+ await menu("toggle", "true");
+ await clickIn(0, "assistantAction:folded", "folded");
+ const folded = await settled(0, "assistantAction:folded", "folded item outcome");
+ const afterFolded = await page(() => window.__labE2E.composerText());
+ check("the folded item works from the menu", folded.text === "inserted" && afterFolded.includes("lab: sent from the ⋯ menu"), JSON.stringify([folded, afterFolded]));
+ await menu("escape", "false");
+
+ // --- dispatch round trips -------------------------------------------------
+ await clickIn(0, "assistantAction:left", "echo");
+ const echo = await settled(0, "assistantAction:left", "assistant echo");
+ check("plugin.call round-trips to the headless entry", echo.status === "ok" && echo.text === "echo ✓", JSON.stringify(echo));
+ await clickIn(0, "assistantAction:refuse", "refuse");
+ const refused = await settled(0, "assistantAction:refuse", "refuse outcome");
+ check("a plugin's own error code comes back unchanged", refused.status === "error" && refused.text === "LAB_REFUSED", JSON.stringify(refused));
+ const stallStarted = Date.now();
+ await clickIn(0, "entryExtra", "stall");
+ const stalled = await settled(0, "entryExtra", "stall outcome", 10_000);
+ const stallMs = Date.now() - stallStarted;
+ check("a stalled call ends at the host's budget", stalled.text === "PLUGIN_CALL_TIMEOUT" && stallMs < 4_500, `${JSON.stringify(stalled)} after ${stallMs}ms`);
+
+ const messageId = await page(() => window.__labE2E.one(window.__labE2E.turn(0), "entryExtra").querySelector("[data-lab-message]")?.getAttribute("data-lab-message") ?? "");
+ await clickIn(0, "entryExtra", "insert");
+ await settled(0, "entryExtra", "insert outcome");
+ await page(() => window.__labE2E.click(window.__labE2E.userRow(0), "userAction:right", "quote"));
+ await clickIn(null, "composerControl:left", "insert");
+ await settled(null, "composerControl:left", "composer insert outcome");
+ const draft = await until(
+ () => {
+ const text = window.__labE2E.composerText() ?? "";
+ return text.includes("> lab: probe ok") ? text : null;
+ },
+ null,
+ "quoted user message in the composer",
+ );
+ check(
+ "composer.insertText lands in the draft from every slot",
+ Boolean(messageId) && draft.includes(`lab: about ${messageId}`) && draft.includes("lab: hello from the composer"),
+ JSON.stringify(draft),
+ );
+ await clickIn(null, "composerControl:right", "echo");
+ const composerEcho = await settled(null, "composerControl:right", "composer echo");
+ check("a composer control round-trips plugin.call", composerEcho.text === "echo ✓", JSON.stringify(composerEcho));
+
+ // --- entryExtra height ------------------------------------------------------
+ const entryBlock = (action) =>
+ page((action) => {
+ const panel = window.__labE2E.one(window.__labE2E.turn(0), "entryExtra");
+ const block = panel?.closest(".pi-entry-extra-block");
+ const toggle = block?.querySelector(".pi-entry-extra-toggle");
+ if (action === "toggle") toggle?.click();
+ const viewport = block?.querySelector(".pi-entry-extra-viewport");
+ return {
+ toggle: Boolean(toggle),
+ expanded: toggle?.getAttribute("aria-expanded") ?? null,
+ clipped: viewport?.getAttribute("data-clipped") ?? null,
+ height: viewport?.clientHeight ?? -1,
+ grown: Boolean(panel?.querySelector("[data-lab-grown]")),
+ };
+ }, action);
+ const compact = await entryBlock("read");
+ check("a short entryExtra block has no host toggle", !compact.toggle && compact.height <= ENTRY_COLLAPSED_PX, JSON.stringify(compact));
+ await clickIn(0, "entryExtra", "grow");
+ const clipped = await until(
+ () => {
+ const block = window.__labE2E.one(window.__labE2E.turn(0), "entryExtra")?.closest(".pi-entry-extra-block");
+ const viewport = block?.querySelector(".pi-entry-extra-viewport");
+ return block?.querySelector(".pi-entry-extra-toggle") ? { height: viewport.clientHeight, clipped: viewport.getAttribute("data-clipped") } : null;
+ },
+ null,
+ "entryExtra toggle after Grow",
+ );
+ check("a grown block clamps at the collapsed height behind the host toggle", clipped.clipped === "true" && clipped.height <= ENTRY_COLLAPSED_PX, JSON.stringify(clipped));
+ const expanded = await entryBlock("toggle");
+ const expandedNow = await until(
+ () => {
+ const block = window.__labE2E.one(window.__labE2E.turn(0), "entryExtra")?.closest(".pi-entry-extra-block");
+ const viewport = block?.querySelector(".pi-entry-extra-viewport");
+ return viewport?.getAttribute("data-expanded") === "true" ? viewport.clientHeight : 0;
+ },
+ null,
+ "expanded entryExtra",
+ );
+ check("the host toggle expands the block", expandedNow > ENTRY_COLLAPSED_PX, JSON.stringify({ ...expanded, height: expandedNow }));
+
+ // --- crash isolation ------------------------------------------------------
+ const crashCounts = () =>
+ page(() => {
+ const turn = window.__labE2E.turn(0);
+ return {
+ labs: window.__labE2E.labs(document),
+ hostKeys: turn.querySelectorAll(".message-actions > .copy-btn, .message-actions > * > .copy-btn").length,
+ entryBlocks: turn.querySelectorAll(".pi-entry-extra-block").length,
+ composer: Boolean(document.querySelector(".composer-input")),
+ };
+ });
+ const before = await crashCounts();
+ await clickIn(0, "assistantAction:crash", "crash");
+ await clickIn(0, "entryExtra", "crash");
+ await clickIn(null, "composerControl:crash", "crash");
+ await until(
+ () => !document.querySelector('[data-lab="assistantAction:crash"], [data-lab="entryExtra"], [data-lab="composerControl:crash"]'),
+ null,
+ "crashed samples contained",
+ );
+ const after = await crashCounts();
+ const survivors = ["assistantAction:left", "assistantAction:right", "assistantAction:refuse", "entryExtra:notes", "composerControl:left", "composerControl:right"];
+ check("a crashing action item leaves the bar alone", !after.labs.includes("assistantAction:crash") && after.hostKeys === before.hostKeys, JSON.stringify([before.hostKeys, after.hostKeys]));
+ check("a crashing entryExtra block collapses alone", !after.labs.includes("entryExtra") && after.entryBlocks === before.entryBlocks - 1, JSON.stringify([before.entryBlocks, after.entryBlocks]));
+ check("a crashing composer control leaves the composer", !after.labs.includes("composerControl:crash") && after.composer, after.labs.join(","));
+ check("every other sample survives the crashes", survivors.every((lab) => after.labs.includes(lab)), after.labs.join(","));
+
+ // --- toolCard failure, fallback and cadence -------------------------------
+ await prompt(sessionId, "lab: probe fail");
+ const failed = await until(
+ () => {
+ const card = window.__labE2E.one(window.__labE2E.turn(1), "toolCard");
+ return card ? { status: card.getAttribute("data-lab-status"), error: card.querySelector("[data-lab-error]")?.textContent ?? "" } : null;
+ },
+ null,
+ "failed probe card",
+ );
+ check("a failed call reaches the card as toolError", failed.status === "error" && failed.error.includes("lab_probe failed on request: fail"), JSON.stringify(failed));
+
+ await prompt(sessionId, "lab: probe crash");
+ const crashRow = (await control.messages(sessionId)).findLast((message) => message.role === "tool" && message.toolName === PROBE_TOOL);
+ const fallback = await until(
+ (id) => {
+ const turn = window.__labE2E.turn(2);
+ if (!turn || !window.__labE2E.one(turn, "entryExtra")) return null;
+ return {
+ card: Boolean(window.__labE2E.one(turn, "toolCard")),
+ hostRow: Boolean(turn.querySelector(`.tool-row[data-message-id="${id}"]`)),
+ mounts: turn.querySelectorAll('[data-pi-slot="toolCard"]').length,
+ };
+ },
+ crashRow?.id,
+ "crash turn",
+ );
+ check("a throwing toolCard hands the call back to the host card", crashRow?.toolArgs?.mode === "crash" && !fallback.card && fallback.hostRow && fallback.mounts === 0, JSON.stringify({ ...fallback, row: crashRow?.id }));
+
+ // Record every committed status of the slow card, not just polled samples.
+ await page(() => {
+ const seen = [];
+ const observer = new MutationObserver(() => {
+ const status = window.__labE2E.one(window.__labE2E.turn(3), "toolCard")?.getAttribute("data-lab-status");
+ if (status && status !== seen.at(-1)) seen.push(status);
+ });
+ observer.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-lab-status"] });
+ window.__labE2E.slow = { seen, stop: () => observer.disconnect() };
+ return true;
+ });
+ await prompt(sessionId, "lab: probe slow");
+ const statuses = await until(
+ () => {
+ const { seen, stop } = window.__labE2E.slow;
+ if (seen.at(-1) !== "success") return null;
+ stop();
+ return seen;
+ },
+ null,
+ "slow card success",
+ );
+ check("a slow call's card goes from running to success", statuses[0] === "running" && statuses.at(-1) === "success", statuses.join(" → "));
+
+ // --- blockRenderer contract failures --------------------------------------
+ for (const [index, kind] of [[4, "crash"], [5, "tall"]]) {
+ await prompt(sessionId, `lab: chart ${kind}`);
+ const host = await until(
+ (index) => {
+ const turn = window.__labE2E.turn(index);
+ const block = turn?.querySelector(".code-block");
+ if (!block) return null;
+ return {
+ lang: block.querySelector(".code-block-lang")?.textContent,
+ text: block.textContent,
+ plugin: Boolean(window.__labE2E.one(turn, "blockRenderer")),
+ };
+ },
+ index,
+ `${kind} chart fallback`,
+ );
+ check(`a ${kind} chart falls back to the host code block`, host.lang === `${LAB}:chart` && host.text.includes(kind) && !host.plugin, JSON.stringify(host));
+ }
+ const firstChart = await page(() => Boolean(window.__labE2E.one(window.__labE2E.turn(0), "blockRenderer")));
+ check("the healthy chart keeps its plugin block", firstChart);
+
+ // --- unload and reload ----------------------------------------------------
+ await page((id) => window.piDesktop.invoke("pi-desktop/plugin/disable", id), LAB);
+ const unloaded = await until(
+ () => {
+ if (document.querySelector("[data-lab], [data-pi-plugin]")) return null;
+ const turn = window.__labE2E.turn(0);
+ return {
+ sheets: document.querySelectorAll("style[data-pi-plugin-style]").length,
+ hostChart: turn.querySelector(".code-block .code-block-lang")?.textContent ?? null,
+ overflow: document.querySelectorAll(".pi-action-overflow").length,
+ entryStacks: document.querySelectorAll(".pi-entry-extra-stack").length,
+ };
+ },
+ null,
+ "lab samples removed",
+ );
+ check(
+ "disabling the plugin takes every sample, menu, block and sheet with it",
+ unloaded.sheets === 0 && unloaded.hostChart === `${LAB}:chart` && unloaded.overflow === 0 && unloaded.entryStacks === 0,
+ JSON.stringify(unloaded),
+ );
+ await page((id) => window.piDesktop.invoke("pi-desktop/plugin/enable", id), LAB);
+ const reloaded = await until(
+ () => {
+ const labs = window.__labE2E.labs(document);
+ return labs.includes("entryExtra") && labs.includes("composerControl:crash") ? [...new Set(labs)] : null;
+ },
+ null,
+ "lab samples back",
+ 30_000,
+ );
+ check("re-enabling loads the lab again with fresh samples", reloaded.includes("toolCard") && reloaded.includes("blockRenderer"), reloaded.join(","));
+ return { sessionId };
+}
+
+function sameSet(actual, expected) {
+ return actual.length === expected.length && expected.every((item) => actual.includes(item));
+}
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/seed.mjs b/apps/desktop/test/e2e/plugin-ui-slots/seed.mjs
new file mode 100644
index 000000000..08fe4b9f3
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/seed.mjs
@@ -0,0 +1,37 @@
+// Seeds the E2E data dir through host-core's own JSON-RPC (the MCP control
+// plane blocks provider writes): a provider row pointing at the stub model
+// and the UI Slots Lab as a development plugin, which a dev load enables with
+// the permissions its manifest declares.
+import { cpSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { Host } from "../../../../../scripts/e2e/host.mjs";
+
+export async function seed({ hostBin, dataDir, runRoot, labDir, stubPort }) {
+ const project = join(runRoot, "project");
+ const pluginDir = join(runRoot, "plugins", "ui-slots-lab");
+ mkdirSync(project, { recursive: true });
+ writeFileSync(join(project, "README.md"), "UI slots E2E project\n");
+ // The dev plugin is watched from its directory: load a copy, not the repo.
+ cpSync(labDir, pluginDir, { recursive: true });
+
+ const host = new Host(hostBin, dataDir);
+ await host.start();
+ try {
+ const created = await host.call("providers.create", {
+ name: "E2E stub",
+ type: "openai_compatible",
+ baseUrl: `http://127.0.0.1:${stubPort}/v1`,
+ apiStyle: "chat_completions",
+ authKind: "api_key",
+ secretValue: "sk-e2e",
+ models: [{ id: "stub-1", contextWindow: 128000, maxTokens: 4096, thinkingLevels: ["off"] }],
+ defaultModelId: "stub-1",
+ });
+ const providerId = created.provider?.id ?? created.id;
+ await host.call("settings.set", { defaultProviderId: providerId, defaultModelId: "stub-1", defaultMode: "agent" });
+ const loaded = await host.call("plugins.loadDev", { path: pluginDir });
+ return { project: realpathSync(project), pluginId: loaded?.plugin?.id };
+ } finally {
+ await host.stop();
+ }
+}
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs b/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs
new file mode 100644
index 000000000..81f1c67f4
--- /dev/null
+++ b/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs
@@ -0,0 +1,99 @@
+// Deterministic OpenAI-compatible Chat Completions stub for the UI slots E2E.
+// The latest user prompt names the scenario:
+// "lab: probe <mode>" -> activate the lab's tool through ToolSearch when it
+// is deferred, call it with that mode, then answer
+// "lab: chart <kind>" -> answer with a `lab.ui-slots:chart` fence whose
+// first line is <kind> (`crash`, `tall`)
+// The first probe answer also carries a normal chart, so one turn fills every
+// transcript slot.
+import { createServer } from "node:http";
+
+export const PROBE_TOOL = "plugin_lab_ui_slots_lab_probe";
+
+const CHART = "```lab.ui-slots:chart\nalpha,3\nbeta,5\n```";
+
+const ANSWERS = {
+ ok: `Probe answered.\n\n${CHART}\n`,
+ fail: "The probe failed on request.",
+ crash: "The probe answered; its card crashes on request.",
+ slow: "The slow probe answered.",
+};
+
+function textOf(content) {
+ return typeof content === "string" ? content : (content ?? []).map((part) => part.text ?? "").join("");
+}
+
+/** The latest user prompt and the tools called since it. */
+function turnState(messages) {
+ const lastUser = messages.findLastIndex((message) => message.role === "user");
+ const called = messages
+ .slice(lastUser + 1)
+ .flatMap((message) => message.tool_calls ?? [])
+ .map((call) => call.function?.name);
+ return { prompt: textOf(messages[lastUser]?.content).trim().toLowerCase(), called: new Set(called) };
+}
+
+function reply(payload) {
+ const { prompt, called } = turnState(payload.messages ?? []);
+ const tools = new Set((payload.tools ?? []).map((tool) => tool.function?.name));
+ const probe = /lab: probe (ok|fail|crash|slow)/.exec(prompt)?.[1];
+ if (probe) {
+ if (called.has(PROBE_TOOL)) return { text: ANSWERS[probe] };
+ if (tools.has(PROBE_TOOL)) return { call: PROBE_TOOL, args: { mode: probe, text: probe } };
+ if (tools.has("ToolSearch") && !called.has("ToolSearch")) {
+ return { call: "ToolSearch", args: { query: PROBE_TOOL } };
+ }
+ return { text: "lab_probe is not available to this turn." };
+ }
+ const chart = /lab: chart (crash|tall)/.exec(prompt)?.[1];
+ if (chart) return { text: `A ${chart} chart:\n\n\`\`\`lab.ui-slots:chart\n${chart}\nalpha,1\n\`\`\`\n` };
+ return { text: "Hello from the UI slots stub." };
+}
+
+/** Starts the stub on a loopback port; resolves with its port and a closer. */
+export async function startStubModel() {
+ let counter = 0;
+ const server = createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk) => (body += chunk));
+ req.on("end", () => {
+ if (!req.url.endsWith("/chat/completions")) {
+ res.writeHead(404);
+ res.end("{}");
+ return;
+ }
+ const payload = JSON.parse(body || "{}");
+ const id = `chatcmpl-${++counter}`;
+ const base = { id, object: "chat.completion.chunk", created: 1, model: payload.model };
+ const usage = { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 };
+ const answer = reply(payload);
+ const delta = answer.call
+ ? {
+ role: "assistant",
+ tool_calls: [{
+ index: 0,
+ id: `call_${counter}`,
+ type: "function",
+ function: { name: answer.call, arguments: JSON.stringify(answer.args) },
+ }],
+ }
+ : { role: "assistant", content: answer.text };
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
+ for (const chunk of [
+ { ...base, choices: [{ index: 0, delta, finish_reason: null }] },
+ { ...base, choices: [{ index: 0, delta: {}, finish_reason: answer.call ? "tool_calls" : "stop" }], usage },
+ ]) {
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
+ }
+ res.end("data: [DONE]\n\n");
+ });
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ return {
+ port: server.address().port,
+ close: () => new Promise((resolve) => server.close(resolve)),
+ };
+}
diff --git a/apps/desktop/test/helpers/composer-toolbar.mjs b/apps/desktop/test/helpers/composer-toolbar.mjs
new file mode 100644
index 000000000..4a0a1e684
--- /dev/null
+++ b/apps/desktop/test/helpers/composer-toolbar.mjs
@@ -0,0 +1,79 @@
+/**
+ * The production composer toolbar for slot tests: an idle agent session's
+ * props, its model menu closed, rendered outside any session provider as
+ * the composer is.
+ */
+import { createElement } from "react";
+
+const USAGE = { inputTokens: 1_000, outputTokens: 200, totalTokens: 1_200 };
+const noop = () => {};
+const idle = async () => {};
+
+export const TOOLBAR_PROPS = {
+ t: (key) => key,
+ mode: "agent",
+ planningLive: false,
+ providerId: "provider-1",
+ modelId: "model-1",
+ thinkingLevel: "off",
+ composerPermissionMode: "ask",
+ permissionOpen: false,
+ setPermissionOpen: noop,
+ controlsBlocked: false,
+ pasting: false,
+ pickAndAttach: idle,
+ configureActiveSession: idle,
+ showToast: noop,
+ modelMenu: {
+ open: false,
+ setOpen: noop,
+ view: "root",
+ query: "",
+ setQuery: noop,
+ modelHighlight: -1,
+ setModelHighlight: noop,
+ thinkingHighlight: -1,
+ setThinkingHighlight: noop,
+ rootMenuRef: { current: null },
+ modelSearchRef: { current: null },
+ modelListRef: { current: null },
+ thinkingListRef: { current: null },
+ modelGroups: [],
+ thinkingMenuLevels: [],
+ showView: noop,
+ selectModel: noop,
+ commitThinkingLevel: noop,
+ selectThinkingLevel: noop,
+ onMenuKeyDown: noop,
+ },
+ modelLabel: "Model",
+ thinkingLabel: "Off",
+ contextUsage: { usage: USAGE, turnUsage: USAGE, contextWindow: 200_000, tools: [] },
+ enhancementDraft: "",
+ value: "",
+ modelReady: true,
+ sendBlocked: false,
+ enhancingPrompt: false,
+ enhancementUndoText: null,
+ enhancePrompt: idle,
+ undoPromptEnhancement: noop,
+ clearEnhancementError: noop,
+ runActive: false,
+ hasDraftContent: false,
+ abort: idle,
+ submit: idle,
+};
+
+/** A `() => html` of the toolbar, for a `slotSsr` harness. */
+export async function composerToolbar(t, ssr) {
+ const hadWindow = "window" in globalThis;
+ const { window } = globalThis;
+ // The toolbar reads the shortcut platform off the preload bridge.
+ globalThis.window = { piDesktop: { platform: "darwin" } };
+ t.after(() => {
+ if (hadWindow) globalThis.window = window;
+ else delete globalThis.window;
+ });
+ const { ComposerToolbar } = await ssr.load("/src/features/chat/composer/ComposerToolbar.tsx");
+ return () => ssr.render(createElement(ComposerToolbar, TOOLBAR_PROPS), { sessionId: null });
+}
diff --git a/apps/desktop/test/helpers/slot-ssr.mjs b/apps/desktop/test/helpers/slot-ssr.mjs
new file mode 100644
index 000000000..00325ef92
--- /dev/null
+++ b/apps/desktop/test/helpers/slot-ssr.mjs
@@ -0,0 +1,112 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { createServer } from "vite";
+import { fileURLToPath } from "node:url";
+
+/**
+ * Slot outlets rendered through Vite SSR with the production modules: the
+ * app-wide slot registry, its React glue and the host components that mount
+ * the slots. Registrations go into the registry instance those modules read,
+ * and every one made through `register` is disposed when the test ends.
+ *
+ * Server rendering runs no effects: what a test sees is the first frame of a
+ * mount, before any measuring, timer or listener. Behavior that needs those
+ * is covered at the logic layer or in the Electron E2E.
+ */
+export async function slotSsr(t) {
+ const server = await createServer({
+ root: fileURLToPath(new URL("../..", import.meta.url)),
+ configFile: false,
+ logLevel: "silent",
+ server: { middlewareMode: true, hmr: false, ws: false },
+ esbuild: { jsx: "automatic" },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ const originalDocument = globalThis.document;
+ // `useThemeMode` reads the theme off the document during render.
+ globalThis.document = { documentElement: { dataset: {} } };
+ const disposers = [];
+ t.after(async () => {
+ for (const dispose of disposers.splice(0)) dispose();
+ globalThis.document = originalDocument;
+ await server.close();
+ });
+
+ const i18n = createInstance();
+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });
+ const load = (path) => server.ssrLoadModule(path);
+ const { slotRegistry } = await load("/src/plugins/renderer-slots/registry.ts");
+ const { SlotSessionProvider } = await load("/src/plugins/renderer-slots/use-slots.tsx");
+
+ return {
+ load,
+ registry: slotRegistry,
+ /** Register as `pluginId` would through `pi.slots.register`. */
+ register(pluginId, registration, ownTools = []) {
+ const dispose = slotRegistry.register(pluginId, registration, ownTools);
+ disposers.push(dispose);
+ return dispose;
+ },
+ /** Dispose every registration made so far. */
+ clear() {
+ for (const dispose of disposers.splice(0)) dispose();
+ },
+ /**
+ * Markup of `element` inside the providers the transcript gives it;
+ * `sessionId: null` leaves the session provider out.
+ */
+ render(element, { sessionId = "session-1" } = {}) {
+ const inSession =
+ sessionId === null ? element : createElement(SlotSessionProvider, { sessionId }, element);
+ return renderToStaticMarkup(createElement(I18nextProvider, { i18n }, inSession));
+ },
+ };
+}
+
+/**
+ * A slot component that renders the props it was given as JSON, so a test
+ * reads the exact projection off the markup.
+ */
+export function propsProbe(label) {
+ return function Probe(props) {
+ return createElement("output", { "data-probe": label }, JSON.stringify(props));
+ };
+}
+
+/** The JSON each probe with `label` rendered, in document order. */
+export function probed(html, label) {
+ return [...html.matchAll(/<output data-probe="([^"]*)">([^<]*)<\/output>/g)]
+ .filter((match) => match[1] === label)
+ .map((match) => parseProbe(match[2]));
+}
+
+/** The props a probe rendered, from the escaped text of its `<output>`. */
+export function parseProbe(text) {
+ return JSON.parse(unescapeHtml(text));
+}
+
+/** `html` with every probe emptied, so a test can compare the host markup. */
+export function withoutProbeProps(html) {
+ return html.replaceAll(/(<output data-probe="[^"]*">)[^<]*(<\/output>)/g, "$1$2");
+}
+
+/** `[pluginId, slot]` of every slot mount in `html`, in document order. */
+export function slotMounts(html) {
+ return [...html.matchAll(/data-pi-plugin="([^"]*)" data-pi-slot="([^"]*)"/g)].map((match) => [
+ match[1],
+ match[2],
+ ]);
+}
+
+function unescapeHtml(text) {
+ return text
+ .replaceAll("&quot;", '"')
+ .replaceAll("&#x27;", "'")
+ .replaceAll("&lt;", "<")
+ .replaceAll("&gt;", ">")
+ .replaceAll("&amp;", "&");
+}
diff --git a/apps/desktop/test/plugin-action-slots.test.mjs b/apps/desktop/test/plugin-action-slots.test.mjs
index eca998797..ea8f05b00 100644
--- a/apps/desktop/test/plugin-action-slots.test.mjs
+++ b/apps/desktop/test/plugin-action-slots.test.mjs
@@ -1,160 +1,219 @@
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,
+import { createElement } from "react";
+import { catalogs } from "@pi-desktop/i18n";
+import { parseProbe, probed, propsProbe, slotMounts, slotSsr } from "./helpers/slot-ssr.mjs";
+
+/*
+ * The action-bar slots `userAction` and `assistantAction`
+ * (`docs/plugin-plan/ui/user-action/`, `docs/plugin-plan/ui/assistant-action/`)
+ * rendered with the production modules. A bar is its left items, its host
+ * keys, then its right items; a side shows three items and folds the rest
+ * into its own ⋯ menu at the outer end of the bar; every item is fed
+ * `{ message, messageId, sessionId, position }`. Server rendering is the
+ * first frame, where every ⋯ menu is closed: opening one, closing it on
+ * Escape or an outside press, and a throwing item disappearing alone are
+ * covered by the Electron E2E.
+ */
+
+const { chat } = catalogs.en;
+const USER_KEYS = [chat.copy, chat.editMessage, chat.deleteMessage];
+const REPLY_KEYS = [chat.copy, chat.forkResponse, chat.retry];
+
+const USER = {
+ id: "u1",
+ role: "user",
content: "hello",
- createdAt: "2026-09-17T00:00:00.000Z",
- ...extra,
-});
+ status: "complete",
+ createdAt: "2026-09-24T00:00:00.000Z",
+};
-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);
-});
+/** The prompt answered in two parts around a tool call. */
+function conversation(overrides = {}) {
+ return [
+ USER,
+ { id: "a1", role: "assistant", content: "Let me look.", status: "complete", createdAt: "2026-09-24T00:00:01.000Z" },
+ {
+ id: "t1",
+ role: "tool",
+ content: "",
+ status: "complete",
+ createdAt: "2026-09-24T00:00:02.000Z",
+ toolName: "read",
+ toolCallId: "call-1",
+ toolArgs: { path: "a.txt" },
+ toolStatus: "success",
+ toolResult: "x",
+ },
+ { id: "a2", role: "assistant", content: "It says x.", status: "complete", createdAt: "2026-09-24T00:00:03.000Z", ...overrides },
+ ];
+}
-test("the action projection keeps the row's real role", () => {
- assert.equal(actionSlotMessage(message("assistant")).role, "assistant");
- assert.equal(actionSlotMessage(message("user")).role, "user");
-});
+async function bars(t) {
+ const ssr = await slotSsr(t);
+ const { MessageRow } = await ssr.load("/src/features/chat/transcript/MessageRow.tsx");
+ const { AssistantTurn } = await ssr.load("/src/features/chat/transcript/AssistantTurn.tsx");
+ const { buildTranscriptEntries } = await ssr.load("/src/lib/assistant-turns.ts");
+ return {
+ ...ssr,
+ row: (message = USER) => ssr.render(createElement(MessageRow, { message, isRunning: false })),
+ turn: (messages = conversation(), isActive = false) => {
+ const { entries } = buildTranscriptEntries(messages);
+ const entry = entries.find((candidate) => candidate.kind === "assistant-turn");
+ return ssr.render(createElement(AssistantTurn, { entry, isActive }));
+ },
+ };
+}
-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: [] });
-});
+/**
+ * What the first action bar in `html` shows, in order: a host key by its
+ * label, a plugin item as `probe:position`, a ⋯ menu as `⋯side`.
+ */
+function barOf(html) {
+ const start = html.indexOf('<div class="message-actions">');
+ assert.ok(start >= 0, "the row has an action bar");
+ const end = html.indexOf('<div class="pi-entry-extra-stack">', start);
+ const bar = html.slice(start, end < 0 ? undefined : end);
+ const shown = [];
+ const token =
+ /<div class="pi-action-overflow" data-side="(\w+)">|<output data-probe="([^"]*)">([^<]*)<\/output>|<button\b([^>]*)>/g;
+ for (const [, menuSide, probe, props, button] of bar.matchAll(token)) {
+ if (menuSide) shown.push(`⋯${menuSide}`);
+ else if (probe) shown.push(`${probe}:${parseProbe(props).position}`);
+ else if (!button.includes("pi-action-overflow-btn")) shown.push(button.match(/aria-label="([^"]*)"/)[1]);
+ }
+ return shown;
+}
-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);
-});
+/** `html` without its plugin items and ⋯ menus: the host's own markup. */
+function hostOnly(html) {
+ return html
+ .replaceAll(/<div class="pi-plugin-slot"[^>]*><output data-probe="[^"]*">[^<]*<\/output><\/div>/g, "")
+ .replaceAll(/<div class="pi-action-overflow" data-side="\w+"><button\b[^>]*>⋯<\/button><\/div>/g, "");
+}
-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("a bar keeps exactly its host keys when no plugin adds to its slot", async (t) => {
+ const ssr = await bars(t);
+ const row = ssr.row();
+ const turn = ssr.turn();
+ assert.deepEqual(barOf(row), USER_KEYS);
+ assert.deepEqual(barOf(turn), REPLY_KEYS);
+
+ ssr.register("demo.a", { slot: "assistantAction", component: propsProbe("reply") });
+ assert.equal(ssr.row(), row, "an assistantAction item is not on a user's bar");
+ ssr.clear();
+ ssr.register("demo.a", { slot: "userAction", component: propsProbe("user") });
+ assert.equal(ssr.turn(), turn, "a userAction item is not on a reply's bar");
});
-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("items sit around the host keys, the left side before them and the right after", async (t) => {
+ const ssr = await bars(t);
+ const plain = ssr.row();
+ ssr.register("demo.a", { slot: "userAction", component: propsProbe("a") });
+ ssr.register("demo.b", { slot: "userAction", component: propsProbe("b"), positions: ["left"] });
+ ssr.register("demo.c", { slot: "userAction", component: propsProbe("c"), positions: ["right"] });
+ const html = ssr.row();
+
+ assert.deepEqual(barOf(html), ["a:left", "b:left", ...USER_KEYS, "a:right", "c:right"]);
+ assert.deepEqual(slotMounts(html), [
+ ["demo.a", "userAction"],
+ ["demo.b", "userAction"],
+ ["demo.a", "userAction"],
+ ["demo.c", "userAction"],
+ ]);
+ assert.equal(hostOnly(html), plain, "the host keys and the row around them are untouched");
+
+ const message = { id: "u1", role: "user", content: "hello", createdAt: USER.createdAt };
+ assert.deepEqual(probed(html, "a"), [
+ { message, messageId: "u1", sessionId: "session-1", position: "left" },
+ { message, messageId: "u1", sessionId: "session-1", position: "right" },
+ ]);
});
-test("ActionBarSlots keeps the finalized 【left】【host】【right】 shape", () => {
- const source = readFileSync(
- src("features/chat/transcript/ActionBarSlots.tsx"),
- "utf8",
+test("past three items a side folds the rest into a ⋯ menu at the bar's outer end", async (t) => {
+ const ssr = await bars(t);
+ const plain = ssr.turn();
+ const left = ["l1", "l2", "l3", "l4"].map((label) =>
+ ssr.register("demo.a", { slot: "assistantAction", component: propsProbe(label), positions: ["left"] }),
);
- // 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\}>/);
-});
+ for (const label of ["r1", "r2", "r3", "r4", "r5"]) {
+ ssr.register("demo.b", { slot: "assistantAction", component: propsProbe(label), positions: ["right"] });
+ }
+ const html = ssr.turn();
-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.deepEqual(barOf(html), [
+ "⋯left", "l1:left", "l2:left", "l3:left",
+ ...REPLY_KEYS,
+ "r1:right", "r2:right", "r3:right", "⋯right",
+ ]);
+ for (const side of ["left", "right"]) {
assert.ok(
- typeof catalog.chat?.actionSlotMore === "string" &&
- catalog.chat.actionSlotMore.length > 0,
- `${name} is missing chat.actionSlotMore`,
+ html.includes(
+ `<div class="pi-action-overflow" data-side="${side}"><button type="button" class="copy-btn icon pi-action-overflow-btn" aria-label="${chat.actionSlotMore}" title="${chat.actionSlotMore}" aria-expanded="false">⋯</button></div>`,
+ ),
+ `the ${side} menu starts closed, with no panel`,
);
}
+ for (const folded of ["l4", "r4", "r5"]) assert.deepEqual(probed(html, folded), [], folded);
+ assert.equal(hostOnly(html), plain, "the host keys never fold");
+
+ // A side reflows as soon as its registrations change.
+ left[0]();
+ assert.deepEqual(barOf(ssr.turn()), [
+ "l2:left", "l3:left", "l4:left",
+ ...REPLY_KEYS,
+ "r1:right", "r2:right", "r3:right", "⋯right",
+ ]);
});
-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"/);
+test("a reply's items act on the answer message the host keys act on", async (t) => {
+ const ssr = await bars(t);
+ ssr.register("demo.a", { slot: "assistantAction", component: propsProbe("reply"), positions: ["right"] });
+ const html = ssr.turn();
+ assert.deepEqual(barOf(html), [...REPLY_KEYS, "reply:right"]);
+ // Regenerate and Branch act on the last answer message; Copy copies the
+ // whole turn's text.
+ assert.deepEqual(probed(html, "reply"), [
+ {
+ message: {
+ id: "a2",
+ role: "assistant",
+ content: "Let me look.\n\nIt says x.",
+ createdAt: "2026-09-24T00:00:03.000Z",
+ },
+ messageId: "a2",
+ sessionId: "session-1",
+ position: "right",
+ },
+ ]);
+ assert.deepEqual(
+ probed(ssr.turn(conversation({ status: "streaming" }), true), "reply"),
+ [],
+ "a reply still streaming has no bar to add to",
+ );
});
-test("slot outlets render plugin components as elements, never direct calls", () => {
- // A direct entry.component(props) call runs the plugin's hooks inside the
- // host component's hook chain → React "Invalid hook call". Every outlet
- // must hand the component to createElement so it owns its fiber.
- const outlets = {
- "features/chat/transcript/ActionBarSlots.tsx": /createElement\(\s*entry\.component/,
- "features/chat/transcript/EntryExtraStack.tsx": /createElement\(\s*entry\.component/,
- "features/chat/transcript/PluginToolCard.tsx": /createElement\(\s*entry\.component/,
- "components/PluginBlockRenderer.tsx": /createElement\(\s*entry\.component/,
- "features/chat/composer/ComposerToolbar.tsx": /createElement\(\s*entry\.component/,
- "components/Composer.tsx": /createElement\(\s*\n?\s*activeTrigger\.entry\.component/,
+test("a session message carries userAction around Copy; other rows keep a plugin-free bar", async (t) => {
+ const ssr = await bars(t);
+ const system = { ...USER, id: "s1", role: "system" };
+ const plainSystem = ssr.row(system);
+ ssr.register("demo.a", { slot: "userAction", component: propsProbe("user") });
+
+ const delivered = {
+ ...USER,
+ sessionMessage: {
+ messageId: "d1",
+ sourceSessionId: "session-0",
+ sourceTitle: "Parent review",
+ targetSessionId: "session-1",
+ kind: "task",
+ },
};
- for (const [file, pattern] of Object.entries(outlets)) {
- const source = readFileSync(src(file), "utf8");
- assert.match(source, pattern, `${file} must render via createElement`);
- assert.doesNotMatch(source, /entry\.component\(\{/, `${file} must not call entry.component directly`);
- }
+ const html = ssr.row(delivered);
+ assert.deepEqual(barOf(html), ["user:left", chat.copy, "user:right"]);
+ assert.deepEqual(
+ probed(html, "user").map((props) => props.message.role),
+ ["user", "user"],
+ );
+ assert.equal(ssr.row(system), plainSystem);
});
diff --git a/apps/desktop/test/plugin-block-renderer-slot.test.mjs b/apps/desktop/test/plugin-block-renderer-slot.test.mjs
index ffbd39642..e7e2af846 100644
--- a/apps/desktop/test/plugin-block-renderer-slot.test.mjs
+++ b/apps/desktop/test/plugin-block-renderer-slot.test.mjs
@@ -1,100 +1,96 @@
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));
+import { createElement } from "react";
+import { probed, propsProbe, slotSsr } from "./helpers/slot-ssr.mjs";
-const here = dirname(fileURLToPath(import.meta.url));
-const src = (relative) => join(here, "..", "src", relative);
+/*
+ * The keyed `blockRenderer` slot (`docs/plugin-plan/ui/block-renderer/`)
+ * rendered with the production modules: a closed fence whose language a
+ * plugin registered becomes that plugin's block, handed the fence's tag and
+ * text; every other fence keeps the host block. Server rendering is the
+ * first frame of a mount: a renderer that throws or draws past the 4000px
+ * clamp handing the fence back to the host block is covered by the Electron
+ * E2E.
+ */
-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");
+const FENCE = "```Demo.Lab:Chart\na,b\n1,2\n```";
+const SOURCE = `Intro.\n\n${FENCE}\n\nAfter.`;
+const START = SOURCE.indexOf(FENCE);
+const END = START + FENCE.length;
-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");
-});
+async function blocks(t) {
+ const ssr = await slotSsr(t);
+ const { Markdown } = await ssr.load("/src/components/Markdown.tsx");
+ const helpers = await ssr.load("/src/lib/block-renderer.ts");
+ return {
+ ...ssr,
+ ...helpers,
+ markdown: (source = SOURCE) => ssr.render(createElement(Markdown, { source })),
+ claim: (language = "demo.lab:chart") =>
+ ssr.register("demo.lab", { slot: "blockRenderer", language, component: propsProbe("block") }),
+ };
+}
-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);
-});
+/** The host code block in `html`, up to the paragraph after it. */
+function hostBlock(html) {
+ const start = html.indexOf('<div class="code-block"');
+ assert.ok(start >= 0, "the fence renders as the host code block");
+ return html.slice(start, html.indexOf("<p ", start));
+}
-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("a closed fence in a claimed language becomes the plugin's block", async (t) => {
+ const ssr = await blocks(t);
+ const plain = ssr.markdown();
+ const host = hostBlock(plain);
+ assert.ok(
+ host.startsWith(`<div class="code-block" data-source-start="${START}" data-source-end="${END}">`),
+ "the host block is anchored on the fence's span of the message",
);
-});
-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");
+
+ const dispose = ssr.claim();
+ const html = ssr.markdown();
+ const [before, after] = plain.split(host);
+ assert.ok(html.startsWith(before) && html.endsWith(after), "the text around the fence is untouched");
assert.match(
- source,
- /closedFence \? blockRendererCandidate\(info\?\.lang \?\? ""\) : undefined/,
- "an unclosed fence never resolves a registration",
+ html.slice(before.length, html.length - after.length),
+ new RegExp(
+ `^<div class="pi-plugin-block-renderer" style="max-height:4000px" data-source-start="${START}" data-source-end="${END}">` +
+ '<div class="pi-plugin-slot" data-pi-plugin="demo.lab" data-pi-slot="blockRenderer">' +
+ '<output data-probe="block">[^<]*</output></div></div>$',
+ ),
+ "the host clamp keeps the fence's anchor for search and holds the plugin's mount",
);
- 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",
+ assert.deepEqual(
+ probed(html, "block"),
+ [{ language: "Demo.Lab:Chart", source: "a,b\n1,2" }],
+ "the tag as written, the text without the closing newline",
);
+
+ dispose();
+ assert.equal(ssr.markdown(), plain, "the host block is back once the renderer leaves");
});
-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("open fences, host languages and unclaimed tags keep the host block", async (t) => {
+ const ssr = await blocks(t);
+ const cases = [
+ ["a fence still streaming", "```Demo.Lab:Chart\na,b\n1,2\n"],
+ ["a host language", "```json\n{}\n```"],
+ ["a diagram", "```mermaid\ngraph TD\nA-->B\n```"],
+ ["a tag the plugin did not register", "```demo.lab:table\na\n```"],
+ ["the same tag under another plugin", "```demo.other:chart\na\n```"],
+ ];
+ const plain = cases.map(([, source]) => ssr.markdown(source));
+ ssr.claim();
+ cases.forEach(([label, source], index) => {
+ assert.equal(ssr.markdown(source), plain[index], label);
+ });
});
-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/,
- );
+test("only a prefixed tag is looked up, and only past 4000px is a block too tall", async (t) => {
+ const { BLOCK_RENDERER_MAX_HEIGHT_PX, blockRendererCandidate, blockRendererOverflow } = await blocks(t);
+ const candidates = ["json", "mermaid", "", "demo:chart", " Demo.Lab:Chart "].map(blockRendererCandidate);
+ assert.deepEqual(candidates, [undefined, undefined, undefined, "demo:chart", "demo.lab:chart"]);
+
+ assert.equal(BLOCK_RENDERER_MAX_HEIGHT_PX, 4000);
+ assert.deepEqual([3_999, 4_000, 4_001].map(blockRendererOverflow), [false, false, true]);
});
diff --git a/apps/desktop/test/plugin-composer-slots.test.mjs b/apps/desktop/test/plugin-composer-slots.test.mjs
index cbc522b15..c81fa1b2d 100644
--- a/apps/desktop/test/plugin-composer-slots.test.mjs
+++ b/apps/desktop/test/plugin-composer-slots.test.mjs
@@ -1,224 +1,91 @@
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));
+import { composerToolbar } from "./helpers/composer-toolbar.mjs";
+import { parseProbe, probed, propsProbe, slotMounts, slotSsr } from "./helpers/slot-ssr.mjs";
-const here = dirname(fileURLToPath(import.meta.url));
-const src = (relative) => join(here, "..", "src", relative);
+/*
+ * The composer's `composerControl` slot (`docs/plugin-plan/ui/composer/`)
+ * rendered with the production toolbar. The host controls keep their places
+ * and their order: a plugin's controls sit after the host's left row and
+ * before the host's right row, in registration order, fed only the side they
+ * sit on. Server rendering is the first frame: a control that throws
+ * disappearing alone is covered by the Electron E2E, and the draft actions a
+ * control dispatches by the dispatch channel's tests.
+ */
-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");
+/** The toolbar's own controls below, by label. */
+const HOST_LEFT = ["chat.addFiles", "settings.mode", "chat.permissionMode"];
+const HOST_RIGHT = ["context", "chat.model: Model. chat.reasoningLevel: Off", "chat.enhancePrompt", "chat.send"];
-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");
-});
+async function composer(t) {
+ const ssr = await slotSsr(t);
+ return { ...ssr, toolbar: await composerToolbar(t, ssr) };
+}
-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);
-});
+/**
+ * What each toolbar side shows, in order: a host control by its label, a
+ * plugin control as `probe:position`.
+ */
+function sidesOf(html) {
+ const right = html.indexOf('<div class="composer-right">');
+ assert.ok(right >= 0, "the toolbar has a right side");
+ const side = (part) => {
+ const shown = [];
+ const token = /<output data-probe="([^"]*)">([^<]*)<\/output>|<button\b([^>]*)>/g;
+ for (const [, probe, props, button] of part.matchAll(token)) {
+ if (probe) shown.push(`${probe}:${parseProbe(props).position}`);
+ // The context meter is labeled with its live numbers.
+ else if (button.includes("context-inspector-trigger")) shown.push("context");
+ else shown.push(button.match(/aria-label="([^"]*)"/)[1]);
+ }
+ return shown;
+ };
+ return { left: side(html.slice(0, right)), right: side(html.slice(right)) };
+}
-test("plugin trigger items insert as #label chips", () => {
- assert.equal(formatPluginTriggerInsert("alpha"), "#alpha ");
-});
+/** `html` without its plugin controls: the host's own markup. */
+function hostOnly(html) {
+ return html.replaceAll(/<div class="pi-plugin-slot"[^>]*><output data-probe="[^"]*">[^<]*<\/output><\/div>/g, "");
+}
-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 toolbar is the host's own until a plugin adds a control", async (t) => {
+ const ssr = await composer(t);
+ const plain = ssr.toolbar();
+ assert.deepEqual(sidesOf(plain), { left: HOST_LEFT, right: HOST_RIGHT });
+ ssr.register("demo.a", { slot: "userAction", component: propsProbe("user") });
+ assert.equal(ssr.toolbar(), plain, "a control of another slot is not on the toolbar");
});
-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("controls follow the host's left row and lead its right row, in registration order", async (t) => {
+ const ssr = await composer(t);
+ const plain = ssr.toolbar();
+ ssr.register("demo.a", { slot: "composerControl", component: propsProbe("a") });
+ ssr.register("demo.b", { slot: "composerControl", component: propsProbe("b"), positions: ["left"] });
+ ssr.register("demo.c", { slot: "composerControl", component: propsProbe("c"), positions: ["right"] });
+ const html = ssr.toolbar();
-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.deepEqual(sidesOf(html), {
+ left: [...HOST_LEFT, "a:left", "b:left"],
+ right: ["a:right", "c:right", ...HOST_RIGHT],
+ });
+ assert.deepEqual(slotMounts(html), [
+ ["demo.a", "composerControl"],
+ ["demo.b", "composerControl"],
+ ["demo.a", "composerControl"],
+ ["demo.c", "composerControl"],
]);
- 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, and insert bridge", () => {
- const composer = readFileSync(src("components/Composer.tsx"), "utf8");
- assert.match(composer, /useComposerPluginTrigger\(/);
- assert.match(composer, /useComposerPluginTokens\(\)/);
- assert.match(composer, /useComposerTriggerAcceptBridge\(/);
- assert.match(composer, /registerComposerInsert\(/);
- assert.match(composer, /registerComposerInsert\(null\)/);
- assert.match(composer, /⧉ \+\{pluginTokens\.foldedCount\}/);
- // The trigger menu renders the plugin's own component with query+dispatch.
- assert.match(composer, /query: activeTrigger\.query/);
-});
-
-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\)/);
+ assert.equal(hostOnly(html), plain, "the host controls and their order are untouched");
+ assert.deepEqual(probed(html, "a"), [{ position: "left" }, { position: "right" }], "the side is the only prop");
});
-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 \{/);
-});
-
-test("the composer mounts a composerToken outlet keyed by label", () => {
- // The composerToken slot had no host outlet: registrations were dead.
- // The chip renders the claiming plugin's component and falls back to the
- // host chip when no registration covers the label.
- const chip = readFileSync(src("features/chat/composer/ComposerTokenChip.tsx"), "utf8");
- assert.match(chip, /useSlotEntryForKey\("composerToken", token\.label\)/);
- assert.match(chip, /createElement\(/);
- const composer = readFileSync(src("components/Composer.tsx"), "utf8");
- assert.match(composer, /<ComposerTokenChip\b/);
-});
+test("a control leaves its side as soon as it is disposed", async (t) => {
+ const ssr = await composer(t);
+ const plain = ssr.toolbar();
+ const disposeA = ssr.register("demo.a", { slot: "composerControl", component: propsProbe("a") });
+ ssr.register("demo.b", { slot: "composerControl", component: propsProbe("b"), positions: ["right"] });
-test("the composer's plugin effects stay top-level and independent", () => {
- // Regression: an earlier edit nested the insert-bridge effect inside the
- // dock-height effect, so React committed the outer effect and called
- // useEffect from within its setup — crash-on-boot React error #321.
- const composer = readFileSync(src("components/Composer.tsx"), "utf8");
- const bridgeAt = composer.indexOf("registerComposerInsert((text)");
- const dockAt = composer.indexOf("const el = dockRef.current;");
- assert.ok(bridgeAt > -1 && dockAt > bridgeAt, "insert-bridge effect precedes the dock effect");
- const bridgeHead = composer.lastIndexOf("useEffect(() => {", bridgeAt);
- assert.ok(
- bridgeHead > -1 && !composer.slice(bridgeHead + 17, bridgeAt).includes("useEffect(() => {"),
- "insert-bridge effect opens with its own useEffect, not one inherited from another effect",
- );
+ disposeA();
+ assert.deepEqual(sidesOf(ssr.toolbar()), { left: HOST_LEFT, right: ["b:right", ...HOST_RIGHT] });
+ ssr.clear();
+ assert.equal(ssr.toolbar(), plain);
});
diff --git a/apps/desktop/test/plugin-entry-extra-slot.test.mjs b/apps/desktop/test/plugin-entry-extra-slot.test.mjs
index 153f3a64c..c864a8327 100644
--- a/apps/desktop/test/plugin-entry-extra-slot.test.mjs
+++ b/apps/desktop/test/plugin-entry-extra-slot.test.mjs
@@ -1,205 +1,156 @@
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));
+import { createElement } from "react";
+import {
+ probed,
+ propsProbe,
+ slotMounts,
+ slotSsr,
+ withoutProbeProps,
+} from "./helpers/slot-ssr.mjs";
-const here = dirname(fileURLToPath(import.meta.url));
-const src = (relative) => join(here, "..", "src", relative);
+/*
+ * The `entryExtra` outlet (`docs/plugin-plan/ui/entry-extra/`) rendered with
+ * the production modules: one block per registration under a finished reply,
+ * in registration order, each in its plugin's mount inside the host's clamped
+ * viewport, fed `{ message, messageId, sessionId }`. Server rendering is the
+ * first frame of a mount; the expand toggle, which needs a measurement, and
+ * a throwing block collapsing alone are covered by the Electron E2E.
+ */
-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",
+const REPLY = {
+ id: "a2",
role: "assistant",
- content: "answer",
- createdAt: "2026-09-17T00:00:00.000Z",
- ...extra,
-});
+ content: "It says x.",
+ createdAt: "2026-09-24T00:00:03.000Z",
+};
-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);
-});
+/** A user prompt answered in two parts around a tool call. */
+function conversation(overrides = {}) {
+ return [
+ { id: "u1", role: "user", content: "hello", status: "complete", createdAt: "2026-09-24T00:00:00.000Z" },
+ { id: "a1", role: "assistant", content: "Let me look.", status: "complete", createdAt: "2026-09-24T00:00:01.000Z" },
+ {
+ id: "t1",
+ role: "tool",
+ content: "",
+ status: "complete",
+ createdAt: "2026-09-24T00:00:02.000Z",
+ toolName: "read",
+ toolCallId: "call-1",
+ toolArgs: { path: "a.txt" },
+ toolStatus: "success",
+ toolResult: "x",
+ },
+ { ...REPLY, status: "complete", ...overrides },
+ ];
+}
-test("entryExtra projection pins the role to assistant", () => {
- const projected = entryExtraMessage(message({ role: "tool" }));
- assert.equal(projected.role, "assistant");
-});
+async function outlet(t) {
+ const ssr = await slotSsr(t);
+ const { EntryExtraStack } = await ssr.load("/src/features/chat/transcript/EntryExtraStack.tsx");
+ const { AssistantTurn } = await ssr.load("/src/features/chat/transcript/AssistantTurn.tsx");
+ const { assistantTurnContent, buildTranscriptEntries } = await ssr.load("/src/lib/assistant-turns.ts");
+ const turnOf = (messages) =>
+ buildTranscriptEntries(messages).entries.find((entry) => entry.kind === "assistant-turn");
+ return {
+ ...ssr,
+ assistantTurnContent,
+ turnOf,
+ stack: (message = REPLY, options) => ssr.render(createElement(EntryExtraStack, { message }), options),
+ turn: (entry, props = {}) =>
+ ssr.render(createElement(AssistantTurn, { entry, isActive: false, ...props })),
+ };
+}
-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("a reply with no entryExtra registration has no slot region", async (t) => {
+ const ssr = await outlet(t);
+ assert.equal(ssr.stack(), "");
+ ssr.register("demo.a", { slot: "assistantAction", component: propsProbe("action") });
+ assert.equal(ssr.stack(), "", "another slot's registration is not a block");
+ assert.doesNotMatch(ssr.turn(ssr.turnOf(conversation())), /pi-entry-extra/);
});
-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("each registration is one clamped block around its plugin's mount", async (t) => {
+ const ssr = await outlet(t);
+ ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("extra") });
+ const html = ssr.stack(REPLY, { sessionId: "session-7" });
+ assert.equal(
+ withoutProbeProps(html),
+ [
+ '<div class="pi-entry-extra-stack">',
+ '<div class="pi-entry-extra-block">',
+ '<div class="pi-entry-extra-viewport" style="max-height:320px">',
+ '<div><div class="pi-plugin-slot" data-pi-plugin="demo.a" data-pi-slot="entryExtra">',
+ '<output data-probe="extra"></output>',
+ "</div></div></div></div></div>",
+ ].join(""),
+ "the first frame is collapsed at 320px, with no toggle until a measurement asks for one",
);
+ assert.deepEqual(probed(html, "extra"), [
+ { message: REPLY, messageId: "a2", sessionId: "session-7" },
+ ]);
});
-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("blocks stack in registration order across plugins, and each leaves on its own", async (t) => {
+ const ssr = await outlet(t);
+ const first = ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("a") });
+ ssr.register("demo.b", { slot: "entryExtra", component: propsProbe("b") });
+ ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("a2") });
+ assert.deepEqual(slotMounts(ssr.stack()), [
+ ["demo.a", "entryExtra"],
+ ["demo.b", "entryExtra"],
+ ["demo.a", "entryExtra"],
+ ]);
+ assert.equal((ssr.stack().match(/pi-entry-extra-block/g) ?? []).length, 3);
-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",
- );
+ first();
+ assert.deepEqual(slotMounts(ssr.stack()), [
+ ["demo.b", "entryExtra"],
+ ["demo.a", "entryExtra"],
+ ]);
+ ssr.clear();
+ assert.equal(ssr.stack(), "");
});
-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("a finished turn shows the stack under its action bar, fed the reply the host keys act on", async (t) => {
+ const ssr = await outlet(t);
+ ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("extra") });
+ const entry = ssr.turnOf(conversation());
+ const html = ssr.turn(entry);
-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);
-});
+ const actionsAt = html.indexOf('<div class="message-actions">');
+ const stackAt = html.indexOf('<div class="pi-entry-extra-stack">');
+ assert.ok(actionsAt >= 0, "the host action bar stays");
+ assert.ok(stackAt > actionsAt, "the stack sits under the action bar");
+ assert.equal(html.indexOf('<div class="pi-entry-extra-stack">', stackAt + 1), -1, "one stack per turn");
-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/);
+ // The id is the answer message Regenerate and Branch act on; the content
+ // is the whole turn's text, as Copy copies it.
+ const content = ssr.assistantTurnContent(entry);
+ assert.equal(content, "Let me look.\n\nIt says x.");
+ assert.deepEqual(probed(html, "extra"), [
+ {
+ message: { id: "a2", role: "assistant", content, createdAt: REPLY.createdAt },
+ messageId: "a2",
+ sessionId: "session-1",
+ },
+ ]);
});
-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`,
- );
+test("a live, failed or text-less turn has no slot region", async (t) => {
+ const ssr = await outlet(t);
+ ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("extra") });
+ const cases = [
+ ["live", ssr.turn(ssr.turnOf(conversation({ status: "streaming" })), { isActive: true })],
+ [
+ "failed",
+ ssr.turn(ssr.turnOf(conversation({ error: { code: "PROVIDER_ERROR", message: "upstream failed" } }))),
+ ],
+ ["text-less", ssr.turn(ssr.turnOf(conversation().slice(0, 3).map((m) => ({ ...m, content: m.role === "user" ? m.content : "" }))))],
+ ];
+ for (const [label, html] of cases) {
+ assert.doesNotMatch(html, /pi-entry-extra/, label);
+ assert.deepEqual(probed(html, "extra"), [], label);
}
});
diff --git a/apps/desktop/test/plugin-renderer-call-runtime.test.mjs b/apps/desktop/test/plugin-renderer-call-runtime.test.mjs
new file mode 100644
index 000000000..e8ef5c855
--- /dev/null
+++ b/apps/desktop/test/plugin-renderer-call-runtime.test.mjs
@@ -0,0 +1,193 @@
+import assert from "node:assert/strict";
+import { fork } from "node:child_process";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const hostProcessEntry = join(here, "../electron/main/plugin-host-process.mjs");
+
+// Set before the runtime is imported so per-plugin data lands in a throwaway
+// directory instead of the developer's real one.
+process.env.PI_DESKTOP_DATA_DIR = mkdtempSync(join(tmpdir(), "pi-renderer-call-data-"));
+
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+
+/*
+ * A renderer extension against the real runtime and a real plugin host
+ * process (`docs/plugin-plan/render/plugin-call/`): the descriptor and the
+ * source resolver follow the live load, and `plugin.call` crosses the process
+ * boundary to the plugin's `onRendererCall` and back with its codes intact.
+ */
+
+const RENDERER_CALL_MAIN = `
+ module.exports = {
+ onLoad() {},
+ async onRendererCall(method, args) {
+ if (method === "echo") return { method, args };
+ if (method === "coded") throw Object.assign(new Error("not ready"), { code: "LAB_NOT_READY" });
+ if (method === "fail") throw new Error("boom");
+ if (method === "bigint") return { n: 1n };
+ if (method === "silent") return new Promise(() => {});
+ return null;
+ },
+ };
+`;
+
+function forkPluginProcess({ entry }) {
+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
+ return {
+ postMessage: (message) => {
+ if (child.connected) child.send(message);
+ },
+ onMessage: (handler) => child.on("message", handler),
+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
+ kill: () => child.kill(),
+ };
+}
+
+function writePlugin(t, { id, main = RENDERER_CALL_MAIN }) {
+ const dir = mkdtempSync(join(tmpdir(), "pi-renderer-call-plugin-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ mkdirSync(join(dir, "renderer"));
+ writeFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({
+ schemaVersion: 1,
+ id,
+ name: id,
+ version: "0.0.1",
+ main: "main.js",
+ renderer: "renderer/index.js",
+ rendererActions: ["plugin.call"],
+ rendererCallMethods: ["echo", "coded", "fail", "bigint", "silent"],
+ permissions: ["renderer.extension"],
+ contributes: { agentTools: [{ name: "lookup", description: "Look something up" }] },
+ }),
+ );
+ writeFileSync(join(dir, "main.js"), main);
+ writeFileSync(join(dir, "renderer/index.js"), "export function onLoad() {}\n");
+ return dir;
+}
+
+function runtimeFor(t) {
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ getWorkspacePath: () => null,
+ audit: () => {},
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ return runtime;
+}
+
+function refusedWith(code, pattern) {
+ return (error) => {
+ assert.equal(error.code, code, error.message);
+ if (pattern) assert.match(error.message, pattern);
+ return true;
+ };
+}
+
+test("the descriptor and the served sources follow the plugin's current load", async (t) => {
+ const runtime = runtimeFor(t);
+ const dir = writePlugin(t, { id: "lab.sources" });
+ const entry = realpathSync(join(dir, "renderer/index.js"));
+ await runtime.loadFromPath(dir, ["renderer.extension"]);
+
+ const first = runtime.rendererDescriptor("lab.sources");
+ assert.deepEqual(first, {
+ entry: "renderer/index.js",
+ generation: first.generation,
+ actions: ["plugin.call"],
+ callMethods: ["echo", "coded", "fail", "bigint", "silent"],
+ tools: ["lookup"],
+ });
+ assert.equal(runtime.resolveRendererSource("lab.sources", first.generation, "renderer/index.js"), entry);
+ assert.equal(runtime.resolveRendererSource("lab.sources", first.generation, "main.js"), realpathSync(join(dir, "main.js")));
+ assert.equal(runtime.resolveRendererSource("lab.sources", first.generation, "../main.js"), null);
+ assert.equal(runtime.resolveRendererSource("lab.other", first.generation, "renderer/index.js"), null);
+
+ // A reload is a new load: new generation, and the old URLs stop resolving.
+ await runtime.loadFromPath(dir, ["renderer.extension"]);
+ const second = runtime.rendererDescriptor("lab.sources");
+ assert.ok(second.generation > first.generation);
+ assert.equal(runtime.resolveRendererSource("lab.sources", first.generation, "renderer/index.js"), null);
+ assert.equal(runtime.resolveRendererSource("lab.sources", second.generation, "renderer/index.js"), entry);
+
+ await runtime.unload("lab.sources");
+ assert.equal(runtime.rendererDescriptor("lab.sources"), undefined);
+ assert.equal(runtime.resolveRendererSource("lab.sources", second.generation, "renderer/index.js"), null);
+});
+
+test("plugin.call reaches onRendererCall in the plugin process and returns its answer or its code", async (t) => {
+ const runtime = runtimeFor(t);
+ await runtime.loadFromPath(writePlugin(t, { id: "lab.calls" }), ["renderer.extension"]);
+
+ assert.deepEqual(await runtime.callRenderer("lab.calls", "echo", { n: 1, list: ["a"] }), {
+ method: "echo",
+ args: { n: 1, list: ["a"] },
+ });
+ assert.deepEqual(
+ await runtime.callRenderer("lab.calls", "echo", undefined),
+ { method: "echo", args: {} },
+ "omitted args reach the plugin as {}",
+ );
+ await assert.rejects(runtime.callRenderer("lab.calls", "coded"), refusedWith("LAB_NOT_READY", /^not ready$/));
+ await assert.rejects(runtime.callRenderer("lab.calls", "fail"), refusedWith("PLUGIN_CALL_FAILED", /^boom$/));
+ await assert.rejects(
+ runtime.callRenderer("lab.calls", "bigint"),
+ refusedWith("PLUGIN_CALL_UNSERIALIZABLE", /not JSON/),
+ );
+ await assert.rejects(
+ runtime.callRenderer("lab.calls", "shutdown"),
+ refusedWith("PLUGIN_CALL_NO_HANDLER"),
+ "an undeclared method never reaches the plugin",
+ );
+ assert.deepEqual(await runtime.callRenderer("lab.calls", "echo"), { method: "echo", args: {} });
+
+ // The relay does not wait past 2s for a plugin that never answers.
+ const started = Date.now();
+ await assert.rejects(
+ runtime.callRenderer("lab.calls", "silent"),
+ refusedWith("PLUGIN_CALL_TIMEOUT", /within 2000ms/),
+ );
+ assert.ok(Date.now() - started >= 1_900, "the timeout is the relay's 2s");
+
+ await runtime.unload("lab.calls");
+ await assert.rejects(runtime.callRenderer("lab.calls", "echo"), refusedWith("PLUGIN_NOT_FOUND"));
+});
+
+test("a plugin without onRendererCall answers every declared method with NO_HANDLER", async (t) => {
+ const runtime = runtimeFor(t);
+ await runtime.loadFromPath(
+ writePlugin(t, { id: "lab.mute", main: "module.exports = { onLoad() {} };\n" }),
+ ["renderer.extension"],
+ );
+ await assert.rejects(
+ runtime.callRenderer("lab.mute", "echo", {}),
+ refusedWith("PLUGIN_CALL_NO_HANDLER", /does not implement onRendererCall/),
+ );
+});
+
+test("without the renderer.extension grant the plugin runs but has no renderer extension", async (t) => {
+ const runtime = runtimeFor(t);
+ const dir = writePlugin(t, { id: "lab.ungranted" });
+ await runtime.loadFromPath(dir, []);
+ assert.ok(runtime.getLoaded("lab.ungranted"), "the headless entry still runs");
+ assert.equal(runtime.rendererDescriptor("lab.ungranted"), undefined);
+ await assert.rejects(
+ runtime.callRenderer("lab.ungranted", "echo", {}),
+ refusedWith("PLUGIN_PERMISSION_DENIED"),
+ );
+ // No generation was ever handed out, so there is none to guess.
+ for (let generation = 1; generation < 64; generation += 1) {
+ assert.equal(runtime.resolveRendererSource("lab.ungranted", generation, "renderer/index.js"), null);
+ }
+});
diff --git a/apps/desktop/test/plugin-renderer-dispatch.test.mjs b/apps/desktop/test/plugin-renderer-dispatch.test.mjs
new file mode 100644
index 000000000..cd5e55ffc
--- /dev/null
+++ b/apps/desktop/test/plugin-renderer-dispatch.test.mjs
@@ -0,0 +1,236 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * `pi.dispatch`, the only outbound channel of plugin renderer code
+ * (`docs/plugin-plan/slot-contract.html` §3): which words pass, what their
+ * payloads must look like, where each word goes, and that the end of a load
+ * cuts the channel off, answers in flight included.
+ */
+const { createDispatchChannel } = await import("../src/plugins/renderer-host/dispatch.ts");
+const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
+const { registerComposerInsert, resetComposerInsertBridge } = await import(
+ "../src/features/chat/composer/insert-bridge.ts"
+);
+const { IPC } = await import("@pi-desktop/shared");
+
+const PLUGIN = "demo.lab";
+const BOTH = ["plugin.call", "composer.insertText"];
+
+function rejectsWith(code) {
+ return (error) => {
+ assert.ok(error instanceof PluginRendererError, `expected a PluginRendererError, got ${error}`);
+ assert.equal(error.code, code);
+ return true;
+ };
+}
+
+/** Routes that record what reached them. */
+function fakeRoutes({ call = async () => ({ ok: true }), insert = () => true } = {}) {
+ const calls = [];
+ const inserts = [];
+ return {
+ calls,
+ inserts,
+ routes: {
+ pluginCall: (pluginId, method, args) => {
+ calls.push({ pluginId, method, args });
+ return call(pluginId, method, args);
+ },
+ insertText: (text) => {
+ inserts.push(text);
+ return insert(text);
+ },
+ },
+ };
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((ok, fail) => {
+ resolve = ok;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+test("a word outside the vocabulary or the manifest is refused before any route runs", async () => {
+ const { routes, calls, inserts } = fakeRoutes();
+ const { dispatch } = createDispatchChannel(PLUGIN, ["plugin.call"], routes);
+
+ const refused = dispatch("composer.insertText", { text: "hi" });
+ assert.ok(refused instanceof Promise, "refusals reject; dispatch never throws synchronously");
+ await assert.rejects(refused, rejectsWith("PLUGIN_ACTION_UNDECLARED"));
+ await assert.rejects(dispatch("ui.toast", { text: "hi" }), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
+ await assert.rejects(dispatch(42, {}), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
+ await assert.rejects(dispatch(undefined, {}), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
+ assert.deepEqual(calls, []);
+ assert.deepEqual(inserts, []);
+
+ // Declaring a word the host does not implement grants nothing.
+ const { dispatch: widened } = createDispatchChannel(PLUGIN, ["ui.toast"], routes);
+ await assert.rejects(widened("ui.toast", {}), rejectsWith("PLUGIN_ACTION_UNKNOWN"));
+});
+
+test("a payload must be an object of the word's shape", async () => {
+ const { routes, calls, inserts } = fakeRoutes();
+ const { dispatch } = createDispatchChannel(PLUGIN, BOTH, routes);
+ for (const payload of [undefined, null, "ping", [], [{ method: "ping" }], {}, { method: "" }, { method: 3 }]) {
+ await assert.rejects(
+ dispatch("plugin.call", payload),
+ rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
+ `plugin.call ${JSON.stringify(payload)}`,
+ );
+ }
+ for (const payload of [undefined, "hi", ["hi"], {}, { text: "" }, { text: 3 }, { text: ["hi"] }]) {
+ await assert.rejects(
+ dispatch("composer.insertText", payload),
+ rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
+ `composer.insertText ${JSON.stringify(payload)}`,
+ );
+ }
+ assert.deepEqual(calls, []);
+ assert.deepEqual(inserts, []);
+});
+
+test("composer.insertText takes up to 32KB of UTF-8 and answers ok, or NO_COMPOSER", async () => {
+ const { routes, inserts } = fakeRoutes();
+ const { dispatch } = createDispatchChannel(PLUGIN, ["composer.insertText"], routes);
+
+ assert.deepEqual(await dispatch("composer.insertText", { text: "a".repeat(32 * 1024) }), { ok: true });
+ // "é" is two bytes: the ceiling counts bytes, not characters.
+ assert.deepEqual(await dispatch("composer.insertText", { text: "é".repeat(16 * 1024) }), { ok: true });
+ await assert.rejects(
+ dispatch("composer.insertText", { text: "é".repeat(16 * 1024 + 1) }),
+ rejectsWith("PLUGIN_ACTION_INVALID_PAYLOAD"),
+ );
+ assert.deepEqual(
+ inserts.map((text) => text.length),
+ [32 * 1024, 16 * 1024],
+ "only accepted text reaches the composer, unchanged",
+ );
+
+ const { routes: noComposer } = fakeRoutes({ insert: () => false });
+ const { dispatch: unmounted } = createDispatchChannel(PLUGIN, ["composer.insertText"], noComposer);
+ await assert.rejects(
+ unmounted("composer.insertText", { text: "hi" }),
+ rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
+ );
+});
+
+test("plugin.call relays the plugin's own id and the JSON reading of its args", async () => {
+ const { routes, calls } = fakeRoutes({ call: async (_id, method) => ({ answered: method }) });
+ const { dispatch } = createDispatchChannel(PLUGIN, ["plugin.call"], routes);
+
+ assert.deepEqual(
+ await dispatch("plugin.call", {
+ method: "echo",
+ args: { at: new Date(0), skipped: undefined, list: [1, undefined], n: 1 },
+ }),
+ { answered: "echo" },
+ );
+ assert.deepEqual(await dispatch("plugin.call", { method: "ping" }), { answered: "ping" });
+ assert.deepEqual(calls, [
+ {
+ pluginId: PLUGIN,
+ method: "echo",
+ args: { at: "1970-01-01T00:00:00.000Z", list: [1, null], n: 1 },
+ },
+ { pluginId: PLUGIN, method: "ping", args: undefined },
+ ]);
+
+ const cyclic = {};
+ cyclic.self = cyclic;
+ for (const args of [cyclic, { big: 1n }, () => "not data"]) {
+ await assert.rejects(
+ dispatch("plugin.call", { method: "echo", args }),
+ rejectsWith("PLUGIN_CALL_UNSERIALIZABLE"),
+ );
+ }
+ assert.equal(calls.length, 2, "unserializable args never leave the renderer");
+});
+
+test("plugin.call passes the relay's coded refusal through untouched", async () => {
+ const refusal = Object.assign(new Error("slow down"), { code: "PLUGIN_CALL_RATE_LIMITED" });
+ const { routes } = fakeRoutes({ call: async () => Promise.reject(refusal) });
+ const { dispatch } = createDispatchChannel(PLUGIN, ["plugin.call"], routes);
+ await assert.rejects(dispatch("plugin.call", { method: "ping" }), (error) => error === refusal);
+});
+
+test("closing the channel rejects the calls in flight and refuses every later dispatch", async () => {
+ const pending = [];
+ const { routes } = fakeRoutes({
+ call: () => {
+ const answer = deferred();
+ pending.push(answer);
+ return answer.promise;
+ },
+ });
+ const channel = createDispatchChannel(PLUGIN, BOTH, routes);
+
+ const settledFirst = channel.dispatch("plugin.call", { method: "first" });
+ pending[0].resolve("before the end");
+ assert.equal(await settledFirst, "before the end");
+
+ const late = channel.dispatch("plugin.call", { method: "late" });
+ const failing = channel.dispatch("plugin.call", { method: "failing" });
+ channel.close();
+ await assert.rejects(late, rejectsWith("PLUGIN_UNLOADED"));
+ await assert.rejects(failing, rejectsWith("PLUGIN_UNLOADED"));
+ // The answers that arrive afterwards go nowhere.
+ pending[1].resolve("after the end");
+ pending[2].reject(new Error("after the end"));
+
+ await assert.rejects(channel.dispatch("plugin.call", { method: "ping" }), rejectsWith("PLUGIN_UNLOADED"));
+ await assert.rejects(channel.dispatch("composer.insertText", { text: "hi" }), rejectsWith("PLUGIN_UNLOADED"));
+ await assert.rejects(channel.dispatch("ui.toast", {}), rejectsWith("PLUGIN_UNLOADED"));
+ channel.close();
+ assert.equal(pending.length, 3, "nothing is relayed once the channel is closed");
+});
+
+test("the default routes reach the composer insert bridge and the main-process relay", async (t) => {
+ const originalWindow = globalThis.window;
+ t.after(() => {
+ resetComposerInsertBridge();
+ globalThis.window = originalWindow;
+ });
+ const { dispatch } = createDispatchChannel(PLUGIN, BOTH);
+
+ resetComposerInsertBridge();
+ await assert.rejects(
+ dispatch("composer.insertText", { text: "hi" }),
+ rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
+ );
+ const inserted = [];
+ registerComposerInsert((text) => inserted.push(text));
+ assert.deepEqual(await dispatch("composer.insertText", { text: "hi" }), { ok: true });
+ assert.deepEqual(inserted, ["hi"]);
+ registerComposerInsert(null);
+ await assert.rejects(
+ dispatch("composer.insertText", { text: "again" }),
+ rejectsWith("PLUGIN_ACTION_NO_COMPOSER"),
+ );
+
+ const invoked = [];
+ let reply = { ok: true, data: { pong: true } };
+ globalThis.window = {
+ piDesktop: {
+ invoke: async (channel, ...args) => {
+ invoked.push([channel, ...args]);
+ return reply;
+ },
+ },
+ };
+ assert.deepEqual(await dispatch("plugin.call", { method: "ping", args: { n: 1 } }), { pong: true });
+ assert.deepEqual(invoked, [[IPC.invoke.pluginRendererCall, PLUGIN, "ping", { n: 1 }]]);
+
+ reply = { ok: false, error: { code: "PLUGIN_CALL_TIMEOUT", message: "no answer within 2000ms" } };
+ await assert.rejects(dispatch("plugin.call", { method: "ping" }), (error) => {
+ assert.equal(error.code, "PLUGIN_CALL_TIMEOUT");
+ assert.equal(error.message, "no answer within 2000ms");
+ return true;
+ });
+});
diff --git a/apps/desktop/test/plugin-renderer-extension.test.mjs b/apps/desktop/test/plugin-renderer-extension.test.mjs
new file mode 100644
index 000000000..ed1f83cce
--- /dev/null
+++ b/apps/desktop/test/plugin-renderer-extension.test.mjs
@@ -0,0 +1,471 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { register, registerHooks } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+
+// Electron is the boundary: the protocol module hands its request handler to
+// `protocol.handle`, and this stand-in keeps it for the tests to drive.
+const electron = `data:text/javascript,${encodeURIComponent(`
+ export const protocol = {
+ handle(scheme, handler) {
+ globalThis.__piProtocolHandlers ??= new Map();
+ globalThis.__piProtocolHandlers.set(scheme, handler);
+ },
+ };
+`)}`;
+registerHooks({ resolve(specifier, context, next) {
+ return specifier === "electron" ? { url: electron, shortCircuit: true } : next(specifier, context);
+} });
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * The main-process half of a renderer extension (`docs/plugin-plan/ui/`,
+ * `docs/plugin-plan/render/plugin-call/`): which loads get a descriptor, which
+ * files `plugin-renderer://` serves for them, and what the `plugin.call` relay
+ * lets through to the plugin's headless entry.
+ */
+const {
+ RENDERER_CALL_BREAKER_COOLDOWN_MS,
+ RENDERER_CALL_MAX_BYTES,
+ RENDERER_CALL_QPS,
+ RENDERER_CALL_TIMEOUT_MS,
+ RendererCallRelay,
+ rendererDescriptorFor,
+ resolveRendererSourcePath,
+} = await import("../electron/main/plugin-renderer-extension.ts");
+const { PLUGIN_RENDERER_SCHEME_PRIVILEGES, installPluginRendererProtocol, parseRendererRequestPath } =
+ await import("../electron/main/plugin-renderer-protocol.ts");
+
+const PLUGIN = "demo.lab";
+const GRANT = "renderer.extension";
+
+/** A runtime load record as the extension reads it. */
+function loadedPlugin({ dir = "/nowhere", permissions = [GRANT], disposing = false, manifest = {} } = {}) {
+ return {
+ path: dir,
+ permissions: new Set(permissions),
+ disposing,
+ manifest: {
+ id: PLUGIN,
+ renderer: "renderer/index.js",
+ rendererActions: ["plugin.call"],
+ rendererCallMethods: ["ping", "echo"],
+ contributes: { agentTools: [{ name: "lookup" }, { name: "fetch" }] },
+ ...manifest,
+ },
+ };
+}
+
+const ENTRY_SOURCE = "export function onLoad() {}\n";
+
+/** A plugin package next to files it must never serve. */
+function pluginPackage(t) {
+ const root = mkdtempSync(join(tmpdir(), "pi-renderer-source-"));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ const dir = join(root, "pkg");
+ const files = {
+ "pkg/renderer/index.js": ENTRY_SOURCE,
+ "pkg/renderer/lib/chart.js": "export const chart = 1;\n",
+ "pkg/renderer/extra.mjs": "export {};\n",
+ "pkg/renderer/LOUD.JS": "export {};\n",
+ "pkg/renderer/style.css": ".lab {}\n",
+ "pkg/renderer/data.json": "{}\n",
+ "pkg/renderer/index.js.map": "{}\n",
+ "pkg/renderer/page.html": "<p></p>\n",
+ "pkg/renderer/module.wasm": "\0asm",
+ "pkg/renderer/README": "readme\n",
+ "pkg-evil/x.js": "export const evil = 1;\n",
+ "secret.js": "export const secret = 1;\n",
+ };
+ for (const [path, content] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), content);
+ }
+ symlinkSync(join(root, "secret.js"), join(dir, "renderer", "escape.js"));
+ symlinkSync(join(dir, "renderer", "lib", "chart.js"), join(dir, "renderer", "alias.js"));
+ return { root, dir };
+}
+
+function codedAs(code) {
+ return (error) => {
+ assert.ok(error instanceof Error, `expected an Error, got ${error}`);
+ assert.equal(error.code, code);
+ assert.equal(error.errorCode, code, "errorCode is what the IPC layer forwards");
+ return true;
+ };
+}
+
+test("a running plugin with the grant and a renderer entry gets a descriptor stamped with its load", () => {
+ const plugin = loadedPlugin();
+ const descriptor = rendererDescriptorFor(plugin);
+ assert.ok(Number.isSafeInteger(descriptor.generation) && descriptor.generation > 0);
+ assert.deepEqual(descriptor, {
+ entry: "renderer/index.js",
+ generation: descriptor.generation,
+ actions: ["plugin.call"],
+ callMethods: ["ping", "echo"],
+ tools: ["lookup", "fetch"],
+ });
+ assert.notEqual(descriptor.actions, plugin.manifest.rendererActions, "the descriptor holds copies");
+
+ // One load keeps its generation; a reload is a new record with a new one.
+ assert.equal(rendererDescriptorFor(plugin).generation, descriptor.generation);
+ assert.ok(rendererDescriptorFor(loadedPlugin()).generation > descriptor.generation);
+
+ const { generation: _generation, ...bare } = rendererDescriptorFor(
+ loadedPlugin({ manifest: { rendererActions: undefined, rendererCallMethods: undefined, contributes: undefined } }),
+ );
+ assert.deepEqual(bare, { entry: "renderer/index.js", actions: [], callMethods: [], tools: [] });
+
+ for (const [label, candidate] of [
+ ["not running", undefined],
+ ["unloading", loadedPlugin({ disposing: true })],
+ ["without the grant", loadedPlugin({ permissions: ["ui.panel"] })],
+ ["without an entry", loadedPlugin({ manifest: { renderer: undefined } })],
+ ]) {
+ assert.equal(rendererDescriptorFor(candidate), undefined, label);
+ }
+});
+
+test("the source resolver serves the current load's regular files from inside the package only", (t) => {
+ const { root, dir } = pluginPackage(t);
+ const plugin = loadedPlugin({ dir });
+ const real = (path) => realpathSync(join(dir, path));
+
+ // Asking the resolver never hands a generation out; only a descriptor does.
+ const probe = rendererDescriptorFor(loadedPlugin({ dir })).generation;
+ assert.equal(resolveRendererSourcePath(plugin, probe + 1, "renderer/index.js"), null);
+ const { generation } = rendererDescriptorFor(plugin);
+ assert.equal(generation, probe + 1);
+
+ assert.equal(resolveRendererSourcePath(plugin, generation, "renderer/index.js"), real("renderer/index.js"));
+ assert.equal(resolveRendererSourcePath(plugin, generation, "renderer/lib/chart.js"), real("renderer/lib/chart.js"));
+ assert.equal(
+ resolveRendererSourcePath(plugin, generation, "renderer/alias.js"),
+ real("renderer/lib/chart.js"),
+ "a link inside the package serves its target",
+ );
+ for (const [label, requestPath] of [
+ ["a parent escape", "../secret.js"],
+ ["a parent escape through the entry folder", "renderer/../../secret.js"],
+ ["a sibling folder sharing the name prefix", "../pkg-evil/x.js"],
+ ["an absolute path", join(root, "secret.js")],
+ ["a link out of the package", "renderer/escape.js"],
+ ["a folder", "renderer"],
+ ["the package itself", ""],
+ ["a missing file", "renderer/missing.js"],
+ ]) {
+ assert.equal(resolveRendererSourcePath(plugin, generation, requestPath), null, label);
+ }
+
+ // Only the generation the current load handed out resolves.
+ assert.equal(resolveRendererSourcePath(plugin, probe, "renderer/index.js"), null);
+ assert.equal(resolveRendererSourcePath(plugin, generation + 1, "renderer/index.js"), null);
+ const reloaded = loadedPlugin({ dir });
+ const next = rendererDescriptorFor(reloaded).generation;
+ assert.equal(resolveRendererSourcePath(reloaded, generation, "renderer/index.js"), null, "a URL from before the reload");
+ assert.equal(resolveRendererSourcePath(reloaded, next, "renderer/index.js"), real("renderer/index.js"));
+
+ // The same record stops serving while it lacks the grant or unloads.
+ plugin.permissions.delete(GRANT);
+ assert.equal(resolveRendererSourcePath(plugin, generation, "renderer/index.js"), null, "without the grant");
+ plugin.permissions.add(GRANT);
+ plugin.disposing = true;
+ assert.equal(resolveRendererSourcePath(plugin, generation, "renderer/index.js"), null, "while unloading");
+ plugin.disposing = false;
+ assert.equal(resolveRendererSourcePath(plugin, generation, "renderer/index.js"), real("renderer/index.js"));
+ assert.equal(resolveRendererSourcePath(undefined, generation, "renderer/index.js"), null, "not running");
+});
+
+/** The relay over a fake clock and a fake child process. */
+function relayHarness() {
+ let clock = 1_000_000;
+ const relay = new RendererCallRelay(() => clock);
+ const sent = [];
+ let answer = async (payload) => ({ pong: payload.method });
+ const send = (plugin, payload, timeoutMs) => {
+ sent.push({ plugin, payload, timeoutMs });
+ return answer(payload);
+ };
+ return {
+ sent,
+ advance(ms) {
+ clock += ms;
+ },
+ answerWith(fn) {
+ answer = fn;
+ },
+ call: (plugin, method, args) => relay.call(PLUGIN, plugin, method, args, send),
+ };
+}
+
+const boom = async () => {
+ throw new Error("boom");
+};
+
+test("calls the relay must not make are refused before it, and never count against the plugin", async () => {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ const cyclic = {};
+ cyclic.self = cyclic;
+ // 66 bytes short of nothing: 1 + 2 × 32767 bytes of text plus the quotes is
+ // 65537 bytes, while its length in characters is only 32770.
+ const oversize = `a${"é".repeat(32_767)}`;
+ const cases = [
+ ["not running", undefined, "ping", undefined, "PLUGIN_NOT_FOUND"],
+ ["unloading", loadedPlugin({ disposing: true }), "ping", undefined, "PLUGIN_NOT_FOUND"],
+ ["without the grant", loadedPlugin({ permissions: [] }), "ping", undefined, "PLUGIN_PERMISSION_DENIED"],
+ ["without an entry", loadedPlugin({ manifest: { renderer: undefined } }), "ping", undefined, "PLUGIN_CALL_NO_HANDLER"],
+ ["without methods", loadedPlugin({ manifest: { rendererCallMethods: undefined } }), "ping", undefined, "PLUGIN_CALL_NO_HANDLER"],
+ ["an undeclared method", plugin, "shutdown", undefined, "PLUGIN_CALL_NO_HANDLER"],
+ ["cyclic args", plugin, "echo", cyclic, "PLUGIN_CALL_UNSERIALIZABLE"],
+ ["BigInt args", plugin, "echo", { n: 1n }, "PLUGIN_CALL_UNSERIALIZABLE"],
+ ["function args", plugin, "echo", () => 1, "PLUGIN_CALL_UNSERIALIZABLE"],
+ ["args over 64KB of UTF-8", plugin, "echo", oversize, "PLUGIN_CALL_TOO_LARGE"],
+ ];
+ // Twice over: ten refusals of `plugin` would trip both the rate brake and
+ // the breaker if either of them counted refusals.
+ for (let round = 0; round < 2; round += 1) {
+ for (const [label, target, method, args, code] of cases) {
+ await assert.rejects(h.call(target, method, args), codedAs(code), label);
+ }
+ }
+ assert.deepEqual(h.sent, []);
+ assert.deepEqual(await h.call(plugin, "ping"), { pong: "ping" });
+});
+
+test("the plugin gets the JSON reading of the args, and the caller the JSON reading of the answer", async () => {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ const shaped = () => ({ at: new Date(0), skipped: undefined, list: [1, undefined] });
+ const json = { at: "1970-01-01T00:00:00.000Z", list: [1, null] };
+ h.answerWith(async () => shaped());
+ assert.deepEqual(await h.call(plugin, "echo", shaped()), json);
+ assert.deepEqual(h.sent, [{ plugin, payload: { method: "echo", args: json }, timeoutMs: 2_000 }]);
+ assert.equal(RENDERER_CALL_TIMEOUT_MS, 2_000);
+
+ h.answerWith(async () => undefined);
+ assert.equal(await h.call(plugin, "ping"), null, "no answer is null");
+ assert.deepEqual(h.sent[1].payload, { method: "ping", args: undefined }, "omitted args stay omitted");
+});
+
+test("args and answer share one budget of 64KB counted in UTF-8 bytes", async () => {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ assert.equal(RENDERER_CALL_MAX_BYTES, 65_536);
+ // The JSON text of these args is 65532 bytes: four are left for the answer.
+ const args = "x".repeat(RENDERER_CALL_MAX_BYTES - 4 - 2);
+ h.answerWith(async () => undefined);
+ assert.equal(await h.call(plugin, "echo", args), null);
+ h.answerWith(async () => "ab");
+ assert.equal(await h.call(plugin, "echo", args), "ab");
+ // Four characters of JSON text, six bytes.
+ h.answerWith(async () => "éé");
+ await assert.rejects(h.call(plugin, "echo", args), codedAs("PLUGIN_CALL_TOO_LARGE"));
+});
+
+test("more than ten relayed calls inside one second are refused until the window moves on", async () => {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ assert.equal(RENDERER_CALL_QPS, 10);
+ for (let i = 0; i < 10; i += 1) {
+ await h.call(plugin, "ping");
+ h.advance(50);
+ }
+ // Ten calls at t, t+50 … t+450; the clock reads t+500.
+ for (let i = 0; i < 6; i += 1) {
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_RATE_LIMITED"));
+ }
+ h.advance(499);
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_RATE_LIMITED"), "t is still inside the window");
+ h.advance(1);
+ assert.deepEqual(await h.call(plugin, "ping"), { pong: "ping" }, "t has left it");
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_RATE_LIMITED"), "and the slot is taken again");
+ assert.equal(h.sent.length, 11, "refused calls are never relayed, nor counted as failures");
+ // The brake belongs to the load: a reload starts with an empty window.
+ assert.deepEqual(await h.call(loadedPlugin(), "ping"), { pong: "ping" });
+});
+
+test("five relayed failures in a row close the relay for 30s; a success resets the count", async () => {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ // One call a second keeps the rate brake out of the way.
+ const call = () => {
+ h.advance(1_000);
+ return h.call(plugin, "ping");
+ };
+ h.answerWith(boom);
+ for (let i = 0; i < 4; i += 1) await assert.rejects(call(), codedAs("PLUGIN_CALL_FAILED"));
+ h.answerWith(async () => "fine");
+ assert.equal(await call(), "fine");
+ h.answerWith(boom);
+ for (let i = 0; i < 4; i += 1) await assert.rejects(call(), codedAs("PLUGIN_CALL_FAILED"));
+ await assert.rejects(call(), codedAs("PLUGIN_CALL_FAILED"), "the fifth in a row is still relayed");
+ assert.equal(h.sent.length, 10);
+
+ h.answerWith(async () => "fine");
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_DISABLED"));
+ assert.equal(RENDERER_CALL_BREAKER_COOLDOWN_MS, 30_000);
+ h.advance(RENDERER_CALL_BREAKER_COOLDOWN_MS - 1);
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_DISABLED"));
+ assert.equal(h.sent.length, 10, "a closed relay relays nothing");
+ // Another load of the plugin has a relay of its own.
+ assert.equal(await h.call(loadedPlugin(), "ping"), "fine");
+
+ // Reopened, the count starts from zero: four more failures leave it open.
+ h.advance(1);
+ h.answerWith(boom);
+ for (let i = 0; i < 4; i += 1) await assert.rejects(call(), codedAs("PLUGIN_CALL_FAILED"));
+ h.answerWith(async () => "fine");
+ assert.equal(await call(), "fine");
+});
+
+test("what goes wrong past the relay reaches the caller coded, and counts against the plugin", async () => {
+ const coded = (code, message) => async () => {
+ throw Object.assign(new Error(message), { code });
+ };
+ const cases = [
+ ["a timeout", coded("TIMEOUT", "no reply"), "PLUGIN_CALL_TIMEOUT", /did not answer ping within 2000ms/],
+ ["the plugin's own code", coded("LAB_NOT_READY", "not ready"), "LAB_NOT_READY", /^not ready$/],
+ ["a missing handler", coded("PLUGIN_CALL_NO_HANDLER", "no onRendererCall"), "PLUGIN_CALL_NO_HANDLER", /onRendererCall/],
+ ["an uncoded error", boom, "PLUGIN_CALL_FAILED", /^boom$/],
+ [
+ "a thrown string",
+ async () => {
+ throw "bad";
+ },
+ "PLUGIN_CALL_FAILED",
+ /^bad$/,
+ ],
+ ["an answer that is not JSON", async () => ({ n: 1n }), "PLUGIN_CALL_UNSERIALIZABLE", /answer/],
+ ["an answer over the budget", async () => "x".repeat(RENDERER_CALL_MAX_BYTES), "PLUGIN_CALL_TOO_LARGE", /answer/],
+ ];
+ for (const [label, answer, code, message] of cases) {
+ const h = relayHarness();
+ const plugin = loadedPlugin();
+ h.answerWith(answer);
+ for (let i = 0; i < 5; i += 1) {
+ await assert.rejects(
+ h.call(plugin, "ping"),
+ (error) => codedAs(code)(error) && message.test(error.message),
+ label,
+ );
+ h.advance(1_000);
+ }
+ await assert.rejects(h.call(plugin, "ping"), codedAs("PLUGIN_CALL_DISABLED"), `${label} counts`);
+ assert.equal(h.sent.length, 5, label);
+ }
+});
+
+test("the request path splits into the load generation and the package-relative path", () => {
+ assert.deepEqual(parseRendererRequestPath("/g1/renderer/index.js"), { generation: 1, requestPath: "renderer/index.js" });
+ assert.deepEqual(parseRendererRequestPath("g12/a.js"), { generation: 12, requestPath: "a.js" });
+ assert.deepEqual(parseRendererRequestPath("//g3/a/b.js"), { generation: 3, requestPath: "a/b.js" });
+ assert.deepEqual(parseRendererRequestPath("/g999999999999999/a.js"), {
+ generation: 999_999_999_999_999,
+ requestPath: "a.js",
+ });
+ for (const pathname of ["", "/", "/g1", "/g1/", "/g0/a.js", "/g01/a.js", "/g1234567890123456/a.js", "/G1/a.js", "/x1/a.js", "/g-1/a.js", "/g1.5/a.js"]) {
+ assert.equal(parseRendererRequestPath(pathname), null, JSON.stringify(pathname));
+ }
+});
+
+function assertNotFound(response, label) {
+ assert.equal(response.status, 404, label);
+ assert.equal(response.headers.get("content-type"), "text/plain", label);
+ assert.equal(response.headers.get("x-content-type-options"), "nosniff", label);
+}
+
+test("plugin-renderer:// answers GET for module files the resolver allows, and 404 for anything else", async (t) => {
+ const { dir } = pluginPackage(t);
+ const stale = rendererDescriptorFor(loadedPlugin({ dir })).generation;
+ const plugin = loadedPlugin({ dir });
+ const { generation } = rendererDescriptorFor(plugin);
+ const asked = [];
+ // The wiring `startup.ts` installs: the runtime's current load decides.
+ installPluginRendererProtocol((pluginId, requested, requestPath) => {
+ asked.push([pluginId, requested, requestPath]);
+ return resolveRendererSourcePath(pluginId === PLUGIN ? plugin : undefined, requested, requestPath);
+ });
+ assert.deepEqual(PLUGIN_RENDERER_SCHEME_PRIVILEGES, {
+ scheme: "plugin-renderer",
+ privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true },
+ });
+ const handler = globalThis.__piProtocolHandlers.get("plugin-renderer");
+ const fetchSource = (url, init) => handler(new Request(url, init));
+ const base = `plugin-renderer://${PLUGIN}/g${generation}`;
+
+ const entry = await fetchSource(`${base}/renderer/index.js`);
+ assert.equal(entry.status, 200);
+ assert.equal(await entry.text(), ENTRY_SOURCE);
+ assert.deepEqual(Object.fromEntries(entry.headers), {
+ "access-control-allow-origin": "*",
+ "cache-control": "no-store",
+ "content-length": String(Buffer.byteLength(ENTRY_SOURCE)),
+ "content-type": "text/javascript",
+ "x-content-type-options": "nosniff",
+ });
+ assert.deepEqual(asked, [[PLUGIN, generation, "renderer/index.js"]]);
+
+ for (const [path, type] of [
+ ["renderer/lib/chart.js", "text/javascript"],
+ ["renderer/extra.mjs", "text/javascript"],
+ ["renderer/LOUD.JS", "text/javascript"],
+ ["renderer/style.css", "text/css"],
+ ["renderer/data.json", "application/json"],
+ ["renderer/index.js.map", "application/json"],
+ ]) {
+ const response = await fetchSource(`${base}/${path}`);
+ assert.equal(response.status, 200, path);
+ assert.equal(response.headers.get("content-type"), type, path);
+ assert.equal(response.headers.get("x-content-type-options"), "nosniff", path);
+ }
+ const spaced = await fetchSource(`${base}/renderer/lib/chart.js`.replace("chart", "%63hart"));
+ assert.equal(spaced.status, 200, "segments are percent-decoded");
+
+ asked.length = 0;
+ for (const [label, url, init] of [
+ ["a POST", `${base}/renderer/index.js`, { method: "POST", body: "x" }],
+ ["a HEAD", `${base}/renderer/index.js`, { method: "HEAD" }],
+ ["no generation", `plugin-renderer://${PLUGIN}/renderer/index.js`],
+ ["generation zero", `plugin-renderer://${PLUGIN}/g0/renderer/index.js`],
+ ["a zero-padded generation", `plugin-renderer://${PLUGIN}/g0${generation}/renderer/index.js`],
+ ["a parent segment", `${base}/../secret.js`],
+ ["an encoded parent segment", `${base}/%2e%2e/secret.js`],
+ ["nothing after the generation", `${base}/`],
+ ["an HTML page", `${base}/renderer/page.html`],
+ ["a wasm module", `${base}/renderer/module.wasm`],
+ ["a file without an extension", `${base}/renderer/README`],
+ ["broken percent-encoding", `${base}/renderer/%E0%A4%A.js`],
+ ]) {
+ assertNotFound(await fetchSource(url, init), label);
+ }
+ assert.deepEqual(asked, [], "none of these reach the resolver");
+
+ const refusedByResolver = [
+ ["a URL from before the reload", `plugin-renderer://${PLUGIN}/g${stale}/renderer/index.js`],
+ ["another plugin", `plugin-renderer://demo.other/g${generation}/renderer/index.js`],
+ ["an escape hidden in one segment", `${base}/..%2Fsecret.js`],
+ ["an escape hidden after the entry folder", `${base}/renderer%2F..%2F..%2Fsecret.js`],
+ ["a link out of the package", `${base}/renderer/escape.js`],
+ ["a missing file", `${base}/renderer/missing.js`],
+ ];
+ for (const [label, url] of refusedByResolver) {
+ assertNotFound(await fetchSource(url), label);
+ }
+ assert.equal(asked.length, refusedByResolver.length);
+ assert.deepEqual(asked[2], [PLUGIN, generation, "../secret.js"]);
+});
+
+test("only the app's main window may relay a plugin.call", () => {
+ // Renderer extensions run in the main window's `PluginRendererHost`; the
+ // launcher window loads the same bundle and must not reach plugin entries.
+ const source = readFileSync(new URL("../electron/main/ipc/plugin-ipc.ts", import.meta.url), "utf8");
+ assert.match(
+ source,
+ /registrar\.handleWithEvent\(\s*IPC\.invoke\.pluginRendererCall,[\s\S]*?registrar\.assertMainWindowSender\(event\);[\s\S]*?plugins\.callRenderer\(pluginId, method, args\)/,
+ );
+ assert.doesNotMatch(source, /handle\(IPC\.invoke\.pluginRendererCall/);
+});
diff --git a/apps/desktop/test/plugin-renderer-import-map.test.mjs b/apps/desktop/test/plugin-renderer-import-map.test.mjs
new file mode 100644
index 000000000..4ad8e3c4e
--- /dev/null
+++ b/apps/desktop/test/plugin-renderer-import-map.test.mjs
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { register } from "node:module";
+import test from "node:test";
+import * as React from "react";
+import * as ReactDom from "react-dom";
+import * as ReactDomClient from "react-dom/client";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * The shared-React import map (`docs/plugin-plan/slot-contract.html` §1): the
+ * bare specifiers a plugin module imports resolve to shims over the host's
+ * own React, so hooks and context work across the two. The shims are the
+ * generated sources, evaluated as modules; only the document and the blob
+ * store are faked.
+ */
+const { RENDERER_HOST_KEY, installRendererImportMap, resetRendererImportMap } = await import(
+ "../src/plugins/renderer-host/import-map.ts"
+);
+
+function fakeDocument(t) {
+ const scripts = [];
+ const blobs = new Map();
+ const saved = {
+ document: Object.getOwnPropertyDescriptor(globalThis, "document"),
+ createObjectURL: URL.createObjectURL,
+ };
+ globalThis.document = {
+ createElement: (tag) => ({ tag }),
+ head: { appendChild: (node) => scripts.push(node) },
+ };
+ URL.createObjectURL = (blob) => {
+ const url = `blob:shim-${blobs.size}`;
+ blobs.set(url, blob);
+ return url;
+ };
+ resetRendererImportMap();
+ t.after(() => {
+ if (saved.document) Object.defineProperty(globalThis, "document", saved.document);
+ else delete globalThis.document;
+ URL.createObjectURL = saved.createObjectURL;
+ delete globalThis[RENDERER_HOST_KEY];
+ resetRendererImportMap();
+ });
+ return { scripts, blobs };
+}
+
+/** The shim behind `url`, evaluated as the module a plugin would import. */
+async function evaluate(blobs, url) {
+ const source = await blobs.get(url).text();
+ return import(`data:text/javascript,${encodeURIComponent(source)}`);
+}
+
+test("react, react-dom and react-dom/client resolve to the host's own modules", async (t) => {
+ const { scripts, blobs } = fakeDocument(t);
+ installRendererImportMap();
+
+ assert.equal(scripts.length, 1);
+ assert.equal(scripts[0].type, "importmap");
+ const { imports } = JSON.parse(scripts[0].textContent);
+ assert.deepEqual(Object.keys(imports), ["react", "react-dom", "react-dom/client"]);
+
+ const expected = { react: React, "react-dom": ReactDom, "react-dom/client": ReactDomClient };
+ for (const [specifier, host] of Object.entries(expected)) {
+ const shim = await evaluate(blobs, imports[specifier]);
+ // Node's CommonJS interop adds a `module.exports` key, which no import
+ // can name; everything else a plugin can import is the host's binding.
+ const names = Object.keys(host).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name));
+ assert.ok(names.includes("default"), `${specifier} has a default export`);
+ for (const name of names) assert.equal(shim[name], host[name], `${specifier}.${name}`);
+ }
+});
+
+test("the map is installed once per document", (t) => {
+ const { scripts } = fakeDocument(t);
+ installRendererImportMap();
+ installRendererImportMap();
+ assert.equal(scripts.length, 1);
+});
+
+test("the page lets the shims and plugin modules load", () => {
+ // A script-src without blob: blocks every plugin module at load (seen live
+ // as PLUGIN_SLOT_LOAD_FAILED after a CSP security error).
+ const html = readFileSync(new URL("../index.html", import.meta.url), "utf8");
+ const scriptSrc = html.match(/script-src([^;]*);/)?.[1] ?? "";
+ assert.match(scriptSrc, /\bblob:/);
+ assert.match(scriptSrc, /\bplugin-renderer:/);
+});
diff --git a/apps/desktop/test/plugin-renderer-loader.test.mjs b/apps/desktop/test/plugin-renderer-loader.test.mjs
index a5cf54d3d..161cc8ce7 100644
--- a/apps/desktop/test/plugin-renderer-loader.test.mjs
+++ b/apps/desktop/test/plugin-renderer-loader.test.mjs
@@ -1,26 +1,487 @@
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);
-
-test("unload races the async load and late registrations are dropped", () => {
- // Contract (卸载摘注册): when a plugin is disabled/uninstalled while its
- // renderer module is still loading, the load must not leave orphan
- // registrations, injected styles, or a dispatch binding behind.
- const loader = readFileSync(src("plugins/renderer-host/loader.ts"), "utf8");
- // The lost-race check happens after onLoad resolves: the memo deleted by
- // unloadRendererModule is the signal, and every teardown surface runs.
- const checkAt = loader.indexOf("if (!loaded.has(pluginId)) {");
- const onLoadAt = loader.indexOf("await mod.onLoad(");
- const returnAt = loader.indexOf("return { pluginId, module: mod as PiRendererModule };");
- assert.ok(onLoadAt > -1 && checkAt > onLoadAt, "the race check follows onLoad");
- assert.ok(returnAt > checkAt, "the race check precedes the successful return");
- const guarded = loader.slice(checkAt, returnAt);
- assert.match(guarded, /slotRegistry\.unregisterPlugin\(pluginId\)/);
- assert.match(guarded, /removePluginStyles\(pluginId\)/);
- assert.match(guarded, /unbindDispatch\(pluginId\)/);
+/*
+ * The renderer module loader (`docs/plugin-plan/slot-contract.html` §1, §5):
+ * one load per plugin generation, a frozen `pi` bound to the plugin, and an
+ * end that takes everything the load registered, injected or dispatched with
+ * it before the plugin's `onUnload` runs, whatever the plugin did. The
+ * registry and the dispatch channel are the real ones; only the module
+ * import, the style sheets and the routes behind the channel are faked.
+ */
+const { RendererModuleLoader, rendererModuleUrl, rendererLoadSpecs } = await import(
+ "../src/plugins/renderer-host/loader.ts"
+);
+const { SlotRegistry } = await import("../src/plugins/renderer-slots/registry.ts");
+const { createDispatchChannel } = await import("../src/plugins/renderer-host/dispatch.ts");
+const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
+
+const PLUGIN = "demo.lab";
+const component = () => null;
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+function unloadedError(error) {
+ assert.ok(error instanceof PluginRendererError, `expected a PluginRendererError, got ${error}`);
+ assert.equal(error.code, "PLUGIN_UNLOADED");
+ return true;
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((ok, fail) => {
+ resolve = ok;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+function spec(pluginId = PLUGIN, overrides = {}) {
+ return {
+ pluginId,
+ version: "1.2.3",
+ descriptor: {
+ entry: "renderer/index.js",
+ generation: 1,
+ actions: ["plugin.call"],
+ callMethods: ["ping"],
+ tools: ["lookup"],
+ ...overrides,
+ },
+ };
+}
+
+/**
+ * A loader over fake module imports. `modules` maps a module URL to a module
+ * namespace, a promise of one, or a function returning either.
+ */
+function harness(modules = {}) {
+ const registry = new SlotRegistry();
+ const sheets = [];
+ const imports = [];
+ const warnings = [];
+ const calls = [];
+ let answerCall = () => Promise.resolve({ pong: true });
+ const loader = new RendererModuleLoader({
+ importModule: async (url) => {
+ imports.push(url);
+ const entry = modules[url];
+ if (entry === undefined) throw new Error(`no module at ${url}`);
+ return typeof entry === "function" ? entry() : entry;
+ },
+ registry,
+ injectStyle: (pluginId, css) => {
+ const sheet = { pluginId, css };
+ sheets.push(sheet);
+ return () => {
+ const at = sheets.indexOf(sheet);
+ if (at >= 0) sheets.splice(at, 1);
+ };
+ },
+ openChannel: (pluginId, actions) =>
+ createDispatchChannel(pluginId, actions, {
+ pluginCall: (id, method, args) => {
+ calls.push({ id, method, args });
+ return answerCall(id, method, args);
+ },
+ insertText: () => true,
+ }),
+ warn: (message, error) => warnings.push({ message, error }),
+ });
+ return {
+ loader,
+ registry,
+ sheets,
+ imports,
+ warnings,
+ calls,
+ answerCallsWith(fn) {
+ answerCall = fn;
+ },
+ };
+}
+
+const url = (pluginId = PLUGIN, generation = 1, entry = "renderer/index.js") =>
+ rendererModuleUrl(pluginId, { entry, generation });
+
+test("the module URL carries the plugin, its load generation and the encoded entry path", () => {
+ assert.equal(
+ rendererModuleUrl("demo.lab", { entry: "renderer/index.js", generation: 7 }),
+ "plugin-renderer://demo.lab/g7/renderer/index.js",
+ );
+ assert.equal(
+ rendererModuleUrl("demo.lab", { entry: "/ui/main entry#1?.js", generation: 1 }),
+ "plugin-renderer://demo.lab/g1/ui/main%20entry%231%3F.js",
+ );
+});
+
+test("onLoad gets a frozen pi bound to its plugin, and what it registers shows up", async () => {
+ let pi;
+ const h = harness({
+ [url()]: {
+ onLoad(api) {
+ pi = api;
+ api.slots.register({ slot: "entryExtra", component });
+ api.slots.register({ slot: "toolCard", toolName: "lookup", component });
+ api.ui.injectStyle(".lab { color: red; }");
+ },
+ },
+ });
+ assert.deepEqual(await h.loader.load(spec()), { status: "loaded" });
+ assert.deepEqual(h.imports, [url()]);
+
+ assert.ok(Object.isFrozen(pi) && Object.isFrozen(pi.plugin) && Object.isFrozen(pi.slots) && Object.isFrozen(pi.ui));
+ assert.deepEqual({ ...pi.plugin }, { id: PLUGIN, version: "1.2.3" });
+ assert.deepEqual(
+ h.registry.getSnapshot().entries.map((entry) => [entry.pluginId, entry.slot, entry.key]),
+ [
+ [PLUGIN, "entryExtra", undefined],
+ [PLUGIN, "toolCard", "plugin_demo_lab_lookup"],
+ ],
+ );
+ assert.deepEqual(h.sheets, [{ pluginId: PLUGIN, css: ".lab { color: red; }" }]);
+
+ // The descriptor is the plugin's grant: its own tools, its declared words.
+ assert.throws(
+ () => pi.slots.register({ slot: "toolCard", toolName: "search", component }),
+ (error) => error instanceof PluginRendererError && error.code === "PLUGIN_SLOT_NOT_OWNED",
+ );
+ assert.deepEqual(await pi.dispatch("plugin.call", { method: "ping", args: { n: 1 } }), { pong: true });
+ assert.deepEqual(h.calls, [{ id: PLUGIN, method: "ping", args: { n: 1 } }]);
+ await assert.rejects(
+ pi.dispatch("composer.insertText", { text: "hi" }),
+ (error) => error.code === "PLUGIN_ACTION_UNDECLARED",
+ );
+ assert.deepEqual(h.warnings, []);
+});
+
+test("a module's default export can carry onLoad and onUnload", async () => {
+ const seen = [];
+ const h = harness({
+ [url()]: {
+ default: {
+ onLoad: (pi) => {
+ seen.push("load");
+ pi.slots.register({ slot: "entryExtra", component });
+ },
+ onUnload: () => seen.push("unload"),
+ },
+ },
+ });
+ assert.deepEqual(await h.loader.load(spec()), { status: "loaded" });
+ await h.loader.unload(PLUGIN);
+ assert.deepEqual(seen, ["load", "unload"]);
+ assert.deepEqual(h.registry.getSnapshot().entries, []);
+});
+
+test("a load that fails is torn down, reported once and not retried for its generation", async () => {
+ const broken = new Error("onLoad broke");
+ const cases = [
+ ["the import rejects", () => Promise.reject(new Error("syntax error"))],
+ ["the module has no onLoad", () => ({ onUnload() {} })],
+ [
+ "onLoad throws after registering",
+ () => ({
+ onLoad(pi) {
+ pi.slots.register({ slot: "entryExtra", component });
+ pi.ui.injectStyle(".half { }");
+ throw broken;
+ },
+ }),
+ ],
+ [
+ "onLoad rejects after registering",
+ () => ({
+ async onLoad(pi) {
+ pi.slots.register({ slot: "assistantAction", component });
+ await tick();
+ throw broken;
+ },
+ }),
+ ],
+ ];
+ for (const [label, module] of cases) {
+ const h = harness({ [url()]: module, [url(PLUGIN, 2)]: { onLoad() {} } });
+ const outcome = await h.loader.load(spec());
+ assert.equal(outcome.status, "failed", label);
+ assert.ok(outcome.error instanceof Error, label);
+ await tick();
+ assert.deepEqual(h.registry.getSnapshot().entries, [], `${label}: registrations are gone`);
+ assert.deepEqual(h.sheets, [], `${label}: styles are gone`);
+ assert.deepEqual(
+ h.warnings.map((warning) => warning.message),
+ [`[plugin-renderer] ${PLUGIN} failed to load`],
+ label,
+ );
+ assert.equal(h.warnings[0].error, outcome.error, label);
+
+ // Asking again for the same generation is the same failed load.
+ assert.equal(await h.loader.load(spec()), outcome, label);
+ assert.deepEqual(h.loader.loadedPluginIds(), [PLUGIN], label);
+ assert.equal(h.imports.length, 1, `${label}: no retry`);
+ // A reload of the plugin is a new generation, and a new load.
+ assert.deepEqual(await h.loader.load(spec(PLUGIN, { generation: 2 })), { status: "loaded" }, label);
+ assert.deepEqual(h.imports, [url(), url(PLUGIN, 2)], label);
+ }
+});
+
+test("a plugin whose onLoad failed still gets its onUnload, after the host cleaned up", async () => {
+ const seen = [];
+ const h = harness({
+ [url()]: {
+ onLoad(pi) {
+ pi.slots.register({ slot: "entryExtra", component });
+ throw new Error("half loaded");
+ },
+ onUnload() {
+ seen.push(h.registry.getSnapshot().entries.length);
+ },
+ },
+ });
+ assert.equal((await h.loader.load(spec())).status, "failed");
+ await tick();
+ assert.deepEqual(seen, [0]);
+});
+
+test("ending a load disposes its registrations, styles and calls before onUnload runs", async () => {
+ let pi;
+ let kept;
+ const observed = [];
+ const answer = deferred();
+ const h = harness({
+ [url()]: {
+ onLoad(api) {
+ pi = api;
+ api.slots.register({ slot: "entryExtra", component });
+ kept = api.slots.register({ slot: "userAction", component, positions: ["left"] });
+ api.ui.injectStyle(".lab { }");
+ },
+ onUnload() {
+ observed.push({
+ entries: h.registry.getSnapshot().entries.length,
+ sheets: h.sheets.length,
+ });
+ },
+ },
+ });
+ h.answerCallsWith(() => answer.promise);
+ await h.loader.load(spec());
+ const inFlight = pi.dispatch("plugin.call", { method: "ping" });
+ // Another plugin's registration is not this load's to dispose.
+ h.registry.register("demo.other", { slot: "entryExtra", component }, []);
+
+ await h.loader.unload(PLUGIN);
+ assert.deepEqual(observed, [{ entries: 1, sheets: 0 }]);
+ assert.deepEqual(
+ h.registry.getSnapshot().entries.map((entry) => entry.pluginId),
+ ["demo.other"],
+ );
+ await assert.rejects(inFlight, unloadedError);
+ answer.resolve({ late: true });
+
+ // The pi of an ended load stays dead.
+ assert.throws(() => pi.slots.register({ slot: "entryExtra", component }), unloadedError);
+ assert.throws(() => pi.ui.injectStyle(".late { }"), unloadedError);
+ await assert.rejects(pi.dispatch("plugin.call", { method: "ping" }), unloadedError);
+ const version = h.registry.getSnapshot().version;
+ kept();
+ assert.equal(h.registry.getSnapshot().version, version, "a kept disposer does nothing afterwards");
+ assert.deepEqual(h.loader.loadedPluginIds(), []);
+ await h.loader.unload(PLUGIN);
+ assert.equal(observed.length, 1, "unloading twice runs onUnload once");
+});
+
+test("a registration the plugin disposed itself is not disposed again at the end", async () => {
+ let dispose;
+ const h = harness({
+ [url()]: {
+ onLoad(pi) {
+ dispose = pi.slots.register({ slot: "entryExtra", component });
+ },
+ },
+ });
+ await h.loader.load(spec());
+ dispose();
+ const version = h.registry.getSnapshot().version;
+ await h.loader.unload(PLUGIN);
+ assert.equal(h.registry.getSnapshot().version, version);
+});
+
+test("onUnload waits for a slow onLoad, whose late registrations are refused", async () => {
+ const gate = deferred();
+ const order = [];
+ let lateRegistration;
+ const h = harness({
+ [url()]: {
+ async onLoad(pi) {
+ pi.slots.register({ slot: "entryExtra", component });
+ order.push("onLoad awaits");
+ await gate.promise;
+ try {
+ pi.slots.register({ slot: "assistantAction", component });
+ } catch (error) {
+ lateRegistration = error;
+ }
+ order.push("onLoad done");
+ },
+ onUnload() {
+ order.push("onUnload");
+ },
+ },
+ });
+ const ready = h.loader.load(spec());
+ await tick();
+ const unloaded = h.loader.unload(PLUGIN).then(() => order.push("unloaded"));
+ assert.deepEqual(h.registry.getSnapshot().entries, [], "the host side ends at once");
+ await tick();
+ assert.deepEqual(order, ["onLoad awaits"], "onUnload does not overtake onLoad");
+
+ gate.resolve();
+ assert.deepEqual(await ready, { status: "cancelled" });
+ await unloaded;
+ assert.deepEqual(order, ["onLoad awaits", "onLoad done", "onUnload", "unloaded"]);
+ assert.ok(unloadedError(lateRegistration));
+ assert.deepEqual(h.registry.getSnapshot().entries, []);
+ assert.deepEqual(h.warnings, []);
+});
+
+test("a load ended during its import never runs the plugin", async () => {
+ for (const settle of ["resolve", "reject"]) {
+ const imported = deferred();
+ let ran = false;
+ const h = harness({ [url()]: () => imported.promise });
+ const ready = h.loader.load(spec());
+ await tick();
+ await h.loader.unload(PLUGIN);
+ if (settle === "resolve") {
+ imported.resolve({
+ onLoad() {
+ ran = true;
+ },
+ });
+ } else {
+ imported.reject(new Error("network gone"));
+ }
+ assert.deepEqual(await ready, { status: "cancelled" }, settle);
+ assert.equal(ran, false, settle);
+ assert.deepEqual(h.warnings, [], `${settle}: a cancelled load is not a failure`);
+ }
+});
+
+test("the same generation is one load; a new generation ends it at once and replaces it", async () => {
+ const seen = [];
+ const module = (name) => ({
+ onLoad(pi) {
+ seen.push(`${name} load`);
+ pi.slots.register({ slot: "entryExtra", component: Object.assign(() => null, { label: name }) });
+ },
+ onUnload() {
+ seen.push(`${name} unload`);
+ },
+ });
+ const secondImport = deferred();
+ const h = harness({ [url()]: module("g1"), [url(PLUGIN, 2)]: () => secondImport.promise });
+ const labels = () => h.registry.entriesFor("entryExtra").map((entry) => entry.component.label);
+ const first = h.loader.load(spec());
+ assert.equal(h.loader.load(spec()), first);
+ await first;
+ assert.equal(await h.loader.load(spec()), await first);
+ assert.deepEqual(h.imports, [url()]);
+ assert.deepEqual(labels(), ["g1"]);
+
+ // The old load does not wait for the new code to arrive.
+ const second = h.loader.load(spec(PLUGIN, { generation: 2 }));
+ assert.deepEqual(labels(), []);
+ await tick();
+ assert.deepEqual(seen, ["g1 load", "g1 unload"]);
+
+ secondImport.resolve(module("g2"));
+ assert.deepEqual(await second, { status: "loaded" });
+ assert.deepEqual(seen, ["g1 load", "g1 unload", "g2 load"]);
+ assert.deepEqual(labels(), ["g2"]);
+ assert.deepEqual(h.imports, [url(), url(PLUGIN, 2)]);
+});
+
+test("sync loads exactly the given plugins and leaves failed ones failed", async () => {
+ const unloaded = [];
+ const module = (id) => ({
+ onLoad(pi) {
+ pi.slots.register({ slot: "entryExtra", component });
+ },
+ onUnload() {
+ unloaded.push(id);
+ },
+ });
+ const h = harness({
+ [url("demo.a")]: module("demo.a"),
+ [url("demo.b")]: module("demo.b"),
+ [url("demo.broken")]: { onLoad() { throw new Error("broken"); } },
+ });
+ h.loader.sync([spec("demo.a"), spec("demo.b"), spec("demo.broken")]);
+ await tick();
+ await tick();
+ assert.deepEqual(h.loader.loadedPluginIds().sort(), ["demo.a", "demo.b", "demo.broken"]);
+ assert.deepEqual(
+ h.registry.getSnapshot().entries.map((entry) => entry.pluginId).sort(),
+ ["demo.a", "demo.b"],
+ );
+
+ h.loader.sync([spec("demo.b"), spec("demo.broken")]);
+ await tick();
+ assert.deepEqual(unloaded, ["demo.a"]);
+ assert.deepEqual(h.loader.loadedPluginIds().sort(), ["demo.b", "demo.broken"]);
+ assert.equal(h.imports.length, 3, "kept and failed plugins are not imported again");
+
+ h.loader.sync([]);
+ await tick();
+ assert.deepEqual(unloaded.sort(), ["demo.a", "demo.b"]);
+ assert.deepEqual(h.loader.loadedPluginIds(), []);
+ assert.deepEqual(h.registry.getSnapshot().entries, []);
+});
+
+test("an onUnload that throws is reported and the load still ends", async () => {
+ const broken = new Error("cleanup broke");
+ const h = harness({
+ [url()]: {
+ onLoad(pi) {
+ pi.slots.register({ slot: "entryExtra", component });
+ },
+ onUnload() {
+ throw broken;
+ },
+ },
+ });
+ await h.loader.load(spec());
+ await h.loader.unload(PLUGIN);
+ assert.deepEqual(h.warnings, [{ message: `[plugin-renderer] ${PLUGIN} onUnload failed`, error: broken }]);
+ assert.deepEqual(h.registry.getSnapshot().entries, []);
+ assert.deepEqual(h.loader.loadedPluginIds(), []);
+});
+
+test("the plugin list asks for the running renderer plugins active in the open project", () => {
+ const descriptor = spec().descriptor;
+ const plugins = [
+ { id: "demo.global", version: "1.0.0", enabled: true, renderer: descriptor },
+ { id: "demo.headless", version: "1.0.0", enabled: true },
+ { id: "demo.off", version: "1.0.0", enabled: false, renderer: descriptor },
+ {
+ id: "demo.scoped",
+ version: "2.0.0",
+ enabled: true,
+ scope: { mode: "projects", projects: ["/work/app"] },
+ renderer: descriptor,
+ },
+ ];
+ const ids = (projectPath) => rendererLoadSpecs(plugins, projectPath).map((entry) => entry.pluginId);
+ assert.deepEqual(ids("/work/app"), ["demo.global", "demo.scoped"]);
+ assert.deepEqual(ids("/Work/App/packages/ui"), ["demo.global", "demo.scoped"]);
+ assert.deepEqual(ids("/work/other"), ["demo.global"]);
+ assert.deepEqual(ids(null), ["demo.global"]);
+ assert.deepEqual(rendererLoadSpecs(plugins, "/work/app")[1], {
+ pluginId: "demo.scoped",
+ version: "2.0.0",
+ descriptor,
+ });
});
diff --git a/apps/desktop/test/plugin-self-dialog.test.mjs b/apps/desktop/test/plugin-self-dialog.test.mjs
deleted file mode 100644
index c419d5e6a..000000000
--- a/apps/desktop/test/plugin-self-dialog.test.mjs
+++ /dev/null
@@ -1,83 +0,0 @@
-import assert from "node:assert/strict";
- import { readdirSync, 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");
- // 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.
- 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-services.test.mjs b/apps/desktop/test/plugin-services.test.mjs
index 2a47798ed..db739a316 100644
--- a/apps/desktop/test/plugin-services.test.mjs
+++ b/apps/desktop/test/plugin-services.test.mjs
@@ -510,6 +510,7 @@ test("capability badges include every declared plugin capability", () => {
assert.deepEqual(order, [
"panel",
"views",
+ "rendererUi",
"commands",
"tools",
"agentExtension",
diff --git a/apps/desktop/test/plugin-slot-glue.test.mjs b/apps/desktop/test/plugin-slot-glue.test.mjs
new file mode 100644
index 000000000..ff7a6e5a0
--- /dev/null
+++ b/apps/desktop/test/plugin-slot-glue.test.mjs
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createElement, useState } from "react";
+import { probed, propsProbe, slotSsr } from "./helpers/slot-ssr.mjs";
+
+/*
+ * The React glue every slot outlet shares (`src/plugins/renderer-slots/
+ * use-slots.tsx`): a registration's component becomes an element of its own,
+ * mounts inside the element its plugin's styles are scoped to, and sits in an
+ * error boundary that takes only its own region down (出错隔离). Server
+ * rendering has no error boundaries, so the boundary is driven here the way
+ * React drives it after a throw; the Electron E2E crashes real slots.
+ */
+
+const entry = (overrides = {}) => ({
+ id: "slot-1",
+ pluginId: "demo.a",
+ slot: "entryExtra",
+ component: () => null,
+ sides: [],
+ ...overrides,
+});
+
+test("a registration's component is rendered as its own element, so its hooks are its own", async (t) => {
+ const ssr = await slotSsr(t);
+ const { slotElement, SlotMount } = await ssr.load("/src/plugins/renderer-slots/use-slots.tsx");
+ function Counter({ start }) {
+ const [count] = useState(start);
+ return createElement("output", { "data-probe": "count" }, JSON.stringify({ count }));
+ }
+ const counter = entry({ component: Counter });
+ const element = slotElement(counter, { start: 2 });
+ assert.equal(element.type, Counter, "an element of the component, not the result of calling it");
+ assert.deepEqual(element.props, { start: 2 });
+ const html = ssr.render(createElement(SlotMount, { entry: counter }, element));
+ assert.equal(
+ html,
+ '<div class="pi-plugin-slot" data-pi-plugin="demo.a" data-pi-slot="entryExtra"><output data-probe="count">{&quot;count&quot;:2}</output></div>',
+ );
+});
+
+test("the error boundary renders its region until it catches, then nothing or the fallback", async (t) => {
+ const ssr = await slotSsr(t);
+ const { SlotErrorBoundary } = await ssr.load("/src/plugins/renderer-slots/use-slots.tsx");
+ assert.deepEqual(SlotErrorBoundary.getDerivedStateFromError(new Error("boom")), { failed: true });
+
+ const bare = new SlotErrorBoundary({ entry: entry(), children: "plugin region" });
+ assert.equal(bare.render(), "plugin region");
+ bare.state = SlotErrorBoundary.getDerivedStateFromError(new Error("boom"));
+ assert.equal(bare.render(), null, "an additive region collapses");
+
+ const keyed = new SlotErrorBoundary({ entry: entry(), fallback: "host card", children: "plugin card" });
+ keyed.state = SlotErrorBoundary.getDerivedStateFromError(new Error("boom"));
+ assert.equal(keyed.render(), "host card", "a replacing region gives the host's back");
+});
+
+test("a caught throw is reported on the console with the plugin and slot it came from", async (t) => {
+ const ssr = await slotSsr(t);
+ const { SlotErrorBoundary } = await ssr.load("/src/plugins/renderer-slots/use-slots.tsx");
+ const warned = [];
+ t.mock.method(console, "warn", (...args) => warned.push(args));
+ const error = new Error("boom");
+ new SlotErrorBoundary({
+ entry: entry({ pluginId: "demo.b", slot: "toolCard" }),
+ children: null,
+ }).componentDidCatch(error);
+ assert.deepEqual(warned, [["[plugin-slot] demo.b toolCard component failed", error]]);
+});
+
+test("slot props carry the transcript's session, and an empty id outside of one", async (t) => {
+ const ssr = await slotSsr(t);
+ const { EntryExtraStack } = await ssr.load("/src/features/chat/transcript/EntryExtraStack.tsx");
+ ssr.register("demo.a", { slot: "entryExtra", component: propsProbe("extra") });
+ const message = { id: "a1", role: "assistant", content: "x", createdAt: "2026-09-24T00:00:00.000Z" };
+ const stack = createElement(EntryExtraStack, { message });
+ assert.equal(probed(ssr.render(stack, { sessionId: "s-9" }), "extra")[0].sessionId, "s-9");
+ assert.equal(probed(ssr.render(stack, { sessionId: null }), "extra")[0].sessionId, "");
+});
diff --git a/apps/desktop/test/plugin-slot-registry.test.mjs b/apps/desktop/test/plugin-slot-registry.test.mjs
new file mode 100644
index 000000000..35689d16d
--- /dev/null
+++ b/apps/desktop/test/plugin-slot-registry.test.mjs
@@ -0,0 +1,234 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * The renderer slot registry (`docs/plugin-plan/slot-contract.html` §2):
+ * what `pi.slots.register` accepts, how additive slots stack, how keyed slots
+ * refuse a second claim, and that a disposer removes exactly its own
+ * registration. Outlets only ever read what this store publishes.
+ */
+const { SlotRegistry } = await import("../src/plugins/renderer-slots/registry.ts");
+const { PluginRendererError } = await import("../src/plugins/renderer-error.ts");
+
+const PLUGIN = "demo.lab";
+const OTHER = "demo.other";
+const component = () => null;
+const named = (name) => Object.assign(() => null, { displayName: name });
+
+function refusedWith(code) {
+ return (error) => {
+ assert.ok(error instanceof PluginRendererError, `expected a PluginRendererError, got ${error}`);
+ assert.equal(error.name, "PluginRendererError");
+ assert.equal(error.code, code);
+ return true;
+ };
+}
+
+test("additive slots stack in registration order across plugins", () => {
+ const registry = new SlotRegistry();
+ const a1 = named("a1");
+ const b1 = named("b1");
+ const a2 = named("a2");
+ registry.register(PLUGIN, { slot: "entryExtra", component: a1 }, []);
+ registry.register(OTHER, { slot: "entryExtra", component: b1 }, []);
+ registry.register(PLUGIN, { slot: "entryExtra", component: a2 }, []);
+ registry.register(PLUGIN, { slot: "assistantAction", component }, []);
+
+ const stacked = registry.entriesFor("entryExtra");
+ assert.deepEqual(
+ stacked.map((entry) => entry.component),
+ [a1, b1, a2],
+ );
+ assert.deepEqual(
+ stacked.map((entry) => entry.pluginId),
+ [PLUGIN, OTHER, PLUGIN],
+ );
+ assert.equal(new Set(stacked.map((entry) => entry.id)).size, 3, "entry ids are unique");
+ for (const entry of stacked) {
+ assert.equal(entry.slot, "entryExtra");
+ assert.deepEqual(entry.sides, []);
+ assert.equal(entry.key, undefined);
+ }
+});
+
+test("a disposer removes exactly its own registration, once", () => {
+ const registry = new SlotRegistry();
+ const first = named("first");
+ const second = named("second");
+ const disposeFirst = registry.register(PLUGIN, { slot: "entryExtra", component: first }, []);
+ registry.register(PLUGIN, { slot: "entryExtra", component: second }, []);
+
+ disposeFirst();
+ assert.deepEqual(
+ registry.entriesFor("entryExtra").map((entry) => entry.component),
+ [second],
+ );
+ const version = registry.getSnapshot().version;
+ disposeFirst();
+ assert.equal(registry.getSnapshot().version, version, "a second call publishes nothing");
+ assert.equal(registry.entriesFor("entryExtra").length, 1);
+
+ // Registering the same component again is a new registration of its own.
+ const disposeAgain = registry.register(PLUGIN, { slot: "entryExtra", component: second }, []);
+ assert.equal(registry.entriesFor("entryExtra").length, 2);
+ disposeAgain();
+ assert.equal(registry.entriesFor("entryExtra").length, 1);
+});
+
+test("every accepted registration and disposal publishes a new snapshot; a refusal does not", () => {
+ const registry = new SlotRegistry();
+ let notified = 0;
+ const unsubscribe = registry.subscribe(() => {
+ notified += 1;
+ });
+ const empty = registry.getSnapshot();
+ assert.equal(empty.version, 0);
+ assert.deepEqual(empty.entries, []);
+
+ const dispose = registry.register(PLUGIN, { slot: "entryExtra", component }, []);
+ const registered = registry.getSnapshot();
+ assert.equal(notified, 1);
+ assert.equal(registered.version, 1);
+ assert.notEqual(registered, empty, "a change is a new snapshot object");
+ assert.equal(registry.getSnapshot(), registered, "no change keeps the snapshot");
+
+ assert.throws(() => registry.register(PLUGIN, { slot: "nope", component }, []));
+ assert.equal(notified, 1);
+ assert.equal(registry.getSnapshot(), registered);
+
+ dispose();
+ assert.equal(notified, 2);
+ assert.equal(registry.getSnapshot().version, 2);
+ assert.deepEqual(registry.getSnapshot().entries, []);
+
+ unsubscribe();
+ registry.register(PLUGIN, { slot: "entryExtra", component }, []);
+ assert.equal(notified, 2, "an unsubscribed listener hears nothing");
+});
+
+test("positioned slots take both sides by default and the listed sides in canonical order", () => {
+ const registry = new SlotRegistry();
+ const both = named("both");
+ const right = named("right");
+ const reversed = named("reversed");
+ const repeated = named("repeated");
+ for (const slot of ["userAction", "assistantAction", "composerControl"]) {
+ registry.register(PLUGIN, { slot, component: both }, []);
+ registry.register(PLUGIN, { slot, component: right, positions: ["right"] }, []);
+ registry.register(PLUGIN, { slot, component: reversed, positions: ["right", "left"] }, []);
+ registry.register(PLUGIN, { slot, component: repeated, positions: ["left", "left"] }, []);
+
+ assert.deepEqual(
+ registry.entriesFor(slot).map((entry) => entry.sides),
+ [["left", "right"], ["right"], ["left", "right"], ["left"]],
+ slot,
+ );
+ assert.deepEqual(
+ registry.entriesForSide(slot, "left").map((entry) => entry.component),
+ [both, reversed, repeated],
+ `${slot} left`,
+ );
+ assert.deepEqual(
+ registry.entriesForSide(slot, "right").map((entry) => entry.component),
+ [both, right, reversed],
+ `${slot} right`,
+ );
+ }
+ assert.deepEqual(registry.entriesForSide("entryExtra", "left"), []);
+});
+
+test("malformed registrations are refused with their code and change nothing", () => {
+ const cases = [
+ ["not an object", null, "PLUGIN_SLOT_UNKNOWN"],
+ ["a string", "entryExtra", "PLUGIN_SLOT_UNKNOWN"],
+ ["no slot", { component }, "PLUGIN_SLOT_UNKNOWN"],
+ ["an unknown slot", { slot: "sidebar", component }, "PLUGIN_SLOT_UNKNOWN"],
+ ["a non-string slot", { slot: 3, component }, "PLUGIN_SLOT_UNKNOWN"],
+ ["no component", { slot: "entryExtra" }, "PLUGIN_SLOT_INVALID_COMPONENT"],
+ ["an element for a component", { slot: "entryExtra", component: {} }, "PLUGIN_SLOT_INVALID_COMPONENT"],
+ ["positions on a sideless slot", { slot: "entryExtra", component, positions: ["left"] }, "PLUGIN_SLOT_INVALID_POSITION"],
+ ["empty positions", { slot: "userAction", component, positions: [] }, "PLUGIN_SLOT_INVALID_POSITION"],
+ ["an unknown side", { slot: "assistantAction", component, positions: ["top"] }, "PLUGIN_SLOT_INVALID_POSITION"],
+ ["a bare side", { slot: "composerControl", component, positions: "left" }, "PLUGIN_SLOT_INVALID_POSITION"],
+ ["a toolCard without a tool", { slot: "toolCard", component }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a blank tool name", { slot: "toolCard", component, toolName: " " }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["another plugin's tool", { slot: "toolCard", component, toolName: "search" }, "PLUGIN_SLOT_NOT_OWNED"],
+ ["a qualified tool name", { slot: "toolCard", component, toolName: "plugin_demo_lab_lookup" }, "PLUGIN_SLOT_NOT_OWNED"],
+ ["a blockRenderer without a language", { slot: "blockRenderer", component }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["another plugin's language", { slot: "blockRenderer", component, language: "demo.other:chart" }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a bare language", { slot: "blockRenderer", component, language: "chart" }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["an empty suffix", { slot: "blockRenderer", component, language: "demo.lab:" }, "PLUGIN_SLOT_INVALID_KEY"],
+ ["a suffix with a space", { slot: "blockRenderer", component, language: "demo.lab:bar chart" }, "PLUGIN_SLOT_INVALID_KEY"],
+ ];
+ const registry = new SlotRegistry();
+ for (const [label, registration, code] of cases) {
+ assert.throws(
+ () => registry.register(PLUGIN, registration, ["lookup"]),
+ refusedWith(code),
+ label,
+ );
+ }
+ assert.equal(registry.getSnapshot().version, 0);
+ assert.deepEqual(registry.getSnapshot().entries, []);
+});
+
+test("a tool card is keyed by the plugin's qualified tool name, first claim wins", () => {
+ const registry = new SlotRegistry();
+ const card = named("card");
+ const disposeCard = registry.register(
+ PLUGIN,
+ { slot: "toolCard", component: card, toolName: "lookup" },
+ ["lookup", "fetch"],
+ );
+ const [entry] = registry.entriesFor("toolCard");
+ assert.equal(entry.key, "plugin_demo_lab_lookup");
+ assert.equal(entry.toolName, "lookup");
+ assert.equal(registry.entryForKey("toolCard", "plugin_demo_lab_lookup")?.component, card);
+ assert.equal(registry.entryForKey("toolCard", "lookup"), undefined, "the bare name is not the key");
+
+ assert.throws(
+ () =>
+ registry.register(PLUGIN, { slot: "toolCard", component: named("late"), toolName: "lookup" }, [
+ "lookup",
+ ]),
+ refusedWith("PLUGIN_SLOT_DUPLICATE"),
+ );
+ assert.equal(registry.entryForKey("toolCard", "plugin_demo_lab_lookup")?.component, card);
+
+ // Another plugin's tool of the same bare name is another key.
+ const theirs = named("theirs");
+ registry.register(OTHER, { slot: "toolCard", component: theirs, toolName: "lookup" }, ["lookup"]);
+ assert.equal(registry.entryForKey("toolCard", "plugin_demo_other_lookup")?.component, theirs);
+ assert.equal(registry.entryForKey("toolCard", "plugin_demo_lab_lookup")?.component, card);
+
+ // The key frees up with its disposer.
+ disposeCard();
+ const next = named("next");
+ registry.register(PLUGIN, { slot: "toolCard", component: next, toolName: "lookup" }, ["lookup"]);
+ assert.equal(registry.entryForKey("toolCard", "plugin_demo_lab_lookup")?.component, next);
+});
+
+test("a block renderer is keyed by its normalized language tag, first claim wins", () => {
+ const registry = new SlotRegistry();
+ const chart = named("chart");
+ registry.register(PLUGIN, { slot: "blockRenderer", component: chart, language: " Demo.Lab:Chart " }, []);
+ const [entry] = registry.entriesFor("blockRenderer");
+ assert.equal(entry.key, "demo.lab:chart");
+ assert.equal(entry.toolName, undefined);
+ assert.equal(registry.entryForKey("blockRenderer", "demo.lab:chart")?.component, chart);
+
+ assert.throws(
+ () =>
+ registry.register(PLUGIN, { slot: "blockRenderer", component: named("late"), language: "demo.lab:CHART" }, []),
+ refusedWith("PLUGIN_SLOT_DUPLICATE"),
+ );
+ registry.register(PLUGIN, { slot: "blockRenderer", component: named("table"), language: "demo.lab:table" }, []);
+ assert.deepEqual(
+ registry.entriesFor("blockRenderer").map((candidate) => candidate.key),
+ ["demo.lab:chart", "demo.lab:table"],
+ );
+ // Keys are per slot: the same string never matches another slot's entry.
+ assert.equal(registry.entryForKey("toolCard", "demo.lab:chart"), undefined);
+});
diff --git a/apps/desktop/test/plugin-style-injection.test.mjs b/apps/desktop/test/plugin-style-injection.test.mjs
new file mode 100644
index 000000000..8582203b5
--- /dev/null
+++ b/apps/desktop/test/plugin-style-injection.test.mjs
@@ -0,0 +1,136 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * `pi.ui.injectStyle` (`docs/plugin-plan/slot-contract.html` §4): a plugin's
+ * style rules apply inside its own slot mounts only, rules that define names
+ * stay global, and `@import` is dropped. The browser parses the sheet, so the
+ * scoper is driven here with the rule objects the CSS engine hands back.
+ */
+const { scopedPluginCss, injectPluginStyle } = await import(
+ "../src/plugins/renderer-slots/style-injection.ts"
+);
+
+const rule = (kind, cssText) => ({ cssText, constructor: { name: kind } });
+
+test("style rules, also inside group rules, go into the plugin's scope in source order", () => {
+ const css = scopedPluginCss("demo.lab", [
+ rule("CSSStyleRule", ".card { color: red; }"),
+ rule("CSSMediaRule", "@media (width > 600px) { .card { padding: 8px; } }"),
+ rule("CSSSupportsRule", "@supports (display: grid) { .grid { display: grid; } }"),
+ rule("CSSContainerRule", "@container (width > 10px) { .x { margin: 0; } }"),
+ rule("CSSLayerBlockRule", "@layer lab { .y { gap: 1px; } }"),
+ rule("CSSScopeRule", "@scope (.card) { p { margin: 0; } }"),
+ rule("CSSStartingStyleRule", "@starting-style { .card { opacity: 0; } }"),
+ ]);
+ assert.equal(
+ css,
+ [
+ '@scope ([data-pi-plugin="demo.lab"]) {',
+ ".card { color: red; }",
+ "@media (width > 600px) { .card { padding: 8px; } }",
+ "@supports (display: grid) { .grid { display: grid; } }",
+ "@container (width > 10px) { .x { margin: 0; } }",
+ "@layer lab { .y { gap: 1px; } }",
+ "@scope (.card) { p { margin: 0; } }",
+ "@starting-style { .card { opacity: 0; } }",
+ "}",
+ ].join("\n"),
+ );
+});
+
+test("rules that define names stay global and come first; @import is dropped", () => {
+ const css = scopedPluginCss("demo.lab", [
+ rule("CSSImportRule", '@import url("https://example.invalid/x.css");'),
+ rule("CSSStyleRule", ".spin { animation: lab-spin 1s; }"),
+ rule("CSSKeyframesRule", "@keyframes lab-spin { to { rotate: 1turn; } }"),
+ rule("CSSFontFaceRule", '@font-face { font-family: "Lab"; src: local("Lab"); }'),
+ rule("CSSPropertyRule", "@property --lab-angle { syntax: \"<angle>\"; inherits: false; initial-value: 0deg; }"),
+ rule("CSSLayerStatementRule", "@layer lab, lab2;"),
+ ]);
+ const lines = css.split("\n");
+ assert.deepEqual(lines.slice(0, 4), [
+ "@keyframes lab-spin { to { rotate: 1turn; } }",
+ '@font-face { font-family: "Lab"; src: local("Lab"); }',
+ "@property --lab-angle { syntax: \"<angle>\"; inherits: false; initial-value: 0deg; }",
+ "@layer lab, lab2;",
+ ]);
+ assert.deepEqual(lines.slice(4), [
+ '@scope ([data-pi-plugin="demo.lab"]) {',
+ ".spin { animation: lab-spin 1s; }",
+ "}",
+ ]);
+ assert.doesNotMatch(css, /@import/);
+});
+
+test("a sheet without style rules adds no scope, and the scope id is a CSS string", () => {
+ assert.equal(
+ scopedPluginCss("demo.lab", [rule("CSSKeyframesRule", "@keyframes a { }")]),
+ "@keyframes a { }",
+ );
+ assert.equal(scopedPluginCss("demo.lab", []), "");
+ assert.match(
+ scopedPluginCss('odd"id\\x\ny', [rule("CSSStyleRule", "p { }")]),
+ /^@scope \(\[data-pi-plugin="odd\\"id\\\\x\\a y"\]\) \{/,
+ );
+});
+
+test("injectStyle adds one scoped <style> per sheet and its disposer removes it once", (t) => {
+ const originalDocument = globalThis.document;
+ const originalSheet = globalThis.CSSStyleSheet;
+ t.after(() => {
+ globalThis.document = originalDocument;
+ globalThis.CSSStyleSheet = originalSheet;
+ });
+ const head = [];
+ globalThis.document = {
+ head: { appendChild: (element) => head.push(element) },
+ createElement: (tag) => {
+ const element = {
+ tag,
+ attributes: {},
+ textContent: "",
+ setAttribute(name, value) {
+ element.attributes[name] = value;
+ },
+ remove() {
+ const at = head.indexOf(element);
+ if (at >= 0) head.splice(at, 1);
+ element.removed = (element.removed ?? 0) + 1;
+ },
+ };
+ return element;
+ },
+ };
+ // The engine's reading of the text: one style rule and one keyframes rule.
+ globalThis.CSSStyleSheet = class {
+ replaceSync(text) {
+ this.text = text;
+ this.cssRules = [
+ rule("CSSStyleRule", ".card { color: red; }"),
+ rule("CSSKeyframesRule", "@keyframes lab { }"),
+ ];
+ }
+ };
+
+ const dispose = injectPluginStyle("demo.lab", ".card { color: red } @keyframes lab {}");
+ assert.equal(head.length, 1);
+ const [style] = head;
+ assert.equal(style.tag, "style");
+ assert.deepEqual(style.attributes, { "data-pi-plugin-style": "demo.lab" });
+ assert.equal(
+ style.textContent,
+ '@keyframes lab { }\n@scope ([data-pi-plugin="demo.lab"]) {\n.card { color: red; }\n}',
+ );
+ dispose();
+ dispose();
+ assert.equal(head.length, 0);
+ assert.equal(style.removed, 1, "the disposer is idempotent");
+
+ for (const css of [undefined, null, 3, { toString: () => "p {}" }]) {
+ assert.throws(() => injectPluginStyle("demo.lab", css), TypeError);
+ }
+ assert.equal(head.length, 0);
+});
diff --git a/apps/desktop/test/plugin-tool-card-slot.test.mjs b/apps/desktop/test/plugin-tool-card-slot.test.mjs
index 5d049a826..fb23cc735 100644
--- a/apps/desktop/test/plugin-tool-card-slot.test.mjs
+++ b/apps/desktop/test/plugin-tool-card-slot.test.mjs
@@ -1,118 +1,153 @@
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));
+import { createElement } from "react";
+import { probed, propsProbe, slotSsr } from "./helpers/slot-ssr.mjs";
-const here = dirname(fileURLToPath(import.meta.url));
-const src = (relative) => join(here, "..", "src", relative);
+/*
+ * The keyed `toolCard` slot (`docs/plugin-plan/ui/tool-card/`) rendered with
+ * the production modules: a call of a plugin's own tool renders the card that
+ * plugin registered for it in place of the host card, fed the call's
+ * projection; every other row keeps the host card. Server rendering is the
+ * first frame of a mount: the merged running beat is driven below as the
+ * decision it is, and a card that throws or unloads handing the call back to
+ * the host card is covered by the Electron E2E.
+ */
-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 PLUGIN = "demo.lab";
+const QUALIFIED = "plugin_demo_lab_lookup";
-const message = (extra = {}) => ({
- id: "m1",
+const call = (overrides = {}) => ({
+ id: "t1",
role: "tool",
content: "",
- createdAt: "2026-09-17T00:00:00.000Z",
- toolName: "query_db",
+ status: "complete",
+ createdAt: "2026-09-24T00:00:02.000Z",
+ toolName: QUALIFIED,
toolCallId: "call-1",
+ toolArgs: { q: "x" },
toolStatus: "success",
- ...extra,
+ toolResult: { rows: 1 },
+ toolDurationMs: 12,
+ ...overrides,
});
-test("the no-claim gate refuses cards for tools the plugin does not own", () => {
+async function rows(t) {
+ const ssr = await slotSsr(t);
+ const { ToolRow } = await ssr.load("/src/features/chat/transcript/ToolRow.tsx");
+ const cadence = await ssr.load("/src/features/chat/transcript/tool-card-props.ts");
+ return {
+ ...ssr,
+ ...cadence,
+ row: (message, props = {}) => ssr.render(createElement(ToolRow, { message, ...props })),
+ claim: () =>
+ ssr.register(PLUGIN, { slot: "toolCard", toolName: "lookup", component: propsProbe("card") }, ["lookup"]),
+ };
+}
+
+test("a call of the plugin's own tool renders its card instead of the host card", async (t) => {
+ const ssr = await rows(t);
+ assert.match(ssr.row(call()), /^<div class="tool-row /, "the host card until a plugin claims the tool");
+ ssr.claim();
+ const html = ssr.row(call());
assert.match(
- toolCardOwnershipError("query_db", undefined) ?? "",
- /contributes\.agentTools/,
+ html,
+ /^<div class="pi-plugin-slot" data-pi-plugin="demo.lab" data-pi-slot="toolCard"><output data-probe="card">[^<]*<\/output><\/div>$/,
+ "the whole card is the plugin's",
);
- assert.match(
- toolCardOwnershipError("query_db", []) ?? "",
- /contributes\.agentTools/,
+ assert.deepEqual(probed(html, "card"), [
+ {
+ toolName: "lookup",
+ toolCallId: "call-1",
+ toolArgs: { q: "x" },
+ toolStatus: "success",
+ toolResult: { rows: 1 },
+ durationMs: 12,
+ messageId: "t1",
+ sessionId: "session-1",
+ },
+ ]);
+});
+
+test("a failed call reaches the card as data, a running one without a result", async (t) => {
+ const ssr = await rows(t);
+ ssr.claim();
+ assert.deepEqual(
+ probed(ssr.row(call({ toolStatus: "error", toolResult: "no such table" })), "card"),
+ [
+ {
+ toolName: "lookup",
+ toolCallId: "call-1",
+ toolArgs: { q: "x" },
+ toolStatus: "error",
+ toolError: "no such table",
+ durationMs: 12,
+ messageId: "t1",
+ sessionId: "session-1",
+ },
+ ],
+ "what the failed tool returned is toolError, never toolResult",
);
- assert.match(
- toolCardOwnershipError("other_tool", ["query_db"]) ?? "",
- /not in the plugin's own/,
+ assert.deepEqual(
+ probed(
+ ssr.row(call({ toolStatus: "running", toolCallId: undefined, toolResult: undefined, toolDurationMs: undefined })),
+ "card",
+ ),
+ [
+ {
+ toolName: "lookup",
+ toolCallId: "t1",
+ toolArgs: { q: "x" },
+ toolStatus: "running",
+ messageId: "t1",
+ sessionId: "session-1",
+ },
+ ],
+ "a call without its own id is known by its message id",
);
- 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" },
+test("denied calls, topology nodes and every other tool keep the host card", async (t) => {
+ const ssr = await rows(t);
+ const cases = [
+ ["a denied call", call({ toolStatus: "denied" }), {}],
+ ["a topology node", call(), { variant: "topology" }],
+ ["a host tool", call({ toolName: "read" }), {}],
+ ["the bare tool name", call({ toolName: "lookup" }), {}],
+ ["another plugin's tool of the same name", call({ toolName: "plugin_demo_other_lookup" }), {}],
+ ];
+ const plain = cases.map(([, message, props]) => ssr.row(message, props));
+ const dispose = ssr.claim();
+ cases.forEach(([label, message, props], index) => {
+ assert.equal(ssr.row(message, props), plain[index], label);
});
- 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");
+ const hostCard = ssr.row(call());
+ dispose();
+ assert.notEqual(hostCard, ssr.row(call()));
+ assert.match(ssr.row(call()), /^<div class="tool-row /, "the host card is back once the card leaves");
});
-test("running pushes merge on the 500ms beat; transitions are immediate", () => {
+test("running updates merge onto a 500ms beat; a transition or a finished call pushes at once", async (t) => {
+ const { TOOL_CARD_RUNNING_INTERVAL_MS, shouldEmitToolCard } = await rows(t);
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);
+ const cases = [
+ ["running inside the beat", 1_000, "running", "running", 1_499, false],
+ ["running on the beat", 1_000, "running", "running", 1_500, true],
+ ["running past the beat", 1_000, "running", "running", 2_200, true],
+ ["running to success", 1_000, "running", "success", 1_001, true],
+ ["running to error", 1_000, "running", "error", 1_001, true],
+ ["a finished call's update", 1_000, "success", "success", 1_001, true],
+ ];
+ for (const [label, lastAt, lastStatus, nextStatus, now, emits] of cases) {
+ assert.equal(shouldEmitToolCard(lastAt, lastStatus, nextStatus, now), emits, label);
+ }
+ assert.equal(shouldEmitToolCard(1_000, "running", "running", 1_100, 100), true, "the beat is a parameter");
});
-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*\)/,
+test("the card's status vocabulary is running, error or success", async (t) => {
+ const { toolCardStatusOf } = await rows(t);
+ const statuses = ["running", "error", "success", undefined].map((toolStatus) =>
+ toolCardStatusOf(call({ toolStatus })),
);
- 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\[\]/);
+ assert.deepEqual(statuses, ["running", "error", "success", "success"]);
});
diff --git a/apps/desktop/test/plugin-ui-slots-demo.test.mjs b/apps/desktop/test/plugin-ui-slots-demo.test.mjs
deleted file mode 100644
index b1560e0d8..000000000
--- a/apps/desktop/test/plugin-ui-slots-demo.test.mjs
+++ /dev/null
@@ -1,162 +0,0 @@
-import assert from "node:assert/strict";
-import { execFileSync } from "node:child_process";
- import { readdirSync, 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");
- // 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",
-);
-
-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.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 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", () => {
- // The React import map serves shims from blob: URLs; a built page whose
- // script-src lacks blob: blocks every plugin module at load (seen live as
- // PLUGIN_SLOT_LOAD_FAILED after a CSP security error).
- const html = readFileSync(root("apps/desktop/index.html"), "utf8");
- assert.match(html, /script-src[^;]*\bblob:/);
-});
-
-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 every renderer module as ESM.
- checkRendererSyntax();
-
- const registrations = [...rendererSource.matchAll(/pi\.slots\.register\(\s*"([^"]+)"/g)].map(
- (match) => match[1],
- );
- // 7 slots + three entryExtra registrations (runner, spark, self-dialog).
- assert.deepEqual(
- registrations,
- [
- "entryExtra",
- "userAction",
- "assistantAction",
- "toolCard",
- "blockRenderer",
- "composerControl",
- "composerTrigger",
- "composerToken",
- "entryExtra",
- "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/apps/desktop/test/plugin-ui-slots-lab.test.mjs b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
new file mode 100644
index 000000000..e30ca3184
--- /dev/null
+++ b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
@@ -0,0 +1,249 @@
+import assert from "node:assert/strict";
+import { fork } from "node:child_process";
+import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { PLUGIN_RENDERER_ACTIONS, validateManifest } from "@pi-desktop/plugin-sdk";
+import { composerToolbar } from "./helpers/composer-toolbar.mjs";
+import { slotMounts, slotSsr } from "./helpers/slot-ssr.mjs";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const hostProcessEntry = join(here, "../electron/main/plugin-host-process.mjs");
+const LAB_DIR = join(here, "../../../examples/plugins/ui-slots-lab");
+
+// Set before the runtime is imported so per-plugin data lands in a throwaway
+// directory instead of the developer's real one.
+process.env.PI_DESKTOP_DATA_DIR = mkdtempSync(join(tmpdir(), "pi-ui-slots-lab-data-"));
+
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+
+/*
+ * The UI Slots Lab (`examples/plugins/ui-slots-lab`), the test plugin with a
+ * visible sample in every slot, run the way the app runs it: its manifest
+ * through the SDK validator and the plugin runtime, its headless entry in a
+ * real plugin host process, and its renderer entry through the production
+ * loader into the slot registry the host outlets read. What needs a live
+ * window (clicks, crashes the host contains, the size clamps) is driven by
+ * the Electron E2E against this same plugin.
+ */
+
+const LAB = "lab.ui-slots";
+const PROBE = "plugin_lab_ui_slots_lab_probe";
+const SESSION = "session-1";
+const manifest = JSON.parse(readFileSync(join(LAB_DIR, "manifest.json"), "utf8"));
+
+function forkPluginProcess({ entry }) {
+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
+ return {
+ postMessage: (message) => {
+ if (child.connected) child.send(message);
+ },
+ onMessage: (handler) => child.on("message", handler),
+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
+ kill: () => child.kill(),
+ };
+}
+
+/** The lab loaded in a real runtime, with the grants its manifest asks for. */
+async function labRuntime(t) {
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ getWorkspacePath: () => null,
+ audit: () => {},
+ });
+ t.after(() => runtime.disposeAll());
+ await runtime.loadFromPath(LAB_DIR, manifest.permissions);
+ return runtime;
+}
+
+function refusedWith(code) {
+ return (error) => {
+ assert.equal(error.code, code, error.message);
+ return true;
+ };
+}
+
+/**
+ * The lab's renderer entry, loaded by the production loader from the files
+ * the runtime serves for its current generation, into the registry the host
+ * outlets read. Its `plugin.call` goes to the runtime; its composer inserts
+ * are recorded.
+ */
+async function labWindow(t) {
+ const runtime = await labRuntime(t);
+ const ssr = await slotSsr(t);
+ const { RendererModuleLoader, rendererModuleUrl } = await ssr.load("/src/plugins/renderer-host/loader.ts");
+ const { createDispatchChannel } = await ssr.load("/src/plugins/renderer-host/dispatch.ts");
+ const descriptor = runtime.rendererDescriptor(LAB);
+ const sheets = new Set();
+ const inserted = [];
+ const channels = [];
+ const loader = new RendererModuleLoader({
+ importModule: (url) => {
+ assert.equal(url, rendererModuleUrl(LAB, descriptor), "the loader asks for the current generation");
+ return import(pathToFileURL(runtime.resolveRendererSource(LAB, descriptor.generation, descriptor.entry)).href);
+ },
+ registry: ssr.registry,
+ injectStyle: (pluginId, css) => {
+ const sheet = { pluginId, css };
+ sheets.add(sheet);
+ return () => sheets.delete(sheet);
+ },
+ openChannel: (pluginId, actions) => {
+ const channel = createDispatchChannel(pluginId, actions, {
+ pluginCall: (id, method, args) => runtime.callRenderer(id, method, args),
+ insertText: (text) => inserted.push(text) > 0,
+ });
+ channels.push(channel);
+ return channel;
+ },
+ warn: (message, error) => assert.fail(`${message}: ${error?.stack ?? error}`),
+ });
+ const outcome = await loader.load({ pluginId: LAB, version: manifest.version, descriptor });
+ t.after(() => loader.unload(LAB));
+ return { ...ssr, runtime, loader, outcome, sheets, inserted, dispatch: channels[0].dispatch };
+}
+
+const USER = { id: "u1", role: "user", content: "Probe the lab\nplease", status: "complete", createdAt: "2026-09-24T00:00:00.000Z" };
+const CHART = "```lab.ui-slots:chart\nalpha,3\nbeta,5\n```";
+
+/** A reply that called the lab's tool and answered with a chart. */
+const TURN = [
+ USER,
+ { id: "a1", role: "assistant", content: "Probing.", status: "complete", createdAt: "2026-09-24T00:00:01.000Z" },
+ {
+ id: "t1",
+ role: "tool",
+ content: "",
+ status: "complete",
+ createdAt: "2026-09-24T00:00:02.000Z",
+ toolName: PROBE,
+ toolCallId: "call-lab-1",
+ toolArgs: { mode: "ok", text: "hi" },
+ toolStatus: "success",
+ toolResult: { ok: true, mode: "ok", text: "hi", length: 2 },
+ toolDurationMs: 7,
+ },
+ { id: "a2", role: "assistant", content: `Here it is.\n\n${CHART}\n`, status: "complete", createdAt: "2026-09-24T00:00:03.000Z" },
+];
+
+async function transcript(ssr) {
+ const { MessageRow } = await ssr.load("/src/features/chat/transcript/MessageRow.tsx");
+ const { AssistantTurn } = await ssr.load("/src/features/chat/transcript/AssistantTurn.tsx");
+ const { buildTranscriptEntries } = await ssr.load("/src/lib/assistant-turns.ts");
+ const { createElement } = await import("react");
+ const entry = buildTranscriptEntries(TURN).entries.find((candidate) => candidate.kind === "assistant-turn");
+ return {
+ row: () => ssr.render(createElement(MessageRow, { message: USER, isRunning: false }), { sessionId: SESSION }),
+ turn: () => ssr.render(createElement(AssistantTurn, { entry, isActive: false }), { sessionId: SESSION }),
+ };
+}
+
+/** Every lab sample in `html`, in document order. */
+function samples(html) {
+ return [...html.matchAll(/data-lab="([^"]*)"/g)].map((match) => match[1]);
+}
+
+/** The session every sample that carries one was mounted for. */
+function sessions(html) {
+ return [...new Set([...html.matchAll(/data-lab-session="([^"]*)"/g)].map((match) => match[1]))];
+}
+
+test("the manifest declares exactly what the lab uses", () => {
+ const validation = validateManifest(manifest);
+ assert.ok(validation.ok, validation.error);
+ assert.deepEqual(manifest.rendererActions, [...PLUGIN_RENDERER_ACTIONS], "every action word the host implements");
+ assert.deepEqual(manifest.permissions, ["renderer.extension", "agent.tool.register"]);
+ assert.deepEqual(manifest.contributes.agentTools.map((tool) => tool.name), ["lab_probe"]);
+
+ // Every word a sample dispatches, and every method it calls, is declared;
+ // every declared method is one a sample calls.
+ const renderer = join(LAB_DIR, "renderer");
+ const source = readdirSync(renderer).map((file) => readFileSync(join(renderer, file), "utf8")).join("\n");
+ const words = new Set([...source.matchAll(/run\("([^"]+)"/g)].map((match) => match[1]));
+ const methods = new Set([...source.matchAll(/method: "([^"]+)"/g)].map((match) => match[1]));
+ assert.deepEqual([...words].sort(), [...manifest.rendererActions].sort());
+ assert.deepEqual([...methods].sort(), [...manifest.rendererCallMethods].sort());
+});
+
+test("the headless entry answers the lab's calls and runs its tool", async (t) => {
+ const runtime = await labRuntime(t);
+
+ assert.deepEqual(await runtime.callRenderer(LAB, "lab.echo", { messageId: "a2" }), { echo: { messageId: "a2" } });
+ await assert.rejects(runtime.callRenderer(LAB, "lab.refuse", {}), refusedWith("LAB_REFUSED"));
+ const started = Date.now();
+ await assert.rejects(runtime.callRenderer(LAB, "lab.stall", {}), refusedWith("PLUGIN_CALL_TIMEOUT"));
+ assert.ok(Date.now() - started < 4_000, "a stall ends at the relay's budget, not the plugin's sleep");
+
+ const probe = runtime.getTools().find((tool) => tool.fullName === PROBE);
+ assert.ok(probe, "the tool is registered under its qualified name");
+ assert.deepEqual(await probe.execute({ text: "hi" }), { ok: true, mode: "ok", text: "hi", length: 2 });
+ await assert.rejects(probe.execute({ mode: "fail", text: "x" }), /lab_probe failed on request: x/);
+});
+
+test("the renderer entry loads a sample into every slot", async (t) => {
+ const lab = await labWindow(t);
+ assert.deepEqual(lab.outcome, { status: "loaded" });
+ assert.equal(lab.sheets.size, 1, "one style sheet");
+ assert.equal([...lab.sheets][0].pluginId, LAB);
+
+ const { row, turn } = await transcript(lab);
+ const toolbar = await composerToolbar(t, lab);
+
+ const user = row();
+ assert.deepEqual(samples(user), ["userAction:left", "userAction:right"]);
+ assert.deepEqual(sessions(user), [SESSION]);
+
+ const reply = turn();
+ assert.deepEqual(samples(reply), [
+ "toolCard",
+ "blockRenderer",
+ "assistantAction:left",
+ "assistantAction:right",
+ "assistantAction:refuse",
+ "assistantAction:crash",
+ "entryExtra",
+ "entryExtra:notes",
+ ]);
+ assert.deepEqual(sessions(reply), [SESSION]);
+ assert.ok(slotMounts(reply).every(([pluginId]) => pluginId === LAB));
+ // The fourth right item waits in the ⋯ menu, closed in the first frame.
+ assert.match(reply, /<div class="pi-action-overflow" data-side="right">/);
+ assert.match(reply, /data-lab="toolCard" data-lab-status="success"/);
+ assert.match(reply, /data-lab-output="">result \{&quot;ok&quot;:true,&quot;mode&quot;:&quot;ok&quot;/);
+ assert.match(reply, /data-lab="blockRenderer" data-lab-language="lab.ui-slots:chart"/);
+ assert.equal([...reply.matchAll(/class="lab-bar-row"/g)].length, 2, "one bar per data line");
+ assert.match(reply, /data-lab-message="a2"/, "the entryExtra panel sits under the final reply");
+
+ assert.deepEqual(samples(toolbar()), ["composerControl:left", "composerControl:right", "composerControl:crash"]);
+});
+
+test("the samples' calls work through the host channel", async (t) => {
+ const lab = await labWindow(t);
+
+ assert.deepEqual(await lab.dispatch("plugin.call", { method: "lab.echo", args: { messageId: "a2" } }), {
+ echo: { messageId: "a2" },
+ });
+ await assert.rejects(lab.dispatch("plugin.call", { method: "lab.refuse" }), refusedWith("LAB_REFUSED"));
+ assert.deepEqual(await lab.dispatch("composer.insertText", { text: "lab: hi " }), { ok: true });
+ assert.deepEqual(lab.inserted, ["lab: hi "]);
+});
+
+test("unloading the renderer entry takes every sample and its styles with it", async (t) => {
+ const lab = await labWindow(t);
+ const { row, turn } = await transcript(lab);
+ const toolbar = await composerToolbar(t, lab);
+
+ await lab.loader.unload(LAB);
+ assert.equal(lab.sheets.size, 0);
+ for (const html of [row(), turn(), toolbar()]) {
+ assert.deepEqual(samples(html), []);
+ assert.deepEqual(slotMounts(html), []);
+ }
+ await assert.rejects(lab.dispatch("plugin.call", { method: "lab.echo" }), refusedWith("PLUGIN_UNLOADED"));
+});
diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjs
index fda97fc69..621dd3f89 100644
--- a/apps/desktop/test/session-message-presentation.test.mjs
+++ b/apps/desktop/test/session-message-presentation.test.mjs
@@ -49,8 +49,8 @@ function loadComponent(name, extras = {}) {
useTranscriptMenu: () => () => {},
useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),
},
- "./ActionBarSlots": { ActionBarSlots: ({ children }) => children },
- "../../../plugins/renderer-slots/use-slots": { useSlotEntries: () => [] },
+ "./ActionBarSlots": { ActionSlotSide: () => null },
+ "../../../plugins/renderer-slots/slot-message": { slotMessage: () => undefined },
...extras,
};
const module = { exports: {} };
diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rs
index f7f37c90f..3cab6aaa7 100644
--- a/crates/host-core/src/plugins.rs
+++ b/crates/host-core/src/plugins.rs
@@ -67,9 +67,7 @@ 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, renderer_row, sanitize_id, tools_row,
-};
+pub(crate) use permissions::{derive_capabilities, derive_settings, permission_diff, sanitize_id};
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,
diff --git a/crates/host-core/src/plugins/install.rs b/crates/host-core/src/plugins/install.rs
index 38e30787d..8ec766dc0 100644
--- a/crates/host-core/src/plugins/install.rs
+++ b/crates/host-core/src/plugins/install.rs
@@ -133,8 +133,6 @@ 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/model.rs b/crates/host-core/src/plugins/model.rs
index acaecceec..43a03d2f2 100644
--- a/crates/host-core/src/plugins/model.rs
+++ b/crates/host-core/src/plugins/model.rs
@@ -81,19 +81,6 @@ 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 90dfe2e80..b2f7ee220 100644
--- a/crates/host-core/src/plugins/permissions.rs
+++ b/crates/host-core/src/plugins/permissions.rs
@@ -115,41 +115,6 @@ 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 edf4e1565..75c057e36 100644
--- a/crates/host-core/src/plugins/registry.rs
+++ b/crates/host-core/src/plugins/registry.rs
@@ -143,8 +143,6 @@ 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(),
@@ -329,8 +327,6 @@ 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/renderer.rs b/crates/host-core/src/plugins/renderer.rs
index 5960cd3ae..d614f8801 100644
--- a/crates/host-core/src/plugins/renderer.rs
+++ b/crates/host-core/src/plugins/renderer.rs
@@ -123,6 +123,9 @@ mod tests {
let parsed = PluginManager::read_manifest(&root).unwrap();
assert_eq!(parsed.renderer.as_deref(), Some("renderer/index.mjs"));
assert_eq!(parsed.renderer_actions, vec!["plugin.call".to_string()]);
+ // The Plugins page shows the surface; what the renderer host may load
+ // comes from the live load in the desktop host, not from this row.
+ assert!(derive_capabilities(&parsed).contains(&"rendererUi".to_string()));
}
#[test]
diff --git a/docs/plugin-plan/index.html b/docs/plugin-plan/index.html
index 844a76793..3ad256c5a 100644
--- a/docs/plugin-plan/index.html
+++ b/docs/plugin-plan/index.html
@@ -146,7 +146,7 @@
</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>
+ <p class="note"><b>落地状态:</b>以上 7 项已实现(SDK + 宿主挂载 + 契约测试 + 示例插件 <code>examples/plugins/ui-slots-lab</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 e8080c671..41744f3bc 100644
--- a/docs/plugin-plan/slot-contract.html
+++ b/docs/plugin-plan/slot-contract.html
@@ -145,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 与宿主已实现(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>
+ <li>SDK 与宿主已实现(7 槽 + self-dialog 指导项;dispatch 词表 <code>plugin.call</code> / <code>composer.insertText</code> / <code>composer.acceptTriggerItem</code>);示例见 <code>examples/plugins/ui-slots-lab</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 f331f4962..d024fe613 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 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-lab</div>
</header>
<main>
diff --git a/docs/plugin-plan/ui/composer/data-flow.html b/docs/plugin-plan/ui/composer/data-flow.html
index 4493885f3..8a4f68b45 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 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-lab</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 7617eab84..358d89ed8 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 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-lab</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 ec8bb82e8..462add8a2 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 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-lab</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 21c7193d5..6711655fd 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 与宿主已实现,示例见 examples/plugins/ui-slots-demo</div>
+ <div class="meta">status: finalized · 槽名与 props 字段名已定稿(见 slot-contract.html §6);SDK 与宿主已实现,示例见 examples/plugins/ui-slots-lab</div>
</header>
<main>
diff --git a/examples/plugins/README.md b/examples/plugins/README.md
index 855147481..14816df8d 100644
--- a/examples/plugins/README.md
+++ b/examples/plugins/README.md
@@ -36,6 +36,29 @@ Panel chrome contract:
`top: var(--pi-plugin-titlebar-height, 46px)`. The plugin owns that UI and
should add `-webkit-app-region: no-drag` to its interactive controls.
+## ui-slots-lab
+
+Test plugin for the renderer UI slots (`docs/plugin-plan/`). It puts one
+visible sample in every slot, each marked `data-lab="<slot>[:<side>]"`:
+
+- `userAction` / `assistantAction` items; the assistant bar's right side has
+ four items, so the fourth sits in the ⋯ menu
+- two stacked `entryExtra` blocks under a reply
+- the `toolCard` of its own `lab_probe` tool
+- the `blockRenderer` for `lab.ui-slots:chart` fences (`label,value` lines)
+- `composerControl` controls on both toolbar sides
+
+The samples exercise the contract a person should see working: `plugin.call`
+round trips (`Echo`, `Refuse` → `LAB_REFUSED`, `Stall` →
+`PLUGIN_CALL_TIMEOUT`), `composer.insertText`, a `Crash` control the host
+must contain, `Grow` past the entryExtra collapsed height, and deliberate
+contract failures that hand the block back to the host: `lab_probe`
+with `mode: "crash"`, and a chart whose first line is `crash` or `tall`
+(taller than the 4000px clamp).
+
+Covered by `apps/desktop/test/plugin-ui-slots-lab.test.mjs` and the Electron
+E2E.
+
## Planned examples
- `panel-basic`
diff --git a/examples/plugins/ui-slots-demo/main.js b/examples/plugins/ui-slots-demo/main.js
deleted file mode 100644
index 4371564b3..000000000
--- a/examples/plugins/ui-slots-demo/main.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 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
deleted file mode 100644
index dc98cfd07..000000000
--- a/examples/plugins/ui-slots-demo/manifest.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "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/actions.mjs b/examples/plugins/ui-slots-demo/renderer/actions.mjs
deleted file mode 100644
index dd4831225..000000000
--- a/examples/plugins/ui-slots-demo/renderer/actions.mjs
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 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.mjs
deleted file mode 100644
index e4b5717e9..000000000
--- a/examples/plugins/ui-slots-demo/renderer/cards.mjs
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * 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.mjs
deleted file mode 100644
index 6519d4538..000000000
--- a/examples/plugins/ui-slots-demo/renderer/composer.mjs
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 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.mjs
deleted file mode 100644
index 5f98a3384..000000000
--- a/examples/plugins/ui-slots-demo/renderer/extras.mjs
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * 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.mjs
deleted file mode 100644
index 6d2580be6..000000000
--- a/examples/plugins/ui-slots-demo/renderer/index.mjs
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * UI Slots Demo — renderer entry ("demo.ui-slots").
- *
- * 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 { 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";
-
-export function onLoad(pi) {
- applyDemoStyles(pi);
-
- // 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 });
- // composerControl 双侧一个组件,按 position 分形态。
- pi.slots.register("composerControl", ComposerControl);
- pi.slots.register("composerTrigger", ComposerTrigger, { trigger: "#" });
- pi.slots.register("composerToken", ComposerToken);
- 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 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.mjs
deleted file mode 100644
index bfb57e66e..000000000
--- a/examples/plugins/ui-slots-demo/renderer/styles.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-/**
- * 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;
-}
-`);
-}
diff --git a/examples/plugins/ui-slots-lab/main.js b/examples/plugins/ui-slots-lab/main.js
new file mode 100644
index 000000000..a378893d7
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/main.js
@@ -0,0 +1,62 @@
+/**
+ * UI Slots Lab — headless entry (`lab.ui-slots`).
+ *
+ * Owns what the renderer samples need from the plugin process: the
+ * `lab_probe` agent tool (a `toolCard` only draws the plugin's own tools) and
+ * the `plugin.call` methods the renderer lists in `rendererCallMethods`.
+ */
+
+const TOOL = "lab_probe";
+const SLOW_MS = 1_500;
+/** Past the host's 2s `plugin.call` budget, so a stall ends as a timeout. */
+const STALL_MS = 5_000;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function onLoad() {
+ await pi.agent.registerTool({
+ name: TOOL,
+ description:
+ "UI Slots Lab probe. mode: ok (default) answers at once, slow after 1.5s, fail throws, crash answers but its card throws",
+ risk: "low",
+ schema: {
+ type: "object",
+ properties: {
+ mode: { type: "string", enum: ["ok", "slow", "fail", "crash"] },
+ text: { type: "string" },
+ },
+ },
+ execute: async (args) => {
+ const mode = String(args?.mode ?? "ok");
+ const text = String(args?.text ?? "");
+ if (mode === "slow") await sleep(SLOW_MS);
+ if (mode === "fail") throw new Error(`lab_probe failed on request: ${text}`);
+ return { ok: true, mode, text, length: text.length };
+ },
+ });
+}
+
+async function onUnload() {
+ await pi.agent.unregisterTool(TOOL);
+}
+
+/** The `plugin.call` target. Thrown codes reach the renderer unchanged. */
+async function onRendererCall(method, args) {
+ switch (method) {
+ case "lab.echo":
+ return { echo: args ?? null };
+ case "lab.refuse":
+ throw Object.assign(new Error("the lab refuses on request"), { code: "LAB_REFUSED" });
+ case "lab.stall":
+ await sleep(STALL_MS);
+ return { late: true };
+ default:
+ throw Object.assign(new Error(`unknown lab method: ${method}`), { code: "LAB_UNKNOWN_METHOD" });
+ }
+}
+
+module.exports = {
+ onLoad,
+ onUnload,
+ onRendererCall,
+};
diff --git a/examples/plugins/ui-slots-lab/manifest.json b/examples/plugins/ui-slots-lab/manifest.json
new file mode 100644
index 000000000..1f1b4d06d
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/manifest.json
@@ -0,0 +1,33 @@
+{
+ "schemaVersion": 1,
+ "id": "lab.ui-slots",
+ "name": "UI Slots Lab",
+ "version": "0.1.0",
+ "description": "Test plugin with one visible sample in every renderer UI slot, plus controls that exercise dispatch, errors, crash isolation and the host size clamps",
+ "author": "PI-Desktop",
+ "main": "main.js",
+ "renderer": "renderer/index.mjs",
+ "rendererActions": ["plugin.call", "composer.insertText"],
+ "rendererCallMethods": ["lab.echo", "lab.refuse", "lab.stall"],
+ "contributes": {
+ "agentTools": [
+ {
+ "name": "lab_probe",
+ "description": "UI Slots Lab probe. mode: ok (default) answers at once, slow after 1.5s, fail throws, crash answers but its card throws",
+ "risk": "low",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "mode": { "type": "string", "enum": ["ok", "slow", "fail", "crash"] },
+ "text": { "type": "string" }
+ }
+ }
+ }
+ ]
+ },
+ "permissions": ["renderer.extension", "agent.tool.register"],
+ "engines": {
+ "piDesktop": ">=0.1.0"
+ },
+ "activationEvents": ["onStartup"]
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/blocks.mjs b/examples/plugins/ui-slots-lab/renderer/blocks.mjs
new file mode 100644
index 000000000..917fe1c6d
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/blocks.mjs
@@ -0,0 +1,70 @@
+/**
+ * Block samples: the `toolCard` of the plugin's own `lab_probe` tool and the
+ * `blockRenderer` for `lab.ui-slots:chart` fences.
+ *
+ * Both have a way to fail the contract on purpose, which must hand the block
+ * back to the host: a `lab_probe` call with `mode: "crash"` makes its card
+ * throw, a chart whose first line is `crash` throws, and one whose first line
+ * is `tall` draws past the host's height clamp.
+ */
+import { createElement as h } from "react";
+import { SessionTag } from "./lab.mjs";
+
+/** Taller than the host's 4000px block clamp. */
+const TALL_PX = 5_000;
+
+function json(value) {
+ return value === undefined ? "—" : JSON.stringify(value);
+}
+
+function errorText(error) {
+ if (typeof error === "string") return error;
+ return typeof error?.message === "string" ? error.message : json(error);
+}
+
+export function ProbeCard({ toolName, toolCallId, toolArgs, toolStatus, toolResult, toolError, durationMs, sessionId }) {
+ if (toolArgs?.mode === "crash") throw new Error("lab: toolCard crashed on request");
+ return h("div", { className: "lab-card", "data-lab": "toolCard", "data-lab-status": toolStatus, "data-lab-session": sessionId },
+ h("div", { className: "lab-head" },
+ h("strong", null, `UI Slots Lab · ${toolName}`),
+ h("span", { className: `lab-pill lab-${toolStatus}` }, toolStatus),
+ h(SessionTag, { sessionId })),
+ h("div", { className: "lab-facts" },
+ h("span", { "data-lab-call": toolCallId }, `call ${toolCallId.slice(0, 12)}`),
+ typeof durationMs === "number" ? h("span", null, `${durationMs}ms`) : null),
+ h("code", { className: "lab-code" }, `args ${json(toolArgs)}`),
+ toolStatus === "running"
+ ? h("div", { className: "lab-quiet" }, "running…")
+ : toolStatus === "error"
+ ? h("div", { className: "lab-error", "data-lab-error": "" }, errorText(toolError))
+ : h("code", { className: "lab-code", "data-lab-output": "" }, `result ${json(toolResult)}`));
+}
+
+/** `label,value` lines; a line whose value is not a number is skipped. */
+function bars(source) {
+ return source.split("\n").flatMap((line) => {
+ const [label, raw] = line.split(",");
+ const value = Number(raw);
+ return label && raw !== undefined && Number.isFinite(value) ? [{ label: label.trim(), value }] : [];
+ });
+}
+
+export function ChartBlock({ language, source }) {
+ const first = source.split("\n")[0]?.trim();
+ if (first === "crash") throw new Error("lab: blockRenderer crashed on request");
+ const rows = bars(source);
+ const max = Math.max(1, ...rows.map((row) => row.value));
+ return h("div", { className: "lab-card", "data-lab": "blockRenderer", "data-lab-language": language },
+ h("div", { className: "lab-head" },
+ h("strong", null, "UI Slots Lab · blockRenderer"),
+ h("code", null, language)),
+ rows.length
+ ? h("div", { className: "lab-bars" },
+ rows.map((row, index) =>
+ h("div", { key: index, className: "lab-bar-row" },
+ h("span", { className: "lab-bar-label" }, row.label),
+ h("span", { className: "lab-bar", style: { width: `${(row.value / max) * 100}%` } }),
+ h("span", { className: "lab-bar-value" }, String(row.value)))))
+ : h("div", { className: "lab-quiet" }, "no label,value lines"),
+ first === "tall" ? h("div", { "data-lab-tall": "", style: { height: TALL_PX } }) : null);
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/composer.mjs b/examples/plugins/ui-slots-lab/renderer/composer.mjs
new file mode 100644
index 000000000..ee890e85c
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/composer.mjs
@@ -0,0 +1,32 @@
+/**
+ * Composer samples: a `composerControl` on each side of the toolbar and a
+ * right-side control that crashes when asked.
+ */
+import { createElement as h } from "react";
+import { Button, Outcome, useCrash, useDispatch } from "./lab.mjs";
+
+/** Left: insert text at the caret. Right: a `plugin.call` round trip. */
+export function ComposerControl({ position }) {
+ const [outcome, run] = useDispatch();
+ if (position === "left") {
+ return h("span", { className: "lab-action", "data-lab": "composerControl:left" },
+ h(Button, {
+ lab: "insert",
+ onClick: () => run("composer.insertText", { text: "lab: hello from the composer " }, () => "inserted"),
+ }, "Lab insert"),
+ h(Outcome, { outcome }));
+ }
+ return h("span", { className: "lab-action", "data-lab": "composerControl:right" },
+ h(Button, {
+ lab: "echo",
+ onClick: () => run("plugin.call", { method: "lab.echo", args: { from: "composer" } }, (answer) =>
+ answer?.echo?.from === "composer" ? "echo ✓" : "echo ✗"),
+ }, "Lab echo"),
+ h(Outcome, { outcome }));
+}
+
+export function ComposerCrash() {
+ const crash = useCrash("composerControl");
+ return h("span", { className: "lab-action", "data-lab": "composerControl:crash" },
+ h(Button, { lab: "crash", onClick: crash }, "Crash"));
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/index.mjs b/examples/plugins/ui-slots-lab/renderer/index.mjs
new file mode 100644
index 000000000..a36d6e3b5
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/index.mjs
@@ -0,0 +1,43 @@
+/**
+ * UI Slots Lab — renderer entry (`lab.ui-slots`).
+ *
+ * One visible sample in every renderer slot, each able to exercise the parts
+ * of the contract a person or the Electron E2E has to see working: dispatch
+ * round trips and their error codes, a crash the host contains, and the
+ * host's size clamps. A plain ES module with no build step; `react`
+ * resolves to the host's React through the window's import map.
+ */
+import { bindLab } from "./lab.mjs";
+import { ChartBlock, ProbeCard } from "./blocks.mjs";
+import { ComposerControl, ComposerCrash } from "./composer.mjs";
+import {
+ AssistantAction,
+ AssistantCrash,
+ AssistantFolded,
+ AssistantRefuse,
+ EntryNotes,
+ EntryPanel,
+ UserAction,
+} from "./messages.mjs";
+import { LAB_CSS } from "./styles.mjs";
+
+export function onLoad(pi) {
+ bindLab(pi);
+ pi.ui.injectStyle(LAB_CSS);
+
+ pi.slots.register({ slot: "userAction", component: UserAction });
+
+ pi.slots.register({ slot: "assistantAction", component: AssistantAction });
+ pi.slots.register({ slot: "assistantAction", component: AssistantRefuse, positions: ["right"] });
+ pi.slots.register({ slot: "assistantAction", component: AssistantCrash, positions: ["right"] });
+ pi.slots.register({ slot: "assistantAction", component: AssistantFolded, positions: ["right"] });
+
+ pi.slots.register({ slot: "entryExtra", component: EntryPanel });
+ pi.slots.register({ slot: "entryExtra", component: EntryNotes });
+
+ pi.slots.register({ slot: "toolCard", toolName: "lab_probe", component: ProbeCard });
+ pi.slots.register({ slot: "blockRenderer", language: `${pi.plugin.id}:chart`, component: ChartBlock });
+
+ pi.slots.register({ slot: "composerControl", component: ComposerControl });
+ pi.slots.register({ slot: "composerControl", component: ComposerCrash, positions: ["right"] });
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/lab.mjs b/examples/plugins/ui-slots-lab/renderer/lab.mjs
new file mode 100644
index 000000000..373feaf5f
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/lab.mjs
@@ -0,0 +1,64 @@
+/**
+ * What every lab sample shares: the running load's `pi`, a dispatch hook
+ * that shows how a call ended, a crash switch, and the session tag.
+ *
+ * Every sample carries `data-lab="<slot>[:<side>]"`, and every result or
+ * error code lands in a `data-lab-result` output, so a person reads the
+ * outcome at a glance and the E2E reads it off the DOM.
+ */
+import { createElement as h, useState } from "react";
+
+let labPi = null;
+
+/** Keep the `pi` of the current load; the host hands a new one per load. */
+export function bindLab(pi) {
+ labPi = pi;
+}
+
+/**
+ * One dispatch at a time, and what came of it: `idle`, `pending`, the text
+ * `describe` made of the answer, or the error's `code`.
+ */
+export function useDispatch() {
+ const [outcome, setOutcome] = useState({ status: "idle", text: "" });
+ const run = (action, payload, describe = (value) => JSON.stringify(value)) => {
+ setOutcome({ status: "pending", text: "…" });
+ labPi.dispatch(action, payload).then(
+ (value) => setOutcome({ status: "ok", text: describe(value) }),
+ (error) => setOutcome({ status: "error", text: String(error?.code ?? "ERROR") }),
+ );
+ };
+ return [outcome, run];
+}
+
+/** The outcome of `useDispatch`, as its sample shows it. */
+export function Outcome({ outcome }) {
+ return h(
+ "output",
+ { className: "lab-result", "data-lab-result": outcome.status },
+ outcome.text,
+ );
+}
+
+/**
+ * A crash switch: `crash()` makes the next render of the calling component
+ * throw, which the host has to contain.
+ */
+export function useCrash(where) {
+ const [crashed, setCrashed] = useState(false);
+ if (crashed) throw new Error(`lab: ${where} crashed on request`);
+ return () => setCrashed(true);
+}
+
+/** The session a sample was mounted for, shortened for the eye. */
+export function SessionTag({ sessionId }) {
+ return h(
+ "span",
+ { className: "lab-session", "data-lab-session": sessionId, title: `session ${sessionId}` },
+ sessionId ? sessionId.slice(0, 8) : "no session",
+ );
+}
+
+export function Button({ lab, onClick, children, title }) {
+ return h("button", { type: "button", className: "lab-btn", "data-lab-button": lab, title, onClick }, children);
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/messages.mjs b/examples/plugins/ui-slots-lab/renderer/messages.mjs
new file mode 100644
index 000000000..2ff9cd448
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/messages.mjs
@@ -0,0 +1,126 @@
+/**
+ * Message samples: the action-bar items of `userAction` / `assistantAction`
+ * and the `entryExtra` blocks under a reply.
+ *
+ * The assistant bar gets four items on its right side, one more than a side
+ * shows, so the fourth sits in the host's ⋯ menu.
+ */
+import { createElement as h, useState } from "react";
+import { Button, Outcome, SessionTag, useCrash, useDispatch } from "./lab.mjs";
+
+function firstLine(text) {
+ return String(text ?? "").split("\n").find((line) => line.trim()) ?? "";
+}
+
+function ActionItem({ lab, sessionId, children }) {
+ return h("span", { className: "lab-action", "data-lab": lab, "data-lab-session": sessionId }, children);
+}
+
+/** Left: a local star toggle. Right: quote the message into the composer. */
+export function UserAction({ message, sessionId, position }) {
+ const [starred, setStarred] = useState(false);
+ const [outcome, run] = useDispatch();
+ if (position === "left") {
+ return h(ActionItem, { lab: "userAction:left", sessionId },
+ h(Button, { lab: "star", title: `lab · ${message.id}`, onClick: () => setStarred(!starred) },
+ starred ? "★ Starred" : "☆ Star"));
+ }
+ return h(ActionItem, { lab: "userAction:right", sessionId },
+ h(Button, {
+ lab: "quote",
+ onClick: () => run("composer.insertText", { text: `> ${firstLine(message.content)}\n\n` }, () => "quoted"),
+ }, "Quote"),
+ h(Outcome, { outcome }));
+}
+
+/** Left: a `plugin.call` round trip. Right: quote the reply. */
+export function AssistantAction({ message, messageId, sessionId, position }) {
+ const [outcome, run] = useDispatch();
+ if (position === "left") {
+ return h(ActionItem, { lab: "assistantAction:left", sessionId },
+ h(Button, {
+ lab: "echo",
+ onClick: () =>
+ run("plugin.call", { method: "lab.echo", args: { messageId } }, (answer) =>
+ answer?.echo?.messageId === messageId ? "echo ✓" : "echo ✗"),
+ }, "Echo"),
+ h(Outcome, { outcome }));
+ }
+ return h(ActionItem, { lab: "assistantAction:right", sessionId },
+ h(Button, {
+ lab: "quote",
+ onClick: () => run("composer.insertText", { text: `> ${firstLine(message.content)}\n\n` }, () => "quoted"),
+ }, "Quote"),
+ h(Outcome, { outcome }));
+}
+
+/** A call the plugin process refuses: its own code comes back. */
+export function AssistantRefuse({ sessionId }) {
+ const [outcome, run] = useDispatch();
+ return h(ActionItem, { lab: "assistantAction:refuse", sessionId },
+ h(Button, { lab: "refuse", onClick: () => run("plugin.call", { method: "lab.refuse" }) }, "Refuse"),
+ h(Outcome, { outcome }));
+}
+
+/** An item that throws when asked: it leaves the bar, nothing else does. */
+export function AssistantCrash({ sessionId }) {
+ const crash = useCrash("assistantAction");
+ return h(ActionItem, { lab: "assistantAction:crash", sessionId },
+ h(Button, { lab: "crash", onClick: crash }, "Crash"));
+}
+
+/** The fourth right item, so it lives in the ⋯ menu. */
+export function AssistantFolded({ sessionId }) {
+ const [outcome, run] = useDispatch();
+ return h(ActionItem, { lab: "assistantAction:folded", sessionId },
+ h(Button, {
+ lab: "folded",
+ onClick: () => run("composer.insertText", { text: "lab: sent from the ⋯ menu " }, () => "inserted"),
+ }, "Folded"),
+ h(Outcome, { outcome }));
+}
+
+const GROWN_LINES = 30;
+
+/**
+ * The main block under a reply: its ids, dispatch round trips (an echo, a
+ * stall past the call budget, a composer insert), a switch that grows it
+ * past the host's collapsed height, and a crash switch.
+ */
+export function EntryPanel({ message, messageId, sessionId }) {
+ const [outcome, run] = useDispatch();
+ const [grown, setGrown] = useState(false);
+ const crash = useCrash("entryExtra");
+ return h("div", { className: "lab-card", "data-lab": "entryExtra", "data-lab-session": sessionId },
+ h("div", { className: "lab-head" },
+ h("strong", null, "UI Slots Lab · entryExtra"),
+ h(SessionTag, { sessionId })),
+ h("div", { className: "lab-facts" },
+ h("span", { "data-lab-message": messageId }, `message ${messageId.slice(0, 8)}`),
+ h("span", null, `${message.content.length} chars`)),
+ h("div", { className: "lab-row" },
+ h(Button, {
+ lab: "echo",
+ onClick: () =>
+ run("plugin.call", { method: "lab.echo", args: { messageId } }, (answer) =>
+ answer?.echo?.messageId === messageId ? "echo ✓" : "echo ✗"),
+ }, "Echo"),
+ h(Button, { lab: "stall", onClick: () => run("plugin.call", { method: "lab.stall" }) }, "Stall"),
+ h(Button, {
+ lab: "insert",
+ onClick: () => run("composer.insertText", { text: `lab: about ${messageId} ` }, () => "inserted"),
+ }, "Insert"),
+ h(Button, { lab: "grow", onClick: () => setGrown(!grown) }, grown ? "Shrink" : "Grow"),
+ h(Button, { lab: "crash", onClick: crash }, "Crash"),
+ h(Outcome, { outcome })),
+ grown
+ ? h("ol", { className: "lab-lines", "data-lab-grown": "true" },
+ Array.from({ length: GROWN_LINES }, (_, index) => h("li", { key: index }, `line ${index + 1}`)))
+ : null);
+}
+
+/** A second block, stacked after the panel and unaffected by its crash. */
+export function EntryNotes({ sessionId }) {
+ return h("div", { className: "lab-card lab-quiet", "data-lab": "entryExtra:notes", "data-lab-session": sessionId },
+ "UI Slots Lab · second entryExtra block. It stays when the panel above crashes.");
+}
diff --git a/examples/plugins/ui-slots-lab/renderer/styles.mjs b/examples/plugins/ui-slots-lab/renderer/styles.mjs
new file mode 100644
index 000000000..abdbf93ea
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/styles.mjs
@@ -0,0 +1,91 @@
+/**
+ * The lab's style sheet. `pi.ui.injectStyle` scopes every rule to the lab's
+ * own slot mounts, so plain class names are enough; the host tokens keep
+ * the samples readable in both themes.
+ */
+export const LAB_CSS = `
+.lab-card {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 8px 10px;
+ border: 1px dashed var(--ds-accent);
+ border-radius: 8px;
+ color: var(--ds-text-primary);
+ font-size: 12px;
+ line-height: 1.5;
+}
+.lab-head, .lab-row, .lab-facts {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+}
+.lab-facts, .lab-quiet {
+ color: var(--ds-text-muted);
+}
+.lab-action {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+.lab-btn {
+ padding: 1px 8px;
+ border: 1px solid var(--ds-border-default);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--ds-accent);
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+.lab-btn:hover {
+ background: var(--ds-bg-hover);
+}
+.lab-result {
+ color: var(--ds-text-muted);
+ font-size: 11px;
+}
+.lab-result[data-lab-result="ok"] {
+ color: var(--ds-success);
+}
+.lab-result[data-lab-result="error"] {
+ color: var(--ds-error);
+}
+.lab-session, .lab-pill {
+ padding: 0 6px;
+ border-radius: 99px;
+ background: var(--ds-bg-chip);
+ color: var(--ds-text-secondary);
+ font-size: 10px;
+}
+.lab-running { color: var(--ds-warning); }
+.lab-success { color: var(--ds-success); }
+.lab-error, .lab-pill.lab-error { color: var(--ds-error); }
+.lab-code {
+ overflow-wrap: anywhere;
+ font-size: 11px;
+}
+.lab-lines {
+ margin: 0;
+ padding-left: 20px;
+}
+.lab-bars {
+ display: grid;
+ gap: 4px;
+}
+.lab-bar-row {
+ display: grid;
+ grid-template-columns: 80px 1fr 48px;
+ align-items: center;
+ gap: 6px;
+}
+.lab-bar {
+ height: 10px;
+ border-radius: 3px;
+ background: var(--ds-accent);
+}
+.lab-bar-value {
+ text-align: right;
+}
+`;
diff --git a/package.json b/package.json
index 317835446..b39f75079 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"test:e2e:capability-move": "node scripts/e2e-capability-move.mjs",
"test:e2e:plugin-import-deps": "node scripts/e2e-plugin-import-deps.mjs",
"test:e2e:trusted-extensions": "node scripts/e2e-trusted-extensions.mjs",
+ "test:e2e:plugin-ui-slots": "node scripts/e2e-plugin-ui-slots.mjs",
"test:e2e:collaboration": "node scripts/e2e-session-collaboration.mjs",
"test:e2e:session-completion": "node scripts/e2e-session-completion.mjs",
"test:e2e:remote-host": "node scripts/e2e-remote-host.mjs",
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 601ca7d11..87009a180 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2057,6 +2057,7 @@ sklm: {
"commands": "Befehle",
"tools": "Agententools",
"agentExtension": "Agent-Erweiterung",
+ "rendererUi": "Chat-UI-Erweiterung",
"skills": "Fähigkeiten",
"themes": "Thema",
"mcp": "MCP-Server",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 45b0e7f6a..b9e7f6892 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2076,6 +2076,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a
commands: "Commands",
tools: "Agent tools",
agentExtension: "Agent extension",
+ rendererUi: "Chat UI extension",
skills: "Skills",
themes: "Theme",
mcp: "MCP server",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 89a9e6e68..a2c06e034 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2057,6 +2057,7 @@ sklm: {
"commands": "Comandos",
"tools": "Herramientas del agente",
"agentExtension": "Extensión del agente",
+ "rendererUi": "Extensión de la interfaz del chat",
"skills": "Habilidades",
"themes": "Tema",
"mcp": "Servidor MCP",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 923382924..29e9b73f3 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2057,6 +2057,7 @@ sklm: {
"commands": "Commandes",
"tools": "Outils d'agent",
"agentExtension": "Extension de l'agent",
+ "rendererUi": "Extension de l'interface du chat",
"skills": "Compétences",
"themes": "Thème",
"mcp": "Serveur MCP",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index a078ed812..b02215a83 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2073,6 +2073,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
commands: "명령",
tools: "에이전트 도구",
agentExtension: "에이전트 확장",
+ rendererUi: "채팅 UI 확장",
skills: "스킬",
themes: "테마",
mcp: "MCP 서버",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index d2ca693c0..c3c7364bf 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2063,6 +2063,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
commands: "Komutlar",
tools: "Ajan araçları",
agentExtension: "Ajan uzantısı",
+ rendererUi: "Sohbet arayüzü uzantısı",
skills: "Beceriler",
themes: "Tema",
mcp: "MCP sunucusu",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index ab558b90e..d83e8a0b9 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2043,6 +2043,7 @@ sklm: {
commands: "命令",
tools: "智能体工具",
agentExtension: "Agent 扩展",
+ rendererUi: "对话界面扩展",
skills: "技能",
themes: "主题",
mcp: "MCP 服务",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 075dd4f55..5b68be496 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2043,6 +2043,7 @@ sklm: {
commands: "命令",
tools: "智慧體工具",
agentExtension: "Agent 擴充",
+ rendererUi: "對話介面擴充",
skills: "技能",
themes: "主題",
mcp: "MCP 服務",
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index c724a5bbd..a4839647c 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -67,9 +67,12 @@ export type PluginManifest = {
*/
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`.
+ * Outbound actions the renderer components may dispatch
+ * (`PLUGIN_RENDERER_ACTIONS`). Declaring fewer is safe; an action outside
+ * this list is refused with `PLUGIN_ACTION_UNDECLARED`. A word this host does
+ * not implement still installs, so a manifest written for a newer host
+ * loads, and is refused at dispatch with `PLUGIN_ACTION_UNKNOWN`. Requires
+ * `renderer.extension`.
*/
rendererActions?: string[];
/**
@@ -1265,6 +1268,12 @@ export type PluginModule = {
onUnload?: () => Promise<void> | void;
/** Optional fixed-channel operations for an isolated plugin panel. */
onPanelInvoke?: (channel: string, payload: unknown) => Promise<unknown> | unknown;
+ /**
+ * Answers the renderer entry's `plugin.call` for a method listed in
+ * `manifest.rendererCallMethods`. `args` defaults to `{}`; the answer must
+ * be JSON. Throw an `Error` with a `code` to hand that code to the caller.
+ */
+ onRendererCall?: (method: string, args: unknown) => Promise<unknown> | unknown;
};
/** Upper bound on ExtensionAPI modules one plugin may contribute. */
@@ -2140,32 +2149,35 @@ export {
PLUGIN_RENDERER_SCHEME,
PLUGIN_RENDERER_SLOTS,
PLUGIN_SLOT_POSITIONS,
- PLUGIN_COMPOSER_TRIGGERS,
- PLUGIN_COMPOSER_TOKEN_LIMIT,
- slotKeyError,
- slotPositionsError,
- toolCardOwnershipError,
+ PLUGIN_RENDERER_ACTIONS,
+ PLUGIN_INSERT_TEXT_MAX_BYTES,
+ blockRendererLanguageKey,
+ slotRegistrationRefusal,
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 PluginSlotMessage,
type PluginActionSlotProps,
type PluginEntryExtraSlotProps,
+ type PluginToolCardStatus,
type PluginToolCardSlotProps,
type PluginBlockRendererSlotProps,
type PluginComposerControlSlotProps,
- type PluginComposerTriggerProps,
- type PluginComposerTrigger,
- type PluginComposerTriggerItem,
- type PluginComposerTokenProps,
- type PluginRendererCall,
+ type PluginSlotComponent,
+ type PluginActionSlotRegistration,
+ type PluginEntryExtraSlotRegistration,
+ type PluginToolCardSlotRegistration,
+ type PluginBlockRendererSlotRegistration,
+ type PluginComposerControlSlotRegistration,
+ type PluginSlotRegistration,
+ type PluginDisposer,
+ type PluginRendererActionName,
+ type PluginRendererActionMap,
+ type PluginRendererDispatch,
+ type PluginCallPayload,
+ type PluginInsertTextPayload,
+ type PluginSlotErrorCode,
+ type PluginRendererErrorCode,
+ type PluginSlotRefusal,
} from "./renderer.js";
diff --git a/packages/plugin-sdk/src/renderer.test.ts b/packages/plugin-sdk/src/renderer.test.ts
new file mode 100644
index 000000000..da5c2451a
--- /dev/null
+++ b/packages/plugin-sdk/src/renderer.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+import {
+ PLUGIN_RENDERER_ACTIONS,
+ PLUGIN_RENDERER_SLOTS,
+ blockRendererLanguageKey,
+ slotRegistrationRefusal,
+} from "./renderer.js";
+
+const PLUGIN = "demo.lab";
+const component = () => null;
+
+function codeOf(registration: unknown, ownTools: readonly string[] = []) {
+ return slotRegistrationRefusal(PLUGIN, registration, ownTools)?.code ?? null;
+}
+
+describe("renderer vocabulary", () => {
+ it("names every slot the host mounts and only implemented actions", () => {
+ expect(PLUGIN_RENDERER_SLOTS).toEqual([
+ "userAction",
+ "assistantAction",
+ "entryExtra",
+ "toolCard",
+ "blockRenderer",
+ "composerControl",
+ ]);
+ expect(PLUGIN_RENDERER_ACTIONS).toEqual(["plugin.call", "composer.insertText"]);
+ });
+});
+
+describe("slotRegistrationRefusal", () => {
+ it("accepts a well-formed registration for every slot", () => {
+ expect(codeOf({ slot: "entryExtra", component })).toBeNull();
+ expect(codeOf({ slot: "userAction", component })).toBeNull();
+ expect(codeOf({ slot: "assistantAction", component, positions: ["left"] })).toBeNull();
+ expect(codeOf({ slot: "composerControl", component, positions: ["left", "right"] })).toBeNull();
+ expect(codeOf({ slot: "toolCard", toolName: "query_db", component }, ["query_db"])).toBeNull();
+ expect(codeOf({ slot: "blockRenderer", language: "demo.lab:chart", component })).toBeNull();
+ });
+
+ it("refuses a slot outside the vocabulary", () => {
+ expect(codeOf(undefined)).toBe("PLUGIN_SLOT_UNKNOWN");
+ expect(codeOf("entryExtra")).toBe("PLUGIN_SLOT_UNKNOWN");
+ expect(codeOf({ component })).toBe("PLUGIN_SLOT_UNKNOWN");
+ expect(codeOf({ slot: "composerToken", component })).toBe("PLUGIN_SLOT_UNKNOWN");
+ expect(codeOf({ slot: "composerTrigger", component })).toBe("PLUGIN_SLOT_UNKNOWN");
+ });
+
+ it("requires a function component", () => {
+ expect(codeOf({ slot: "entryExtra" })).toBe("PLUGIN_SLOT_INVALID_COMPONENT");
+ expect(codeOf({ slot: "entryExtra", component: "<div/>" })).toBe(
+ "PLUGIN_SLOT_INVALID_COMPONENT",
+ );
+ expect(codeOf({ slot: "entryExtra", component: { render: component } })).toBe(
+ "PLUGIN_SLOT_INVALID_COMPONENT",
+ );
+ });
+
+ it("takes positions only on sided slots, as a non-empty left/right list", () => {
+ expect(codeOf({ slot: "entryExtra", component, positions: ["left"] })).toBe(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ );
+ expect(
+ codeOf({ slot: "toolCard", toolName: "query_db", component, positions: ["left"] }, [
+ "query_db",
+ ]),
+ ).toBe("PLUGIN_SLOT_INVALID_POSITION");
+ expect(codeOf({ slot: "userAction", component, positions: [] })).toBe(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ );
+ expect(codeOf({ slot: "userAction", component, positions: "left" })).toBe(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ );
+ expect(codeOf({ slot: "composerControl", component, positions: ["top"] })).toBe(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ );
+ // Repeating a side is harmless; the host keeps one mount per side.
+ expect(codeOf({ slot: "userAction", component, positions: ["left", "left"] })).toBeNull();
+ });
+
+ it("keys a tool card on one of the plugin's own agent tools", () => {
+ expect(codeOf({ slot: "toolCard", component }, ["query_db"])).toBe("PLUGIN_SLOT_INVALID_KEY");
+ expect(codeOf({ slot: "toolCard", toolName: " ", component }, ["query_db"])).toBe(
+ "PLUGIN_SLOT_INVALID_KEY",
+ );
+ expect(codeOf({ slot: "toolCard", toolName: "query_db", component }, [])).toBe(
+ "PLUGIN_SLOT_NOT_OWNED",
+ );
+ // The bare name is the key; the qualified agent-facing name is not.
+ expect(
+ codeOf({ slot: "toolCard", toolName: "plugin_demo_lab_query_db", component }, ["query_db"]),
+ ).toBe("PLUGIN_SLOT_NOT_OWNED");
+ });
+
+ it("keys a block renderer on the plugin's own language namespace", () => {
+ expect(codeOf({ slot: "blockRenderer", component })).toBe("PLUGIN_SLOT_INVALID_KEY");
+ expect(codeOf({ slot: "blockRenderer", language: "chart", component })).toBe(
+ "PLUGIN_SLOT_INVALID_KEY",
+ );
+ expect(codeOf({ slot: "blockRenderer", language: "other.plugin:chart", component })).toBe(
+ "PLUGIN_SLOT_INVALID_KEY",
+ );
+ expect(codeOf({ slot: "blockRenderer", language: "demo.lab:", component })).toBe(
+ "PLUGIN_SLOT_INVALID_KEY",
+ );
+ expect(codeOf({ slot: "blockRenderer", language: "demo.lab:a b", component })).toBe(
+ "PLUGIN_SLOT_INVALID_KEY",
+ );
+ // Tags compare case-insensitively and ignore surrounding space.
+ expect(codeOf({ slot: "blockRenderer", language: " Demo.Lab:Chart_2 ", component })).toBeNull();
+ });
+});
+
+describe("blockRendererLanguageKey", () => {
+ it("normalizes a tag the same way on both sides of the lookup", () => {
+ expect(blockRendererLanguageKey(" Demo.Lab:Chart ")).toBe("demo.lab:chart");
+ expect(blockRendererLanguageKey("demo.lab:chart")).toBe("demo.lab:chart");
+ });
+});
diff --git a/packages/plugin-sdk/src/renderer.ts b/packages/plugin-sdk/src/renderer.ts
index 7b7c3b93e..0d7c2eb14 100644
--- a/packages/plugin-sdk/src/renderer.ts
+++ b/packages/plugin-sdk/src/renderer.ts
@@ -1,28 +1,34 @@
/**
- * UI slot contract shared by all renderer slots (`docs/plugin-plan/ui/`).
+ * Renderer extension contract (`docs/plugin-plan/slot-contract.html`).
*
- * 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`):
+ * A plugin holding `renderer.extension` ships a renderer entry
+ * (`manifest.renderer`): an ES module the host evaluates in its own window.
+ * `onLoad(pi)` registers slot components with `pi.slots.register`, styles with
+ * `pi.ui.injectStyle`, and reaches the host only through `pi.dispatch` and the
+ * action vocabulary below. Every registration returns a disposer, and
+ * unloading the plugin disposes all of them.
*
- * - `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.
+ * Slots (`docs/plugin-plan/ui/`):
+ * - `userAction` / `assistantAction` — additive items left and right of the
+ * host keys on a message's action bar.
+ * - `entryExtra` — additive block below an assistant reply.
+ * - `toolCard` — the card for calls of one of the plugin's own agent tools.
+ * - `blockRenderer` — a fenced code block tagged `<pluginId>:<lang>`.
+ * - `composerControl` — additive controls left and right in the composer
+ * toolbar.
*
- * Self-dialog (modal/overlay) is deliberately **not** a slot: plugins draw
- * it themselves inside their own components (`docs/plugin-plan/ui/self-dialog/`).
+ * Self-dialogs are not a slot: a component draws them itself
+ * (`docs/plugin-plan/ui/self-dialog/`).
+ *
+ * The module runs in the host's own realm, so none of this is a security
+ * boundary. The contract keeps well-behaved plugins apart and out of the
+ * host's way; the `renderer.extension` grant is what trusts the code.
*/
/** Privileged scheme that serves renderer entry modules. */
export const PLUGIN_RENDERER_SCHEME = "plugin-renderer";
-/** Every renderer slot the host mounts. */
+/** Every slot the host mounts. */
export const PLUGIN_RENDERER_SLOTS = [
"userAction",
"assistantAction",
@@ -30,152 +36,172 @@ export const PLUGIN_RENDERER_SLOTS = [
"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`. */
+/** Sides of the action bars and of the composer toolbar. */
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];
+export type PluginSlotPosition = (typeof PLUGIN_SLOT_POSITIONS)[number];
-/** In-draft token cap: the 9th token onward collapses into a host `⧉ +N` chip. */
-export const PLUGIN_COMPOSER_TOKEN_LIMIT = 8;
+/** Slots whose registration takes `positions`. */
+const POSITIONED_SLOTS: readonly PluginRendererSlot[] = [
+ "userAction",
+ "assistantAction",
+ "composerControl",
+];
-/** Message shape the host hands to message-anchored slots. */
+/** A message as message-anchored slots see it. */
export type PluginSlotMessage = {
readonly id: string;
- readonly role: "user" | "assistant" | "system" | "tool";
+ readonly role: "user" | "assistant";
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.
+ * `userAction` / `assistantAction` props: the message, its ids, and the side
+ * the item is mounted on. No host functions and no other 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. */
+/** `entryExtra` props: assistant replies only, so no `position`. */
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 PluginToolCardStatus = "running" | "success" | "error";
+
+/**
+ * `toolCard` props for one call of the plugin's own tool. `toolName` is the
+ * bare name the card registered for. A failed call is data (`toolError`),
+ * never a throw.
+ */
export type PluginToolCardSlotProps = {
readonly toolName: string;
readonly toolCallId: string;
readonly toolArgs?: unknown;
- readonly toolStatus: "running" | "success" | "error";
+ readonly toolStatus: PluginToolCardStatus;
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. */
+/** `blockRenderer` props: the fence's language tag and its raw text, once. */
export type PluginBlockRendererSlotProps = {
readonly language: string;
readonly source: string;
};
-/** Props for the composer control slot — a rendering position, no data. */
+/** `composerControl` props: only where the control is mounted. */
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;
+/**
+ * A slot component: a React function component, rendered with the React the
+ * host shares through its import map (`import React from "react"`).
+ */
+export type PluginSlotComponent<Props> = (props: Props) => unknown;
+
+/** `userAction` / `assistantAction`: sides to occupy; omitted means both. */
+export type PluginActionSlotRegistration = {
+ readonly slot: "userAction" | "assistantAction";
+ readonly component: PluginSlotComponent<PluginActionSlotProps>;
+ readonly positions?: readonly PluginSlotPosition[];
};
-/** 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;
+export type PluginEntryExtraSlotRegistration = {
+ readonly slot: "entryExtra";
+ readonly component: PluginSlotComponent<PluginEntryExtraSlotProps>;
};
-/** Token props — label for display, send data preserved into the submit payload. */
-export type PluginComposerTokenProps = {
- readonly label: string;
- readonly send: unknown;
- readonly dispatch: PluginRendererDispatch;
+/** `toolName` is a bare `contributes.agentTools[].name` of this plugin. */
+export type PluginToolCardSlotRegistration = {
+ readonly slot: "toolCard";
+ readonly toolName: string;
+ readonly component: PluginSlotComponent<PluginToolCardSlotProps>;
};
-/** Host → plugin, once per `plugin.call`. Plugin answers with a JSON value. */
-export type PluginRendererCall = {
- readonly pluginId: string;
- readonly method: string;
- readonly args?: unknown;
+/** `language` is `<pluginId>:<lang>`; tags compare case-insensitively. */
+export type PluginBlockRendererSlotRegistration = {
+ readonly slot: "blockRenderer";
+ readonly language: string;
+ readonly component: PluginSlotComponent<PluginBlockRendererSlotProps>;
+};
+
+/** Sides to occupy; omitted means both. */
+export type PluginComposerControlSlotRegistration = {
+ readonly slot: "composerControl";
+ readonly component: PluginSlotComponent<PluginComposerControlSlotProps>;
+ readonly positions?: readonly PluginSlotPosition[];
};
-/** Plugin → host, the only outbound channel for slot components. */
-export type PluginRendererDispatch = (
- action: PluginRendererActionName,
- payload?: unknown,
-) => Promise<unknown>;
+/** What `pi.slots.register` accepts, discriminated by `slot`. */
+export type PluginSlotRegistration =
+ | PluginActionSlotRegistration
+ | PluginEntryExtraSlotRegistration
+ | PluginToolCardSlotRegistration
+ | PluginBlockRendererSlotRegistration
+ | PluginComposerControlSlotRegistration;
/**
- * 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.
+ * Outbound actions the host implements. A plugin may dispatch only the words
+ * it lists in `manifest.rendererActions`; a word outside this vocabulary is
+ * refused with `PLUGIN_ACTION_UNKNOWN`, one outside the manifest with
+ * `PLUGIN_ACTION_UNDECLARED`.
*/
-export type PluginRendererActionName =
- | "plugin.call"
- | "composer.insertText"
- | "composer.acceptTriggerItem";
+export const PLUGIN_RENDERER_ACTIONS = ["plugin.call", "composer.insertText"] as const;
-/** `plugin.call` payload — `pluginId` is host-injected, never plugin-supplied. */
+export type PluginRendererActionName = (typeof PLUGIN_RENDERER_ACTIONS)[number];
+
+/** `composer.insertText` text ceiling, in UTF-8 bytes. */
+export const PLUGIN_INSERT_TEXT_MAX_BYTES = 32 * 1024;
+
+/**
+ * `plugin.call`: one JSON answer from this plugin's `onRendererCall`. The
+ * host adds the plugin id; a component can only ever call its own plugin.
+ */
export type PluginCallPayload = {
readonly method: string;
readonly args?: unknown;
};
-/** A registration handle; `remove()` unregisters (卸载摘注册). */
-export type PluginRendererRegistration = {
- readonly slot: PluginRendererSlot;
- remove(): void;
+/** `composer.insertText`: plain text at the composer caret. */
+export type PluginInsertTextPayload = {
+ readonly text: string;
};
-/** A style handle; `remove()` drops the injected sheet. */
-export type PluginRendererStyleHandle = {
- remove(): void;
+/** Payload and result of every action word. */
+export type PluginRendererActionMap = {
+ "plugin.call": { payload: PluginCallPayload; result: unknown };
+ "composer.insertText": { payload: PluginInsertTextPayload; result: { ok: true } };
};
/**
- * 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.
+ * The only outbound channel of renderer code. Rejects with an `Error` whose
+ * `code` is a `PluginRendererErrorCode`, or the code the plugin's own
+ * `onRendererCall` threw with.
*/
+export type PluginRendererDispatch = <Action extends PluginRendererActionName>(
+ action: Action,
+ payload: PluginRendererActionMap[Action]["payload"],
+) => Promise<PluginRendererActionMap[Action]["result"]>;
+
+/** Undoes one registration; calling it again does nothing. */
+export type PluginDisposer = () => void;
+
+/** The `pi` object handed to a renderer entry's `onLoad`. */
export type PiRendererApi = {
readonly plugin: {
readonly id: string;
@@ -183,170 +209,163 @@ export type PiRendererApi = {
};
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).
+ * Mount a component in a slot. Throws an `Error` whose `code` is a
+ * `PluginSlotErrorCode` when the host refuses the registration, or
+ * `PLUGIN_UNLOADED` once this load has ended.
*/
- register<Props>(
- slot: PluginRendererSlot,
- component: (props: Props) => unknown,
- options?: PluginRendererSlotOptions,
- ): PluginRendererRegistration;
+ register(registration: PluginSlotRegistration): PluginDisposer;
};
readonly ui: {
- /** Inject a style sheet scoped under `.pi-plugin-slot.<pluginId>`. */
- injectStyle(css: string): PluginRendererStyleHandle;
+ /**
+ * Add a style sheet that applies only inside this plugin's own slot
+ * mounts. Style rules are scoped, also inside `@media`, `@supports`,
+ * `@container` and `@layer` blocks; rules that define names
+ * (`@keyframes`, `@font-face`, `@property`) stay global, and `@import` is
+ * dropped. Throws a `TypeError` for anything but a string, and
+ * `PLUGIN_UNLOADED` once this load has ended.
+ */
+ injectStyle(css: string): PluginDisposer;
};
+ readonly dispatch: PluginRendererDispatch;
};
-/** Renderer entry module shape — plain ES module, no build step required. */
+/** Renderer entry module shape: a 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 =
+/** Why `pi.slots.register` refused a registration. */
+export type PluginSlotErrorCode =
+ /** `slot` is not in `PLUGIN_RENDERER_SLOTS`. */
| "PLUGIN_SLOT_UNKNOWN"
- | "PLUGIN_SLOT_DUPLICATE"
+ /** `component` is not a function. */
| "PLUGIN_SLOT_INVALID_COMPONENT"
+ /** A keyed slot's `toolName` / `language` is malformed. */
| "PLUGIN_SLOT_INVALID_KEY"
+ /** `positions` is malformed, or given to a slot without sides. */
| "PLUGIN_SLOT_INVALID_POSITION"
- | "PLUGIN_SLOT_NOT_DECLARED"
- | "PLUGIN_SLOT_RENDER_FAILED"
- | "PLUGIN_SLOT_LOAD_FAILED"
+ /** The key is already registered; the first registration keeps it. */
+ | "PLUGIN_SLOT_DUPLICATE"
+ /** `toolName` is not one of the plugin's own agent tools. */
+ | "PLUGIN_SLOT_NOT_OWNED";
+
+/**
+ * Every code the host hands renderer code: the registration refusals above
+ * and what `pi.dispatch` rejects with.
+ */
+export type PluginRendererErrorCode =
+ | PluginSlotErrorCode
+ /** The word is not in `PLUGIN_RENDERER_ACTIONS`. */
+ | "PLUGIN_ACTION_UNKNOWN"
+ /** The word is not in `manifest.rendererActions`. */
| "PLUGIN_ACTION_UNDECLARED"
- | "PLUGIN_ACTION_UNROUTED"
+ /** The payload does not have the word's shape or exceeds its limit. */
| "PLUGIN_ACTION_INVALID_PAYLOAD"
+ /** No composer is mounted to take the action. */
+ | "PLUGIN_ACTION_NO_COMPOSER"
+ /** This load has ended: nothing registers, injects or dispatches through it. */
+ | "PLUGIN_UNLOADED"
+ /** `plugin.call`: the method is not declared, or `onRendererCall` is missing. */
| "PLUGIN_CALL_NO_HANDLER"
+ /** `plugin.call`: args or answer are not JSON. */
| "PLUGIN_CALL_UNSERIALIZABLE"
+ /** `plugin.call`: no answer within 2s. */
| "PLUGIN_CALL_TIMEOUT"
+ /** `plugin.call`: args and answer exceed 64KB together. */
| "PLUGIN_CALL_TOO_LARGE"
+ /** `plugin.call`: more than 10 calls in one second. */
| "PLUGIN_CALL_RATE_LIMITED"
- | "PLUGIN_CALL_DISABLED";
+ /** `plugin.call`: closed for 30s after five failures in a row. */
+ | "PLUGIN_CALL_DISABLED"
+ /** `plugin.call`: `onRendererCall` threw without a code of its own. */
+ | "PLUGIN_CALL_FAILED";
-/** 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;
+export type PluginSlotRefusal = {
+ readonly code: PluginSlotErrorCode;
+ readonly message: 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`.
+ * The comparison form of a block-renderer language tag, shared by the
+ * registration and the fence lookup.
+ */
+export function blockRendererLanguageKey(language: string): string {
+ return language.trim().toLowerCase();
+}
+
+const BLOCK_RENDERER_LANGUAGE_SUFFIX = /^[a-z0-9_-]+$/;
+
+function describe(value: unknown): string {
+ return typeof value === "string" ? JSON.stringify(value) : typeof value;
+}
+
+function refusal(code: PluginSlotErrorCode, message: string): PluginSlotRefusal {
+ return { code, message };
+}
+
+/**
+ * Check a registration the way the host does before accepting it. Only a clash
+ * with an earlier registration (`PLUGIN_SLOT_DUPLICATE`) is left to the host,
+ * which alone sees the other plugins. `ownTools` is the plugin's own
+ * `contributes.agentTools[].name` list.
*/
-export function slotKeyError(
- slot: PluginRendererSlot,
+export function slotRegistrationRefusal(
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";
+ registration: unknown,
+ ownTools: readonly string[],
+): PluginSlotRefusal | null {
+ if (!registration || typeof registration !== "object") {
+ return refusal("PLUGIN_SLOT_UNKNOWN", "a registration must be an object naming its slot");
+ }
+ const candidate = registration as Record<string, unknown>;
+ const slot = candidate.slot;
+ if (typeof slot !== "string" || !(PLUGIN_RENDERER_SLOTS as readonly string[]).includes(slot)) {
+ return refusal("PLUGIN_SLOT_UNKNOWN", `unknown slot ${describe(slot)}`);
+ }
+ if (typeof candidate.component !== "function") {
+ return refusal("PLUGIN_SLOT_INVALID_COMPONENT", `${slot} component must be a function`);
+ }
+ const positions = candidate.positions;
+ if (positions !== undefined) {
+ if (!(POSITIONED_SLOTS as readonly string[]).includes(slot)) {
+ return refusal("PLUGIN_SLOT_INVALID_POSITION", `${slot} takes no positions`);
}
- const prefix = `${pluginId}:`;
if (
- language === prefix ||
- !language.startsWith(prefix) ||
- language.slice(prefix.length).trim().length === 0
+ !Array.isArray(positions) ||
+ positions.length === 0 ||
+ positions.some((side) => side !== "left" && side !== "right")
) {
- 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 refusal(
+ "PLUGIN_SLOT_INVALID_POSITION",
+ `${slot} positions must be a non-empty array of "left" and "right"`,
+ );
}
- 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(" ")}`;
+ const toolName = candidate.toolName;
+ if (typeof toolName !== "string" || !toolName.trim()) {
+ return refusal("PLUGIN_SLOT_INVALID_KEY", "toolCard requires a toolName");
}
- // 宿主先占: `@` 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 "#"`;
+ if (!ownTools.includes(toolName)) {
+ return refusal(
+ "PLUGIN_SLOT_NOT_OWNED",
+ `toolCard toolName ${describe(toolName)} is not one of this plugin's contributes.agentTools`,
+ );
}
- 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"`;
+ if (slot === "blockRenderer") {
+ const language = candidate.language;
+ if (typeof language !== "string") {
+ return refusal("PLUGIN_SLOT_INVALID_KEY", "blockRenderer requires a language");
+ }
+ const key = blockRendererLanguageKey(language);
+ const prefix = `${pluginId}:`;
+ if (!key.startsWith(prefix) || !BLOCK_RENDERER_LANGUAGE_SUFFIX.test(key.slice(prefix.length))) {
+ return refusal(
+ "PLUGIN_SLOT_INVALID_KEY",
+ `blockRenderer language must be "${prefix}<lang>" with <lang> in [A-Za-z0-9_-] (got ${describe(language)})`,
+ );
}
}
return null;
diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.ts
index f6c18c844..a3f6d8917 100644
--- a/packages/shared/src/composer-trigger.ts
+++ b/packages/shared/src/composer-trigger.ts
@@ -164,26 +164,6 @@ 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 {
const candidate = preferredName?.trim() || path;
diff --git a/packages/shared/src/types/plugins.ts b/packages/shared/src/types/plugins.ts
index 6e45b9372..134cd4c6e 100644
--- a/packages/shared/src/types/plugins.ts
+++ b/packages/shared/src/types/plugins.ts
@@ -203,6 +203,33 @@ export type PluginCapability =
/** `manifest.renderer`: the plugin ships a renderer slot entry (`docs/plugin-plan/ui/`). */
| "rendererUi";
+/**
+ * A loaded plugin's renderer extension as the renderer host sees it
+ * (`docs/plugin-plan/ui/`). The main process builds it from the live load, so
+ * it never outlives the plugin: unload, crash, or a revoked permission drops
+ * it from the next plugin list.
+ */
+export type PluginRendererDescriptor = {
+ /** Renderer module path relative to the plugin root. */
+ entry: string;
+ /**
+ * Load generation. Every load of the plugin gets a new one, and module URLs
+ * carry it (`plugin-renderer://<id>/g<generation>/<entry>`), so a reload
+ * evaluates fresh modules instead of the ES module cache's stale copy and a
+ * stale generation is refused outright.
+ */
+ generation: number;
+ /** `manifest.rendererActions`: the outbound actions dispatch accepts. */
+ actions: string[];
+ /** `manifest.rendererCallMethods`: the `plugin.call` method whitelist. */
+ callMethods: string[];
+ /**
+ * Bare `contributes.agentTools[].name`s. A `toolCard` registration must
+ * name one of these; the card then serves only that tool's calls.
+ */
+ tools: string[];
+};
+
export type PluginSettingType =
| "string"
| "number"
@@ -288,20 +315,11 @@ export type PluginSummary = {
/** 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.
+ * Present only while the plugin is loaded, holds `renderer.extension`, and
+ * declares `manifest.renderer`: everything the renderer host needs to load
+ * the plugin's slot module and gate what it registers and dispatches.
*/
- 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[];
+ renderer?: PluginRendererDescriptor;
description?: string;
author?: string;
installedAt?: string;
diff --git a/scripts/e2e-plugin-ui-slots.mjs b/scripts/e2e-plugin-ui-slots.mjs
new file mode 100644
index 000000000..5cbcf1864
--- /dev/null
+++ b/scripts/e2e-plugin-ui-slots.mjs
@@ -0,0 +1,192 @@
+#!/usr/bin/env node
+/**
+ * Plugin UI slots E2E runner (E2E-PLUGIN-ui-slots-*).
+ *
+ * Launches the real Electron app with the UI Slots Lab loaded as a dev plugin
+ * and a deterministic in-process model stub, then drives every renderer slot
+ * through the MCP control plane and the renderer DOM (Chrome DevTools
+ * Protocol). See apps/desktop/test/e2e/plugin-ui-slots/README.md.
+ *
+ * Prerequisites: built JS packages, the desktop bundle, Electron, and a
+ * host-core binary (PI_DESKTOP_HOST_BIN overrides the lookup). The runner
+ * does not build the repository.
+ */
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { connectControl, connectRenderer } from "../apps/desktop/test/e2e/plugin-ui-slots/clients.mjs";
+import { drive } from "../apps/desktop/test/e2e/plugin-ui-slots/drive.mjs";
+import { seed } from "../apps/desktop/test/e2e/plugin-ui-slots/seed.mjs";
+import { startStubModel } from "../apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs";
+import { assertDesktopBuild, repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+import { resolveHostBinary } from "./e2e/host.mjs";
+
+const root = repositoryRoot();
+const configuredRoot = process.env.E2E_ROOT?.trim();
+const runRoot = configuredRoot ? resolve(configuredRoot) : mkdtempSync(join(tmpdir(), "pi-ui-slots-e2e-"));
+const dataDir = join(runRoot, "data");
+const homeDir = join(runRoot, "home");
+const keepArtifacts = process.env.E2E_KEEP_ARTIFACTS === "1";
+const debug = process.env.DEBUG_E2E === "1";
+const configuredTimeout = Number(process.env.E2E_TIMEOUT_MS || 240_000);
+const timeoutMs = Number.isFinite(configuredTimeout) && configuredTimeout > 0 ? configuredTimeout : 240_000;
+
+const results = [];
+function check(name, ok, detail = "") {
+ results.push({ name, ok: Boolean(ok) });
+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
+}
+
+async function freePort() {
+ const server = createServer();
+ await new Promise((done, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", done);
+ });
+ const { port } = server.address();
+ await new Promise((done) => server.close(done));
+ return port;
+}
+
+function isolatedEnv(extra) {
+ mkdirSync(homeDir, { recursive: true });
+ const env = { ...process.env, ...extra };
+ delete env.ELECTRON_RUN_AS_NODE;
+ return {
+ ...env,
+ HOME: homeDir,
+ USERPROFILE: homeDir,
+ XDG_CONFIG_HOME: join(homeDir, ".config"),
+ XDG_CACHE_HOME: join(homeDir, ".cache"),
+ PI_DESKTOP_DATA_DIR: dataDir,
+ PI_CODING_AGENT_DIR: join(homeDir, ".pi", "agent"),
+ };
+}
+
+function launchElectron(electronBinary, hostBin, mcpPort, cdpPort) {
+ const child = spawn(
+ electronBinary,
+ [`--user-data-dir=${join(runRoot, "profile")}`, `--remote-debugging-port=${cdpPort}`, "."],
+ {
+ cwd: join(root, "apps", "desktop"),
+ env: isolatedEnv({
+ PI_DESKTOP_HOST_BIN: hostBin,
+ PI_DESKTOP_MCP_CONTROL: "1",
+ PI_DESKTOP_MCP_PORT: String(mcpPort),
+ ELECTRON_RENDERER_URL: "",
+ PI_DESKTOP_START_MAXIMIZED: "0",
+ }),
+ stdio: ["ignore", "pipe", "pipe"],
+ detached: process.platform !== "win32",
+ },
+ );
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => {
+ output = `${output}${chunk}`.slice(-12_000);
+ if (debug) process.stderr.write(`[electron] ${chunk}`);
+ });
+ }
+ return { child, output: () => output };
+}
+
+async function stop(child) {
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
+ const closed = new Promise((done) => child.once("close", done));
+ const kill = (signal) => {
+ try {
+ if (process.platform === "win32") spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" });
+ else process.kill(-child.pid, signal);
+ } catch {
+ child.kill(signal);
+ }
+ };
+ kill("SIGTERM");
+ const timedOut = await Promise.race([closed.then(() => false), new Promise((done) => setTimeout(() => done(true), 3_000))]);
+ if (timedOut) {
+ kill("SIGKILL");
+ await closed;
+ }
+}
+
+async function waitForControl(mcpPort, electron) {
+ const deadline = Date.now() + 90_000;
+ let last = "file not found";
+ while (Date.now() < deadline) {
+ if (electron.child.exitCode !== null) throw new Error(`Electron exited early:\n${electron.output()}`);
+ try {
+ const info = JSON.parse(readFileSync(join(dataDir, "mcp-control.json"), "utf8"));
+ if (info?.active === true && typeof info.token === "string" && new URL(info.url).port === String(mcpPort)) return;
+ last = "control plane not active";
+ } catch (error) {
+ last = error.message;
+ }
+ await new Promise((done) => setTimeout(done, 100));
+ }
+ throw new Error(`MCP control plane not ready: ${last}`);
+}
+
+async function main() {
+ const hostBin = resolveHostBinary();
+ const { electronBinary } = resolveElectronBinary(root);
+ assertDesktopBuild(root);
+ mkdirSync(runRoot, { recursive: true });
+
+ const stub = await startStubModel();
+ let electron;
+ let renderer;
+ try {
+ const { project } = await seed({
+ hostBin,
+ dataDir,
+ runRoot,
+ labDir: join(root, "examples", "plugins", "ui-slots-lab"),
+ stubPort: stub.port,
+ });
+ const mcpPort = await freePort();
+ const cdpPort = await freePort();
+ electron = launchElectron(electronBinary, hostBin, mcpPort, cdpPort);
+ await waitForControl(mcpPort, electron);
+ const control = await connectControl(dataDir);
+ renderer = await connectRenderer(cdpPort);
+ let timer;
+ const budget = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`drive exceeded ${timeoutMs}ms`)), timeoutMs);
+ });
+ try {
+ await Promise.race([drive({ control, renderer, check, project }), budget]);
+ } finally {
+ clearTimeout(timer);
+ const shot = join(runRoot, "final.png");
+ await renderer
+ .screenshot()
+ .then((data) => writeFileSync(shot, Buffer.from(data, "base64")))
+ .catch(() => {});
+ }
+ } finally {
+ renderer?.close();
+ await stop(electron?.child);
+ await stub.close();
+ }
+}
+
+let failed = false;
+try {
+ await main();
+} catch (error) {
+ failed = true;
+ console.error(`FAIL plugin UI slots E2E runner — ${error?.stack || error}`);
+}
+const passed = results.filter((result) => result.ok).length;
+console.log(`SUMMARY ${passed}/${results.length} passed`);
+if (failed || passed !== results.length || results.length === 0) {
+ process.exitCode = 1;
+ console.error(`E2E artifacts retained at ${runRoot}`);
+} else if (!keepArtifacts && !configuredRoot) {
+ rmSync(runRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+} else {
+ console.error(`E2E artifacts retained at ${runRoot}`);
+}