PotionUI Docs v0.3.0

Build a plugin

A plugin is a folder with a manifest.yml that adds something to PotionUI without changing its core: a provider, a backend, a pipe, a page, a chat tool. This guide builds a small working plugin, then covers the rules every plugin follows and how to test and ship one.

GuideWritten for v0.3.0
On this page
Note

Plugin code runs inside the PotionUI server process, with the same rights as the application: it can read the database, the files PotionUI can read and every setting. Install only plugins whose code you have read or whose author you trust.

What a plugin can add#

Almost every part of PotionUI is open to plugins. Each kind of contribution is a section of the manifest; the Plugin API reference shows the manifest entry for each, for example the plugin category and the settings form.

To addDeclareWhere it shows
Model marketplace (a provider)A provider.register hookModel downloads and metadata; see Models, providers and cloud models
An engine or backendA backend.register hook; hosted models through register_cloud_providerAdministration, Backends
A generation step (a pipe)pipes:Any preset's pipeline; see Write a pipe
Presets, modes, form fields on existing modespresets:, preset_modes:, preset_extensions:The Preset and Mode menus
A form field typefield_types:Any preset form
Chat modes and toolschat_modes:, tools:, resources:The PotionAI assistant
An LLM provider typellm_providers:Administration, LLM / Assistant
Recipes and recipe step kindsrecipes:, recipe_steps:Setup and Administration, Recipes
Automation nodes and templatesautomation_nodes:, automation_templates:Automations
Samplers and sigma schedulessamplers:, schedules:Sampler and schedule fields of native presets
Media tools, photo filters and video effectsmedia_tools:, filters:, filter_ops:, effects:The editors and media tools
Pages, sidebar entries, admin tabs, tool tabs, quick actions, sidebar widgetspages:, sidebar:, admin_tabs:, tool_tabs:, quick_actions:, sidebar_widgets:The app's frame; see Plugin frontends
HTTP routesapi:Under /api/plugins/<plugin id>/
Reactions to eventshooks:Runs when the event happens; the hook catalog lists them
Settings and setup checkssettings:, setup:The plugin's page in Administration, Plugins
Documentation pagesdocs:Administration, Documentation

Login providers, plan limit kinds, model classifiers and types, prompt importers, Auto-organize conditions and actions, and phrasebook batch tools are open the same way; the Plugin API reference covers each.

The plugin folder#

A plugin lives in its own folder under one of two roots, each scanned the same way:

  • content/plugins/local/<folder>/ for your own plugins. Ignored by git. When a plugin id exists in both roots, the local copy wins.
  • content/plugins/marketplace/<folder>/ for the plugins PotionUI ships.

The only required file is manifest.yml. Python modules sit wherever the manifest points; most plugins keep them under backend/. Frontend code lives in frontend/src/ and its build in frontend/dist/. Tests go in tests/.

Your first plugin#

The example counts finished generations by status since the server started and returns the counts from a route. It uses a hook, a route and a setting, the three pieces most plugins have.

  1. Write the manifest

    Create content/plugins/local/run-counter/manifest.yml. id, name, version, description, author and type are required; any key the schema does not know is rejected.

    YAMLrun-counter/manifest.yml
    id: "run-counter"
    name: "Run Counter"
    version: "0.1.0"
    description: "Counts finished generations by status since the server started"
    author: "Your name"
    type: "backend-only"
    category: "monitoring"
    
    api:
      module: "backend/api.py"
    
    hooks:
      backend:
        - hook: "generation.after_complete"
          handler: "backend.hooks.on_after_complete"
    
    settings:
      - name: "count_cancelled"
        type: "boolean"
        label: "Count cancelled runs"
        description: "Include generations that were cancelled"
        default: false

    type is frontend-only, backend-only or full-stack. category decides the group the plugin appears under: backends, sources, steps, tools, security, monitoring, developer or other (the default). A handler is written module.path.function, relative to the plugin folder.

  2. Write the hook handler

    Keep shared state in its own module so the hook and the route import the same object.

    PYrun-counter/backend/store.py
    from collections import Counter
    
    counts: Counter = Counter()
    PYrun-counter/backend/hooks.py
    from src.plugin_api import HookContext, plugin_settings
    
    from .store import counts
    
    PLUGIN_ID = "run-counter"
    
    
    def on_after_complete(context: HookContext) -> HookContext:
        status = context.data.get("status")
        if status == "cancelled" and not plugin_settings(PLUGIN_ID)["count_cancelled"]:
            return context
        counts[status] += 1
        return context

    Hook handlers are synchronous: an async def handler is refused when it is registered. Always return the context you were given. generation.after_complete fires when a generation ends as completed, failed or cancelled, with generation_id, status, duration, preset_id and user_id in context.data.

  3. Write the route

    PYrun-counter/backend/api.py
    from fastapi import APIRouter, Depends
    
    from src.plugin_api import User, get_current_active_user
    
    from .store import counts
    
    router = APIRouter(prefix="/api/plugins/run-counter", tags=["Run Counter"])
    
    
    @router.get("/counts")
    async def get_counts(user: User = Depends(get_current_active_user)):
        return {"success": True, "data": dict(counts)}

    The module named by api.module must expose router (and may expose ws_router for WebSockets). Keep every route under /api/plugins/<plugin id>; PotionUI logs a warning for a router that is not. To limit a route to administrators, check user.account_type != AccountType.ADMIN and answer 403.

  4. Scan and enable it

    Open Administration, Plugins and choose Scan for plugins. Select Run Counter and switch it on.

    Administration, Plugins with the ComfyUI Backend plugin open: its enable switch, Overview, Settings, Import workflow and Imported presets tabs, and its registered hooks. Plugin management
    A plugin open in Administration, Plugins, with its enable switch, its tabs and the hooks it registers.
    What you will see

    Run Counter under Monitoring, with an Overview tab and a Settings tab holding Count cancelled runs. Its registered hook is listed under Technical details. A manifest that does not validate shows Invalid manifest with the reason and cannot be enabled.

  5. Try it

    Generate something, then ask the route, logged in as any user:

    GET/api/plugins/run-counter/counts
    curl http://localhost:26730/api/plugins/run-counter/counts \
      -H "Authorization: Bearer $TOKEN"
    200response
    {"success": true, "data": {"completed": 1}}

