PotionUI Docs v0.3.0

Plugin frontends

A plugin can put its own Svelte components into the app: a page in the sidebar, a form field, an admin tab, a tool tab, a renderer for History. This guide adds a page to a plugin, shows what the app hands your code and which of its components you should reuse, then builds and ships it.

GuideWritten for v0.3.0
On this page

Two kinds of frontend code#

Frontend source lives in the plugin's frontend/src/ and compiles to frontend/dist/. The manifest names compiled files, such as component: "RunCounterPage.js". The build tells the two kinds apart by one file:

  • A page plugin has frontend/src/index.js. It imports one Svelte component and exports mountPlugin and unmountPlugin. The output is frontend/dist/<Component>.js.
  • Components: every frontend/src/<Name>.svelte that the manifest names under a component: key (field types, renderers, contributions, admin tabs, sidebar widgets, tool tabs) compiles on its own to frontend/dist/<Name>.js.

A plugin may have both. Each compiled file carries its own copy of the Svelte runtime, so a plugin cannot import the app's $lib; it reaches the app through the host described below.

Note

Files in frontend/dist/ are served without a login, so the browser can load them. Never put a key or other secret in frontend code; keep it in the plugin's settings and use it from a backend route.

Add a page#

This adds a page to the Run Counter plugin from Build a plugin, listing the counts its route returns.

  1. Declare the page and its sidebar entry

    Change type to full-stack and add:

    YAMLrun-counter/manifest.yml (added)
    pages:
      - route: "run-counter"
        component: "RunCounterPage.js"
        label: "Run Counter"
    
    sidebar:
      - label: "Run Counter"
        route: "run-counter"
        icon: "M4 20V10m6 10V4m6 16v-7"
        order: 90

    The page opens at /plugins/<route>; use one word, such as the plugin id. A sidebar entry with the same route puts the page in the sidebar. Its icon is an SVG path for a 24 by 24 view box, not an icon name. Add require_role: "ADMIN" to the sidebar entry to show it to administrators only.

  2. Write the entry module

    JSrun-counter/frontend/src/index.js
    import { mount, unmount } from 'svelte';
    import RunCounterPage from './RunCounterPage.svelte';
    
    export { RunCounterPage as default };
    
    export function mountPlugin(target, props) {
      return mount(RunCounterPage, { target, props });
    }
    
    export function unmountPlugin(instance) {
      unmount(instance);
    }
  3. Write the page component

    Page components compile in Svelte 5 runes mode. This one uses the app's own Button through HostUi and the app's token classes for colour.

    SVELTErun-counter/frontend/src/RunCounterPage.svelte
    <script>
      import { onMount } from 'svelte';
      import HostUi from '../../../../sdk/HostUi.svelte';
    
      let counts = $state({});
      let loading = $state(true);
    
      async function load() {
        loading = true;
        const body = await window.__potionui.api.json('/api/plugins/run-counter/counts');
        counts = body?.data ?? {};
        loading = false;
      }
    
      onMount(load);
    </script>
    
    <div class="flex flex-col gap-3 p-4">
      <HostUi name="Button" props={{ variant: 'secondary', icon: 'refresh', loading, onclick: load }}>
        Refresh
      </HostUi>
      {#each Object.entries(counts) as [status, count]}
        <div class="flex justify-between rounded-lg border border-line bg-surface-1 px-3 py-2">
          <span class="text-fg">{status}</span>
          <span class="font-mono tabular-nums text-fg-muted">{count}</span>
        </div>
      {:else}
        <p class="text-fg-muted">No finished generations yet.</p>
      {/each}
    </div>

    content/plugins/sdk/HostUi.svelte mounts an app component by name, passes updated props through, and projects its children into the component.

  4. Build, scan and open it

    SHbuild one plugin
    cd content/plugins && npm install      # once
    cd ../.. && node scripts/build-plugins.mjs run-counter

    Then choose Scan for plugins in Administration, Plugins so the new manifest keys are read, and make sure the plugin is on.

    What you will see

    Run Counter in the sidebar. The page opens under the app's page header, showing the plugin's label, with your component below it.

What a page receives#

The app calls mountPlugin(target, props) with these props:

PropWhat it is
pluginId, routeThe page's address segment and its route.
apiA small client: get(path), post(path, data), put, delete and uploadFile(path, formData), each prefixed with /api/plugins/<first part of the page address>, plus fetchFromApp(path) for any app route. Keep the page route equal to the plugin id so the prefix matches your routes.
userThe signed-in user.
navigate(path), replaceUrl(path)Move within the app, or change the address without a new history entry.
hostComponentsThe same component registry as window.__potionui.components.
headerActionsAn empty element in the page header row, right of the title, for your own controls.
setHeaderTitleHidden(hidden), setHeaderHidden(hidden)Hide the header's title so headerActions owns the row, or hide the whole row for a page with its own header. Both reset when the page loads again; call them as setHeaderHidden?.(true).

Other components get their own props. A form field type receives name, config, value, onChange(name, value) and host; the Example Field Type plugin is the reference. A component in an extension slot receives context, hookName and pluginId. A tool tab receives one host prop, described below.

The window.__potionui host#

Every plugin script can reach the app through window.__potionui. Its version is 1 and changes only for breaking changes. Newer members may be missing on an older build, so feature-detect them: window.__potionui.layers?.overlayLayer.

MemberUse it to
componentsMount the app's components: components.<Name>.mount(el, props), update(instance, props), unmount(instance).
apiMake signed-in requests: api.fetch(path, init) returns a standard Response, api.json(path, init) the parsed body. Never read the token yourself. Calls time out after 30 seconds unless you pass timeout: 0.
confirm({ title, message, variant })Open the app's confirm dialog; resolves to a boolean.
notificationstoast(level, message) for a passing message, notify({...}) for a saved notification.
registerFieldComponent, registerRenderer(kind, key, entry), registriesRegister field types and renderers from code. Renderer kinds are history.artifact, workbench.file, model.view and chat.tool. Most plugins declare these in the manifest instead.
formReactionsThe same reaction engine core forms use.
chatprovideContext(key, provider), declareMode(modeId) and onToolApplied(toolName, handler): work with the assistant from your page.
layers, inputJoin the app's overlay stack; keep window shortcuts out of text fields.
generation.prepareRequest(input)Build the request a Generate tab would send, from a saved session.
imageEditorAdd tools, adjustments, image sources and actions to the image editor.
modelTypeslist(), get(id) and presentation(id) for model types, plugin types included.

Reuse the app's components#

A plugin page should look like the rest of the app. Use the host components rather than your own markup for the same thing:

  • Basics from the app's UI kit: Button, IconButton, CopyButton, Card, PageHeader, PageTitle, Badge, Kbd, Input, InputGroup, Spinner, PageContainer, EmptyState, LoadErrorState, SegmentedControl, Pagination, Switch, Alert, UserPicker, plus Tooltip and Icon. Button takes no title; wrap it in Tooltip for a hover hint.
  • Detail views: DetailLayout, DetailHeader, DetailBody, DetailSection, DetailFooter, DetailTabs, DetailField, KVGrid, KVItem.
  • List pages: LibraryPage gives the frame of History and Models (title with count, a rail of sections, search, sort and a primary action) from props alone. LibraryShell, LibraryFilterBar and the other library parts are available for a custom frame.
  • Dialogs: PluginModal has the same Cancel, Escape, backdrop and Confirm behaviour as every core dialog. Pass title, confirmLabel, onConfirm, onCancel, and mountBody(el) to place your content.
  • App views: DynamicForm renders a preset's form outside the Generate page; GenerationDetailsModal is the History details view; GenerationHistoryModal and UploadLibraryModal are media pickers, with multi-select through multiple: true. Also PromptModelField and MediaPreviewModal.

Snippet props cannot cross from your bundle into the app's, so pass children as a string or as a function (el) => cleanup that fills the element; HostUi does this for you. The props of the UI kit, detail and library components are a public contract: renaming or removing one is treated as an API change.

For colour, use the app's semantic token classes (bg-surface-1, text-fg-muted, border-line and so on), never fixed colours. The app's Tailwind build scans plugin frontend/src/ folders and content/plugins/sdk/, and a plugin's dist/ carries no CSS of its own, so rebuild the app frontend after using a class the app did not use before.

Field types, renderers, slots and widgets#

Manifest keyWhat the component does
field_typesA new form field type, usable in any preset's form by its type.
renderersShows a kind of item, keyed by key, for example a History artifact.
contributionsFills an extension slot such as admin.tabs, with a label, icon and order.
admin_tabsAdds a tab to the plugin's own page in Administration, Plugins, after Overview and Settings. Shown only while the plugin is enabled.
sidebar_widgetsA widget at the bottom of the sidebar, as System Monitor does. require_role and role_setting control who sees it.
tool_tabsA whole Generate tab owned by your tool.

The Example Field Type and Example Frontend Extensions plugins are the smallest working references for field types, renderers and slot contributions.

Tool tabs and the image editor#

A tool tab sits next to the Image editor and Video editor tabs, with no form, Workbench or deck: the tab area is your component.

YAMLmanifest.yml (tool tab)
tool_tabs:
  - id: stamp
    label: Stamp tool
    icon: brush
    accepts: [image]
    handles: []
    component: StampToolTab.js

The label appears in the plus menu after the two editors. accepts lists the media the tool opens (image, video, audio). The component gets one host prop: the tab's id, the media it was opened on (source), your saved state, whether it renders on a phone, and setters such as setState, setDirty, setTitle, setThumbnail and setActions for the phone top bar. Keep state small (settings and ids, never pixels): it is saved with the tab. A tab whose plugin is disabled later stays open and says the tool is not available.

To extend the image editor instead, register once when your frontend loads, through window.__potionui.imageEditor: registerTool (pointer handlers that edit the active layer and commit with host.commitPixels, which makes the edit undoable), registerAdjustment, registerImageSource and registerAction. Each returns a function that unregisters it. The editor saves its result as a new Library upload, so a plugin never writes files itself.

Overlays, shortcuts and the page header#

  • Overlays. Core dialogs, popovers and menus share one stack: whichever opened last is on top. Do not set your own z-index. Use PluginModal for dialogs. For a custom overlay, put use:window.__potionui.layers.overlayLayer on the positioned element, or from plain DOM code call layers.acquire('overlay') and later layers.release('overlay', value).
  • Shortcuts. A key listener on the window fires while the user types in a field unless it checks first: return early when window.__potionui.input.isTypingInField(event) is true. For paste and other non-key events, use input.isEditableTarget(target).
  • The page header. Put page-level controls in headerActions rather than a second header of your own.

Build and commit#

All plugin frontends share one toolchain, declared in content/plugins/package.json (esbuild with the Svelte plugin, on the same Svelte major version as the app), and one script, scripts/build-plugins.mjs.

SHbuild plugin frontends
# once, from the repository root
cd content/plugins && npm install && cd ../..

# every plugin (npm run build:plugins in frontend/ does the same)
node scripts/build-plugins.mjs

# one plugin
node scripts/build-plugins.mjs run-counter
  • Release builds are the default: minified, no source maps, and identical inputs give identical output. Commit frontend/dist/ with every change to the frontend source.
  • Debug builds (--debug, or PLUGIN_BUILD=debug) are unminified with source maps, for stepping through your code in the browser. Never commit one.
  • Both keep the licence notices of bundled code at the end of each file.
  • @xyflow/svelte is part of the toolchain for graph canvases; copy the styles you need into your component, because the build writes only .js.

The build fails for a plugin whose manifest names a component with no matching .svelte file, and for a page index.js that imports no ./<Component>.svelte; the first one it imports names the output file.

Plugin API ↗Frontend host source ↗