PotionUI Docs v0.3.0

Media tools

A media tool is one declaration of something that edits media: trim a clip, resize an image, loop a video. Core ships nineteen; a plugin adds its own. The Tools menu on the Library and History pages, a media field's toolbar, presets, PotionAI chat and automation all read the same catalog, so a plugin tool shows up in every one of them as soon as the plugin is enabled and disappears when it is disabled. Tools change shape, time, sound or pixels (trim, crop, resize, rotate, flip, speed, split, frame, concat, fit canvas, crop to subject, colour key, fix colours, film grain, mute, volume, replace audio, paint layer) and run deterministically with no model. Looks on still images (grain, VHS, grades) are photo filters, not tools: see Contributing photo filters and filter ops.

On this page

Core tools#

idacceptsproducesparams
trimvideo, audiosamestart, end (seconds)
cropimage, videosamex, y, width, height (px)
resizeimage, videosamewidth, height (one side keeps the aspect ratio), quality high / balanced / small
rotateimage, videosamedegrees 90 / 180 / 270, clockwise
flipimage, videosameaxis horizontal / vertical
speedvideo, audiosamespeed 0.25 to 4, keep_pitch
fit_canvasimagesamewidth, height, scale_percent, anchor, fill
color_keyimagesamekey_mode, key_color, tolerance, softness, despill, feather
crop_subjectimage with transparencysamemargin, alpha_threshold
framevideoimagetime (seconds)
splitaudio, videosame, manymode every / at, part_seconds, at (seconds)
concatvideo, 2 to 8 selectedvideo, oneoverlap, overlap_frames, fit, keep_audio
cut_findervideovideo, manysensitivity 0 to 100, min_shot_seconds
mutevideo with soundsamenone
volumevideo, audio with soundsameunit percent / db, percent 0 to 400, db -60 to 20, fade_in, fade_out (seconds)
replace_audiovideo (editor only)sameaudio (media), start (seconds into the track), loop
paint_layerimage (editor only)samelayer (media, a transparent PNG), opacity (0 to 1, default 1)
place_patchimage (editor only)samepatch (media, an RGBA PNG made by an editor run), x, y, width, height (0 to 1, the patch's place as fractions of the picture), opacity (0 to 1, default 1), canvas_width, canvas_height, canvas_x, canvas_y (pixels, grow the picture onto a larger transparent canvas first), replace (checkbox, default off: the patch is the whole picture at its own size, as an upscale makes it)
replace_backgroundimage (editor only)samekind (color default, picture, transparent), color (#rrggbb, default #ffffff, for kind: color), picture (media, cover-fitted to the canvas, for kind: picture), matte (media, a grayscale mask, white = the background; its soft values are used as they are), opacity (0 to 1, how much of the replacement shows, default 1). transparent makes an RGBA picture with alpha multiplied by 1 minus the matte

Core ids never contain a dot. Video output keeps even dimensions and the sound; images keep their transparency (a JPEG that gains an alpha channel is saved as PNG).

mute, volume and replace_audio copy the video stream when they run alone; next to a picture or timing edit they share that edit's single encode. replace_audio keeps the video's length: the track starts start seconds in and, with loop, repeats until the picture ends. split with mode: at cuts at one time point into two items; video parts are re-encoded so the cut lands on the exact frame. Tools whose scopes are only editor (replace_audio, paint_layer, place_patch, replace_background) are left out of the Library and History menus because they need a file picked in the editor.

A media parameter names another file: {"item_id": "..."} (a Library item or a helper upload) or {"generation_file_id": "..."}; a bare string is read as an item_id. The run checks that the caller owns it and that its kind is one of the parameter's accepts, then hands the tool a staged ToolMedia in its place.

The Effects menu (group: effects) lists effects: tools defined by an effect.yml folder, with a live preview shader and ffmpeg, torch or numpy renders. Film grain (film_grain) and Fix colours (fix_colors) are the core ones. Their contract, the catalog effect block and the shader and analysis endpoints are in Video Effects.

The editor API#

The Image and Video editor tabs keep a stack of steps, {tool, params, hidden?}, and talk to these endpoints. Every one needs a signed-in user, answers 404 for a source, helper file, run or preview owned by someone else, and never puts a file path in a response.

Method and pathBodyAnswer
POST /api/media-tools/runs{steps, inputs: [ref], output: {mode, target_item_id?}}202 {run_id}
GET /api/media-tools/runs{runs: [run]}, my runs still held (queued, running, or finished in the last 10 minutes)
GET /api/media-tools/runs/{id}run
DELETE /api/media-tools/runs/{id}run, cancelled
POST /api/media-tools/preview/frame{input: ref, steps, time_seconds?, max_side? 1280, format? webp / png}the image; header X-Preview-Cache: hit / miss
POST /api/media-tools/preview/clip{input: ref, steps, start_seconds? 0, duration_seconds? 3, height? 480}202 {run_id, preview}
GET /api/media-tools/previews/{id}the preview clip (cookie or bearer, so a <video> can play it)
POST /api/media-tools/artifactsmultipart file{id, media_type, mime_type, url, width, height, duration_seconds, fps, size}
GET /api/media-tools/effects/{tool_id}/shaderthe effect's preview shader as text/plain, with an ETag
POST /api/media-tools/effects/analysis{input: ref, steps, step_index}{values, cached}, an effect's measured values
  • A run is {run_id, kind: run / preview, status, progress 0..1, label, items, replaced, preview, error, summary}. Poll it by id for progress; a reload reattaches through the stored id or the run list.
  • Saving a stack runs it as one background run. Hidden steps are skipped and never validated; up to 64 visible steps run in order. mode: new makes Library items, mode: update with target_item_id replaces the file of the copy a first save made (one input, no split, same kind), and mode: replace replaces a Library source; a History source or a helper upload is refused with replace_not_allowed. A stack with split saves its parts as separate items named "part 1 of 2".
  • Frame preview renders one frame of a video, or the image, through the stack with each tool's frame path, the same code the full render uses: film_grain seeds each frame's grain by a hash of its frame number, so the paused frame shows the grain the render will put there, and fix_colors measures the trimmed range of the source. time_seconds is on the source clip; trim and speed steps map it to the frame the render would show. Sound and timing steps leave the picture alone. A tool with no frame path (frame, concat, most plugin tools) is refused with its step_index. Answers are cached per user, source, time, stack and size.
  • Clip preview cuts duration_seconds from start_seconds (source time, clamped inside the trim), runs the stack on that piece and scales it to height as an MP4. A split step is left out. When the same request is cached the answer is {run_id: null, preview} at once; otherwise poll the run and read preview when it completes, or cancel it. Fades and the replacement track's offset count from the start of the piece, not of the whole clip.
  • Helper uploads (derived_artifact) hold what an editor makes or receives: a paint layer, a mask, a dropped file, a replacement track. Use the returned id as a run input or in a media parameter. They stay out of the Library but count toward the plan's storage and per-file limits. They must be an image, audio or video file of at most 512 MB. The announced size is checked before the body is read and the bytes are checked again after. The same rules apply to POST /api/media/upload with purpose=derived_artifact. The Image editor stores every paint layer as its own helper upload and its own paint step ({layer, url, layers: 1, name}, with the step's layer.opacity and hidden carrying the fade and the eye), so a saved edit keeps each layer; a layer that was added but not painted yet has an empty layer and url and sends no step; a paint step without name is an older one-PNG paint and opens as a single layer. Nothing sweeps these helper uploads, so a saved edit keeps every layer file it names.

From chat, MCP and automation#

PotionAI's run_media_tool chat tool, the same tool over MCP and the action.media_tool automation node run the catalog tools that have a Python implementation (python:). Component-only tools have no run API and are not offered. The chat tool builds its description and tool enum from the live catalog each turn, so a plugin's tools appear in the model's schema while the plugin is enabled, with each parameter written as name type[min..max]unit =default. Keep parameter names short and give a min, max and default where they make sense, because the model reads them verbatim. Every run goes through the same service as the API: the same ownership checks, parameter validation and Library quota. mode: replace is the one call that waits for the user's approval in chat. See Chat Modes and Automation Nodes.

From presets#

A preset step runs any registered tool, a plugin's included, through the media_tool pipe. tool is the catalog id, params are the tool's parameters (the same names and the same validation as the API), and skip_unfit: true passes media the tool cannot work on, such as an image without transparency for crop_subject, through unchanged instead of failing.

yaml
- name: "media_tool"
  id: "crop_subject"
  input:
    - ["image", "matting", "image"]
  configuration:
    display_title: "Cropping subject"
    tool: "crop_subject"
    skip_unfit: true
    params:
      margin: "{{ form.crop_margin }}"

Images, videos and audio files go in and come out as arrays on image, video and audio; a tool that makes a different kind (frame turns a video into an image) fills the output of that kind. A tool that joins (concat) takes every input of one kind and makes one output. Image tools run in memory without writing the picture to disk. The pipe reads the plugin catalog from the MEDIA_TOOLS service the generation engine injects, so a plugin's tool runs while the plugin is enabled; a Remote Native worker has no such service and runs the core tools only. See the Pipes Reference.

Declaring a tool#

A plugin declares tools in manifest.yml under media_tools. Disabling the plugin removes them from every surface.

yaml
media_tools:
  - id: boomerang.loop              # must be "<plugin-id>.<tool>"
    label: Boomerang
    icon: repeat                    # optional, an Icon name; default "extension"
    description: Play the clip forward, then backward   # optional
    accepts: [video]                # image | video | audio, at least one
    produces: same                  # same | image | video | audio
    cardinality: one_to_one         # one_to_one | one_to_many | many_to_one
    params:
      - { name: style, type: select, options: [forward, pingpong], default: pingpong }
      - { name: repeats, type: integer, min: 1, max: 8, default: 2 }
    requires: { has_audio: false }  # optional: has_audio, has_alpha, min_duration (seconds)
    selection: { min: 1, max: 4 }   # optional: how many items the tool takes
    scopes: [library, history]      # optional: library | history | field | editor; default library, history, field
    preview: false                  # true needs python; the dialog then shows a before/after pane
    python: tools/loop.py:LoopTool  # optional: a path inside the plugin dir, then :ClassName
    component: loop-preview         # optional: a plugin frontend asset

At least one of python and component is required. The id must start with your plugin id and a dot, and a plugin cannot take an id another plugin or core already registered; an entry that breaks either rule keeps the plugin from enabling.

A tool that needs sound (requires: { has_audio: true }) is greyed out in the Tools menu on a Library video recorded as silent. The Library records whether a video has sound when it is uploaded or copied from History, by probing the file, and a sound file always counts as having sound. For a media tool's result it records the has_audio of the ToolMedia the tool returns: the core tools probe their output, and a plugin tool's value is taken as the tool reports it. The value stays unknown on a History file, on an item stored before PotionUI recorded sound, on an item saved from Inspirations, on a file uploaded again with the same bytes as an item of unknown sound, and when the probe fails. The menu then offers the tool, and the run checks requires on each input and refuses it with unsupported_media. In the Library menu, Mute and Replace audio sit under the Audio entry, which opens the video editor on Volume; that entry stays enabled on a silent clip, since Replace audio needs no sound.

params are form fields. type is integer, float, select, checkbox, color, string or anchor, with these keys: name, label, default, min, max, step, unit, options (a list of values or of {label, value}), allow_transparent (a color that may also be transparent), when and description. when uses the preset form's when: grammar ({ field: key_mode, equals: color }), and a parameter whose condition is false is dropped from the validated params. A parameter without a default is required; default: null makes it optional. The dialog builds its controls from this list: a select with up to four options becomes a segmented control, a number with min and max a slider, a checkbox a switch.

The Python half#

python
from src.plugin_api.media_tools import FilterFragment, InvalidToolParams, MediaTool, ToolContext, ToolMedia


class LoopTool(MediaTool):
    def run(self, inputs: list[ToolMedia], params: dict, ctx: ToolContext) -> list[ToolMedia]:
        source = inputs[0]
        out = ctx.new_path(".mp4")
        ctx.ffmpeg(["-i", str(source.path), "-filter_complex", "...", str(out)], duration=source.duration)
        return [ctx.probe(out)]

run(inputs, params, ctx) receives the already validated params and returns the produced files, which must live under ctx.scratch_dir: the host publishes them to the Library and deletes the scratch directory afterwards, whatever happens.

  • ToolMedia is a frozen dataclass: path, kind (image | video | audio), width, height, duration, fps, has_audio, has_alpha. Everything except path and kind may be None.
  • ToolContext gives you scratch_dir, user_id (the user the run belongs to, None outside a Library or History run), new_path(suffix) for a fresh output path, progress(fraction, label=""), is_cancelled(), probe(path) and ffmpeg(args, duration=None). ffmpeg is the one cancellable runner: it adds -y, parses -progress into ctx.progress when you pass the expected output duration, kills the process when the run is cancelled and raises on a failure without ever exposing stderr or server paths. Use it instead of subprocess so cancel works.
  • ctx.summarize(message, links=()) lets the last step of a run finish with no media: return [] after calling it and the run completes with nothing added to the Library, showing message (and the first (label, href) link: a path inside the app such as /models, with no backslash, whitespace or control character) in place of the Library notice. The run's summary is {message, links: [{label, href}]}.
  • ToolFailed(message) ends the run as failed with message shown to the user, and ToolCancelled() ends it as cancelled; raise it when ctx.is_cancelled() turns true during a long loop.
  • check_params(params) is an optional override for rules that span parameters (end must be greater than start); raise InvalidToolParams(field, message).
  • validate_params(spec, params) is what the API, presets and chat all call before running; it applies defaults, coerces, checks ranges and options, and raises InvalidToolParams.

Chains and the fast paths

A request is a list of steps, and a single tool is a chain of one. The runner fuses neighbouring steps that offer a fast path so the media is decoded and encoded once:

python
class Mirror(MediaTool):
    def video_filter(self, media: ToolMedia, params: dict) -> FilterFragment | None:
        return FilterFragment(vf=["hflip"])

    def image(self, image, params):
        return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  • video_filter(media, params) returns a FilterFragment: vf and af are lists of ffmpeg filters, start and end a time window, drop_audio removes the sound. A fragment that changes the picture size, the length or the quality reports it in the optional width, height, duration and crf so the next step is validated against the right media. Consecutive fragments merge into one ffmpeg pass; a leading start/end becomes an input seek. It is also asked about audio files, where only af and the window apply. Return None to say "no fast path for this input".
  • image(image, params) receives and returns a PIL image. Consecutive image steps run in memory and the result is saved once, with the source's EXIF orientation already applied.
  • A step with neither fast path runs run() on the previous step's output file.

Component-only tools#

An entry with a component and no python is a tool the browser runs itself, the case the old history_tools key covered. It gets no run endpoint: the catalog lists it so the Tools menu can offer it for the selected media, and the host mounts the component in a modal.

yaml
media_tools:
  - id: my-plugin.contact-sheet
    label: Contact sheet
    icon: grid
    accepts: [image]
    selection: { min: 2, max: 12 }
    scopes: [history]
    component: ContactSheetModal.svelte

The catalog serves its component as plugin:<plugin-id>:<asset>, the same reference string a phrasebook_ops[].component resolves to. The component is mounted with the props { items, generationIds, generations, onClose(), onDone() }: items is the selection as { id, kind, url, filename, width, height }, generationIds and generations are filled on the History page, and onDone() clears the selection once the tool finished. If it needs the backend it calls its own plugin API route.

Shipping effects#

An effect is a media tool defined by one folder (see Video effects). Declare one or more roots and put <name>/effect.yml folders in them:

yaml
effects:
  - path: effects
  • Each effect registers as <plugin-id>.<id> under the plugin's source, in the Video editor's Effects panel, the Library Effects menu, presets, chat, MCP and automation. Nothing in the UI names the plugin.
  • Python renders and analyses (render.py:fn) may import only numpy, torch and src.plugin_api.*.
  • A path outside the plugin folder, a missing folder or any broken effect.yml fails the enable with the error, and nothing of the plugin registers. Disabling the plugin removes its effects; the open editor's catalog refreshes.
  • python scripts/effect_parity.py <plugin folder> --golden writes the parity goldens to <plugin>/tests/effects/golden/, and the same command without --golden checks every render against them.
  • tests/e2e/effect_plugins/e2e-effects/ is a complete example (an Invert effect with a shader and a numpy render).

The API#

Successful JSON responses use the usual {success, data} envelope. A refusal answers with detail: {success: false, error, message, ...}; the codes are listed per route.

  • GET /api/media-tools?kind=&scope= returns {tools: [...]}: every tool for the kind and scope, with the declaration (id, label, icon, accepts, produces, cardinality, params, requires, selection, scopes, editor, preview, component, source) plus runnable (true when the tool has a Python implementation, false for a component-only tool that has no run API) and last_params, the values this user ran the tool with last (or null). source is core or the plugin id. A param's max is enforced before a run starts, so a value above it is a 400.
  • POST /api/media-tools/runs takes {steps: [{tool, params, hidden?}], inputs: [{item_id} | {generation_file_id}], output: {mode: "new" | "replace" | "update", target_item_id?}} and answers 202 {run_id}. A generation file is read straight from storage and the result is always a new Library item; replace keeps the row, its tags and its collections, and is only allowed for one Library item, tools that return one file per input, and a result of the same kind. When the result is in another format than the item's name says, the name takes the new file's extension: Color key turns photo.jpg into a PNG named photo.png, a video tool turns clip.avi into clip.mp4, and a name an earlier replace left wrong is mended the same way. .jpg and .jpeg, or a change of case, are one format and leave the name as it is, and so do a name without a media extension and a result without one. update, the save of an editor stack into the copy a first save made (see The editor API), renames that copy by the same rule. A run takes 1 to 64 visible steps (the steps marked hidden are skipped and not counted) and 1 to 50 inputs. A 400 before anything runs carries one of unknown_tool, unsupported_media, invalid_params (with field and step_index), invalid_selection or replace_not_allowed; an item that is missing or not the caller's answers 404 not_found. A user may have 8 runs waiting at once (429 too_many_queued) and nothing starts while the server shuts down (503 shutting_down). The same upload quota the editor used applies (403 limit_exceeded), and a refusal leaves no file behind.
  • Results look like normal uploads: each carries its content hash, images get their thumbnails before the run completes, and a video's thumbnails are rendered right after (the Library card fills in a moment later). A run item lists thumbnail_small, thumbnail_medium and thumbnail_large URLs for the sizes that exist. replace swaps the thumbnails together with the file and deletes the old ones. If another run replaced the same item first, the later run fails with conflict and publishes nothing. A run that would create more than 500 files fails with too_many_outputs before anything is published.
  • GET /api/media-tools/runs/{run_id} returns {run_id, status, progress, label, items, replaced, error, summary}. status is queued, running, completed, failed or cancelled; items are the resulting Library items; a failed run carries error: {code, message} (a tool's requires check ends the run with unsupported_media). An unknown run id, or another user's, is a 404.
  • DELETE /api/media-tools/runs/{run_id} cancels: the encoder is killed and nothing is published.
  • POST /api/media-tools/preview takes {tool, params, input, time_seconds?} for a tool with preview: true and returns image/webp with a long side of at most 512. Pixel params (unit: px) are scaled down together when the largest exceeds 512, so a huge canvas renders as a small one. For a video, time_seconds must be finite, not negative and not past the end, otherwise 400 invalid_params on time_seconds. Only two previews render at once; one that cannot get a slot within a few seconds answers 429 preview_busy.

Runs are in-process: at most two execute at once, the rest wait their turn, and a finished run is kept for ten minutes. A user only ever sees, polls and cancels their own runs. After a single-step run completes, its parameters are stored as that user's last_params for the tool.