Import only from src.plugin_api#

A plugin's Python imports from src.plugin_api and nothing else under src/. Everything else is internal: it is renamed and moved without notice, and a plugin that imports it fails to load in someone else's installation. A name exported from src.plugin_api is not removed or changed in meaning without a deprecation first. If something you need is missing, that is a gap in the API: ask for it to be exported rather than importing around it.

Names are grouped in modules (src.plugin_api.pipes, .hooks, .providers, .backends, .chat, .presets, .storage and more), and every name can also be imported from src.plugin_api itself. Two rules about timing:

  • Import db inside the function that uses it, never at the top of a module, so your code always reads the current database handle.
  • Call get_container() inside the function that needs the app's managers, never at import time: the container does not exist yet while your module loads.

Lifecycle: boot, ready, enable, disable#

Four hooks follow a plugin's own life. Declare them like any other backend hook.

HookFires
plugin.lifecycle.bootOnce per process for every enabled plugin: at startup, and right after an admin enables it.
plugin.lifecycle.readyOnce per process, once the event loop runs. The first point where run_on_app_loop() works, for background work.
plugin.lifecycle.enableOnly when an admin switches a plugin from disabled to enabled, never at startup.
plugin.lifecycle.disableOnce whenever an enabled plugin is torn down: disabled, uninstalled, reloaded, or its folder changed or gone.

Put per-process setup, such as creating your tables, in boot and make it safe to run again. enable does not fire after a restart, so setup done only there stops happening after the first restart. boot and ready go only to your own handler; enable and disable go to every enabled plugin, so check context.get("plugin_id"). A handler that raises is logged and skipped and cannot block startup. Cancel background work started in ready from disable.

Settings#

Each settings: entry has a name, a type (string, number, boolean or select with options) and a label, and may add description, required, default, min and max. is_secret: true stores the value encrypted, masks it in every response and shows a password field. An entry of type info shows a notice instead of an input, with an optional link.

Read your settings with plugin_settings("<plugin id>"): one dictionary with each stored value, credentials decrypted, or the manifest default. Values come back typed, and a number outside min or max is clamped. Credentials belong in your own settings; never read another plugin's.

If the plugin needs Python packages or programs, list them under dependencies: (python: and binaries:). Enabling fails with Missing dependencies while one cannot be imported or found. When admins must finish something after enabling, setup: checks show the plugin as Setup needed with the next step.

Presets, modes and recipes from a plugin#

  • presets: [{path: "presets"}] ships whole presets, scanned like the core tree while the plugin is enabled. Presets that only work with your plugin belong here.
  • preset_modes: adds modes to a preset you do not own, by its id. preset_extensions: adds fields, pipes and prompt resources to existing modes. An extension is all or nothing; a conflict rejects it and the preset loads unchanged. A target preset that is not installed is skipped without an error.
  • recipes: ships recipes; recipe_steps: adds step kinds.

Preview a preset with your plugin applied: python scripts/preset_render.py <preset id> <mode> --plugin-dir content/plugins/local/<folder>.

