Skip to content

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

feat(plugins): add pi.ui.openLayer for self-drawn plugin dialogs

vastsa6901ff5f8161
diff --git a/apps/desktop/src/components/ExtensionPromptDialog.tsx b/apps/desktop/src/components/ExtensionPromptDialog.tsx
index 7bd1a8c28..63ce9deb9 100644
--- a/apps/desktop/src/components/ExtensionPromptDialog.tsx
+++ b/apps/desktop/src/components/ExtensionPromptDialog.tsx
@@ -3,6 +3,7 @@ import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import type { TrustedExtensionUiPrompt } from "@pi-desktop/shared";
import { api } from "../lib/api";
+import { useHostSafetySurface } from "../lib/host-safety-layer";
import { useAppStore } from "../stores/app-store";
import { Button, TooltipButton } from "./ui";
import { IconClose, IconPlug } from "./icons";
@@ -84,6 +85,8 @@ function ExtensionPromptDialog({
);
const inputRef = useRef<HTMLInputElement | null>(null);
const dialogId = `extension-prompt-${prompt.promptId}`;
+ // Plugin layers step aside while the user answers.
+ useHostSafetySurface();
useEffect(() => {
const previousOverflow = document.body.style.overflow;
diff --git a/apps/desktop/src/lib/host-safety-layer.ts b/apps/desktop/src/lib/host-safety-layer.ts
new file mode 100644
index 000000000..a1d2648ab
--- /dev/null
+++ b/apps/desktop/src/lib/host-safety-layer.ts
@@ -0,0 +1,59 @@
+import { useLayoutEffect, useSyncExternalStore } from "react";
+import type { PlanProposal } from "@pi-desktop/shared";
+import { headAsk, type AskQueues } from "./pending-asks";
+import { headPermission, type PermissionQueues } from "./pending-permissions";
+
+// The host's own decision surfaces: the places where the user answers the
+// agent or an extension. Plugin layers (`pi.ui.openLayer`) may never cover
+// one, so they step aside while any is waiting. Surfaces the store knows of
+// are read from it (`sessionAwaitsDecision`); the others announce themselves
+// while mounted (`useHostSafetySurface`), counted by owner so one closing
+// cannot clear another.
+const owners = new Set<symbol>();
+const listeners = new Set<() => void>();
+const notify = () => { for (const listener of listeners) listener(); };
+export const subscribeHostSafetySurfaces = (listener: () => void) => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+};
+export const isHostSafetySurfaceMounted = () => owners.size > 0;
+
+/** Holds a host decision surface up until the returned release is called. */
+export function claimHostSafetySurface(): () => void {
+ const owner = Symbol();
+ owners.add(owner);
+ notify();
+ return () => {
+ if (owners.delete(owner)) notify();
+ };
+}
+
+/** Marks the calling component as a host decision surface while mounted. */
+export function useHostSafetySurface() {
+ useLayoutEffect(claimHostSafetySurface, []);
+}
+
+export function useHostSafetySurfaceMounted() {
+ return useSyncExternalStore(subscribeHostSafetySurfaces, isHostSafetySurfaceMounted, () => false);
+}
+
+export type DecisionState = {
+ activeSessionId?: string;
+ pendingPermissions: PermissionQueues;
+ pendingAsks: AskQueues;
+ planCheckpoints: Record<string, PlanProposal>;
+};
+
+/**
+ * Whether the visible session waits on the user: a permission request, a
+ * question, or a plan awaiting approval.
+ */
+export function sessionAwaitsDecision(state: DecisionState): boolean {
+ const sessionId = state.activeSessionId;
+ if (!sessionId) return false;
+ return Boolean(
+ headPermission(state.pendingPermissions, sessionId) ||
+ headAsk(state.pendingAsks, sessionId) ||
+ state.planCheckpoints[sessionId]?.status === "pending",
+ );
+}
diff --git a/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
index 31d075a55..458127880 100644
--- a/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
+++ b/apps/desktop/src/plugins/renderer-host/PluginRendererHost.tsx
@@ -3,10 +3,13 @@
* 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.
+ * along — when it stops being eligible or the host goes away. It also hides
+ * the plugins' layers while the host waits on the user's own decision.
*/
-import { useEffect } from "react";
+import { useEffect, useLayoutEffect } from "react";
+import { sessionAwaitsDecision, useHostSafetySurfaceMounted } from "../../lib/host-safety-layer";
import { useAppStore } from "../../stores/app-store";
+import { pluginLayers } from "../renderer-layers/layer-stack";
import { installRendererImportMap } from "./import-map";
import { rendererLoadSpecs, rendererModules } from "./loader";
import "../renderer-slots/slot-shell.css";
@@ -14,6 +17,9 @@ import "../renderer-slots/slot-shell.css";
export function PluginRendererHost(): null {
const plugins = useAppStore((state) => state.plugins);
const projectPath = useAppStore((state) => state.workspace?.path ?? null);
+ const awaitsDecision = useAppStore(sessionAwaitsDecision);
+ const safetySurfaceMounted = useHostSafetySurfaceMounted();
+ const suspended = awaitsDecision || safetySurfaceMounted;
useEffect(() => {
// Plugin modules import bare `react`: the map must exist before the first.
@@ -23,5 +29,10 @@ export function PluginRendererHost(): null {
useEffect(() => () => rendererModules.sync([]), []);
+ // Before paint, so a decision never shows with a layer over it.
+ useLayoutEffect(() => {
+ pluginLayers.setSuspended(suspended);
+ }, [suspended]);
+
return null;
}
diff --git a/apps/desktop/src/plugins/renderer-host/loader.ts b/apps/desktop/src/plugins/renderer-host/loader.ts
index 40c9d008e..674d49f1d 100644
--- a/apps/desktop/src/plugins/renderer-host/loader.ts
+++ b/apps/desktop/src/plugins/renderer-host/loader.ts
@@ -8,20 +8,21 @@
* 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.
+ * Each load is its own session. Registrations, style sheets, layers 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, injecting or opening a layer 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 PluginDisposer,
+ type PluginLayer,
type PluginSlotRegistration,
} from "@pi-desktop/plugin-sdk";
import {
@@ -30,6 +31,7 @@ import {
type PluginSummary,
} from "@pi-desktop/shared";
import { PluginRendererError } from "../renderer-error";
+import { pluginLayers } from "../renderer-layers/layer-stack";
import { slotRegistry, type SlotRegistry } from "../renderer-slots/registry";
import { injectPluginStyle } from "../renderer-slots/style-injection";
import { createDispatchChannel, type DispatchChannel } from "./dispatch";
@@ -50,6 +52,7 @@ export type RendererLoaderDeps = {
importModule(url: string): Promise<unknown>;
registry: Pick<SlotRegistry, "register">;
injectStyle(pluginId: string, css: string): PluginDisposer;
+ openLayer(pluginId: string): PluginLayer;
openChannel(pluginId: string, actions: readonly string[]): DispatchChannel;
warn(message: string, error: unknown): void;
};
@@ -126,6 +129,11 @@ class RendererLoad {
this.assertAlive();
return this.track(this.deps.injectStyle(pluginId, css));
},
+ openLayer: () => {
+ this.assertAlive();
+ const layer = this.deps.openLayer(pluginId);
+ return Object.freeze({ element: layer.element, close: this.track(layer.close) });
+ },
}),
dispatch: this.channel.dispatch,
});
@@ -267,6 +275,7 @@ export const rendererModules = new RendererModuleLoader({
importModule: (url) => import(/* @vite-ignore */ url),
registry: slotRegistry,
injectStyle: injectPluginStyle,
+ openLayer: (pluginId) => pluginLayers.open(pluginId),
openChannel: (pluginId, actions) => createDispatchChannel(pluginId, actions),
warn: (message, error) => console.warn(message, error),
});
diff --git a/apps/desktop/src/plugins/renderer-layers/layer-stack.ts b/apps/desktop/src/plugins/renderer-layers/layer-stack.ts
new file mode 100644
index 000000000..ceee13003
--- /dev/null
+++ b/apps/desktop/src/plugins/renderer-layers/layer-stack.ts
@@ -0,0 +1,98 @@
+/**
+ * `pi.ui.openLayer` (`docs/plugin-plan/ui/self-dialog/`).
+ *
+ * A self-drawn dialog cannot live inside the slot that opens it: the slot's
+ * ancestors hide it (an action bar fades out until hovered), clip it
+ * (`content-visibility` on transcript rows) or trap it in their stacking
+ * context. So the host hands out layers instead: zero-size, viewport-fixed
+ * elements in one root at the end of the body, each carrying its plugin's style
+ * scope, which the plugin fills through a portal.
+ *
+ * Every layer is its own stacking context one above the topmost open layer,
+ * from 600 and capped at 899, so the latest layer is on top whatever z-index
+ * a plugin uses inside it, and nothing a plugin draws reaches the host's
+ * tooltips and window chrome (1000 and up). Ties at the cap still stack by
+ * opening order, since a new layer is appended last.
+ *
+ * While the host waits on the user's own decision (`host-safety-layer.ts`)
+ * the root is `hidden` and `inert`: every layer steps aside without
+ * unmounting and comes back as it was. The root exists only while a layer is
+ * open, so a window without plugin layers carries no trace of them.
+ */
+import type { PluginLayer } from "@pi-desktop/plugin-sdk";
+
+export const PLUGIN_LAYER_Z_MIN = 600;
+export const PLUGIN_LAYER_Z_MAX = 899;
+export const PLUGIN_LAYER_ROOT_ID = "pi-plugin-layers";
+
+/** What the stack uses of the document; the app passes `document`. */
+export type LayerDocument = {
+ createElement(tagName: "div"): HTMLElement;
+ readonly body: HTMLElement;
+};
+
+export class PluginLayerStack {
+ private readonly document: () => LayerDocument;
+ private root: HTMLElement | null = null;
+ private readonly layers = new Map<HTMLElement, number>();
+ private suspended = false;
+
+ constructor(document: () => LayerDocument) {
+ this.document = document;
+ }
+
+ /** Open a layer for `pluginId` on top of every open one. */
+ open(pluginId: string): PluginLayer {
+ const element = this.document().createElement("div");
+ const z = Math.min(PLUGIN_LAYER_Z_MAX, Math.max(PLUGIN_LAYER_Z_MIN - 1, ...this.layers.values()) + 1);
+ element.setAttribute("data-pi-plugin", pluginId);
+ element.setAttribute("data-pi-layer", "");
+ Object.assign(element.style, {
+ position: "fixed",
+ top: "0",
+ left: "0",
+ width: "0",
+ height: "0",
+ zIndex: String(z),
+ });
+ this.ensureRoot().appendChild(element);
+ this.layers.set(element, z);
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ this.layers.delete(element);
+ element.remove();
+ if (this.layers.size === 0) {
+ this.root?.remove();
+ this.root = null;
+ }
+ };
+ return Object.freeze({ element, close });
+ }
+
+ /** Hide every layer from sight, pointer and focus, or bring them back. */
+ setSuspended(suspended: boolean): void {
+ this.suspended = suspended;
+ if (this.root) applySuspension(this.root, suspended);
+ }
+
+ private ensureRoot(): HTMLElement {
+ if (this.root) return this.root;
+ const document = this.document();
+ const root = document.createElement("div");
+ root.id = PLUGIN_LAYER_ROOT_ID;
+ applySuspension(root, this.suspended);
+ document.body.appendChild(root);
+ this.root = root;
+ return root;
+ }
+}
+
+function applySuspension(root: HTMLElement, suspended: boolean): void {
+ root.hidden = suspended;
+ root.inert = suspended;
+}
+
+/** The app window's layers. */
+export const pluginLayers = new PluginLayerStack(() => document);
diff --git a/apps/desktop/src/plugins/renderer-slots/slot-shell.css b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
index 512b8b8d9..6e7c468b2 100644
--- a/apps/desktop/src/plugins/renderer-slots/slot-shell.css
+++ b/apps/desktop/src/plugins/renderer-slots/slot-shell.css
@@ -3,9 +3,10 @@
* classes (`docs/plugin-plan/ui/self-dialog/`): p-overlay / p-dialog /
* p-notice with the --ds-scrim / --ds-shadow-dialog tokens.
*
- * Plugin self layers own z 600..899 (first 600, +1 per layer); the host
- * safety layer (permission approvals, confirms) pins to 900; the existing
- * 1000+ ladder is untouched.
+ * The self-dialog classes are drawn inside a layer from `pi.ui.openLayer`
+ * (`renderer-layers/layer-stack.ts`), which alone decides the stacking: its
+ * z within the plugin band (600..899), below the host's 1000+ ladder, and
+ * hidden while the host waits on the user's own decision.
*/
.pi-plugin-slot {
@@ -24,15 +25,9 @@
/* ---- self-dialog tool classes ---------------------------------------- */
-:root {
- --ds-z-plugin-layer: 600;
- --ds-z-safety-layer: 900;
-}
-
.p-overlay {
position: fixed;
inset: 0;
- z-index: var(--ds-z-plugin-layer);
display: flex;
align-items: center;
justify-content: center;
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/README.md b/apps/desktop/test/e2e/plugin-ui-slots/README.md
index 2df171456..6c406fbed 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/README.md
+++ b/apps/desktop/test/e2e/plugin-ui-slots/README.md
@@ -14,7 +14,7 @@ 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>`) |
+| `stub-model.mjs` | Stub model; the prompt names the scenario (`lab: probe <ok\|fail\|crash\|slow>`, `lab: chart <crash\|tall>`, `lab: gate`) |
| `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 |
@@ -35,8 +35,13 @@ Covered behavior (`E2E-PLUGIN-ui-slots-*` in the E2E test plan):
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
+- self-drawn layers (`pi.ui.openLayer`): a wizard at z 600 over the app with
+ the plugin's scoped sheet, a notice opened later at 601 above it, Escape
+ closing neither, both hidden and inert while a permission request (a
+ `Bash` call in Ask mode) waits and back unchanged once it is answered, ✕
+ closing one, and the root leaving with the last layer
+- disabling the plugin removes every mount, menu, block, layer 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
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
index 382978682..f50fe5123 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
+++ b/apps/desktop/test/e2e/plugin-ui-slots/drive.mjs
@@ -49,6 +49,30 @@ function installPageHelpers() {
const input = document.querySelector(".composer-input");
return input ? (input.value ?? input.textContent) : null;
},
+ /** The lab's self-drawn layers, and what the pointer meets over them. */
+ layers() {
+ const root = document.getElementById("pi-plugin-layers");
+ const layerOf = (lab) => {
+ const sample = one(document, lab);
+ const layer = sample?.closest("[data-pi-layer]");
+ if (!sample || !layer) return null;
+ const box = (sample.querySelector(".p-dialog, .p-notice") ?? sample).getBoundingClientRect();
+ const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);
+ return {
+ z: Number(layer.style.zIndex),
+ readout: sample.querySelector("[data-lab-layer-z]")?.getAttribute("data-lab-layer-z") ?? null,
+ plugin: layer.getAttribute("data-pi-plugin"),
+ inRoot: layer.parentElement === root,
+ onTop: Boolean(hit && sample.contains(hit)),
+ step: sample.querySelector("[data-lab-step]")?.getAttribute("data-lab-step") ?? null,
+ };
+ };
+ return {
+ root: root ? { hidden: root.hidden, inert: root.inert, layers: root.children.length } : null,
+ wizard: layerOf("layer:wizard"),
+ notice: layerOf("layer:notice"),
+ };
+ },
};
return true;
}
@@ -121,7 +145,11 @@ export async function drive({ control, renderer, check, project }) {
]),
layout.turn.join(","),
);
- check("composerControl samples sit on both toolbar sides", sameSet(layout.toolbar, ["composerControl:left", "composerControl:right", "composerControl:crash"]), layout.toolbar.join(","));
+ check(
+ "composerControl samples sit on both toolbar sides",
+ sameSet(layout.toolbar, ["composerControl:left", "composerControl:right", "composerControl:crash", "composerControl:layers"]),
+ 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(","));
@@ -303,7 +331,15 @@ export async function drive({ control, renderer, check, project }) {
"crashed samples contained",
);
const after = await crashCounts();
- const survivors = ["assistantAction:left", "assistantAction:right", "assistantAction:refuse", "entryExtra:notes", "composerControl:left", "composerControl:right"];
+ const survivors = [
+ "assistantAction:left",
+ "assistantAction:right",
+ "assistantAction:refuse",
+ "entryExtra:notes",
+ "composerControl:left",
+ "composerControl:right",
+ "composerControl:layers",
+ ];
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(","));
@@ -384,11 +420,123 @@ export async function drive({ control, renderer, check, project }) {
const firstChart = await page(() => Boolean(window.__labE2E.one(window.__labE2E.turn(0), "blockRenderer")));
check("the healthy chart keeps its plugin block", firstChart);
+ // --- self-drawn layers ----------------------------------------------------
+ // The layer state once `accept(state)` holds; `accept` runs in the page.
+ const layers = (label, accept) =>
+ until(
+ `() => { const state = window.__labE2E.layers(); return (${accept})(state) ? state : null; }`,
+ null,
+ label,
+ 5_000,
+ ).catch((error) => ({ error: error.message }));
+ const layerClick = (lab, button) => clickIn(null, lab, button);
+
+ await layerClick("composerControl:layers", "wizard");
+ const wizard = await layers("the wizard layer", (state) => state.wizard?.onTop);
+ check(
+ "a self-drawn dialog opens in its own layer at the bottom of the plugin band, over the app",
+ wizard.wizard?.z === 600 && wizard.wizard.readout === "600" && wizard.wizard.plugin === LAB && wizard.wizard.inRoot &&
+ wizard.root?.hidden === false && wizard.root.layers === 1,
+ JSON.stringify(wizard),
+ );
+ const layerStyles = await page(() => {
+ const look = (node) => {
+ const style = getComputedStyle(node);
+ return [style.borderTopStyle, style.paddingLeft, style.borderTopLeftRadius].join(" ");
+ };
+ const inLayer = document.querySelector('[data-lab="layer:wizard"] .lab-btn');
+ const inSlot = document.querySelector('[data-lab="composerControl:layers"] .lab-btn');
+ const stray = document.createElement("button");
+ stray.className = "lab-btn";
+ document.body.appendChild(stray);
+ const outside = look(stray);
+ stray.remove();
+ return {
+ inLayer: look(inLayer),
+ inSlot: look(inSlot),
+ outside,
+ overlay: getComputedStyle(document.querySelector('[data-lab="layer:wizard"]')).position,
+ };
+ });
+ check(
+ "the plugin's scoped sheet and the host's dialog classes style the layer",
+ layerStyles.inLayer === layerStyles.inSlot && layerStyles.inLayer !== layerStyles.outside && layerStyles.overlay === "fixed",
+ JSON.stringify(layerStyles),
+ );
+
+ await layerClick("layer:wizard", "wizard-next");
+ await layerClick("layer:wizard", "wizard-next");
+ await layerClick("layer:wizard", "wizard-notice");
+ const stacked = await layers("the notice over the wizard", (state) => state.notice?.onTop && state.wizard?.step === "3");
+ check(
+ "a layer opened later stacks above the earlier one",
+ stacked.notice?.z === 601 && stacked.wizard?.z === 600 && stacked.root?.layers === 2,
+ JSON.stringify(stacked),
+ );
+
+ await page(() => {
+ const target = document.querySelector('[data-lab="layer:wizard"] [data-lab-button="wizard-next"]');
+ target.focus();
+ target.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ return true;
+ });
+ await new Promise((done) => setTimeout(done, 300));
+ const afterEscape = await page(() => window.__labE2E.layers());
+ check("Escape closes no layer", afterEscape.wizard?.step === "3" && Boolean(afterEscape.notice), JSON.stringify(afterEscape));
+
+ // A permission request in the open session: the layers step aside until
+ // the user has answered it, and come back as they were.
+ await control.tool("pi_session_configure", { id: sessionId, mode: "agent", permissionMode: "ask", confirm: true });
+ await control.tool("pi_agent_prompt", { sessionId, content: "lab: gate" });
+ const gated = await until(
+ () => {
+ const card = document.querySelector(".permission-card");
+ if (!card) return null;
+ const state = window.__labE2E.layers();
+ const button = card.querySelector(".permission-card-actions button");
+ const box = button.getBoundingClientRect();
+ const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);
+ return { ...state, cardReachable: Boolean(hit && button.contains(hit)) };
+ },
+ null,
+ "the permission card",
+ 30_000,
+ ).catch((error) => ({ error: error.message }));
+ check(
+ "a pending permission hides every layer from sight and input, and leaves the card reachable",
+ gated.root?.hidden === true && gated.root.inert === true && gated.root.layers === 2 && gated.cardReachable &&
+ !gated.wizard?.onTop && !gated.notice?.onTop,
+ JSON.stringify(gated),
+ );
+ await page(() => {
+ document.querySelector(".permission-card .permission-card-actions button")?.click();
+ return true;
+ });
+ await control.waitForTurn(sessionId);
+ await control.tool("pi_session_configure", { id: sessionId, mode: "agent", permissionMode: "auto", confirm: true });
+ const restored = await layers("the layers back", (state) => state.root?.hidden === false && state.notice?.onTop);
+ check(
+ "once answered, the layers come back unchanged",
+ restored.root?.inert === false && restored.wizard?.step === "3" && restored.notice?.z === 601,
+ JSON.stringify(restored),
+ );
+
+ await layerClick("layer:notice", "notice-dismiss");
+ const dismissed = await layers("the notice closed", (state) => !state.notice && state.wizard?.onTop);
+ check("a layer's own ✕ closes it and leaves the others", dismissed.root?.layers === 1, JSON.stringify(dismissed));
+ await layerClick("layer:wizard", "wizard-close");
+ const empty = await layers("the wizard closed", (state) => !state.wizard);
+ check("the root goes with the last layer", empty.root === null, JSON.stringify(empty));
+ // Left open for the unload below.
+ await layerClick("composerControl:layers", "wizard");
+ await layers("the wizard open again", (state) => state.wizard?.onTop);
+
// --- 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;
+ if (document.querySelector("[data-lab], [data-pi-plugin], #pi-plugin-layers")) return null;
const turn = window.__labE2E.turn(0);
return {
sheets: document.querySelectorAll("style[data-pi-plugin-style]").length,
@@ -401,7 +549,7 @@ export async function drive({ control, renderer, check, project }) {
"lab samples removed",
);
check(
- "disabling the plugin takes every sample, menu, block and sheet with it",
+ "disabling the plugin takes every sample, menu, block, layer and sheet with it",
unloaded.sheets === 0 && unloaded.hostChart === `${LAB}:chart` && unloaded.overflow === 0 && unloaded.entryStacks === 0,
JSON.stringify(unloaded),
);
diff --git a/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs b/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs
index 81f1c67f4..9293e37ef 100644
--- a/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs
+++ b/apps/desktop/test/e2e/plugin-ui-slots/stub-model.mjs
@@ -4,6 +4,8 @@
// 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`)
+// "lab: gate" -> call the built-in Bash tool, which a session in
+// Ask mode holds for the user's approval, then answer
// The first probe answer also carries a normal chart, so one turn fills every
// transcript slot.
import { createServer } from "node:http";
@@ -47,6 +49,11 @@ function reply(payload) {
}
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` };
+ if (prompt.includes("lab: gate")) {
+ if (called.has("Bash")) return { text: "The gate was answered." };
+ if (tools.has("Bash")) return { call: "Bash", args: { command: "touch lab-gate.txt" } };
+ return { text: "Bash is not available to this turn." };
+ }
return { text: "Hello from the UI slots stub." };
}
diff --git a/apps/desktop/test/helpers/fake-layer-document.mjs b/apps/desktop/test/helpers/fake-layer-document.mjs
new file mode 100644
index 000000000..5fcff504c
--- /dev/null
+++ b/apps/desktop/test/helpers/fake-layer-document.mjs
@@ -0,0 +1,46 @@
+/**
+ * Just enough of a document for the plugin layer stack
+ * (`src/plugins/renderer-layers/layer-stack.ts`): elements with attributes,
+ * inline style, children and `remove()`, under a `body`.
+ */
+class FakeElement {
+ constructor(tagName) {
+ this.tagName = tagName.toUpperCase();
+ this.id = "";
+ this.hidden = false;
+ this.inert = false;
+ this.style = {};
+ this.children = [];
+ this.parentElement = null;
+ this.attributes = new Map();
+ }
+
+ setAttribute(name, value) {
+ this.attributes.set(name, String(value));
+ }
+
+ getAttribute(name) {
+ return this.attributes.get(name) ?? null;
+ }
+
+ appendChild(child) {
+ child.remove();
+ child.parentElement = this;
+ this.children.push(child);
+ return child;
+ }
+
+ remove() {
+ const parent = this.parentElement;
+ if (!parent) return;
+ parent.children.splice(parent.children.indexOf(this), 1);
+ this.parentElement = null;
+ }
+}
+
+export function fakeLayerDocument() {
+ return {
+ body: new FakeElement("body"),
+ createElement: (tagName) => new FakeElement(tagName),
+ };
+}
diff --git a/apps/desktop/test/host-safety-layer.test.mjs b/apps/desktop/test/host-safety-layer.test.mjs
new file mode 100644
index 000000000..a8e049a94
--- /dev/null
+++ b/apps/desktop/test/host-safety-layer.test.mjs
@@ -0,0 +1,58 @@
+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));
+
+/*
+ * When plugin layers (`pi.ui.openLayer`) step aside: while the visible
+ * session waits on the user's own decision, or while a host decision surface
+ * outside the store (an extension prompt) is up.
+ */
+const { sessionAwaitsDecision, claimHostSafetySurface, isHostSafetySurfaceMounted, subscribeHostSafetySurfaces } =
+ await import("../src/lib/host-safety-layer.ts");
+
+const idle = { activeSessionId: "s1", pendingPermissions: {}, pendingAsks: {}, planCheckpoints: {} };
+
+test("the visible session awaits a decision on a permission, a question or a pending plan", () => {
+ assert.equal(sessionAwaitsDecision(idle), false);
+ assert.equal(sessionAwaitsDecision({ ...idle, pendingPermissions: { s1: [{ requestId: "p" }] } }), true);
+ assert.equal(sessionAwaitsDecision({ ...idle, pendingAsks: { s1: [{ requestId: "a" }] } }), true);
+ assert.equal(sessionAwaitsDecision({ ...idle, planCheckpoints: { s1: { status: "pending" } } }), true);
+});
+
+test("settled plans, other sessions' requests and no session at all await nothing", () => {
+ assert.equal(sessionAwaitsDecision({ ...idle, planCheckpoints: { s1: { status: "approved" } } }), false);
+ assert.equal(sessionAwaitsDecision({ ...idle, pendingPermissions: { s2: [{ requestId: "p" }] } }), false);
+ assert.equal(sessionAwaitsDecision({ ...idle, pendingAsks: { s2: [{ requestId: "a" }] } }), false);
+ assert.equal(
+ sessionAwaitsDecision({ ...idle, activeSessionId: undefined, pendingPermissions: { s1: [{ requestId: "p" }] } }),
+ false,
+ );
+});
+
+test("host surfaces are counted by owner, so one closing cannot clear another", () => {
+ let notified = 0;
+ const unsubscribe = subscribeHostSafetySurfaces(() => notified++);
+ assert.equal(isHostSafetySurfaceMounted(), false);
+ const first = claimHostSafetySurface();
+ const second = claimHostSafetySurface();
+ assert.equal(isHostSafetySurfaceMounted(), true);
+ first();
+ first();
+ assert.equal(isHostSafetySurfaceMounted(), true, "the other surface is still up");
+ second();
+ assert.equal(isHostSafetySurfaceMounted(), false);
+ assert.equal(notified, 4, "a repeated release does not notify");
+ unsubscribe();
+ claimHostSafetySurface()();
+ assert.equal(notified, 4);
+});
+
+test("an extension prompt holds the plugin layers aside while it is up", async () => {
+ // The permission, question and plan surfaces are store state, read by
+ // `sessionAwaitsDecision`; the extension prompt queue is the host's own.
+ const { readFile } = await import("node:fs/promises");
+ const source = await readFile(new URL("../src/components/ExtensionPromptDialog.tsx", import.meta.url), "utf8");
+ const dialog = source.slice(source.indexOf("function ExtensionPromptDialog("));
+ assert.match(dialog, /\n useHostSafetySurface\(\);\n/);
+});
diff --git a/apps/desktop/test/plugin-layer-stack.test.mjs b/apps/desktop/test/plugin-layer-stack.test.mjs
new file mode 100644
index 000000000..90762bbbd
--- /dev/null
+++ b/apps/desktop/test/plugin-layer-stack.test.mjs
@@ -0,0 +1,113 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { fakeLayerDocument } from "./helpers/fake-layer-document.mjs";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+/*
+ * The plugin layer stack behind `pi.ui.openLayer`
+ * (`docs/plugin-plan/ui/self-dialog/`): zero-size fixed layers in one root,
+ * each carrying its plugin's style scope, stacked in opening order within the
+ * plugin band, and all stepping aside together while the host waits on the
+ * user's own decision.
+ */
+const { PluginLayerStack, PLUGIN_LAYER_Z_MIN, PLUGIN_LAYER_Z_MAX, PLUGIN_LAYER_ROOT_ID } = await import(
+ "../src/plugins/renderer-layers/layer-stack.ts"
+);
+
+function stack() {
+ const document = fakeLayerDocument();
+ const layers = new PluginLayerStack(() => document);
+ const root = () => document.body.children.find((child) => child.id === PLUGIN_LAYER_ROOT_ID);
+ return { document, layers, root };
+}
+
+const z = (layer) => Number(layer.element.style.zIndex);
+
+test("a layer is a zero-size fixed element in the shared root, scoped to its plugin", () => {
+ const { layers, root } = stack();
+ assert.equal(root(), undefined, "no root before the first layer");
+ const layer = layers.open("demo.lab");
+ assert.ok(Object.isFrozen(layer));
+ assert.equal(layer.element.getAttribute("data-pi-plugin"), "demo.lab");
+ assert.equal(layer.element.getAttribute("data-pi-layer"), "");
+ assert.deepEqual(
+ { ...layer.element.style },
+ { position: "fixed", top: "0", left: "0", width: "0", height: "0", zIndex: String(PLUGIN_LAYER_Z_MIN) },
+ );
+ assert.deepEqual(root().children, [layer.element]);
+ assert.equal(root().hidden, false);
+ assert.equal(root().inert, false);
+});
+
+test("each layer opens above every open one, capped below the host's own ladder", () => {
+ const { layers, root } = stack();
+ const first = layers.open("demo.a");
+ const second = layers.open("demo.b");
+ const third = layers.open("demo.a");
+ assert.deepEqual([first, second, third].map(z), [600, 601, 602]);
+
+ // A layer closed below the top leaves the next one above the top still.
+ second.close();
+ assert.equal(z(layers.open("demo.c")), 603);
+ // With the top closed, the next one takes its place above what is left.
+ const top = layers.open("demo.c");
+ assert.equal(z(top), 604);
+ top.close();
+ assert.equal(z(layers.open("demo.c")), 604);
+
+ // At the cap, layers share its z and stack by DOM order: the later on top.
+ const many = Array.from({ length: PLUGIN_LAYER_Z_MAX - PLUGIN_LAYER_Z_MIN + 5 }, () => layers.open("demo.x"));
+ assert.ok(many.every((layer) => z(layer) <= PLUGIN_LAYER_Z_MAX));
+ const capped = many.slice(-2);
+ assert.deepEqual(capped.map(z), [PLUGIN_LAYER_Z_MAX, PLUGIN_LAYER_Z_MAX]);
+ const children = root().children;
+ assert.ok(children.indexOf(capped[0].element) < children.indexOf(capped[1].element));
+ assert.equal(children.at(-1), capped[1].element);
+});
+
+test("closing is idempotent, and the root goes with the last layer", () => {
+ const { layers, root, document } = stack();
+ const first = layers.open("demo.a");
+ const second = layers.open("demo.b");
+ first.close();
+ first.close();
+ assert.deepEqual(root().children, [second.element]);
+ second.close();
+ assert.equal(root(), undefined);
+ assert.deepEqual(document.body.children, []);
+
+ // The stack starts over from the bottom of the band.
+ const again = layers.open("demo.a");
+ assert.equal(z(again), PLUGIN_LAYER_Z_MIN);
+ second.close();
+ assert.deepEqual(root().children, [again.element], "a stale close does not touch a new root");
+});
+
+test("suspension hides every layer from sight, pointer and focus, and brings them back unchanged", () => {
+ const { layers, root } = stack();
+ const layer = layers.open("demo.lab");
+ layers.setSuspended(true);
+ assert.equal(root().hidden, true);
+ assert.equal(root().inert, true);
+ assert.equal(layer.element.parentElement, root(), "suspended layers stay mounted");
+
+ layers.setSuspended(false);
+ assert.equal(root().hidden, false);
+ assert.equal(root().inert, false);
+ assert.deepEqual(root().children, [layer.element]);
+});
+
+test("a layer opened while suspended starts hidden, in a root created hidden", () => {
+ const { layers, root } = stack();
+ layers.setSuspended(true);
+ assert.equal(root(), undefined, "suspension alone creates no root");
+ const layer = layers.open("demo.lab");
+ assert.equal(root().hidden, true);
+ assert.equal(root().inert, true);
+ layer.close();
+ layers.setSuspended(false);
+ layers.open("demo.lab");
+ assert.equal(root().hidden, false);
+ assert.equal(root().inert, false);
+});
diff --git a/apps/desktop/test/plugin-renderer-loader.test.mjs b/apps/desktop/test/plugin-renderer-loader.test.mjs
index 161cc8ce7..c2177bb36 100644
--- a/apps/desktop/test/plugin-renderer-loader.test.mjs
+++ b/apps/desktop/test/plugin-renderer-loader.test.mjs
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { register } from "node:module";
import test from "node:test";
+import { fakeLayerDocument } from "./helpers/fake-layer-document.mjs";
register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
/*
@@ -8,8 +9,9 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
* 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.
+ * registry, the layer stack and the dispatch channel are the real ones; only
+ * the module import, the style sheets, the document under the layers and the
+ * routes behind the channel are faked.
*/
const { RendererModuleLoader, rendererModuleUrl, rendererLoadSpecs } = await import(
"../src/plugins/renderer-host/loader.ts"
@@ -17,6 +19,7 @@ const { RendererModuleLoader, rendererModuleUrl, rendererLoadSpecs } = await imp
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 { PluginLayerStack } = await import("../src/plugins/renderer-layers/layer-stack.ts");
const PLUGIN = "demo.lab";
const component = () => null;
@@ -59,6 +62,8 @@ function spec(pluginId = PLUGIN, overrides = {}) {
*/
function harness(modules = {}) {
const registry = new SlotRegistry();
+ const document = fakeLayerDocument();
+ const layerStack = new PluginLayerStack(() => document);
const sheets = [];
const imports = [];
const warnings = [];
@@ -80,6 +85,7 @@ function harness(modules = {}) {
if (at >= 0) sheets.splice(at, 1);
};
},
+ openLayer: (pluginId) => layerStack.open(pluginId),
openChannel: (pluginId, actions) =>
createDispatchChannel(pluginId, actions, {
pluginCall: (id, method, args) => {
@@ -94,9 +100,12 @@ function harness(modules = {}) {
loader,
registry,
sheets,
+ /** The open layers' elements, bottom to top. */
+ layers: () => document.body.children.flatMap((root) => root.children),
imports,
warnings,
calls,
+ openLayerFor: (pluginId) => layerStack.open(pluginId),
answerCallsWith(fn) {
answerCall = fn;
},
@@ -126,9 +135,11 @@ test("onLoad gets a frozen pi bound to its plugin, and what it registers shows u
api.slots.register({ slot: "entryExtra", component });
api.slots.register({ slot: "toolCard", toolName: "lookup", component });
api.ui.injectStyle(".lab { color: red; }");
+ layer = api.ui.openLayer();
},
},
});
+ let layer;
assert.deepEqual(await h.loader.load(spec()), { status: "loaded" });
assert.deepEqual(h.imports, [url()]);
@@ -142,6 +153,9 @@ test("onLoad gets a frozen pi bound to its plugin, and what it registers shows u
],
);
assert.deepEqual(h.sheets, [{ pluginId: PLUGIN, css: ".lab { color: red; }" }]);
+ assert.ok(Object.isFrozen(layer));
+ assert.deepEqual(h.layers(), [layer.element]);
+ assert.equal(layer.element.getAttribute("data-pi-plugin"), PLUGIN);
// The descriptor is the plugin's grant: its own tools, its declared words.
assert.throws(
@@ -187,6 +201,7 @@ test("a load that fails is torn down, reported once and not retried for its gene
onLoad(pi) {
pi.slots.register({ slot: "entryExtra", component });
pi.ui.injectStyle(".half { }");
+ pi.ui.openLayer();
throw broken;
},
}),
@@ -210,6 +225,7 @@ test("a load that fails is torn down, reported once and not retried for its gene
await tick();
assert.deepEqual(h.registry.getSnapshot().entries, [], `${label}: registrations are gone`);
assert.deepEqual(h.sheets, [], `${label}: styles are gone`);
+ assert.deepEqual(h.layers(), [], `${label}: layers are gone`);
assert.deepEqual(
h.warnings.map((warning) => warning.message),
[`[plugin-renderer] ${PLUGIN} failed to load`],
@@ -245,9 +261,10 @@ test("a plugin whose onLoad failed still gets its onUnload, after the host clean
assert.deepEqual(seen, [0]);
});
-test("ending a load disposes its registrations, styles and calls before onUnload runs", async () => {
+test("ending a load disposes its registrations, styles, layers and calls before onUnload runs", async () => {
let pi;
let kept;
+ let keptLayer;
const observed = [];
const answer = deferred();
const h = harness({
@@ -257,11 +274,14 @@ test("ending a load disposes its registrations, styles and calls before onUnload
api.slots.register({ slot: "entryExtra", component });
kept = api.slots.register({ slot: "userAction", component, positions: ["left"] });
api.ui.injectStyle(".lab { }");
+ api.ui.openLayer();
+ keptLayer = api.ui.openLayer();
},
onUnload() {
observed.push({
entries: h.registry.getSnapshot().entries.length,
sheets: h.sheets.length,
+ layers: h.layers().length,
});
},
},
@@ -271,9 +291,11 @@ test("ending a load disposes its registrations, styles and calls before onUnload
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 }, []);
+ const otherLayer = h.openLayerFor("demo.other");
await h.loader.unload(PLUGIN);
- assert.deepEqual(observed, [{ entries: 1, sheets: 0 }]);
+ assert.deepEqual(observed, [{ entries: 1, sheets: 0, layers: 1 }]);
+ assert.deepEqual(h.layers(), [otherLayer.element]);
assert.deepEqual(
h.registry.getSnapshot().entries.map((entry) => entry.pluginId),
["demo.other"],
@@ -284,29 +306,38 @@ test("ending a load disposes its registrations, styles and calls before onUnload
// The pi of an ended load stays dead.
assert.throws(() => pi.slots.register({ slot: "entryExtra", component }), unloadedError);
assert.throws(() => pi.ui.injectStyle(".late { }"), unloadedError);
+ assert.throws(() => pi.ui.openLayer(), 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");
+ keptLayer.close();
+ assert.deepEqual(h.layers(), [otherLayer.element], "a kept close 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 () => {
+test("a registration or layer the plugin disposed itself is not disposed again at the end", async () => {
let dispose;
+ let layer;
const h = harness({
[url()]: {
onLoad(pi) {
dispose = pi.slots.register({ slot: "entryExtra", component });
+ layer = pi.ui.openLayer();
},
},
});
await h.loader.load(spec());
dispose();
+ layer.close();
const version = h.registry.getSnapshot().version;
+ // A layer another load opens after is not the closed one's to take along.
+ const other = h.openLayerFor("demo.other");
await h.loader.unload(PLUGIN);
assert.equal(h.registry.getSnapshot().version, version);
+ assert.deepEqual(h.layers(), [other.element]);
});
test("onUnload waits for a slow onLoad, whose late registrations are refused", async () => {
diff --git a/apps/desktop/test/plugin-ui-slots-lab.test.mjs b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
index e30ca3184..dce55ee37 100644
--- a/apps/desktop/test/plugin-ui-slots-lab.test.mjs
+++ b/apps/desktop/test/plugin-ui-slots-lab.test.mjs
@@ -8,6 +8,7 @@ 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 { fakeLayerDocument } from "./helpers/fake-layer-document.mjs";
import { slotMounts, slotSsr } from "./helpers/slot-ssr.mjs";
const here = dirname(fileURLToPath(import.meta.url));
@@ -79,6 +80,9 @@ async function labWindow(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 { PluginLayerStack } = await ssr.load("/src/plugins/renderer-layers/layer-stack.ts");
+ const layerDocument = fakeLayerDocument();
+ const layers = new PluginLayerStack(() => layerDocument);
const descriptor = runtime.rendererDescriptor(LAB);
const sheets = new Set();
const inserted = [];
@@ -94,6 +98,7 @@ async function labWindow(t) {
sheets.add(sheet);
return () => sheets.delete(sheet);
},
+ openLayer: (pluginId) => layers.open(pluginId),
openChannel: (pluginId, actions) => {
const channel = createDispatchChannel(pluginId, actions, {
pluginCall: (id, method, args) => runtime.callRenderer(id, method, args),
@@ -220,7 +225,13 @@ test("the renderer entry loads a sample into every slot", async (t) => {
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"]);
+ // The layer launcher opens its layers on a click, never on its own.
+ assert.deepEqual(samples(toolbar()), [
+ "composerControl:left",
+ "composerControl:right",
+ "composerControl:crash",
+ "composerControl:layers",
+ ]);
});
test("the samples' calls work through the host channel", async (t) => {
diff --git a/examples/plugins/ui-slots-lab/manifest.json b/examples/plugins/ui-slots-lab/manifest.json
index 1f1b4d06d..69c16f78e 100644
--- a/examples/plugins/ui-slots-lab/manifest.json
+++ b/examples/plugins/ui-slots-lab/manifest.json
@@ -3,7 +3,7 @@
"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",
+ "description": "Test plugin with one visible sample in every renderer UI slot, plus controls that exercise dispatch, errors, crash isolation, the host size clamps and self-drawn layers",
"author": "PI-Desktop",
"main": "main.js",
"renderer": "renderer/index.mjs",
diff --git a/examples/plugins/ui-slots-lab/renderer/index.mjs b/examples/plugins/ui-slots-lab/renderer/index.mjs
index a36d6e3b5..81ac4c5f4 100644
--- a/examples/plugins/ui-slots-lab/renderer/index.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/index.mjs
@@ -3,13 +3,15 @@
*
* 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.
+ * round trips and their error codes, a crash the host contains, the host's
+ * size clamps, and self-drawn layers over the app. A plain ES module with
+ * no build step; `react` and `react-dom` resolve to the host's through the
+ * window's import map.
*/
import { bindLab } from "./lab.mjs";
import { ChartBlock, ProbeCard } from "./blocks.mjs";
import { ComposerControl, ComposerCrash } from "./composer.mjs";
+import { LayerLauncher } from "./layers.mjs";
import {
AssistantAction,
AssistantCrash,
@@ -40,4 +42,5 @@ export function onLoad(pi) {
pi.slots.register({ slot: "composerControl", component: ComposerControl });
pi.slots.register({ slot: "composerControl", component: ComposerCrash, positions: ["right"] });
+ pi.slots.register({ slot: "composerControl", component: LayerLauncher, positions: ["right"] });
}
diff --git a/examples/plugins/ui-slots-lab/renderer/lab.mjs b/examples/plugins/ui-slots-lab/renderer/lab.mjs
index 373feaf5f..3b61674ce 100644
--- a/examples/plugins/ui-slots-lab/renderer/lab.mjs
+++ b/examples/plugins/ui-slots-lab/renderer/lab.mjs
@@ -15,6 +15,11 @@ export function bindLab(pi) {
labPi = pi;
}
+/** A layer above the app for a self-drawn dialog (`pi.ui.openLayer`). */
+export function openLayer() {
+ return labPi.ui.openLayer();
+}
+
/**
* One dispatch at a time, and what came of it: `idle`, `pending`, the text
* `describe` made of the answer, or the error's `code`.
diff --git a/examples/plugins/ui-slots-lab/renderer/layers.mjs b/examples/plugins/ui-slots-lab/renderer/layers.mjs
new file mode 100644
index 000000000..9865e45d8
--- /dev/null
+++ b/examples/plugins/ui-slots-lab/renderer/layers.mjs
@@ -0,0 +1,79 @@
+/**
+ * Self-drawn layers (`pi.ui.openLayer`): a composer control that opens a
+ * modal wizard, and from it a corner notice on top. Each is an ordinary
+ * component that draws through `createPortal` into its own layer; it opens
+ * the layer when it mounts and closes it when it unmounts, and only its ✕
+ * closes it — Escape does not.
+ */
+import { createElement as h, useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { Button, openLayer } from "./lab.mjs";
+
+/** The element of a layer held open while the caller is mounted. */
+function useLayer() {
+ const [layer, setLayer] = useState(null);
+ useEffect(() => {
+ const opened = openLayer();
+ setLayer(opened);
+ return opened.close;
+ }, []);
+ return layer?.element ?? null;
+}
+
+function LayerZ({ element }) {
+ return h("span", { className: "lab-pill", "data-lab-layer-z": element.style.zIndex }, `z ${element.style.zIndex}`);
+}
+
+function Wizard({ onClose, onNotice }) {
+ const element = useLayer();
+ const [step, setStep] = useState(1);
+ if (!element) return null;
+ return createPortal(
+ h("div", { className: "p-overlay", "data-lab": "layer:wizard" },
+ h("div", { className: "p-dialog", role: "dialog", "aria-modal": "true", "aria-label": "Lab wizard" },
+ h("div", { className: "p-dialog-head" },
+ h("span", null, "Lab wizard"),
+ h("button", {
+ type: "button",
+ className: "p-notice__dismiss",
+ "aria-label": "Close",
+ "data-lab-button": "wizard-close",
+ onClick: onClose,
+ }, "✕")),
+ h("div", { className: "p-dialog__body lab-row" },
+ h("span", { "data-lab-step": step }, `Step ${step}`),
+ h(LayerZ, { element })),
+ h("div", { className: "p-dialog__foot" },
+ h(Button, { lab: "wizard-notice", onClick: onNotice }, "Notice"),
+ h(Button, { lab: "wizard-next", onClick: () => setStep((n) => n + 1) }, "Next")))),
+ element,
+ );
+}
+
+function Notice({ onClose }) {
+ const element = useLayer();
+ if (!element) return null;
+ return createPortal(
+ h("div", { className: "p-overlay p-overlay__corner", "data-lab": "layer:notice" },
+ h("div", { className: "p-notice", role: "status" },
+ h("span", { className: "p-notice-icon", "aria-hidden": "true" }, "●"),
+ h("div", { className: "p-notice__msg lab-row" }, "Lab notice", h(LayerZ, { element })),
+ h("button", {
+ type: "button",
+ className: "p-notice__dismiss",
+ "aria-label": "Dismiss",
+ "data-lab-button": "notice-dismiss",
+ onClick: onClose,
+ }, "✕"))),
+ element,
+ );
+}
+
+export function LayerLauncher() {
+ const [wizard, setWizard] = useState(false);
+ const [notice, setNotice] = useState(false);
+ return h("span", { className: "lab-action", "data-lab": "composerControl:layers" },
+ h(Button, { lab: "wizard", onClick: () => setWizard(true) }, "Lab wizard"),
+ wizard ? h(Wizard, { onClose: () => setWizard(false), onNotice: () => setNotice(true) }) : null,
+ notice ? h(Notice, { onClose: () => setNotice(false) }) : null);
+}
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index a4839647c..c5116f59f 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -2172,6 +2172,7 @@ export {
type PluginComposerControlSlotRegistration,
type PluginSlotRegistration,
type PluginDisposer,
+ type PluginLayer,
type PluginRendererActionName,
type PluginRendererActionMap,
type PluginRendererDispatch,
diff --git a/packages/plugin-sdk/src/renderer.ts b/packages/plugin-sdk/src/renderer.ts
index 0d7c2eb14..74292c30c 100644
--- a/packages/plugin-sdk/src/renderer.ts
+++ b/packages/plugin-sdk/src/renderer.ts
@@ -18,7 +18,8 @@
* toolbar.
*
* Self-dialogs are not a slot: a component draws them itself
- * (`docs/plugin-plan/ui/self-dialog/`).
+ * (`docs/plugin-plan/ui/self-dialog/`), into a layer `pi.ui.openLayer` hands
+ * it.
*
* 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
@@ -201,6 +202,28 @@ export type PluginRendererDispatch = <Action extends PluginRendererActionName>(
/** Undoes one registration; calling it again does nothing. */
export type PluginDisposer = () => void;
+/**
+ * A self-drawn layer (`docs/plugin-plan/ui/self-dialog/`): a host element
+ * above the app for a modal dialog or a corner notice, which the plugin fills
+ * through `createPortal` and draws with `position: fixed`.
+ *
+ * Layers stack in the order they opened, the latest on top, within the band
+ * reserved for plugins (z 600..899): above the app and its dialogs, below the
+ * host's tooltips and window chrome. While the host waits on the user's own
+ * decision (a permission request, a question, a plan approval, an extension
+ * prompt) every layer is hidden and inert, and comes back unchanged after.
+ * The host never closes a layer on Escape; closing is the plugin's own ✕.
+ */
+export type PluginLayer = {
+ /**
+ * The portal target. It carries the plugin's style scope, so the plugin's
+ * injected sheets apply inside it. It has no size of its own.
+ */
+ readonly element: HTMLElement;
+ /** Removes the layer; calling it again does nothing. */
+ readonly close: PluginDisposer;
+};
+
/** The `pi` object handed to a renderer entry's `onLoad`. */
export type PiRendererApi = {
readonly plugin: {
@@ -225,6 +248,12 @@ export type PiRendererApi = {
* `PLUGIN_UNLOADED` once this load has ended.
*/
injectStyle(css: string): PluginDisposer;
+ /**
+ * Open a layer on top of every open one. The end of this load closes
+ * whatever it left open. Throws `PLUGIN_UNLOADED` once this load has
+ * ended.
+ */
+ openLayer(): PluginLayer;
};
readonly dispatch: PluginRendererDispatch;
};