Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.13): plugin element type & renderer contract — service iframes, sanitized render cache, placeholders, export coverage, install-scoped element actions (P4) (#21)
Ashiq Hussain Mircedd4147aa51
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4de598c..fcd0356 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,87 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.13.3] — 2026-11-03++### Added++- **Plugin system, part 4 of 5 — plugin elements & the renderer+ contract (P4).** The research §4.5 milestone: an installed plugin+ can now put its OWN element types on the canvas, draw them from+ inside its sandbox, and have them ride every pipeline a native+ element rides — save, versions, collab, offline merge, SVG/PNG/+ JPG/PDF/video export — with zero per-plugin host code. 56 new+ unit tests + a durability e2e; zero new npm dependencies.+ - **The `plugin` element** (`src/lib/types.ts`): ONE new union+ member — `type: 'plugin'` with `pluginId`, `kind`,+ `pluginVersion` and a capped `data` record. All per-plugin+ variety lives in `data`; the structural move that dodges the+ "three independent switches" problem (§4.4). Factory ++ `addPluginElement` / `updatePluginElementData` design actions:+ caller identity is stamped from the INSTALL row (a plugin can+ never forge another plugin's namespace or edit its elements),+ kinds checked against the manifest, data against the collab+ caps (64 KB/element). Undoable, HLC-stamped, collab-broadcast —+ ordinary elements, only their pixels are delegated.+ - **Renderer contract** (`broker.ts` + `renderer-cache.ts`):+ service iframes answer host→plugin `elements.render` calls+ (`{ kind, data, width, height, mode }`, 10 s deadline →+ E_TIMEOUT → placeholder). Output is `{ svg }` (≤ 2 MB, through+ the P1 accept-or-reject sanitizer — the one place untrusted+ SVG enters the host) or `{ raster }` (base64 png/jpeg/gif/webp+ data URL). `elements.registerRenderer` is service-context only+ and manifest-scoped. Render results ride a widened result+ envelope (2 MB + slack); every other result keeps the 256 KB+ RPC cap (enforced after correlation).+ - **The render cache** (`renderer-cache.ts`): module-level store+ keyed by `(pluginId, elementId, hash(data), size, mode)` —+ restyles and resizes re-render, everything else is a hit;+ in-flight dedupe; LRU 120; transport unmount drops settled+ renders. Failure philosophy (§4.5/§4.9): error/timeout/missing+ plugin → a neutral placeholder card, never a thrown exception,+ never a blocked editor.+ - **Service iframe host** (`PluginServiceLayer` ++ `PluginServiceFrame`): one hidden+ `<iframe sandbox="allow-scripts">` per installed plugin with+ elements in the open design, loading the manifest's+ `entry.service` through the DB-served CSP-pinned route; the+ frame's broker registers with the cache as the plugin's render+ transport. Frames derive purely from present elements (a+ plugin with no elements mounts no iframe); flag off / signed+ out / offline → zero iframes and placeholders.+ - **Canvas + exports**: `PluginNode` (element-node) draws the+ sanitized data URL as a Konva Image or the placeholder card+ with the honest §4.9 reason (checking / disabled on this+ instance / install hint / disabled app / not responding).+ svg-export embeds sanitized svg as a nested `<svg>` pinned to+ the element box (raster output embeds as `<image>`); video+ export awaits renders into its image map; PNG/JPG/PDF ride the+ live stage. The ExportDialog primes renders before SVG export.+ Missing renderers still export a visible placeholder card —+ the element is never silently dropped from a file.+ - **Properties slot** (`PropertiesBar`): selecting a plugin+ element shows a host-rendered schema card (text/number/color/+ select inputs from the manifest `schema` — no plugin code in+ the toolbar) + an "Open in app" button; edits go through the+ same scoped `updatePluginElementData` action.+ - **Snapshot projection**: `design.getSnapshot` returns plugin+ elements with their `data` verbatim (arrays and nesting+ included — it is the plugin's own capped output) so panels can+ restyle their elements; `_m`/bookkeeping still never crosses.+ - **Manifest v1.1** (`canvixPluginApi` minor bump): optional+ `entry.service` (same path rules as the panel, must be in+ `files`); declaring `elements[]` without `entry.service` is+ rejected at install — elements that could only ever render+ placeholders fail honestly, upfront.+ - **Durability, verified end-to-end** (`plugin-elements.spec.ts`):+ a design containing plugin elements from a plugin that is not+ available opens without a crash on a flag-off instance, stays+ editable, and round-trips load → placeholder → edit → autosave+ with the element byte-identical at the API layer. Unit suite+ pins the same for offline merge (LWW by id, type-agnostic) and+ `validateOpPayload`. Uninstall/disable/flag-off never touch+ document data — the §4.9 promise, now executable.+## [0.13.2] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex 2d67300..9568f74 100644--- a/README.md+++ b/README.md@@ -916,7 +916,21 @@ tool descriptions so agents pick the right format.namespaced 256 KB plugin storage, the`<iframe sandbox="allow-scripts">` panel host, and the Appsgrid's "Installed" section with a consent modal that lists- every requested permission verbatim *(v0.13.2)*+ every requested permission verbatim *(v0.13.2)*; the **element+ & renderer contract** (P4) let plugins put their OWN element+ types on the canvas — one new `plugin` union member whose+ per-plugin variety lives in capped `data`, a service iframe+ per plugin-with-elements answering host→plugin+ `elements.render` calls (10 s deadline, sanitized ≤ 2 MB SVG+ or raster output, cached by element+data+size), placeholder+ cards for every §4.9 state (flag off / not installed /+ disabled / not responding), export coverage (SVG embeds the+ sanitized vector; PNG/JPG/PDF/video rasterize it), a+ host-rendered schema properties card, and install-scoped+ `addPluginElement`/`updatePluginElementData` actions whose+ caller identity comes from the install row — verified+ end-to-end that uninstall/crash/flag-off never loses document+ data *(v0.13.3)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/package.json b/package.jsonindex 487880f..4d43e31 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.13.2",+ "version": "0.13.3","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/app/api/plugins/route.ts b/src/app/api/plugins/route.tsindex 433a37c..897d49d 100644--- a/src/app/api/plugins/route.ts+++ b/src/app/api/plugins/route.ts@@ -54,7 +54,8 @@ function installSummary(row: {description?: stringauthor?: { name?: string }permissions?: string[]- entry?: { panel?: string }+ entry?: { panel?: string; service?: string }+ elements?: { kind: string; label: string; schema?: unknown[] }[]}const permissions = (m.permissions ?? []).map((p) => {const parsed = parsePermission(p)@@ -71,6 +72,14 @@ function installSummary(row: {version: row.version,enabled: row.enabled,entry: m.entry ?? {},+ // P4: element kinds + schema — powers the service layer (which+ // plugins need iframes) and the properties slot (host-rendered+ // inputs). initialData never crosses — the plugin supplies it.+ elements: (m.elements ?? []).map((e) => ({+ kind: e.kind,+ label: e.label,+ schema: Array.isArray(e.schema) ? e.schema : [],+ })),permissions,createdAt: row.createdAt,}diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex 2e9dcb9..751a8d9 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -36,6 +36,12 @@ import type { ImageElement, PageData } from '@/lib/types'const CanvasStage = dynamic(() => import('./canvas/CanvasStage'), { ssr: false })+// v0.13 (P4): hidden plugin service iframes — mounted only when the+// open design actually contains plugin elements and the install+// list says the plugin is enabled. Flag-off instances fetch once,+// get 503, and never download the frame chunk at all.+const PluginServiceLayer = dynamic(() => import('./apps/PluginServiceLayer').then((m) => m.PluginServiceLayer), { ssr: false })+const PANEL_TITLES: Record<Exclude<PanelId, null>, string> = {templates: 'Templates',elements: 'Elements',@@ -469,6 +475,8 @@ export default function Editor() {<CanvasStage /><PageBar /><ZoomControls />+ {/* plugin renderers for elements on the canvas (hidden iframes) */}+ <PluginServiceLayer /></main>{/* v0.5: Animate panel — canva-style right side panel */}diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsxindex 884993f..63e7955 100644--- a/src/components/editor/ExportDialog.tsx+++ b/src/components/editor/ExportDialog.tsx@@ -5,6 +5,7 @@ import { Download, Loader2, FileImage, FileType2, FileCode2, Film } from 'lucideimport { useEditorStore } from '@/store/editor-store'import { captureStage, canvasBridge } from './canvas/canvas-bridge'import { exportDesignToSVGs, downloadSVG } from '@/lib/svg-export'+import { collectPluginElements, primePluginRenders } from '@/lib/plugins/renderer-cache'import { detectVideoFormat, downloadVideo, estimateVideoDuration, exportVideo } from '@/lib/video-export'import { toast } from '@/hooks/use-toast'import { Progress } from '@/components/ui/progress'@@ -93,8 +94,13 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChanreturn}if (format === 'svg') {- // true vector export — no rasterization of vector elements- const svgs = exportDesignToSVGs(allPages ? pages : [pages[currentPage]], canvasBridge.pageWidth, canvasBridge.pageHeight)+ // true vector export — no rasterization of vector elements.+ // v0.13 (P4): plugin renders are awaited FIRST (bounded by+ // the 10 s contract deadline) so their sanitized svg can be+ // embedded; missing plugins degrade to placeholder cards.+ const pagesToExport = allPages ? pages : [pages[currentPage]]+ await primePluginRenders(collectPluginElements(pagesToExport), 'export')+ const svgs = exportDesignToSVGs(pagesToExport, canvasBridge.pageWidth, canvasBridge.pageHeight)for (let k = 0; k < svgs.length; k++) {const suffix = svgs.length > 1 ? `-page-${(allPages ? 0 : currentPage) + k + 1}` : ''downloadSVG(svgs[k], `${base}${suffix}.svg`)diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 8e0d2bc..56b63cd 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -1,6 +1,6 @@'use client'-import { useState } from 'react'+import { useState, useSyncExternalStore } from 'react'import {Bold, Italic, Underline, Strikethrough, CaseUpper, AlignLeft, AlignCenter, AlignRight,AlignJustify, Minus, Plus, LetterText, Percent, Sparkles, Move, CopyPlus, Trash2,@@ -9,14 +9,16 @@ import {AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,- Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity,+ Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid,} from 'lucide-react'import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'-import type { AudioElement, EmbedElement, FrameElement, ImageElement, LineElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape } from '@/lib/types'+import type { AudioElement, EmbedElement, FrameElement, ImageElement, LineElement, PluginElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape } from '@/lib/types'import { FRAME_SHAPES, isGroup } from '@/lib/types'import { TEXT_EFFECTS } from '@/lib/types'import { beatSourceOf } from '@/lib/media/beat-detect'import { cn } from '@/lib/utils'+import { getPluginSystemState, subscribePluginSystem } from '@/lib/plugins/renderer-cache'+import { applyDesignAction } from '@/lib/design-actions'import { FontDropdown } from './toolbar/FontDropdown'import { ColorMenu } from './toolbar/ColorMenu'import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'@@ -63,6 +65,7 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mconst table = first.type === 'table' ? (first as TableElement) : nullconst frame = first.type === 'frame' ? (first as FrameElement) : nullconst embed = first.type === 'embed' ? (first as EmbedElement) : null+ const plugin = first.type === 'plugin' ? (first as PluginElement) : nullconst audio = first.type === 'audio' ? (first as AudioElement) : nullconst video = first.type === 'video' ? (first as VideoElement) : null// v0.11: the page's beat grid — powers the Beat Sync popover below@@ -388,6 +391,15 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<Divider /><PositionPopover ids={ids} count={1} element={first} /></>+ ) : plugin ? (+ <>+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">+ <Puzzle size={13} /> {plugin.name?.trim() || plugin.kind}+ </span>+ <PluginToolbar plugin={plugin} ids={ids} />+ <Divider />+ <PositionPopover ids={ids} count={1} element={first} />+ </>) : audio ? (<><span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">@@ -846,3 +858,95 @@ function TBtn({ children, onClick, title, ariaLabel, disabled, danger, className}const Divider = () => <span className="w-px h-5 bg-white/15 mx-1 shrink-0" />++// ── v0.13 (P4): plugin element properties slot ───────────────++/** One schema-driven field row (host-rendered — no plugin code runs+ * in the toolbar; research §4.4 "UI — properties slot"). */+function PluginToolbar({ plugin, ids }: { plugin: PluginElement; ids: string[] }) {+ const setPanel = useEditorStore((s) => s.setPanel)+ const system = useSyncExternalStore(subscribePluginSystem, getPluginSystemState, getPluginSystemState)++ const install = system.installs.get(plugin.pluginId)+ const spec = install?.elements.find((e) => e.kind === plugin.kind)+ const patchData = async (patch: Record<string, unknown>) => {+ if (!install) return+ // host-side editing acts with the install's identity (the host is+ // trusted; the caller scoping exists so PLUGINS cannot forge each+ // other's elements — the user owns the design)+ await applyDesignAction(+ { type: 'updatePluginElementData', ids, patch },+ { pluginId: install.pluginId, pluginVersion: install.version, elementKinds: install.elements.map((e) => e.kind) },+ )+ }++ return (+ <>+ {spec ? (+ spec.schema.slice(0, 5).map((raw) => {+ const f = raw as { key: string; type: string; label: string; min?: number; max?: number; step?: number; maxLength?: number; options?: { value: string; label: string }[] }+ const value = plugin.data[f.key]+ const inputCls = 'h-7 rounded-lg bg-white/[0.07] border border-white/10 px-1.5 text-[11px] text-white outline-none focus:border-[#7630D7] [color-scheme:dark]'+ return (+ <label key={f.key} className="flex items-center gap-1.5 shrink-0" title={f.label}>+ <span className="text-[10px] text-white/45">{f.label}</span>+ {f.type === 'text' && (+ <input+ defaultValue={typeof value === 'string' ? value : ''}+ maxLength={f.maxLength ?? 200}+ onBlur={(e) => { const v = e.target.value; if (v !== (plugin.data[f.key] ?? '')) void patchData({ [f.key]: v }) }}+ className={cn(inputCls, 'w-28')}+ aria-label={f.label}+ />+ )}+ {(f.type === 'number' || f.type === 'range') && (+ <input+ type="number"+ defaultValue={Number(value ?? f.min ?? 0)}+ min={f.min}+ max={f.max}+ step={f.step ?? 1}+ onBlur={(e) => {+ const n = Number(e.target.value)+ const clamped = Math.min(f.max ?? Infinity, Math.max(f.min ?? -Infinity, Number.isFinite(n) ? n : (f.min ?? 0)))+ if (clamped !== Number(plugin.data[f.key] ?? NaN)) void patchData({ [f.key]: clamped })+ }}+ className={cn(inputCls, 'w-16 text-center')}+ aria-label={f.label}+ />+ )}+ {f.type === 'color' && (+ <input+ type="color"+ defaultValue={typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value) ? value : '#7630D7'}+ onBlur={(e) => { const v = e.target.value; if (v !== plugin.data[f.key]) void patchData({ [f.key]: v }) }}+ className="h-7 w-8 rounded-lg border border-white/10 bg-transparent cursor-pointer"+ aria-label={f.label}+ />+ )}+ {f.type === 'select' && (+ <select+ defaultValue={typeof value === 'string' ? value : (f.options?.[0]?.value ?? '')}+ onChange={(e) => { const v = e.target.value; if (v !== plugin.data[f.key]) void patchData({ [f.key]: v }) }}+ className={cn(inputCls, 'w-24')}+ aria-label={f.label}+ >+ {(f.options ?? []).map((o) => (+ <option key={o.value} value={o.value}>{o.label}</option>+ ))}+ </select>+ )}+ </label>+ )+ })+ ) : (+ <span className="text-[11px] text-white/40 shrink-0" title="Install the app to edit this element's settings">+ {install ? `"${plugin.kind}" settings` : 'App not installed — settings unavailable'}+ </span>+ )}+ <TBtn onClick={() => setPanel('apps')} title="Open in app (Apps panel)" ariaLabel="Open in app">+ <LayoutGrid size={14} />+ </TBtn>+ </>+ )+}diff --git a/src/components/editor/apps/PluginServiceFrame.tsx b/src/components/editor/apps/PluginServiceFrame.tsxnew file mode 100644index 0000000..575b64e--- /dev/null+++ b/src/components/editor/apps/PluginServiceFrame.tsx@@ -0,0 +1,120 @@+'use client'++// ─────────────────────────────────────────────────────────────+// PluginServiceFrame — ONE hidden service iframe + its broker+// (P4, research PLUGIN-SYSTEM.md §4.3/§4.5).+//+// Same boundary as the panel host (P3), one difference in kind:+// this frame's broker runs in `context: 'service'`, so it is the+// only context where `elements.registerRenderer` is answered — and+// the frame is registered with the renderer cache as the plugin's+// render transport, so `elements.render` calls flow host → plugin+// with results sanitized before any host use.+//+// The frame is hidden (0×0, aria-hidden): the render contract needs+// it ALIVE, never visible. Unmount = transport deregistered = the+// canvas degrades to placeholders; settled renders stay cached.+// ─────────────────────────────────────────────────────────────++import { useCallback, useEffect, useMemo, useRef } from 'react'+import { PluginBroker, type BrokerInstall } from '@/lib/plugins/broker'+import { PluginStorage } from '@/lib/plugins/plugin-storage'+import { setRenderTransport, type PluginInstallInfo } from '@/lib/plugins/renderer-cache'+import { applyDesignAction } from '@/lib/design-actions'+import { useEditorStore } from '@/store/editor-store'+import { toast } from '@/hooks/use-toast'++/** Cryptographically random handshake token (URL-fragment safe). */+function newHandshakeToken(): string {+ const bytes = new Uint8Array(18)+ crypto.getRandomValues(bytes)+ return Array.from(bytes, (b) => b.toString(36).padStart(2, '0')).join('').slice(0, 24)+}++export interface ServiceFrameProps {+ install: PluginInstallInfo+}++export function PluginServiceFrame({ install }: ServiceFrameProps) {+ const iframeRef = useRef<HTMLIFrameElement | null>(null)+ const brokerRef = useRef<PluginBroker | null>(null)++ // one handshake token per mount — never reused across remounts+ const handshake = useMemo(() => newHandshakeToken(), [])++ // the service entry the manifest declared (validator guarantees a+ // safe relative .html path whenever elements exist; the defensive+ // fallback keeps the iframe pointed inside the bundle either way)+ const serviceSrc = useMemo(() => {+ const file = install.entry?.service && /^[\w][\w./-]*\.html$/.test(install.entry.service) ? install.entry.service : 'service.html'+ return `/api/plugins/${encodeURIComponent(install.installId)}/serve/${file}#${encodeURIComponent(handshake)}`+ }, [install.installId, install.entry, handshake])++ const hostVersion = useMemo(() => {+ const el = document.querySelector('meta[name="canvix-version"]')+ return el?.getAttribute('content') ?? 'dev'+ }, [])++ const attachBroker = useCallback(() => {+ const frame = iframeRef.current?.contentWindow+ if (!frame || brokerRef.current) return++ const record: BrokerInstall = {+ installId: install.installId,+ pluginId: install.pluginId,+ version: install.version,+ // the consent record — renderer registration itself needs+ // `element:plugin`; a plugin that never asked simply never+ // registers, and its elements stay placeholders+ permissions: install.grantedPermissions,+ elementKinds: install.elements.map((e) => e.kind),+ }+ const broker = new PluginBroker({+ install: record,+ host: {+ getDesignState: () => {+ const s = useEditorStore.getState()+ return { pages: s.pages, currentPage: s.currentPage, readOnly: s.readOnly }+ },+ applyAction: (action, caller) => applyDesignAction({ ...action, type: String(action.type) }, caller),+ notify: (text) => toast({ title: install.name, description: text }),+ closePanel: () => undefined, // a service frame has no panel to close+ logError: (scope, error) => console.error(`[plugin:${install.pluginId}] ${scope}`, error),+ },+ storage: new PluginStorage(install.pluginId),+ hostVersion,+ context: 'service',+ })+ const onMessage = (ev: MessageEvent) => broker.handleMessage(ev)+ broker.attach(frame, handshake, onMessage)+ brokerRef.current = broker+ // THIS is what makes it a render transport — plugin elements on+ // the canvas can now be drawn by this frame+ setRenderTransport(install.pluginId, broker)++ return () => {+ setRenderTransport(install.pluginId, null)+ broker.dispose(onMessage)+ brokerRef.current = null+ }+ }, [install, handshake, hostVersion])++ useEffect(() => {+ const cleanup = attachBroker()+ return cleanup+ }, [attachBroker])++ return (+ <iframe+ ref={iframeRef}+ title={`${install.name} renderer (sandboxed service)`}+ // THE SECURITY BOUNDARY — allow-scripts ONLY (same as panels):+ // opaque origin, no cookies/DOM/storage of the host+ sandbox="allow-scripts"+ src={serviceSrc}+ className="w-0 h-0 border-0"+ tabIndex={-1}+ aria-hidden+ />+ )+}diff --git a/src/components/editor/apps/PluginServiceLayer.tsx b/src/components/editor/apps/PluginServiceLayer.tsxnew file mode 100644index 0000000..d9722a2--- /dev/null+++ b/src/components/editor/apps/PluginServiceLayer.tsx@@ -0,0 +1,121 @@+'use client'++// ─────────────────────────────────────────────────────────────+// PluginServiceLayer — the host half of element rendering (P4,+// research PLUGIN-SYSTEM.md §4.3 "lifecycle" + §4.5).+//+// Watches the OPEN DESIGN for plugin elements and mounts one hidden+// service iframe per installed plugin that owns some of them. The+// iframe loads the manifest's entry.service through the same+// DB-served, CSP-pinned asset route as panels; inside it the plugin+// registers renderers (`elements.registerRenderer`) and answers+// `elements.render` calls driven by the renderer cache.+//+// Discipline inherited from the panel runtime (P3):+// · <iframe sandbox="allow-scripts"> — nothing else+// · one-time handshake token in the URL fragment+// · the PluginBroker owns every message in/out+// · unmount when the plugin's elements leave the design — plugins+// are ephemeral, only storage (and the elements themselves,+// which live in the document, not the plugin) survive+//+// Silent degradation everywhere: flag off (503), signed out (401)+// or offline → state 'off', zero iframes, placeholders on canvas.+// ─────────────────────────────────────────────────────────────++import { useEffect, useMemo, useState } from 'react'+import dynamic from 'next/dynamic'+import { useEditorStore } from '@/store/editor-store'+import type { AnyElement, PluginElement } from '@/lib/types'+import { setPluginSystemState, type PluginInstallInfo } from '@/lib/plugins/renderer-cache'++// Unload policy (research §4.7, deviated deliberately): a frame+// unmounts as soon as its plugin has no elements in the open design —+// the 5-min idle grace the research sketched buys nothing the render+// cache doesn't already hold (settled renders survive unmounts), and+// immediate unmount keeps the iframe count trivially bounded. An+// undo/redo remount costs one re-render RPC.++const PluginServiceFrame = dynamic(+ () => import('./PluginServiceFrame').then((m) => m.PluginServiceFrame),+ { ssr: false },+)++/** Distinct pluginIds with elements present anywhere in the design. */+function pluginIdsIn(pages: { elements: AnyElement[] }[]): Set<string> {+ const ids = new Set<string>()+ const walk = (els: AnyElement[]) => {+ for (const el of els) {+ if (el.type === 'plugin') ids.add((el as PluginElement).pluginId)+ else if (el.type === 'group') walk(el.children)+ }+ }+ for (const p of pages) walk(p.elements ?? [])+ return ids+}++export function PluginServiceLayer() {+ const pages = useEditorStore((s) => s.pages)+ const [installs, setInstalls] = useState<PluginInstallInfo[] | null>(null)+ const [off, setOff] = useState(false)++ // fetch the install list once per editor mount; 503 (flag off) and+ // 401 (signed out) both mean "no plugin system" — state 'off'+ useEffect(() => {+ let cancelled = false+ void fetch('/api/plugins', { cache: 'no-store' })+ .then(async (res) => {+ if (cancelled) return+ if (!res.ok) {+ setOff(true)+ return+ }+ const data = (await res.json()) as {+ installs: (PluginInstallInfo & {+ permissions: { permission: string }[]+ })[]+ }+ if (cancelled) return+ setInstalls(+ (data.installs ?? []).map((row) => ({+ ...row,+ grantedPermissions: (row.permissions ?? []).map((p) => p.permission),+ })),+ )+ })+ .catch(() => {+ if (!cancelled) setOff(true)+ })+ return () => {+ cancelled = true+ }+ }, [])++ // push install state into the renderer cache (placeholder reasons)+ useEffect(() => {+ if (off) setPluginSystemState('off')+ else if (installs) setPluginSystemState('ready', installs)+ }, [off, installs])++ const present = useMemo(() => pluginIdsIn(pages), [pages])++ const byPlugin = useMemo(() => {+ const map = new Map<string, PluginInstallInfo>()+ for (const i of installs ?? []) map.set(i.pluginId, i)+ return map+ }, [installs])++ if (off || !installs) return null++ // frames derive PURELY from the elements in the design — a plugin+ // with no elements on any page mounts no iframe at all+ const frames: React.ReactNode[] = []+ for (const pluginId of Array.from(present).sort()) {+ const install = byPlugin.get(pluginId)+ // not installed / disabled → no iframe (canvas shows the reason)+ if (!install?.enabled) continue+ frames.push(<PluginServiceFrame key={install.installId} install={install} />)+ }+ // hidden — the render contract needs the frame ALIVE, not visible+ return frames.length ? <div aria-hidden className="absolute w-0 h-0 overflow-hidden pointer-events-none">{frames}</div> : null+}diff --git a/src/components/editor/canvas/PluginNode.tsx b/src/components/editor/canvas/PluginNode.tsxnew file mode 100644index 0000000..71d249d--- /dev/null+++ b/src/components/editor/canvas/PluginNode.tsx@@ -0,0 +1,191 @@+'use client'++// ─────────────────────────────────────────────────────────────+// PluginNode — the canvas half of the renderer contract+// (research/PLUGIN-SYSTEM.md §4.5, P4).+//+// One `case 'plugin'` in element-node.tsx delegates here; this node+// asks the renderer cache what the element looks like and draws it:+//+// render ok → Konva Image fed by the sanitized data URL+// (the use-loaded-image cache dedupes decodes)+// pending → quiet neutral card (never blocks the editor)+// any failure → placeholder card: element label + plugin id ++// the honest reason (§4.9 matrix: flag off /+// not installed / disabled / not responding)+//+// The element itself is ordinary: selection, drag, transform, undo,+// animations and Beat Sync all apply through `common` — plugin+// elements are first-class citizens, only their pixels are delegated.+// ─────────────────────────────────────────────────────────────++import { useEffect, useSyncExternalStore } from 'react'+import { Group, Image as KonvaImage, Line, Rect, Text } from 'react-konva'+import type { PluginElement } from '@/lib/types'+import {+ getBrokerEpoch,+ getPluginSystemState,+ getRenderEntry,+ placeholderReason,+ renderKey,+ requestRender,+ subscribePluginSystem,+ subscribeRender,+} from '@/lib/plugins/renderer-cache'+import { useLoadedImage } from './use-loaded-image'++/** Placeholder palette — neutral on purpose: it must read as+ * "data intact, renderer absent", never as an error state of the+ * design itself. */+const CARD_FILL = '#F4F5F7'+const CARD_STROKE = '#C9CDD6'+const TITLE_FILL = '#3A3F4B'+const SUB_FILL = '#878E9C'++export function PluginNode({ el, common }: { el: PluginElement; common: Record<string, unknown> }) {+ const key = renderKey(el, 'canvas')++ // install/transport landscape as a value-stable string snapshot+ // (strings compare by value, so a rebuilt identical string is ===)+ const systemVersion = useSyncExternalStore(+ subscribePluginSystem,+ () => {+ const s = getPluginSystemState()+ return `${s.status}:${s.installs.size}:${getBrokerEpoch()}`+ },+ () => 'unknown:0:0',+ )++ const entry = useSyncExternalStore(+ (cb: () => void) => subscribeRender(key, cb),+ () => getRenderEntry(key),+ () => undefined,+ )++ // kick off (or re-kick after a broker/install change) whenever the+ // element's render identity or the plugin landscape changes+ useEffect(() => {+ requestRender(el, 'canvas')+ }, [el, key, systemVersion])++ const image = useLoadedImage(entry?.status === 'ok' ? entry.dataUrl : undefined)++ if (entry?.status === 'ok' && image) {+ return (+ <KonvaImage+ {...common}+ image={image}+ width={el.width}+ height={el.height}+ perfectDrawEnabled={false}+ />+ )+ }++ const reason =+ entry?.status === 'error'+ ? entry.message+ : placeholderReason(el)?.label ?? 'Preparing content…'+ return <PluginPlaceholder el={el} common={common} reason={reason} />+}++/** The neutral degradation card (§4.5 "Failure", §4.9 matrix). */+function PluginPlaceholder({+ el,+ common,+ reason,+}: {+ el: PluginElement+ common: Record<string, unknown>+ reason: string+}) {+ const w = Math.max(24, el.width)+ const h = Math.max(24, el.height)+ const title = el.name?.trim() || el.kind+ const titleSize = Math.max(11, Math.min(20, Math.round(Math.min(w, h) / 12)))+ const subSize = Math.max(9, Math.round(titleSize * 0.72))+ const lines = wrapCardLines(reason, w * 0.86, subSize)+ const blockH = titleSize * 0.9 + titleSize + 6 + lines.length * (subSize + 3)+ const startY = Math.max((h - blockH) / 2, 6)++ return (+ <Group {...common}>+ <Rect+ width={w}+ height={h}+ fill={CARD_FILL}+ stroke={CARD_STROKE}+ strokeWidth={1}+ cornerRadius={Math.min(10, Math.min(w, h) / 8)}+ dash={[6, 4]}+ listening={false}+ />+ {/* puzzle-ish glyph: a rounded diamond, vector-only (export-safe) */}+ <Line+ x={w / 2}+ y={startY + titleSize * 0.35}+ points={[-titleSize * 0.5, 0, 0, -titleSize * 0.36, titleSize * 0.5, 0, 0, titleSize * 0.36]}+ closed+ fill={CARD_STROKE}+ listening={false}+ />+ <Text+ y={startY + titleSize * 0.9}+ width={w}+ align="center"+ text={title}+ fontSize={titleSize}+ fontStyle="600"+ fontFamily="Inter, system-ui, sans-serif"+ fill={TITLE_FILL}+ listening={false}+ perfectDrawEnabled={false}+ />+ {lines.map((line, i) => (+ <Text+ key={i}+ y={startY + titleSize * 0.9 + titleSize + 6 + i * (subSize + 3)}+ width={w}+ align="center"+ text={line}+ fontSize={subSize}+ fontFamily="Inter, system-ui, sans-serif"+ fill={SUB_FILL}+ listening={false}+ perfectDrawEnabled={false}+ />+ ))}+ <Text+ y={Math.max(4, h - subSize - 6)}+ width={w}+ align="center"+ text={el.pluginId}+ fontSize={Math.max(8, subSize - 1)}+ fontFamily="Inter, system-ui, sans-serif"+ fill={SUB_FILL}+ opacity={0.75}+ listening={false}+ perfectDrawEnabled={false}+ />+ </Group>+ )+}++/** Cheap greedy wrap for the reason line(s), capped at 3 lines. */+function wrapCardLines(text: string, maxWidth: number, fontSize: number): string[] {+ const charW = fontSize * 0.54+ const perLine = Math.max(12, Math.floor(maxWidth / charW))+ const words = text.split(/\s+/)+ const out: string[] = []+ let line = ''+ for (const word of words) {+ if ((line ? `${line} ${word}` : word).length > perLine && line) {+ out.push(line)+ line = word+ } else {+ line = line ? `${line} ${word}` : word+ }+ }+ if (line) out.push(line)+ return out.slice(0, 3)+}diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsxindex 9890ea0..34ac240 100644--- a/src/components/editor/canvas/element-node.tsx+++ b/src/components/editor/canvas/element-node.tsx@@ -12,6 +12,7 @@ import type {GroupElement,ImageElement,LineElement,+ PluginElement,ShapeElement,StickerElement,StrokeElement,@@ -24,6 +25,7 @@ import { elementGradientProps } from '@/lib/editor-utils'import { useEditorStore } from '@/store/editor-store'import { useLoadedImage } from './use-loaded-image'import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'+import { PluginNode } from './PluginNode'export interface ElementNodeProps {element: AnyElement@@ -638,6 +640,14 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNreturn <EmbedNode el={em} common={common} />}+ // v0.13 (P4): plugin-owned elements — pixels delegated to the+ // plugin's registered renderer via the cache; every failure+ // state degrades to a placeholder card, never data loss+ case 'plugin': {+ const pl = el as PluginElement+ return <PluginNode el={pl} common={common} />+ }+case 'sticker': {const sk = el as StickerElementreturn <Text {...common} text={sk.char} fontSize={sk.fontSize} fontFamily="'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif" width={sk.width} height={sk.height} align="center" />diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsindex 3c810cf..26a11d2 100644--- a/src/lib/design-actions.ts+++ b/src/lib/design-actions.ts@@ -8,13 +8,32 @@import {createImageElement,+ createPluginElement,createTextElement,type AnyElement,type Background,+ type PluginElement,type TextElement,} from '@/lib/types'+import { checkCloneSafe } from '@/lib/plugins/data-caps'import { useEditorStore } from '@/store/editor-store'+/** Who is calling applyDesignAction. Present ONLY when a plugin's+ * broker drives an action — the plugin identity is stamped from the+ * install row (never from the wire payload), so one plugin can+ * never forge elements in another plugin's namespace. */+export interface ActionCaller {+ pluginId: string+ pluginVersion: string+ /** kinds the install's manifest declared (elements[].kind) */+ elementKinds: readonly string[]+}++/** Byte cap for one plugin element's data — matches the plugin+ * storage value cap so a single element can never out-grow the+ * RPC/autosave budgets that carry it (§4.7). */+const PLUGIN_ELEMENT_DATA_MAX_BYTES = 64 * 1024+export interface DesignAction {type: stringids?: string[]@@ -65,8 +84,9 @@ function resolveIds(ids: string[] | undefined): string[] {return (ids ?? []).filter((id) => typeof id === 'string' && valid.has(id))}-/** Execute one action. Returns a human-readable result message. */-export async function applyDesignAction(action: DesignAction): Promise<string> {+/** Execute one action. Returns a human-readable result message.+ * `caller` is set when a plugin broker drives the action. */+export async function applyDesignAction(action: DesignAction, caller?: ActionCaller): Promise<string> {const store = useEditorStore.getState()const { width, height } = store@@ -112,6 +132,58 @@ export async function applyDesignAction(action: DesignAction): Promise<string> {return 'Image added'}+ // v0.13 (P4): plugin-owned canvas elements (§4.3 whitelist).+ // Everything plugin-supplied is re-validated here — the caller+ // identity comes from the install row, the kind from the manifest,+ // the data from the collab caps. The element then rides the normal+ // addElement path: undoable, HLC-stamped, collab-broadcast.+ case 'addPluginElement': {+ if (!caller) return 'Plugin elements can only be added by installed apps'+ const kind = String(action.kind ?? '')+ if (!caller.elementKinds.includes(kind)) {+ return `This app does not declare an element kind "${kind.slice(0, 40)}"`+ }+ const data = (action.data ?? {}) as Record<string, unknown>+ const dataErr = checkCloneSafe(data, { maxBytes: PLUGIN_ELEMENT_DATA_MAX_BYTES })+ if (dataErr) return `Element data ${dataErr.replace(/^value /, '')}`+ const width = Math.min(8000, Math.max(16, Math.round(Number(action.width) || 480)))+ const height = Math.min(8000, Math.max(16, Math.round(Number(action.height) || 320)))+ const el = createPluginElement(caller.pluginId, kind, caller.pluginVersion, data, {+ width,+ height,+ x: Number.isFinite(Number(action.x)) ? Math.round(Number(action.x)) : Math.round(width * 0.1),+ y: Number.isFinite(Number(action.y)) ? Math.round(Number(action.y)) : Math.round(height * 0.1),+ ...(typeof action.name === 'string' && action.name.trim() ? { name: action.name.slice(0, 60) } : {}),+ })+ useEditorStore.getState().addElement(el)+ return 'Element added'+ }++ // v0.13 (P4): restyle in place — only elements OWNED by the calling+ // plugin, only a data patch. The broker refuses foreign pluginIds+ // before this runs; this is the second, structural check.+ case 'updatePluginElementData': {+ if (!caller) return 'Plugin elements can only be edited by installed apps'+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ const patch = (action.patch ?? {}) as Record<string, unknown>+ const patchErr = checkCloneSafe(patch, { maxBytes: PLUGIN_ELEMENT_DATA_MAX_BYTES })+ if (patchErr) return `Element data ${patchErr.replace(/^value /, '')}`+ const page = currentPageElements()+ const mine: PluginElement[] = []+ for (const el of flatElements(page)) {+ if (ids.includes(el.id) && el.type === 'plugin' && el.pluginId === caller.pluginId) mine.push(el)+ }+ if (!mine.length) return 'No elements from this app match'+ for (const el of mine) {+ const merged = { ...el.data, ...patch }+ const mergedErr = checkCloneSafe(merged, { maxBytes: PLUGIN_ELEMENT_DATA_MAX_BYTES })+ if (mergedErr) return `Merged element data ${mergedErr.replace(/^value /, '')}`+ useEditorStore.getState().updateElements([el.id], { data: merged } as Partial<PluginElement>)+ }+ return `Updated ${mine.length} element${mine.length > 1 ? 's' : ''}`+ }+case 'updateElements': {const ids = resolveIds(action.ids)if (!ids.length) return 'No matching elements'@@ -393,6 +465,8 @@ export function describeAction(action: DesignAction): string {switch (action.type) {case 'addText': return `Add text: “${String(action.text ?? '').slice(0, 40)}${String(action.text ?? '').length > 40 ? '…' : ''}”`case 'addImage': return `Add image (${String(action.src ?? '').startsWith('data:') ? 'embedded' : 'media library'})`+ case 'addPluginElement': return `Add ${String(action.kind ?? 'plugin')} element`+ case 'updatePluginElementData': return `Update ${action.ids?.length ?? 0} plugin element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`case 'updateElements': return `Update ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`case 'deleteElements': return `Delete ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`case 'moveElements': return action.to ? `Move to ${action.to}` : 'Move elements'diff --git a/src/lib/plugins/broker.test.ts b/src/lib/plugins/broker.test.tsindex 69f91ad..8e1d70d 100644--- a/src/lib/plugins/broker.test.ts+++ b/src/lib/plugins/broker.test.ts@@ -66,6 +66,8 @@ const PAGES: PageData[] = [interface TestOpts {permissions?: string[]readOnly?: boolean+ context?: 'panel' | 'service'+ elementKinds?: string[]}function makeBroker(opts: TestOpts = {}) {@@ -74,6 +76,7 @@ function makeBroker(opts: TestOpts = {}) {pluginId: 'com.example.test',version: '1.0.0',permissions: opts.permissions ?? ['design:read', 'design:write', 'storage', 'ui:notify'],+ elementKinds: opts.elementKinds ?? ['cloud'],}const applyAction = vi.fn(async () => 'applied')const notify = vi.fn()@@ -92,6 +95,7 @@ function makeBroker(opts: TestOpts = {}) {host,storage: new PluginStorage(install.pluginId, memoryStorage()),hostVersion: '0.13.2',+ context: opts.context ?? 'panel',now: () => clock.t,})const frame = new FakeWindow()@@ -336,13 +340,16 @@ describe('actions.apply', () => {expect((last().result as { message: string }).message).toBe('applied')})- it('rejects action types outside the panel whitelist with E_PAYLOAD', async () => {+ it('rejects action types outside the plugin whitelist with E_PAYLOAD', async () => {const { callOk, last } = makeBroker()- for (const type of ['generateImage', 'translate', 'addPluginElement', 'updatePluginElementData', '__proto__', '']) {+ for (const type of ['generateImage', 'translate', 'addPluginElemenX', 'constructor', '']) {await callOk('actions.apply', { action: { type } })expect(last().error?.code).toBe('E_PAYLOAD')}+ // the P4 element actions are now first-class whitelist membersexpect(PANEL_ACTION_TYPES.has('addText')).toBe(true)+ expect(PANEL_ACTION_TYPES.has('addPluginElement')).toBe(true)+ expect(PANEL_ACTION_TYPES.has('updatePluginElementData')).toBe(true)})it('suspends writes on read-only designs with E_PERMISSION', async () => {@@ -432,6 +439,139 @@ describe('elements.registerRenderer (P4 preview semantics)', () => {})})+describe('elements.registerRenderer — the service contract (P4)', () => {+ it('registers a manifest-declared kind in service context', async () => {+ const { broker, callOk, last } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('elements.registerRenderer', { kind: 'cloud' })+ expect(last().ok).toBe(true)+ expect((last().result as { registered: string[] }).registered).toEqual(['cloud'])+ expect(broker.kinds.has('cloud')).toBe(true)+ })++ it('requires the element:plugin permission (default-deny)', async () => {+ const { callOk, last } = makeBroker({ context: 'service' })+ await callOk('elements.registerRenderer', { kind: 'cloud' })+ expect(last().error?.code).toBe('E_PERMISSION')+ })++ it('refuses kinds the manifest never declared', async () => {+ const { callOk, last } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('elements.registerRenderer', { kind: 'intruder' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ expect(last().error?.message).toContain('manifest')+ })++ it('refuses malformed kind slugs', async () => {+ const { callOk, last } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('elements.registerRenderer', { kind: 'Not A Slug' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ })++ it('caps registered kinds at MAX_REGISTERED_KINDS', async () => {+ const { callOk, last } = makeBroker({+ context: 'service',+ permissions: ['element:plugin'],+ elementKinds: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],+ })+ for (const k of ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) await callOk('elements.registerRenderer', { kind: k })+ await callOk('elements.registerRenderer', { kind: 'i' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ })+})++describe('callPlugin — host→plugin elements.render (P4)', () => {+ it('refuses before the handshake completed', async () => {+ const { broker } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await expect(broker.callPlugin('elements.render', {})).rejects.toMatchObject({ code: 'E_PERMISSION' })+ })++ it('round-trips a render call and its result envelope', async () => {+ const { broker, frame, ev, callOk } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('ping') // completes the handshake++ const promise = broker.callPlugin('elements.render', { kind: 'cloud', data: {}, width: 10, height: 10, mode: 'canvas' })+ // the frame received a host→plugin call envelope+ const outbound = frame.sent.find((m) => (m as { method?: string }).method === 'elements.render') as { id: string; dir: string }+ expect(outbound.dir).toBe('call')+ broker.handleMessage(ev({ v: 1, id: outbound.id, dir: 'result', ok: true, result: { svg: '<svg xmlns="http://www.w3.org/2000/svg"/>' } }))+ await expect(promise).resolves.toEqual({ svg: '<svg xmlns="http://www.w3.org/2000/svg"/>' })+ })++ it('times out with E_TIMEOUT when the plugin never answers', async () => {+ vi.useFakeTimers()+ try {+ const { broker, callOk } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('ping')+ const promise = broker.callPlugin('elements.render', {}, { timeoutMs: 50 })+ const assertion = expect(promise).rejects.toMatchObject({ code: 'E_TIMEOUT' })+ // the deadline timer only fires when time advances+ await vi.advanceTimersByTimeAsync(60)+ await assertion+ } finally {+ vi.useRealTimers()+ }+ })++ it('carries the plugin error code when the renderer fails', async () => {+ const { broker, frame, ev, callOk } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('ping')+ const promise = broker.callPlugin('elements.render', {})+ const outbound = frame.sent.find((m) => (m as { method?: string }).method === 'elements.render') as { id: string }+ broker.handleMessage(ev({ v: 1, id: outbound.id, dir: 'result', ok: false, error: { code: 'E_PAYLOAD', message: 'bad data' } }))+ await expect(promise).rejects.toMatchObject({ code: 'E_PAYLOAD', message: 'bad data' })+ })++ it('accepts a 2 MB-class render result (the §4.5 output cap rides the wide envelope)', async () => {+ const { broker, frame, ev, callOk } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('ping')+ const big = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">${'<rect width="1" height="1"/>'.repeat(20000)}</svg>`+ expect(big.length).toBeGreaterThan(300 * 1024) // far past MAX_RPC_BYTES+ const promise = broker.callPlugin('elements.render', {})+ const outbound = frame.sent.find((m) => (m as { method?: string }).method === 'elements.render') as { id: string }+ broker.handleMessage(ev({ v: 1, id: outbound.id, dir: 'result', ok: true, result: { svg: big } }))+ await expect(promise).resolves.toMatchObject({ svg: big })+ })++ it('a disposed broker rejects pending render calls', async () => {+ const { broker, callOk } = makeBroker({ context: 'service', permissions: ['element:plugin'] })+ await callOk('ping')+ const promise = broker.callPlugin('elements.render', {})+ broker.dispose()+ await expect(promise).rejects.toMatchObject({ code: 'E_INTERNAL' })+ })+})++describe('plugin-element actions carry the install identity (P4)', () => {+ it('addPluginElement reaches design-actions with the CALLER stamped from the install row', async () => {+ const { callOk, host, last } = makeBroker({ permissions: ['design:write'] })+ await callOk('actions.apply', {+ action: { type: 'addPluginElement', kind: 'cloud', data: { seed: 1 }, pluginId: 'com.OTHER.plugin' },+ })+ expect(last().ok).toBe(true)+ expect(host.applyAction).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'addPluginElement', kind: 'cloud' }),+ { pluginId: 'com.example.test', pluginVersion: '1.0.0', elementKinds: ['cloud'] },+ )+ })++ it('updatePluginElementData is whitelisted and caller-stamped too', async () => {+ const { callOk, host, last } = makeBroker({ permissions: ['design:write'] })+ await callOk('actions.apply', { action: { type: 'updatePluginElementData', ids: ['el_1'], patch: { seed: 2 } } })+ expect(last().ok).toBe(true)+ expect(host.applyAction).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'updatePluginElementData' }),+ expect.objectContaining({ pluginId: 'com.example.test' }),+ )+ })++ it('read-only designs still suspend plugin-element writes', async () => {+ const { callOk, last } = makeBroker({ permissions: ['design:write'], readOnly: true })+ await callOk('actions.apply', { action: { type: 'addPluginElement', kind: 'cloud', data: {} } })+ expect(last().error?.code).toBe('E_PERMISSION')+ expect(last().error?.message).toContain('read-only')+ })+})+describe('lifecycle', () => {it('a disposed broker goes silent', async () => {const { broker, frame, ev } = makeBroker()diff --git a/src/lib/plugins/broker.ts b/src/lib/plugins/broker.tsindex da499f2..df1abc5 100644--- a/src/lib/plugins/broker.ts+++ b/src/lib/plugins/broker.ts@@ -31,6 +31,7 @@ import { PluginStorage } from './plugin-storage'import { pluginSnapshot, type PluginDesignSnapshot } from './snapshot'import { methodAllowed, requiredPermission } from './permissions'import {+ MAX_RENDER_RESULT_BYTES,MAX_RPC_BYTES,RPC_API_MAJOR,RPC_API_MINOR,@@ -43,7 +44,10 @@ import {type RpcErrorCode,} from './rpc'-/** The validated action set a PANEL may drive (§4.3). */+/** The validated action set a plugin may drive (§4.3) — panel and+ * service iframes alike. The two plugin-element actions are scoped+ * to the CALLING plugin inside design-actions.ts (caller identity+ * comes from the install row, never the wire). */export const PANEL_ACTION_TYPES: ReadonlySet<string> = new Set(['addText','addImage',@@ -54,6 +58,8 @@ export const PANEL_ACTION_TYPES: ReadonlySet<string> = new Set(['duplicatePage','alignElements','distributeElements',+ 'addPluginElement',+ 'updatePluginElementData',])/** push-event topics a plugin may subscribe to (§4.3). */@@ -69,6 +75,15 @@ export const EVENT_ACK_TIMEOUT_MS = 5_000/** ui.notify text cap. */export const NOTIFY_TEXT_MAX = 200+/** Renderer contract deadline (§4.5): a render that has not answered+ * in 10 s fails to a placeholder — the plugin keeps running, the+ * editor never blocks on it. */+export const RENDER_DEADLINE_MS = 10_000++/** Cap on distinct kinds one plugin may register (manifest already+ * bounds this; the broker re-asserts it — never trust the wire). */+export const MAX_REGISTERED_KINDS = 8+/** What the broker needs to know about an install. */export interface BrokerInstall {installId: string@@ -76,14 +91,17 @@ export interface BrokerInstall {version: string/** granted (normalized) permission strings — the consent record */permissions: string[]+ /** element kinds the manifest declared (elements[].kind) — P4 */+ elementKinds?: readonly string[]}/** Host capabilities the broker calls into (all injected, all mockable). */export interface BrokerHost {/** current editor state for snapshots + read-only checks */getDesignState(): { pages: Parameters<typeof pluginSnapshot>[0]['pages']; currentPage: number; readOnly: boolean }- /** execute a whitelisted design action (design-actions.ts) */- applyAction(action: Record<string, unknown>): Promise<string>+ /** execute a whitelisted design action (design-actions.ts);+ * `caller` is the plugin identity for the plugin-element actions */+ applyAction(action: Record<string, unknown>, caller?: { pluginId: string; pluginVersion: string; elementKinds: readonly string[] }): Promise<string>/** toast */notify(text: string): void/** close the plugin's panel */@@ -114,6 +132,15 @@ interface PendingAck {settled: boolean}+/** A host→plugin call awaiting its result (renderer contract §4.5). */+interface PendingCall {+ method: string+ resolve: (result: unknown) => void+ reject: (error: BrokerError) => void+ timer: ReturnType<typeof setTimeout>+ settled: boolean+}+export class PluginBroker {private readonly install: BrokerInstallprivate readonly host: BrokerHost@@ -130,6 +157,9 @@ export class PluginBroker {private readonly callTimestamps: number[] = []private readonly subscriptions = new Set<'selection' | 'document'>()private readonly pendingAcks = new Map<string, PendingAck>()+ private readonly pendingCalls = new Map<string, PendingCall>()+ /** element kinds this plugin registered renderers for (service ctx) */+ private readonly registeredKinds = new Set<string>()constructor(opts: BrokerOptions) {this.install = opts.install@@ -156,13 +186,32 @@ export class PluginBroker {return this.subscriptions}+ /** Kinds with a registered renderer (service context). */+ get kinds(): ReadonlySet<string> {+ return this.registeredKinds+ }++ /** True when the plugin answered its first handshake echo. */+ get isHandshaked(): boolean {+ return this.verified+ }+/** Tear down: no listener leaks, no dangling ack timers. */dispose(onMessage?: (ev: MessageEvent) => void): void {this.disposed = trueif (onMessage && typeof window !== 'undefined') window.removeEventListener('message', onMessage)for (const pending of this.pendingAcks.values()) clearTimeout(pending.timer)this.pendingAcks.clear()+ for (const call of this.pendingCalls.values()) {+ if (!call.settled) {+ call.settled = true+ clearTimeout(call.timer)+ call.reject(new BrokerError('E_INTERNAL', 'broker disposed before the plugin answered'))+ }+ }+ this.pendingCalls.clear()this.subscriptions.clear()+ this.registeredKinds.clear()this.iframeWindow = null}@@ -235,14 +284,40 @@ export class PluginBroker {}private handleResult(data: unknown): void {- if (!this.verified) return // acks only count post-handshake- const parsed = parseRpcResult(data)- if (!parsed.ok) return // malformed acks are dropped, not fatal- const pending = this.pendingAcks.get(parsed.value.id)+ if (!this.verified) return // results only count post-handshake+ // parse permissively (renderer results may be 2 MB, §4.5); the+ // per-call cap is re-asserted after correlation below+ const parsed = parseRpcResult(data, { maxResultBytes: MAX_RENDER_RESULT_BYTES })+ if (!parsed.ok) return // malformed results are dropped, not fatal+ const id = parsed.value.id++ const call = this.pendingCalls.get(id)+ if (call && !call.settled) {+ call.settled = true+ clearTimeout(call.timer)+ this.pendingCalls.delete(id)+ if (parsed.value.ok) {+ // non-render results keep the standard RPC cap — only the+ // §4.5 renderer output is allowed the wide envelope+ if (call.method !== 'elements.render' && parsed.value.result !== undefined) {+ const err = checkCloneSafe(parsed.value.result, { maxBytes: MAX_RPC_BYTES })+ if (err) {+ call.reject(new BrokerError('E_PAYLOAD', err))+ return+ }+ }+ call.resolve(parsed.value.result)+ } else {+ call.reject(new BrokerError(parsed.value.error.code, parsed.value.error.message))+ }+ return+ }++ const pending = this.pendingAcks.get(id)if (pending && !pending.settled) {pending.settled = trueclearTimeout(pending.timer)- this.pendingAcks.delete(parsed.value.id)+ this.pendingAcks.delete(id)}}@@ -290,19 +365,47 @@ export class PluginBroker {if (typeof type !== 'string' || !PANEL_ACTION_TYPES.has(type)) {throw new BrokerError('E_PAYLOAD',- `unknown action type — allowed: ${Array.from(PANEL_ACTION_TYPES).join(', ')} (addPluginElement arrives with element support)`,+ `unknown action type — allowed: ${Array.from(PANEL_ACTION_TYPES).join(', ')}`,)}- const message = await this.host.applyAction(action as Record<string, unknown>)+ // plugin-element actions run with the CALLER's identity — the+ // install row, never a wire-supplied pluginId (§4.3)+ const caller =+ type === 'addPluginElement' || type === 'updatePluginElementData'+ ? {+ pluginId: this.install.pluginId,+ pluginVersion: this.install.version,+ elementKinds: this.install.elementKinds ?? [],+ }+ : undefined+ const message = await (caller+ ? this.host.applyAction(action as Record<string, unknown>, caller)+ : this.host.applyAction(action as Record<string, unknown>))return { message }}- case 'elements.registerRenderer':- // P4 wires this for service iframes; a panel cannot render.+ case 'elements.registerRenderer': {+ // Only a service iframe may register renderers — a panel+ // cannot draw (its iframe dies with the panel).if (this.context !== 'service') {- throw new BrokerError('E_METHOD', 'renderer registration is only available to element service iframes (P4)')+ throw new BrokerError('E_METHOD', 'renderer registration is only available to element service iframes')+ }+ const kind = (call.params as { kind?: unknown } | undefined)?.kind+ if (typeof kind !== 'string' || !/^[a-z][a-z0-9-]{0,30}$/.test(kind)) {+ throw new BrokerError('E_PAYLOAD', 'params.kind must be a lowercase slug like "cloud"')+ }+ const declared = this.install.elementKinds ?? []+ if (!declared.includes(kind)) {+ throw new BrokerError('E_PAYLOAD', `kind "${kind}" is not declared in this plugin's manifest (elements[])`)}- throw new BrokerError('E_METHOD', 'service renderer wiring is not enabled in this build')+ if (!this.registeredKinds.has(kind)) {+ if (this.registeredKinds.size >= MAX_REGISTERED_KINDS) {+ throw new BrokerError('E_PAYLOAD', `at most ${MAX_REGISTERED_KINDS} kinds may be registered`)+ }+ this.registeredKinds.add(kind)+ }+ return { registered: Array.from(this.registeredKinds) }+ }case 'storage.get': {const key = (call.params as { key?: unknown } | undefined)?.key@@ -343,6 +446,41 @@ export class PluginBroker {}}+ // ── outbound (host → plugin calls) ────────────────────────++ /**+ * Invoke a method INSIDE the plugin and await its result — the+ * renderer contract's transport (§4.5: `elements.render` with+ * `{ data, width, height, mode }`). Rejects with a BrokerError on+ * deadline (E_TIMEOUT), disposal (E_INTERNAL) or the plugin's own+ * error code. The result is NOT sanitized here — the consumer+ * (renderer cache) runs sanitizePluginSvg before any use.+ */+ callPlugin(method: 'elements.render', params: unknown, opts: { timeoutMs?: number } = {}): Promise<unknown> {+ if (this.disposed || !this.iframeWindow) {+ return Promise.reject(new BrokerError('E_INTERNAL', 'the plugin frame is not mounted'))+ }+ if (!this.verified) {+ return Promise.reject(new BrokerError('E_PERMISSION', 'the plugin has not completed its handshake'))+ }+ const err = checkCloneSafe(params, { maxBytes: MAX_RPC_BYTES })+ if (err) return Promise.reject(new BrokerError('E_PAYLOAD', err))+ const timeoutMs = opts.timeoutMs ?? RENDER_DEADLINE_MS+ return new Promise((resolve, reject) => {+ const id = newRpcId()+ const timer = setTimeout(() => {+ const call = this.pendingCalls.get(id)+ if (call && !call.settled) {+ call.settled = true+ this.pendingCalls.delete(id)+ reject(new BrokerError('E_TIMEOUT', `the plugin did not answer ${method} within ${Math.round(timeoutMs / 1000)} s`))+ }+ }, timeoutMs)+ this.pendingCalls.set(id, { method, resolve, reject, timer, settled: false })+ this.send({ v: RPC_API_MAJOR, id, dir: 'call', method, params })+ })+ }+// ── outbound (host → plugin pushes) ─────────────────────────/**diff --git a/src/lib/plugins/data-caps.ts b/src/lib/plugins/data-caps.tsindex 8a7a1e9..756db42 100644--- a/src/lib/plugins/data-caps.ts+++ b/src/lib/plugins/data-caps.ts@@ -41,10 +41,11 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {*/export function checkCloneSafe(value: unknown,- opts: { maxBytes?: number; depth?: number } = {},+ opts: { maxBytes?: number; depth?: number; maxString?: number } = {},): string | null {const maxBytes = opts.maxBytes ?? PLUGIN_DATA_MAX_BYTESconst maxDepth = opts.depth ?? PLUGIN_DATA_MAX_DEPTH+ const maxString = opts.maxString ?? PLUGIN_DATA_MAX_STRINGlet serialized: stringtry {@@ -67,9 +68,9 @@ export function checkCloneSafe(return Number.isFinite(v) ? null : `${path}: non-finite number`}if (typeof v === 'string') {- return v.length <= PLUGIN_DATA_MAX_STRING+ return v.length <= maxString? null- : `${path}: string longer than ${PLUGIN_DATA_MAX_STRING} characters`+ : `${path}: string longer than ${maxString} characters`}if (Array.isArray(v)) {if (v.length > PLUGIN_DATA_MAX_ARRAY) {diff --git a/src/lib/plugins/element-pipeline.test.ts b/src/lib/plugins/element-pipeline.test.tsnew file mode 100644index 0000000..623eb79--- /dev/null+++ b/src/lib/plugins/element-pipeline.test.ts@@ -0,0 +1,290 @@+// ─────────────────────────────────────────────────────────────+// P4 pipeline tests — the plugin element's FULL journey:+//+// manifest declares → addPluginElement (broker caller identity)+// → editor store (undoable) → collab op validation (type-agnostic)+// → snapshot projection (own data back to the plugin) → offline+// merge (LWW by id) → svg-export embed (nested svg / placeholder)+// → uninstall semantics (data untouched, placeholder everywhere)+// ─────────────────────────────────────────────────────────────++import { beforeEach, describe, expect, it } from 'vitest'+import { useEditorStore } from '@/store/editor-store'+import { applyDesignAction, type ActionCaller } from '@/lib/design-actions'+import { createPluginElement, type AnyElement, type PageData, type PluginElement } from '@/lib/types'+import { validateOpPayload, type CollabOp } from '@/lib/collab/protocol'+import { pluginSnapshot } from '@/lib/plugins/snapshot'+import { mergeElements } from '@/lib/collab/merge'+import { formatHlc } from '@/lib/collab/hlc'+import { exportPageToSVG } from '@/lib/svg-export'+import { __resetRendererCache, setPluginSystemState, setRenderTransport, requestRender, type RenderTransport } from '@/lib/plugins/renderer-cache'++const CALLER: ActionCaller = {+ pluginId: 'com.example.test',+ pluginVersion: '1.0.0',+ elementKinds: ['cloud'],+}++function pluginEl(over: Partial<PluginElement> = {}): PluginElement {+ return createPluginElement('com.example.test', 'cloud', '1.0.0', { words: ['a', 'b'], seed: 1 }, { id: 'plg_1', ...over })+}++function seedPage(elements: AnyElement[]): PageData {+ const page: PageData = { id: 'page_1', background: { type: 'solid', color: '#FFFFFF' }, elements }+ useEditorStore.setState({+ pages: [page],+ currentPage: 0,+ selectedIds: [],+ past: [],+ future: [],+ dirty: false,+ version: 0,+ designId: 'test-design',+ })+ return page+}++beforeEach(() => {+ __resetRendererCache()+})++describe('createPluginElement factory', () => {+ it('stamps the full element shape with a placeholder-friendly default box', () => {+ const el = pluginEl()+ expect(el.type).toBe('plugin')+ expect(el.pluginId).toBe('com.example.test')+ expect(el.kind).toBe('cloud')+ expect(el.pluginVersion).toBe('1.0.0')+ expect(el.data).toEqual({ words: ['a', 'b'], seed: 1 })+ expect(el.width).toBe(480)+ expect(el.height).toBe(320)+ expect(el.id).toBeTruthy()+ expect(el.visible).toBe(true)+ })++ it('honours position/size overrides', () => {+ const el = pluginEl({ x: 40, y: 50, width: 640, height: 480, name: 'My cloud' })+ expect(el).toMatchObject({ x: 40, y: 50, width: 640, height: 480, name: 'My cloud' })+ })+})++describe('addPluginElement (design action)', () => {+ it('rejects callers without a plugin identity (the AI path cannot forge plugin elements)', async () => {+ seedPage([])+ const msg = await applyDesignAction({ type: 'addPluginElement', kind: 'cloud', data: {} })+ expect(msg).toMatch(/only be added by installed apps/i)+ expect(useEditorStore.getState().pages[0]!.elements).toHaveLength(0)+ })++ it('rejects kinds the caller never declared in its manifest', async () => {+ seedPage([])+ const msg = await applyDesignAction({ type: 'addPluginElement', kind: 'intruder', data: {} }, CALLER)+ expect(msg).toMatch(/does not declare/i)+ expect(useEditorStore.getState().pages[0]!.elements).toHaveLength(0)+ })++ it('rejects data that violates the clone caps', async () => {+ seedPage([])+ const msg = await applyDesignAction(+ { type: 'addPluginElement', kind: 'cloud', data: { bomb: 'x'.repeat(80 * 1024) } },+ CALLER,+ )+ expect(msg).toMatch(/larger than|bytes/i)+ expect(useEditorStore.getState().pages[0]!.elements).toHaveLength(0)+ })++ it('adds a fully-formed plugin element through the undoable store path', async () => {+ seedPage([])+ const msg = await applyDesignAction(+ { type: 'addPluginElement', kind: 'cloud', data: { words: ['hi'], seed: 3 }, width: 300, height: 200, x: 11, y: 22, name: 'Cloud 1' },+ CALLER,+ )+ expect(msg).toMatch(/added/i)+ const els = useEditorStore.getState().pages[0]!.elements+ expect(els).toHaveLength(1)+ expect(els[0]).toMatchObject({+ type: 'plugin',+ pluginId: 'com.example.test',+ kind: 'cloud',+ pluginVersion: '1.0.0',+ width: 300,+ height: 200,+ x: 11,+ y: 22,+ name: 'Cloud 1',+ })+ // undoable like any element+ useEditorStore.getState().undo()+ expect(useEditorStore.getState().pages[0]!.elements).toHaveLength(0)+ })++ it('clamps an absurd requested box', async () => {+ seedPage([])+ await applyDesignAction({ type: 'addPluginElement', kind: 'cloud', data: {}, width: 99999, height: 1 }, CALLER)+ const el = useEditorStore.getState().pages[0]!.elements[0] as PluginElement+ expect(el.width).toBe(8000)+ expect(el.height).toBe(16)+ })+})++describe('updatePluginElementData (design action)', () => {+ it('patches only elements owned by the calling plugin', async () => {+ const mine = pluginEl({ id: 'mine' })+ const foreign = pluginEl({ id: 'foreign', pluginId: 'other.plugin', pluginVersion: '2.0.0' })+ seedPage([mine, foreign])++ const msg = await applyDesignAction(+ { type: 'updatePluginElementData', ids: ['mine', 'foreign'], patch: { seed: 99 } },+ CALLER,+ )+ expect(msg).toMatch(/updated 1/i)+ const els = useEditorStore.getState().pages[0]!.elements as PluginElement[]+ expect(els.find((e) => e.id === 'mine')!.data).toEqual({ words: ['a', 'b'], seed: 99 })+ // the foreign element is untouched — not merged, not dropped+ expect(els.find((e) => e.id === 'foreign')!.data).toEqual({ words: ['a', 'b'], seed: 1 })+ expect(els.find((e) => e.id === 'foreign')!.pluginId).toBe('other.plugin')+ })++ it('refuses a patch that would push the merged data over the caps', async () => {+ seedPage([pluginEl()])+ const msg = await applyDesignAction(+ { type: 'updatePluginElementData', ids: ['plg_1'], patch: { bomb: 'y'.repeat(80 * 1024) } },+ CALLER,+ )+ expect(msg).toMatch(/bytes/i)+ const el = useEditorStore.getState().pages[0]!.elements[0] as PluginElement+ expect(el.data).toEqual({ words: ['a', 'b'], seed: 1 }) // unchanged+ })++ it('ignores ids that are not plugin elements at all', async () => {+ seedPage([pluginEl()])+ const msg = await applyDesignAction(+ { type: 'updatePluginElementData', ids: ['nonexistent'], patch: { seed: 2 } },+ CALLER,+ )+ expect(msg).toMatch(/no matching elements|no elements from this app/i)+ })+})++describe('collab op validation — plugin elements are plain payloads', () => {+ it('an elements:add op carrying a plugin element passes validateOpPayload', () => {+ const op: CollabOp = {+ kind: 'elements:add',+ pageId: 'page_1',+ elements: [pluginEl()],+ } as unknown as CollabOp+ expect(validateOpPayload(op)).toBe(true)+ })++ it('a hostile data payload fails the same caps as every other element', () => {+ const op: CollabOp = {+ kind: 'elements:add',+ pageId: 'page_1',+ elements: [pluginEl({ data: { bomb: 'x'.repeat(120_000) } })],+ } as unknown as CollabOp+ expect(validateOpPayload(op)).toBe(false)+ })+})++describe('snapshot projection — the plugin reads its own data back', () => {+ it('projects plugin elements with data verbatim (arrays included)', () => {+ const page: PageData = {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [pluginEl({ data: { words: ['alpha', 'beta'], palette: ['#7630D7', '#02C0CC'], seed: 5 } })],+ }+ const snap = pluginSnapshot({ pages: [page], currentPage: 0 })+ const view = snap.pages[0]!.elements[0] as Record<string, unknown>+ expect(view.type).toBe('plugin')+ expect(view.pluginId).toBe('com.example.test')+ expect(view.kind).toBe('cloud')+ expect(view.data).toEqual({ words: ['alpha', 'beta'], palette: ['#7630D7', '#02C0CC'], seed: 5 })+ // internal bookkeeping still never crosses+ expect(view._m).toBeUndefined()+ })++ it('plugin elements inside groups are projected too', () => {+ const group: AnyElement = {+ type: 'group',+ id: 'g1',+ x: 0,+ y: 0,+ width: 480,+ height: 320,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ shadow: { enabled: false, color: '#000', blur: 0, offsetX: 0, offsetY: 0 },+ children: [pluginEl()],+ }+ const snap = pluginSnapshot({ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [group] }], currentPage: 0 })+ const child = snap.pages[0]!.elements[0]!.children![0] as Record<string, unknown>+ expect(child.type).toBe('plugin')+ expect(child.data).toEqual({ words: ['a', 'b'], seed: 1 })+ })+})++describe('offline merge — LWW by id, type-agnostic (§4.9)', () => {+ it('a plugin element edited on two replicas merges by stamp, not by type', () => {+ const older = pluginEl({ data: { words: ['old'], seed: 1 }, _m: formatHlc(1, 1, 'a') })+ const newer = pluginEl({ data: { words: ['new'], seed: 2 }, _m: formatHlc(2, 1, 'b') })+ const ab = mergeElements([older], [newer], {}, {}).elements as PluginElement[]+ const ba = mergeElements([newer], [older], {}, {}).elements as PluginElement[]+ expect(ab[0]!.data.seed).toBe(2)+ expect(ba[0]!.data.seed).toBe(2) // same verdict from both directions+ })++ it('a plugin element added on one replica survives the merge untouched', () => {+ const text = { type: 'text', id: 't1', text: 'hello', _m: formatHlc(1, 1, 'a') } as unknown as AnyElement+ const added = pluginEl({ _m: formatHlc(2, 1, 'b') })+ const merged = mergeElements([text], [added], {}, {}).elements+ expect(merged.map((e) => e.id).sort()).toEqual(['plg_1', 't1'])+ expect(merged.find((e) => e.id === 'plg_1')).toMatchObject({ type: 'plugin', pluginId: 'com.example.test' })+ })+})++describe('svg-export — plugin elements land in the file', () => {+ const page = (el: PluginElement): PageData => ({+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [el],+ })++ it('embeds a primed render as a nested <svg> at the element box', async () => {+ setPluginSystemState('ready', [{+ installId: 'inst_1',+ pluginId: 'com.example.test',+ name: 'Test',+ version: '1.0.0',+ enabled: true,+ grantedPermissions: ['element:plugin'],+ entry: { service: 'service.html' },+ elements: [{ kind: 'cloud', label: 'Cloud', schema: [] }],+ }])+ setRenderTransport('com.example.test', {+ kinds: new Set(['cloud']),+ isHandshaked: true,+ callPlugin: async () => ({+ svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 320"><text x="8" y="24" font-size="18">wordcloud</text></svg>',+ }),+ } as unknown as RenderTransport)++ const el = pluginEl({ x: 100, y: 50, width: 480, height: 320 })+ requestRender(el, 'export')+ await new Promise((r) => setTimeout(r, 10))++ const svg = exportPageToSVG(page(el), 1080, 720)+ expect(svg).toContain('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 320" x="100" y="50" width="480" height="320"')+ expect(svg).toContain('wordcloud')+ })++ it('an unrenderable plugin element exports as the placeholder card (visible, honest)', () => {+ // no install, no transport — the §4.9 "not installed" state+ const el = pluginEl({ x: 10, y: 10, width: 400, height: 300, name: 'My cloud' })+ const svg = exportPageToSVG(page(el), 1080, 720)+ expect(svg).toContain('My cloud')+ expect(svg).toContain('com.example.test')+ expect(svg).toContain('stroke-dasharray')+ })+})diff --git a/src/lib/plugins/manifest.test.ts b/src/lib/plugins/manifest.test.tsindex ec95d4b..532cc51 100644--- a/src/lib/plugins/manifest.test.ts+++ b/src/lib/plugins/manifest.test.ts@@ -15,8 +15,8 @@ const WORDCLOUD = {version: '1.0.0',author: { name: 'Canvix team' },engines: { canvix: '>=0.13.0 <0.14.0' },- entry: { panel: 'panel.html' },- files: ['panel.html', 'app.js'],+ entry: { panel: 'panel.html', service: 'service.html' },+ files: ['panel.html', 'service.html', 'app.js'],permissions: ['design:read', 'design:write', 'element:plugin', 'storage'],elements: [{@@ -43,7 +43,7 @@ interface ManifestFixture {version?: stringauthor?: { name: string }engines: { canvix: string }- entry: { panel?: string }+ entry: { panel?: string; service?: string }permissions: string[]files?: string[]elements?: Array<{@@ -180,17 +180,37 @@ describe('validateManifest — structural rules', () => {it('entry paths must be relative and safe (files list follows the entry)', () => {for (const bad of ['/abs.html', '../escape.html', 'a/../b.html', 'a\\\\b.html', 'no-ext', 'x.ht', 'a//b.html', 'https://evil/x.html']) {const m = base()- m.entry = { panel: bad }+ m.entry = { service: 'service.html', panel: bad }expect(validateManifest(m, HOST).ok, `entry "${bad}"`).toBe(false)}for (const good of ['panel.html', 'ui/panel.html', 'a/b/c/d/panel.html']) {const m = base()- m.entry = { panel: good }- m.files = [good, 'app.js']+ m.entry = { service: 'service.html', panel: good }+ m.files = ['service.html', good, 'app.js']expect(validateManifest(m, HOST).ok, `entry "${good}"`).toBe(true)}})+ it('entry.service follows the same path rules as the panel', () => {+ for (const bad of ['/svc.html', '../svc.html', 'svc.js', 'a//b.html']) {+ const m = base()+ m.entry.service = bad+ expect(validateManifest(m, HOST).ok, `service "${bad}"`).toBe(false)+ }+ const m = base()+ m.entry.service = 'render/service.html'+ m.files = ['panel.html', 'render/service.html', 'app.js']+ expect(validateManifest(m, HOST).ok).toBe(true)+ })++ it('elements without a service entry can only ever placeholder → rejected at install', () => {+ const m = base()+ delete m.entry.service+ const r = validateManifest(m, HOST)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.errors.join('\n')).toMatch(/entry.service/)+ })+it('a plugin with neither entry.panel nor elements does nothing → rejected', () => {const m = base()delete m.entry.paneldiff --git a/src/lib/plugins/manifest.ts b/src/lib/plugins/manifest.tsindex d4a0ae8..ea99e92 100644--- a/src/lib/plugins/manifest.ts+++ b/src/lib/plugins/manifest.ts@@ -70,7 +70,7 @@ export interface PluginManifest {version: stringauthor?: { name: string; url?: string }engines: { canvix: string }- entry: { panel?: string }+ entry: { panel?: string; service?: string }permissions: string[]/** every file the bundle ships — the install route fetches exactly these */files: string[]@@ -289,10 +289,24 @@ export function validateManifest(raw: unknown, opts: ValidateManifestOptions): Mconst hasElements = Array.isArray(elementsRaw) && elementsRaw.length > 0if (!isPlainObject(entry)) {errors.push('entry must be an object, e.g. { "panel": "panel.html" }')- } else if (entry.panel !== undefined && !isSafeEntryPath(entry.panel)) {- errors.push('entry.panel must be a relative .html path inside the plugin (no "..", no absolute paths)')- } else if (entry.panel === undefined && !hasElements) {- errors.push('a plugin must declare entry.panel and/or elements — otherwise it does nothing')+ } else {+ if (entry.panel !== undefined && !isSafeEntryPath(entry.panel)) {+ errors.push('entry.panel must be a relative .html path inside the plugin (no "..", no absolute paths)')+ }+ // v1.1 (P4): the service entry — the hidden iframe that hosts+ // element renderers. Same path rules as the panel.+ if (entry.service !== undefined && !isSafeEntryPath(entry.service)) {+ errors.push('entry.service must be a relative .html path inside the plugin (no "..", no absolute paths)')+ }+ if (entry.panel === undefined && !hasElements) {+ errors.push('a plugin must declare entry.panel and/or elements — otherwise it does nothing (a service entry alone renders nothing)')+ }+ // elements on the canvas need a renderer host: declaring+ // elements[] without entry.service can only ever produce+ // placeholders, so it fails at install (honest, not silent)+ if (hasElements && entry.service === undefined) {+ errors.push('a plugin with elements must declare entry.service — the hidden iframe that hosts its renderers')+ }}// ── files (the install fetch list, §4.2) ──@@ -319,6 +333,9 @@ export function validateManifest(raw: unknown, opts: ValidateManifestOptions): Mif (isPlainObject(entry) && typeof entry.panel === 'string' && !seen.has(entry.panel)) {errors.push(`files must include the entry panel "${entry.panel}"`)}+ if (isPlainObject(entry) && typeof entry.service === 'string' && !seen.has(entry.service)) {+ errors.push(`files must include the service entry "${entry.service}"`)+ }}// ── permissions ──@@ -409,9 +426,10 @@ export function validateManifest(raw: unknown, opts: ValidateManifestOptions): M: {}),engines: { canvix: (engines as { canvix: string }).canvix },entry: isPlainObject(entry)- ? entry.panel !== undefined- ? { panel: entry.panel as string }- : {}+ ? {+ ...(entry.panel !== undefined ? { panel: entry.panel as string } : {}),+ ...(entry.service !== undefined ? { service: entry.service as string } : {}),+ }: {},permissions: perms.ok ? perms.permissions : [],files,diff --git a/src/lib/plugins/renderer-cache.test.ts b/src/lib/plugins/renderer-cache.test.tsnew file mode 100644index 0000000..d0ab06c--- /dev/null+++ b/src/lib/plugins/renderer-cache.test.ts@@ -0,0 +1,290 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ __resetRendererCache,+ awaitRender,+ getPluginSystemState,+ placeholderReason,+ renderKey,+ requestRender,+ setPluginSystemState,+ setRenderTransport,+ getRenderEntry,+ type PluginInstallInfo,+ type RenderTransport,+} from './renderer-cache'+import type { PluginElement } from '@/lib/types'++// The renderer cache is where the §4.5 contract becomes host code:+// transports come and go, results are sanitized HERE (the one place+// untrusted SVG enters), failures degrade to error entries — never+// exceptions, never a blocked editor.++function el(over: Partial<PluginElement> = {}): PluginElement {+ return {+ id: 'el_plugin_1',+ type: 'plugin',+ pluginId: 'com.example.test',+ kind: 'cloud',+ pluginVersion: '1.0.0',+ data: { words: ['a', 'b'], seed: 7 },+ x: 0,+ y: 0,+ width: 480,+ height: 320,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },+ ...over,+ }+}++function install(over: Partial<PluginInstallInfo> = {}): PluginInstallInfo {+ return {+ installId: 'inst_1',+ pluginId: 'com.example.test',+ name: 'Test plugin',+ version: '1.0.0',+ enabled: true,+ grantedPermissions: ['element:plugin'],+ entry: { service: 'service.html' },+ elements: [{ kind: 'cloud', label: 'Cloud', schema: [] }],+ ...over,+ }+}++/** A controllable transport standing in for a service broker. */+function fakeTransport(over: Partial<RenderTransport> = {}) {+ const t = {+ kinds: new Set(['cloud']),+ isHandshaked: true,+ callPlugin: vi.fn(async () => ({ svg: GOOD_SVG })),+ ...over,+ } as unknown as RenderTransport+ return t+}++const GOOD_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 320"><text x="10" y="20" font-size="14">hello</text></svg>'++beforeEach(() => {+ __resetRendererCache()+ vi.useFakeTimers()+})++afterEach(() => {+ vi.useRealTimers()+})++describe('placeholderReason — the §4.9 matrix', () => {+ it('unknown state → loading', () => {+ expect(placeholderReason(el())).toEqual({ reason: 'loading', label: 'Checking installed apps…' })+ })++ it('off state → instance-level message', () => {+ setPluginSystemState('off')+ expect(placeholderReason(el())?.reason).toBe('off')+ expect(placeholderReason(el())?.label).toMatch(/disabled on this Canvix instance/i)+ })++ it('ready + plugin missing → install hint carrying the plugin id', () => {+ setPluginSystemState('ready', [])+ const r = placeholderReason(el())+ expect(r?.reason).toBe('missing')+ expect(r?.label).toContain('com.example.test')+ })++ it('ready + disabled install → disabled message', () => {+ setPluginSystemState('ready', [install({ enabled: false })])+ expect(placeholderReason(el())?.reason).toBe('disabled')+ })++ it('ready + enabled install → null (render normally)', () => {+ setPluginSystemState('ready', [install()])+ expect(placeholderReason(el())).toBeNull()+ })+})++describe('requestRender — the happy path', () => {+ it('renders through the transport and caches the sanitized result', async () => {+ setPluginSystemState('ready', [install()])+ const transport = fakeTransport()+ setRenderTransport('com.example.test', transport)++ const element = el()+ requestRender(element, 'canvas')+ const key = renderKey(element, 'canvas')+ await vi.runAllTimersAsync()++ expect(getRenderEntry(key)).toEqual({+ status: 'ok',+ dataUrl: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(GOOD_SVG)}`,+ svg: GOOD_SVG,+ })+ expect(transport.callPlugin).toHaveBeenCalledWith('elements.render', {+ kind: 'cloud',+ data: element.data,+ width: 480,+ height: 320,+ mode: 'canvas',+ })+ })++ it('a second request for the same key is a cache hit (one transport call)', async () => {+ setPluginSystemState('ready', [install()])+ const transport = fakeTransport()+ setRenderTransport('com.example.test', transport)++ requestRender(el(), 'canvas')+ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(transport.callPlugin).toHaveBeenCalledTimes(1)+ })++ it('raster results become data URLs; junk results become errors', async () => {+ setPluginSystemState('ready', [install()])+ setRenderTransport('com.example.test', fakeTransport({ callPlugin: vi.fn(async () => ({ raster: 'data:image/png;base64,iVBORw0KGgo=' })) }))+ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(getRenderEntry(renderKey(el(), 'canvas'))).toMatchObject({ status: 'ok', svg: null, dataUrl: 'data:image/png;base64,iVBORw0KGgo=' })++ __resetRendererCache()+ setPluginSystemState('ready', [install()])+ setRenderTransport('com.example.test', fakeTransport({ callPlugin: vi.fn(async () => ({ nope: true })) }))+ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(getRenderEntry(renderKey(el(), 'canvas'))).toMatchObject({ status: 'error' })+ })++ it('data changes and size changes re-render; unrelated changes do not', async () => {+ setPluginSystemState('ready', [install()])+ const transport = fakeTransport()+ setRenderTransport('com.example.test', transport)++ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ // same data + size → same key+ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(transport.callPlugin).toHaveBeenCalledTimes(1)++ // restyle (data change) → new key, new render+ requestRender(el({ data: { words: ['z'], seed: 9 } }), 'canvas')+ await vi.runAllTimersAsync()+ expect(transport.callPlugin).toHaveBeenCalledTimes(2)++ // resize → new key+ requestRender(el({ width: 640 }), 'canvas')+ await vi.runAllTimersAsync()+ expect(transport.callPlugin).toHaveBeenCalledTimes(3)++ // export mode → separate key+ requestRender(el(), 'export')+ await vi.runAllTimersAsync()+ expect(transport.callPlugin).toHaveBeenCalledTimes(4)+ })+})++describe('the sanitizer is the gate — hostile renderer output never caches', () => {+ const hostile = (svg: string) => {+ setPluginSystemState('ready', [install()])+ setRenderTransport('com.example.test', fakeTransport({ callPlugin: vi.fn(async () => ({ svg })) }))+ requestRender(el(), 'canvas')+ }++ it.each([+ ['script tag', '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'],+ ['event handler', '<svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10" onload="alert(1)"/></svg>'],+ ['foreignObject', '<svg xmlns="http://www.w3.org/2000/svg"><foreignObject>hi</foreignObject></svg>'],+ ['external href', '<svg xmlns="http://www.w3.org/2000/svg"><image href="https://evil.example/x.png" width="10" height="10"/></svg>'],+ ['javascript: URI', '<svg xmlns="http://www.w3.org/2000/svg"><a href="javascript:alert(1)"><text x="0" y="10">x</text></a></svg>'],+ ['not svg at all', '<div>hello</div>'],+ ])('rejects %s', async (name, svg) => {+ hostile(svg)+ await vi.runAllTimersAsync()+ const entry = getRenderEntry(renderKey(el(), 'canvas'))+ expect(entry?.status, name).toBe('error')+ expect(entry?.status === 'error' && entry.message.length).toBeGreaterThan(4)+ })+})++describe('failure + recovery (crash containment)', () => {+ it('no transport yet → pending, then the watchdog degrades to an error entry', async () => {+ setPluginSystemState('ready', [install()])+ requestRender(el(), 'canvas')+ const key = renderKey(el(), 'canvas')+ expect(getRenderEntry(key)?.status).toBe('pending')++ await vi.advanceTimersByTimeAsync(12_500)+ const settled = getRenderEntry(key)+ expect(settled?.status).toBe('error')+ if (settled?.status === 'error') {+ expect(settled.message).toMatch(/not responding|registered/)+ }+ })++ it('a transport arriving later rescues the pending render', async () => {+ setPluginSystemState('ready', [install()])+ requestRender(el(), 'canvas')+ const key = renderKey(el(), 'canvas')+ // the iframe boots 2 s later+ await vi.advanceTimersByTimeAsync(2_000)+ setRenderTransport('com.example.test', fakeTransport())+ requestRender(el(), 'canvas') // the node re-requests on epoch change+ await vi.runAllTimersAsync()+ expect(getRenderEntry(key)?.status).toBe('ok')+ })++ it('transport rejection (deadline/crash) becomes an error entry, never a throw', async () => {+ setPluginSystemState('ready', [install()])+ setRenderTransport(+ 'com.example.test',+ fakeTransport({ callPlugin: vi.fn(async () => { throw new Error('the plugin did not answer elements.render within 10 s') }) }),+ )+ requestRender(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(getRenderEntry(renderKey(el(), 'canvas'))).toMatchObject({+ status: 'error',+ message: expect.stringContaining('did not answer'),+ })+ })++ it('unmounting the transport drops its settled renders (fresh frame may differ)', async () => {+ setPluginSystemState('ready', [install()])+ setRenderTransport('com.example.test', fakeTransport())+ requestRender(el(), 'canvas')+ const key = renderKey(el(), 'canvas')+ await vi.runAllTimersAsync()+ expect(getRenderEntry(key)?.status).toBe('ok')++ setRenderTransport('com.example.test', null)+ expect(getRenderEntry(key)).toBeUndefined()+ })+})++describe('awaitRender — the export path', () => {+ it('resolves ok entries and never rejects', async () => {+ setPluginSystemState('ready', [install()])+ setRenderTransport('com.example.test', fakeTransport())+ const entry = await awaitRender(el(), 'export')+ expect(entry.status).toBe('ok')+ })++ it('missing plugin resolves to an error entry (export draws the placeholder)', async () => {+ setPluginSystemState('ready', [])+ const pending = awaitRender(el(), 'export')+ // the boot-grace watchdog is what settles a render with no plugin+ await vi.advanceTimersByTimeAsync(13_000)+ const entry = await pending+ expect(entry.status).toBe('error')+ })+})++describe('install state store', () => {+ it('setPluginSystemState replaces the install map', () => {+ setPluginSystemState('ready', [install(), install({ pluginId: 'other.plugin', installId: 'inst_2' })])+ expect(getPluginSystemState().installs.size).toBe(2)+ setPluginSystemState('ready', [])+ expect(getPluginSystemState().installs.size).toBe(0)+ })+})diff --git a/src/lib/plugins/renderer-cache.ts b/src/lib/plugins/renderer-cache.tsnew file mode 100644index 0000000..b3738ca--- /dev/null+++ b/src/lib/plugins/renderer-cache.ts@@ -0,0 +1,372 @@+// ─────────────────────────────────────────────────────────────+// Plugin renderer cache — the host half of the renderer contract+// (research/PLUGIN-SYSTEM.md §4.5, P4).+//+// One module-level store that answers a single question for every+// consumer (canvas node, svg-export, video-export, thumbnails):+//+// "What does plugin element E look like at box (w, h) in mode M?"+//+// Answers are produced by the owning plugin's SERVICE iframe via+// broker.callPlugin('elements.render', …), sanitized here (the ONE+// place untrusted SVG enters host code), and cached by+//+// (pluginId, elementId, hash(data), w, h, mode)+//+// so a restyle (data change) or a resize re-renders, and everything+// else is a cache hit. Renders are DETERMINISTIC by contract — the+// seed lives in `data` — so a cached answer is the answer.+//+// Failure philosophy (§4.5 "Failure"): render error, timeout, or a+// missing/disabled plugin → a neutral placeholder. Data is never+// touched; the editor never blocks; a plugin iframe death degrades+// to placeholders, never crashes the host.+//+// Environment: pure TS + injectable transports — node unit tests+// drive it with fake brokers, the browser with real ones.+// ─────────────────────────────────────────────────────────────++import type { PluginElement } from '@/lib/types'+import { sanitizePluginSvg, MAX_PLUGIN_SVG_BYTES } from './sanitize-svg'++/** Render modes (§4.5): 'canvas' = editor/thumbnails, 'export' =+ * SVG/PNG/PDF/video serialization. Plugins may sharpen or simplify+ * for export; the input shape is identical. */+export type RenderMode = 'canvas' | 'export'++/** What the layer knows about one install (from GET /api/plugins). */+export interface PluginInstallInfo {+ installId: string+ pluginId: string+ name: string+ version: string+ enabled: boolean+ /** granted (normalized) permission strings — the consent record */+ grantedPermissions: string[]+ /** manifest entry paths (safe relatives, DB-served) */+ entry: { panel?: string; service?: string }+ /** manifest elements[] — kinds + labels + schema (for the properties slot) */+ elements: { kind: string; label: string; schema: unknown[] }[]+}++export type PluginSystemStatus = 'unknown' | 'off' | 'ready'++export interface PluginSystemState {+ /** 'unknown' = not fetched yet · 'off' = flag disabled / signed out · 'ready' = list loaded */+ status: PluginSystemStatus+ installs: Map<string, PluginInstallInfo>+}++/** The minimal broker surface this cache needs (real PluginBroker fits). */+export interface RenderTransport {+ kinds: ReadonlySet<string>+ isHandshaked: boolean+ callPlugin(method: 'elements.render', params: unknown, opts?: { timeoutMs?: number }): Promise<unknown>+}++// ── state ────────────────────────────────────────────────────++let systemState: PluginSystemState = { status: 'unknown', installs: new Map() }+const systemListeners = new Set<() => void>()++const brokers = new Map<string, RenderTransport>()+/** Bumped on every broker mount/unmount — nodes re-attempt renders. */+let brokerEpoch = 0++export type RenderEntry =+ | { status: 'pending' }+ | { status: 'ok'; dataUrl: string; svg: string | null }+ | { status: 'error'; message: string }++interface CacheCell {+ entry: RenderEntry+ listeners: Set<() => void>+ /** watchdog timer id — settles a pending render whose transport never arrived */+ watchdog: ReturnType<typeof setTimeout> | null+ settled: boolean+ /** a transport call is in flight — later kicks are no-ops */+ started: boolean+}++const renderCache = new Map<string, CacheCell>()+/** Bounded cache: settled entries beyond this are evicted oldest-first. */+const MAX_CACHED_RENDERS = 120+/** Grace for a pending render whose service iframe is still booting. */+const BOOT_GRACE_MS = 12_000++// ── install-state store ──────────────────────────────────────++export function getPluginSystemState(): PluginSystemState {+ return systemState+}++export function getBrokerEpoch(): number {+ return brokerEpoch+}++/** Snapshot for useSyncExternalStore (must be referentially stable between changes). */+export function subscribePluginSystem(cb: () => void): () => void {+ systemListeners.add(cb)+ return () => systemListeners.delete(cb)+}++/** Called by the service layer: the installs list arrived (ready) or+ * the flag/auth gate says the system is off. */+export function setPluginSystemState(status: PluginSystemStatus, installs?: PluginInstallInfo[]): void {+ const map = new Map<string, PluginInstallInfo>()+ for (const i of installs ?? []) map.set(i.pluginId, i)+ systemState = { status, installs: map }+ for (const cb of systemListeners) cb()+}++/** Mount/unmount the transport for a plugin (its service broker). */+export function setRenderTransport(pluginId: string, transport: RenderTransport | null): void {+ if (transport) brokers.set(pluginId, transport)+ else brokers.delete(pluginId)+ brokerEpoch += 1+ // drop this plugin's settled renders — a fresh frame may render+ // differently after a plugin update/reinstall; pending cells keep+ // waiting for their own settle (the disposed broker rejects them)+ for (const [key, cell] of renderCache) {+ if (!key.startsWith(pluginId + '|')) continue+ if (cell.settled) renderCache.delete(key)+ }+ for (const cb of systemListeners) cb()+}++/** Placeholder reason for an element whose plugin cannot render it+ * right now (§4.9 matrix). null = render normally. */+export function placeholderReason(el: PluginElement): { reason: 'loading' | 'off' | 'missing' | 'disabled'; label: string } | { reason: 'render'; label: null } | null {+ if (systemState.status === 'unknown') {+ return { reason: 'loading', label: 'Checking installed apps…' }+ }+ if (systemState.status === 'off') {+ return { reason: 'off', label: 'Plugins are disabled on this Canvix instance' }+ }+ const install = systemState.installs.get(el.pluginId)+ if (!install) {+ return { reason: 'missing', label: `Install “${el.pluginId}” to view this element` }+ }+ if (!install.enabled) {+ return { reason: 'disabled', label: `“${install.name}” is disabled` }+ }+ return null+}++// ── cache keys ───────────────────────────────────────────────++/** FNV-1a — fast, deterministic, good enough for a cache key. */+function hashData(data: Record<string, unknown>): string {+ const s = JSON.stringify(data) ?? ''+ let h = 0x811c9dc5+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i)+ h = Math.imul(h, 0x01000193)+ }+ return (h >>> 0).toString(36)+}++export function renderKey(el: PluginElement, mode: RenderMode): string {+ const w = clampDim(el.width)+ const h = clampDim(el.height)+ return `${el.pluginId}|${el.id}|${hashData(el.data)}|${w}x${h}|${mode}`+}++function clampDim(n: number): number {+ return Math.min(8000, Math.max(8, Math.round(Number(n) || 8)))+}++// ── render pipeline ──────────────────────────────────────────++function svgToDataUrl(svg: string): string {+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`+}++/** Validate + normalize a renderer result (§4.5). */+function normalizeRenderResult(result: unknown): { dataUrl: string; svg: string | null } | { error: string } {+ if (typeof result !== 'object' || result === null || Array.isArray(result)) {+ return { error: 'renderer result must be an object { svg } or { raster }' }+ }+ const r = result as { svg?: unknown; raster?: unknown }+ if (typeof r.svg === 'string') {+ const clean = sanitizePluginSvg(r.svg)+ if (!clean.ok) return { error: `renderer output rejected: ${clean.error}` }+ return { dataUrl: svgToDataUrl(clean.svg), svg: clean.svg }+ }+ if (typeof r.raster === 'string') {+ if (!/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(r.raster)) {+ return { error: 'raster must be a base64 png/jpeg/gif/webp data URL' }+ }+ if (r.raster.length > MAX_PLUGIN_SVG_BYTES) {+ return { error: `renderer output is ${r.raster.length} bytes — the cap is ${MAX_PLUGIN_SVG_BYTES}` }+ }+ return { dataUrl: r.raster, svg: null }+ }+ return { error: 'renderer result must carry svg or raster' }+}++function ensureCell(key: string): CacheCell {+ let cell = renderCache.get(key)+ if (!cell) {+ cell = { entry: { status: 'pending' }, listeners: new Set(), watchdog: null, settled: false, started: false }+ renderCache.set(key, cell)+ }+ return cell+}++function settleCell(key: string, cell: CacheCell, entry: RenderEntry): void {+ if (cell.settled) return+ cell.settled = true+ if (cell.watchdog) clearTimeout(cell.watchdog)+ cell.watchdog = null+ cell.entry = entry+ for (const cb of cell.listeners) cb()+ cell.listeners.clear()+ evict()+}++function evict(): void {+ if (renderCache.size <= MAX_CACHED_RENDERS) return+ for (const [key, cell] of renderCache) {+ if (renderCache.size <= MAX_CACHED_RENDERS) break+ if (cell.settled) renderCache.delete(key)+ }+}++/** Kick off (or join) the render for one element. Safe to call+ * repeatedly — idempotent per key until settled. */+export function requestRender(el: PluginElement, mode: RenderMode): void {+ const key = renderKey(el, mode)+ const cell = ensureCell(key)+ if (cell.settled) return++ // placeholder states need no transport (§4.9) — but they can flip+ // (install arrives, plugin enabled), so callers re-request on+ // broker-epoch changes; a pending cell without a reason resolves+ // through its watchdog+ const reason = placeholderReason(el)+ if (reason && reason.reason !== 'render') {+ if (!cell.watchdog) {+ cell.watchdog = setTimeout(() => {+ const c = renderCache.get(key)+ if (c && !c.settled) settleCell(key, c, { status: 'error', message: reason.label })+ }, BOOT_GRACE_MS)+ }+ return+ }++ const transport = brokers.get(el.pluginId)+ if (!transport || !transport.isHandshaked || !transport.kinds.has(el.kind)) {+ // service iframe still booting (or this plugin ships no renderer+ // for the kind) — wait, then degrade honestly+ if (!cell.watchdog) {+ cell.watchdog = setTimeout(() => {+ const c = renderCache.get(key)+ if (c && !c.settled) {+ settleCell(key, c, {+ status: 'error',+ message: transport+ ? `“${el.pluginId}” has not registered a renderer for “${el.kind}”`+ : `“${el.pluginId}” is not responding`,+ })+ }+ }, BOOT_GRACE_MS)+ }+ return+ }++ // one in-flight call per key — re-kicks while the promise is+ // outstanding are no-ops (they carry the same deterministic input)+ if (cell.started) return+ cell.started = true++ void transport+ .callPlugin('elements.render', {+ kind: el.kind,+ data: el.data,+ width: clampDim(el.width),+ height: clampDim(el.height),+ mode,+ })+ .then(+ (result) => {+ const norm = normalizeRenderResult(result)+ const c = renderCache.get(key) ?? cell+ settleCell(+ key,+ c,+ 'dataUrl' in norm+ ? { status: 'ok', dataUrl: norm.dataUrl, svg: norm.svg }+ : { status: 'error', message: norm.error },+ )+ },+ (error: unknown) => {+ const message = error instanceof Error ? error.message : 'renderer failed'+ const c = renderCache.get(key) ?? cell+ settleCell(key, c, { status: 'error', message })+ },+ )+}++/** Current entry for a key (undefined = never requested). */+export function getRenderEntry(key: string): RenderEntry | undefined {+ return renderCache.get(key)?.entry+}++/** Subscribe to one render key (useSyncExternalStore pattern). */+export function subscribeRender(key: string, cb: () => void): () => void {+ const cell = ensureCell(key)+ if (cell.settled) return () => undefined+ cell.listeners.add(cb)+ return () => cell.listeners.delete(cb)+}++/** Export path: await the render (placeholder-generating on failure).+ * Never rejects — an error is returned as an error entry so exports+ * can draw the placeholder instead of failing the whole file. */+export async function awaitRender(el: PluginElement, mode: RenderMode): Promise<RenderEntry> {+ requestRender(el, mode)+ const key = renderKey(el, mode)+ const cell = renderCache.get(key)+ if (!cell) return { status: 'error', message: 'render was not started' }+ if (cell.settled) return cell.entry+ return new Promise<RenderEntry>((resolve) => {+ const done = () => {+ const c = renderCache.get(key)+ if (c?.settled) resolve(c.entry)+ }+ cell.listeners.add(done)+ })+}++/** Prime every plugin element on the pages (export pre-pass). */+export async function primePluginRenders(els: PluginElement[], mode: RenderMode): Promise<void> {+ await Promise.all(els.map((el) => awaitRender(el, mode)))+}++/** Collect every plugin element in the pages (groups included). */+export function collectPluginElements(pages: { elements: unknown[] }[]): PluginElement[] {+ const out: PluginElement[] = []+ const walk = (els: unknown[]) => {+ for (const el of els) {+ if (!el || typeof el !== 'object') continue+ const e = el as { type?: string; children?: unknown[] }+ if (e.type === 'plugin') out.push(el as PluginElement)+ else if (Array.isArray(e.children)) walk(e.children)+ }+ }+ for (const p of pages) walk(p.elements ?? [])+ return out+}++/** Test seam: wipe all state between unit tests. */+export function __resetRendererCache(): void {+ for (const cell of renderCache.values()) {+ if (cell.watchdog) clearTimeout(cell.watchdog)+ }+ renderCache.clear()+ brokers.clear()+ systemState = { status: 'unknown', installs: new Map() }+ brokerEpoch = 0+ for (const cb of systemListeners) cb()+}diff --git a/src/lib/plugins/rpc.ts b/src/lib/plugins/rpc.tsindex 09a5592..e50b284 100644--- a/src/lib/plugins/rpc.ts+++ b/src/lib/plugins/rpc.ts@@ -23,12 +23,23 @@ import { checkCloneSafe } from './data-caps'/** Protocol major of THIS host build. */export const RPC_API_MAJOR = 1-/** Additive minor — grows when new methods/fields are added. */-export const RPC_API_MINOR = 0+/** Additive minor — grows when new methods/fields are added.+ * v1.1 (P4): the renderer contract is live — host→plugin+ * `elements.render` calls with results up to+ * MAX_RENDER_RESULT_BYTES, and `elements.registerRenderer`+ * accepts service-iframe callers. */+export const RPC_API_MINOR = 1/** Byte cap per message — the collab op cap (§4.7). */export const MAX_RPC_BYTES = 256 * 1024+/** Renderer results may be full SVG documents — the §4.5 output cap+ * (MAX_PLUGIN_SVG_BYTES) plus envelope overhead. This is the ONE+ * sanctioned exception to MAX_RPC_BYTES: it applies only to the+ * result of a host→plugin `elements.render` call, and the plugin's+ * svg still has to pass the sanitizer before the host uses it. */+export const MAX_RENDER_RESULT_BYTES = 2 * 1024 * 1024 + 64 * 1024+export type RpcErrorCode =| 'E_VERSION' // protocol major mismatch| 'E_MALFORMED' // envelope is not a valid shape@@ -154,8 +165,19 @@ export function parseRpcCall(}}-/** Parse a RESULT envelope (either direction). */-export function parseRpcResult(data: unknown): ParseOk<RpcResult> | ParseErr {+/** Parse a RESULT envelope (either direction).+ * `maxResultBytes` widens the byte AND per-string caps for the+ * renderer-contract result (§4.5) — default stays the standard RPC+ * cap. A render result is legitimately ONE big string (the svg). */+export function parseRpcResult(+ data: unknown,+ opts: { maxResultBytes?: number } = {},+): ParseOk<RpcResult> | ParseErr {+ const maxBytes = opts.maxResultBytes ?? MAX_RPC_BYTES+ const caps =+ maxBytes > MAX_RPC_BYTES+ ? { maxBytes, maxString: maxBytes }+ : { maxBytes }const common = checkCommon(data)if (!('v' in common)) return commonconst raw = data as Record<string, unknown>@@ -164,7 +186,7 @@ export function parseRpcResult(data: unknown): ParseOk<RpcResult> | ParseErr {}if (raw.ok === true) {if (raw.result !== undefined) {- const err = checkCloneSafe(raw.result, { maxBytes: MAX_RPC_BYTES })+ const err = checkCloneSafe(raw.result, caps)if (err) return { ok: false, code: 'E_PAYLOAD', message: err }}return { ok: true, value: { v: RPC_API_MAJOR, id: common.id, dir: 'result', ok: true, result: raw.result } }diff --git a/src/lib/plugins/snapshot.ts b/src/lib/plugins/snapshot.tsindex 6989ba9..2116079 100644--- a/src/lib/plugins/snapshot.ts+++ b/src/lib/plugins/snapshot.ts@@ -15,6 +15,7 @@// ─────────────────────────────────────────────────────────────import type { AnyElement, PageData } from '@/lib/types'+import { checkCloneSafe } from './data-caps'/** Strings longer than this are dropped (image dataURLs etc.). */export const SNAPSHOT_FIELD_CHAR_CAP = 1024@@ -93,6 +94,17 @@ function projectElement(el: AnyElement): PluginElementView {}continue}+ // plugin elements: `data` is the owning plugin's own output —+ // it wrote those bytes through the capped addPluginElement /+ // updatePluginElementData actions, so it gets them back whole+ // (arrays and nesting included). A foreign plugin reading the+ // snapshot sees the same copy — capped, read-only, its own to+ // interpret or ignore.+ if (el.type === 'plugin' && key === 'data') {+ if (checkCloneSafe(value) === null) view.data = value+ else omitted.push('data')+ continue+ }if (HEAVY_FIELDS.has(key)) {// short refs (e.g. "/api/media/abc") survive; dataURLs never doif (typeof value === 'string' && value.length <= SNAPSHOT_FIELD_CHAR_CAP) {diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.tsindex b403b97..e586a4e 100644--- a/src/lib/svg-export.ts+++ b/src/lib/svg-export.ts@@ -28,6 +28,8 @@ import type {GroupElement,} from '@/lib/types'import { arcForCurve, embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'+import type { PluginElement } from '@/lib/types'+import { getRenderEntry, renderKey } from '@/lib/plugins/renderer-cache'// ── escaping ─────────────────────────────────────────────────@@ -166,6 +168,46 @@ function starPoints(cx: number, cy: number, outer: number, inner: number): strinreturn pts.join(' ')}+// ── v0.13 (P4): plugin element embedding ────────────────────++/** Opening <svg …> tag scanner — attrs may not run past the next+ * `<` (same hardening as the plugin sanitizer's TAG_RE). */+const PLUGIN_SVG_OPEN_RE = /^\uFEFF?\s*(?:<\?xml[^>]*\?>\s*)?<svg\b((?:"[^"]*"|'[^']*'|[^>"'<])*)>/++/**+ * Re-emit a (sanitized) plugin svg as a NESTED <svg> pinned to the+ * element box: keep the plugin's viewBox and attributes, override+ * x/y/width/height with host geometry. Returns null when the string+ * does not parse as an <svg> document (caller falls back to the+ * placeholder card — never a broken export).+ */+function nestPluginSvg(svg: string, x: number, y: number, w: number, h: number): string | null {+ const m = PLUGIN_SVG_OPEN_RE.exec(svg)+ if (!m) return null+ const end = svg.lastIndexOf('</svg>')+ if (end === -1 || end < m[0].length) return null+ const inner = svg.slice(m[0].length, end)+ // keep the plugin's own attributes (viewBox, xmlns, defs ids…) but+ // strip any x/y/width/height — duplicates would invalidate the+ // document, and geometry is the HOST's call, never the plugin's+ const attrs = (m[1] ?? '').replace(/\s(?:x|y|width|height)\s*=\s*(?:"[^"]*"|'[^']*')/g, '')+ return `<svg${attrs} x="${x}" y="${y}" width="${w}" height="${h}">${inner}</svg>`+}++/** The export-side placeholder card — mirrors the canvas card so a+ * missing/failed plugin still shows an honest, styled box. */+function pluginPlaceholderSvg(el: PluginElement, rotate: string): string {+ const title = el.name?.trim() || el.kind+ const titleSize = Math.max(11, Math.min(20, Math.round(Math.min(el.width, el.height) / 12)))+ const subSize = Math.max(9, Math.round(titleSize * 0.72))+ const r = Math.min(10, Math.min(el.width, el.height) / 8)+ return ` <g${rotate ? ` transform="${rotate.trim()}"` : ''}>+ <rect x="${el.x}" y="${el.y}" width="${el.width}" height="${el.height}" rx="${r}" fill="#F4F5F7" stroke="#C9CDD6" stroke-width="1" stroke-dasharray="6 4" />+ <text x="${el.x + el.width / 2}" y="${el.y + el.height / 2}" text-anchor="middle" dominant-baseline="central" font-size="${titleSize}" font-weight="600" font-family="Inter, system-ui, sans-serif" fill="#3A3F4B">${esc(title)}</text>+ <text x="${el.x + el.width / 2}" y="${el.y + el.height / 2 + titleSize}" text-anchor="middle" font-size="${subSize}" font-family="Inter, system-ui, sans-serif" fill="#878E9C">${esc(el.pluginId)}</text>+ </g>`+}+function serializeElement(el: AnyElement, ctx: SvgContext): string {if (!el.visible) return ''const transformBase = rotationTransform(el)@@ -323,6 +365,31 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {return ` <text x="${cx}" y="${cy}" text-anchor="middle" dominant-baseline="central" font-size="${sk.fontSize}" font-family="'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif"${opacityAttr(sk)}${transformBase ? ` transform="rotate(${sk.rotation} ${cx} ${cy})"` : ''}>${esc(sk.char)}</text>`}+ // v0.13 (P4): plugin elements — the renderer's SANITIZED svg is+ // embedded as a nested <svg> positioned at the element box (the+ // research §4.4/§4.5 promise: plugin elements in every export+ // with zero per-plugin code). No cached render (plugin missing /+ // failed / timed out) → the same neutral placeholder card the+ // canvas shows — the element stays VISIBLE in the file.+ case 'plugin': {+ const pl = el as PluginElement+ const entry = getRenderEntry(renderKey(pl, 'export'))+ const cx = pl.x + pl.width / 2+ const cy = pl.y + pl.height / 2+ const rotate = pl.rotation ? ` rotate(${pl.rotation} ${cx} ${cy})` : ''+ if (entry?.status === 'ok' && entry.svg) {+ const nested = nestPluginSvg(entry.svg, pl.x, pl.y, pl.width, pl.height)+ if (nested) {+ return ` <g${rotate ? ` transform="${rotate.trim()}"` : ''}${opacityAttr(pl)}${shadowAttrs(pl, ctx)}>${nested}</g>`+ }+ }+ if (entry?.status === 'ok' && entry.dataUrl) {+ // raster renderer output — embed like an image+ return ` <image href="${esc(entry.dataUrl)}" x="${pl.x}" y="${pl.y}" width="${pl.width}" height="${pl.height}"${rotate ? ` transform="${rotate.trim()}"` : ''}${opacityAttr(pl)} preserveAspectRatio="none" />`+ }+ return pluginPlaceholderSvg(pl, rotate)+ }+case 'group': {const g = el as GroupElementconst children = g.childrendiff --git a/src/lib/types.ts b/src/lib/types.tsindex 9489973..357745e 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -19,6 +19,7 @@ export type ElementType =| 'embed'| 'audio'| 'video'+ | 'plugin'export type TextAlign = 'left' | 'center' | 'right' | 'justify'@@ -325,6 +326,31 @@ export interface VideoElement extends BaseElement {trimEnd: number}+// ── v0.13 (P4): the plugin element — research/PLUGIN-SYSTEM.md §4.5 ──++/** The ONE native element type plugins add (§4.4): a single union+ * member whose per-plugin variety lives entirely in `data` + a+ * renderer registered at runtime by the owning plugin. Structural+ * move that dodges the "three independent switches" problem — every+ * renderer adds ONE `case 'plugin'` that delegates to the contract.+ *+ * Durability rules (§4.9): the element is plain document data — it+ * rides autosave, versions, collab replication and offline merge+ * (LWW by id, type-agnostic) like any other element. Uninstalling+ * or disabling the plugin NEVER touches it; the canvas degrades to+ * a placeholder card and the data stays intact for reinstall. */+export interface PluginElement extends BaseElement {+ type: 'plugin'+ /** owning plugin id, e.g. 'com.canvix.wordcloud' — namespaced by the manifest */+ pluginId: string+ /** element kind declared in the manifest's elements[] — namespaced by pluginId */+ kind: string+ /** plugin semver at creation time, so a later version can migrate its own data */+ pluginVersion: string+ /** JSON data — must pass the collab/validateOpPayload caps (≤ 500-array, ≤ 100 k strings, depth ≤ 12) */+ data: Record<string, unknown>+}+/** Brand kit — persisted per browser (localStorage) */export interface BrandKit {colors: string[]@@ -361,6 +387,7 @@ export type AnyElement =| EmbedElement| AudioElement| VideoElement+ | PluginElementexport type Background =| { type: 'solid'; color: string }@@ -741,6 +768,29 @@ export function createStrokeElement(init: BaseInit & Partial<StrokeElement>): St}}+/** v0.13 (P4): factory for plugin elements. The caller (the+ * addPluginElement design action) has ALREADY validated kind against+ * the install's manifest and data against the clone caps — the+ * factory only stamps defaults. Default box: a 480×320 card that+ * reads well as a placeholder when the plugin cannot render. */+export function createPluginElement(+ pluginId: string,+ kind: string,+ pluginVersion: string,+ data: Record<string, unknown>,+ init: BaseInit & Partial<PluginElement> = {}+): PluginElement {+ return {+ ...baseElement('plugin', { width: 480, height: 320, ...init }),+ type: 'plugin',+ pluginId,+ kind,+ pluginVersion,+ data,+ ...init,+ }+}+/** hex/rgb → rgba with alpha — used by text effect rendering */export function withAlpha(color: string, alpha: number): string {if (color.startsWith('#')) {diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex 32d97b4..ddf1295 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -12,9 +12,10 @@// ─────────────────────────────────────────────────────────────import Konva from 'konva'-import type { AnyElement, AudioElement, ImageElement, PageData, VideoElement } from '@/lib/types'+import type { AnyElement, AudioElement, ImageElement, PageData, PluginElement, VideoElement } from '@/lib/types'import { animateElementAt, pageHoldDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'+import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'export interface VideoExportOptions {designWidth: number@@ -116,6 +117,27 @@ async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElif (img) map.set(src, img)}))++ // v0.13 (P4): plugin elements — await each renderer (bounded by+ // the 10 s contract deadline) and load the sanitized data URL as+ // the element's raster. Failures (missing/failed plugin) leave no+ // entry: buildKonvaNode draws the placeholder card instead.+ const pluginEls: PluginElement[] = []+ const walkPlugins = (els: AnyElement[]) => {+ for (const el of els) {+ if (el.type === 'plugin') pluginEls.push(el)+ else if (el.type === 'group') walkPlugins(el.children)+ }+ }+ for (const p of pages) walkPlugins(p.elements)+ await Promise.all(+ pluginEls.slice(0, 60).map(async (el) => {+ const entry = await awaitRender(el, 'export')+ if (entry.status !== 'ok') return+ const img = await loadImage(entry.dataUrl)+ if (img) map.set(renderKey(el, 'export'), img)+ })+ )return map}@@ -279,6 +301,60 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):})return node}+ case 'plugin': {+ // v0.13 (P4): the renderer's sanitized output as an Image; no+ // render (missing/failed/timed-out plugin) → the placeholder+ // card, mirroring the editor canvas+ const pl = el as PluginElement+ const raster = images.get(renderKey(pl, 'export'))+ if (raster) {+ return new Konva.Image({+ id: pl.id,+ x: pl.x,+ y: pl.y,+ width: pl.width,+ height: pl.height,+ image: raster,+ })+ }+ const group = new Konva.Group({ id: pl.id, x: pl.x, y: pl.y })+ group.add(+ new Konva.Rect({+ width: pl.width,+ height: pl.height,+ cornerRadius: Math.min(10, Math.min(pl.width, pl.height) / 8),+ fill: '#F4F5F7',+ stroke: '#C9CDD6',+ strokeWidth: 1,+ dash: [6, 4],+ }),+ )+ const titleSize = Math.max(11, Math.min(20, Math.round(Math.min(pl.width, pl.height) / 12)))+ group.add(+ new Konva.Text({+ y: pl.height / 2 - titleSize * 0.6,+ width: pl.width,+ align: 'center',+ text: pl.name?.trim() || pl.kind,+ fontSize: titleSize,+ fontStyle: '600',+ fontFamily: 'Inter, system-ui, sans-serif',+ fill: '#3A3F4B',+ }),+ )+ group.add(+ new Konva.Text({+ y: pl.height / 2 + titleSize * 0.6,+ width: pl.width,+ align: 'center',+ text: pl.pluginId,+ fontSize: Math.max(9, Math.round(titleSize * 0.72)),+ fontFamily: 'Inter, system-ui, sans-serif',+ fill: '#878E9C',+ }),+ )+ return group+ }case 'audio': {// vector waveform card — geometry mirrors element-node.tsx AudioNodeconst au = el as AudioElementdiff --git a/tests/e2e/plugin-elements.spec.ts b/tests/e2e/plugin-elements.spec.tsnew file mode 100644index 0000000..277220f--- /dev/null+++ b/tests/e2e/plugin-elements.spec.ts@@ -0,0 +1,131 @@+import { expect, test } from '@playwright/test'++/**+ * v0.13 P4 regression — plugin elements on a flag-off instance.+ *+ * The §4.9 durability promise, verified end-to-end with real+ * persistence: a design containing plugin elements from a plugin+ * that is NOT available (flag off ⇒ /api/plugins 503 ⇒ the renderer+ * cache reports "plugins are disabled on this instance") must+ * 1. open without a crash (the placeholder path is inert, not fatal)+ * 2. still be editable (the element is an ordinary element)+ * 3. round-trip through autosave with the plugin element's data+ * byte-identical — rendering degrades, DATA NEVER DOES+ *+ * Konva canvases are opaque to DOM queries, so the durability claim+ * is asserted at the API layer where the truth lives (jsonb in/out).+ */++const PLUGIN_ELEMENT = {+ id: 'plg_e2e_1',+ type: 'plugin',+ pluginId: 'net.example.notinstalled',+ kind: 'cloud',+ pluginVersion: '1.4.2',+ data: { words: ['alpha', 'beta', 'gamma'], palette: ['#7630D7', '#02C0CC'], seed: 42 },+ x: 120,+ y: 140,+ width: 480,+ height: 320,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ name: 'E2E cloud',+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },+}++const TEXT_ELEMENT = {+ id: 'txt_e2e_1',+ type: 'text',+ text: 'plugin durability probe',+ x: 80,+ y: 60,+ width: 400,+ height: 60,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ fontSize: 36,+ fontFamily: 'Inter',+ bold: false,+ italic: false,+ underline: false,+ strike: false,+ uppercase: false,+ fill: '#1F2226',+ align: 'left',+ lineHeight: 1.25,+ letterSpacing: 0,+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },+}++test.describe('plugin elements with no plugin system available (P4 durability)', () => {+ test('placeholder renders inert, editing works, autosave preserves the element byte-for-byte', async ({ page, request }) => {+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // an ownerless design anyone-with-the-link can edit+ const create = await request.post('/api/designs', {+ data: {+ name: 'cvx_p4_durability_probe',+ width: 1080,+ height: 720,+ pages: [+ {+ id: 'page_p4_e2e',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [TEXT_ELEMENT, PLUGIN_ELEMENT],+ },+ ],+ },+ })+ expect(create.status(), `create: ${await create.text()}`).toBeLessThan(300)+ const design = (await create.json()) as { id: string }+ expect(design.id).toBeTruthy()++ // open the editor — the plugin system is flag-off here, so the+ // element can only ever be a placeholder+ await page.goto(`/design/${design.id}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // the placeholder path must be inert — no page errors from the+ // renderer cache, the service layer, or the Konva node+ await page.waitForTimeout(1500)+ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])++ // edit: add a page — an ordinary mutation that marks the design+ // dirty and fires the debounced autosave+ await expect(page.getByRole('button', { name: 'Add page' })).toBeVisible({ timeout: 20_000 })+ await page.getByRole('button', { name: 'Add page' }).click()+ // debounce (1.6 s) + request+ await page.waitForTimeout(4000)+ expect(errors, `page errors after edit: ${errors.join(' | ')}`).toEqual([])++ // the durability verdict: the plugin element survives the+ // load → placeholder → edit → autosave round-trip UNCHANGED+ const reread = await request.get(`/api/designs/${design.id}`)+ expect(reread.status()).toBe(200)+ const body = (await reread.json()) as {+ pages: { id: string; elements: unknown[] }[]+ }+ const page1 = body.pages.find((p) => p.id === 'page_p4_e2e')+ expect(page1, 'the original page survives the edit').toBeTruthy()+ const pluginEl = page1!.elements.find(+ (e) => (e as { id?: string }).id === 'plg_e2e_1',+ ) as typeof PLUGIN_ELEMENT | undefined+ expect(pluginEl, 'the plugin element was not dropped by the save').toBeTruthy()+ expect(pluginEl!.pluginId).toBe('net.example.notinstalled')+ expect(pluginEl!.kind).toBe('cloud')+ expect(pluginEl!.pluginVersion).toBe('1.4.2')+ expect(pluginEl!.data).toEqual(PLUGIN_ELEMENT.data)+ expect(pluginEl!.x).toBe(PLUGIN_ELEMENT.x)+ expect(pluginEl!.width).toBe(PLUGIN_ELEMENT.width)++ // cleanup: leave no probe rows behind+ const del = await request.delete(`/api/designs/${design.id}`)+ expect([200, 202, 204]).toContain(del.status())+ })+})