Test a plugin#

Put tests in the plugin's own tests/ folder and run them from the repository root. Test your handlers and pipes as plain Python: build the input, call the function, check the result.

PYrun-counter/tests/test_hooks.py
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from backend import hooks  # noqa: E402
from src.plugin_api import HookContext  # noqa: E402


def finished(status):
    return HookContext(hook_name="generation.after_complete", plugin_id="system",
                       data={"generation_id": "g1", "status": status})


def test_cancelled_runs_are_skipped_by_default(monkeypatch):
    monkeypatch.setattr(hooks, "plugin_settings", lambda plugin_id: {"count_cancelled": False})
    hooks.counts.clear()
    hooks.on_after_complete(finished("cancelled"))
    hooks.on_after_complete(finished("completed"))
    assert dict(hooks.counts) == {"completed": 1}
SHrun the tests
python -m pytest content/plugins/local/run-counter/tests -q --no-cov

Run each plugin's tests in its own pytest run: plugins that ship a top-level backend package would otherwise claim the same module name. The shipped plugins' suites run one process per plugin with python tests/plugins/run_suites.py -q --no-cov. For hosted-model providers, src.plugin_api.cloud_testing provides a fake provider and a contract checker. For tests that need a database, scratch_database and use_database from src.plugin_api give your test a new database in a file you name, with the core tables in it, and refuse the application's own database file. There is no other general plugin test kit in 0.3.0.

Ship it#

  1. Build the frontend, if any

    Rebuild frontend/dist/ in release mode and include it; see Plugin frontends.

  2. Copy the folder

    On the other instance, place the folder under content/plugins/local/, then choose Scan for plugins in Administration, Plugins and switch it on. Plugins are off until an admin enables them. default_enabled: true in the manifest enables a plugin the first time an instance finds it; after that, the admin's choice stands.

  3. Say what it needs

    List required packages under dependencies:, the steps admins must take under setup:, and add a README through docs: so it appears in Administration, Documentation.

Plugins that ship with PotionUI#

These plugins are in content/plugins/marketplace/. Each is switched on in Administration, Plugins, and each is also a working example to read.

PluginWhat it adds
A1111 Metadata ExportExports generations as PNGs with A1111 and Forge style parameters, readable by A1111, Forge, CivitAI and PNG info tools.
Black Forest LabsA cloud backend for the FLUX models hosted by Black Forest Labs, its model catalog and an image preset.
CivitAI ProviderModel metadata, preview images and download links from CivitAI. An optional CivitAI API Key allows signed-in requests.
ComfyUI BackendThe comfyui engine and pipe, five ComfyUI presets, the Detect ComfyUI recipe, the workflow import wizard and a Clear VRAM quick action. See ComfyUI presets and workflow import.
DeepSeekA DeepSeek type in Administration, LLM / Assistant, for the assistant and every LLM feature.
Example Field TypeA one-to-five-star form field: the reference for a plugin field type.
Example Frontend ExtensionsA sample History artifact renderer and an admin tab: the reference for renderers and extension slots.
Google GeminiA cloud backend for Google's hosted image and video models through the Gemini API, with image and video presets.
HuggingFace ProviderSearches public models and resolves repository files into downloads. Enabled by default. Gated or private files need a HuggingFace Access Token with access to the repository; accept the model's terms on Hugging Face first.
Image Modal ViewerOpens generated images full screen with zoom and pan.
Model BrowserBrowse and download models from CivitAI, Hugging Face and OpenModelDB, with per-group permissions and monthly download limits.
NVIDIA RTX UpscaleUpscale, denoise and deblur images and video with NVIDIA RTX Video Super Resolution, as a pipe and the RTX Upscale preset. Needs an NVIDIA RTX GPU (Turing or newer), a Linux driver 570.190 or newer and the nvidia-vfx package; the preset's requirements report it until it is installed.
OpenID Connect LoginSign-in through any OpenID Connect issuer, such as Authentik, Keycloak, Zitadel, Auth0 or Entra ID.
OllamaFrees GPU memory held by an Ollama daemon: the admin-only Clear Ollama VRAM quick action and an Unload Ollama Model(s) automation action. Set Ollama Host URL in its settings.
OpenAIA cloud backend for OpenAI's GPT Image models, its model catalog and an image preset.
OpenRouterA cloud backend for hosted image and video models through OpenRouter, with image and video presets.
RunPod ProviderProvisions a RunPod GPU Pod running the Remote Native worker, from Administration, Remote Compute.
System MonitorLive GPU, RAM and CPU use in the sidebar. Its Visible to setting chooses admins only or everyone.

Plugin API ↗Bundled plugin sources ↗