Running generations from a plugin
src.plugin_api.generation is the supported way to start, follow and read generations from
outside the Generate page. Each function takes the acting user and enforces the same rules the
HTTP API enforces for that user: anything that is not theirs is reported as not found rather than
forbidden (administrators may reach anything), and a content-restricted user only sees what the
history API would show them.
| Function | Does |
|---|---|
await submit_generation(user, request) | Same path as POST /api/generations/start: routing, form binding, cloud and content policy. Returns {generation_id, status, queue_position} and raises what the route turns into HTTP errors. With request.idempotency_key set, submitting the same key again returns the first submission instead of starting another (see below). The preset must be one the user is offered: installed and assigned to them, directly or through one of their groups, as GET /api/presets lists them and as the assistant's tools check (administrators may use any preset). Any other preset id, unknown ones included, raises PermissionError with the same message, so the answer does not tell which presets exist. This is checked first, before an idempotency key is looked up: a retry after the preset was unassigned is refused too |
await preview_memory(user, request) | Same path as POST /api/generations/memory-preview: binds the form and picks the backend as a submit would, then returns {estimate, coverage, device, budget, backend} without queueing anything, running a hook or loading a model. A preset the user is not offered raises the same PermissionError as submit_generation. Otherwise it raises what the route turns into HTTP errors: ValueError for an unknown preset, FormBindingError (a ValueError) for a form that does not bind, FormNotFoundException for an unknown form_name, NoBackendForEngineError or NoEligibleBackendError (both RuntimeError) when no backend can run it |
await cancel_generation(user, generation_id) | Cancels one generation; returns whether anything was cancelled |
generation_state(user, generation_id) | The live status record, or the stored row once the process no longer tracks it, scoped as GET /api/generations/{id}/status scopes it: for anyone but an administrator, a failure's message, error_message and error_user_message are the generic user copy for its error_code, with error_contact_admin set |
generation_record(user, generation_id) | The stored row, as generation_state returns it once the generation has left the queue, even while the live record still exists; None while the generation is not stored yet. Its failure text is scoped as GET /api/generations/history/{id} scopes it: the generic user copy for anyone but an administrator. Never carries the raw detail of a failure |
generation_failure(user, generation_id) | The failure of a failed generation with its raw detail, as GET /api/generations/{id}/failure answers it, or None when the generation is unknown or did not fail. Administrators only: anyone else, the generation's owner included, gets PermissionError |
generation_active() | Whether the application's generation queue holds a generation, pending or running, of any user on any backend: a plugin waits for False before a heavy background job. It says nothing about whose generations they are |
list_generation_files(user, generation_id, final_only=True) | The generation's files in canonical order, each with its index in the unfiltered list (the file_index of a <field>__origin link). final_only leaves out intermediate and derived files |
resolve_media_ref(user, ref) | Turns {"kind": "history", "generation_id", "file_id"} or {"kind": "library", "item_id"} into {value, media_type, original_filename, origin}; value is what a media field accepts. Paths and URLs are never accepted; a bad, foreign, hidden or deleted reference raises MediaRefError with a code of invalid_ref or not_found |
get_session(user, session_id, mode=None) | The owner's session as it is now: {session_id, preset_id, name, version, updated_at, mode, data}. version is the write counter every save bumps (layout-only saves included), so compare payloads rather than versions to tell whether settings changed. With mode, data is that mode's payload or None; raises SessionNotFoundError for anyone else |
get_session_snapshot(user, session_id, version=None) | The owner's session payload, or one of its saved versions; raises SessionNotFoundError for anyone else. Its version echoes the history version asked for, not the write counter |
Idempotent submits. GenerationRequest.idempotency_key (1 to 200 characters, also accepted as the
idempotency_key field of the POST /api/generations/start body) makes a submit safe to retry. Keys are
scoped to the submitting user, so two users may use the same key. A second submit with a key the user
already used starts nothing and returns the original {generation_id, status, queue_position}; it is
resolved before the form is bound or any backend is chosen, and concurrent submits with one key produce
exactly one generation. The key is stored with a fingerprint of the request (preset, mode, form name, form data and prompts); reusing a key for a different request raises IdempotencyKeyConflict (HTTP 409 on the route). If the original row exists but this process is no longer tracking it (for example
the process stopped between recording and queueing it), the retry reports it as failed rather than
leaving it pending; use a new key to run it again. Idempotency is settled inside one backend process: concurrent submits are serialised by an in-process lock, so it does not hold across several API processes sharing a database. A submit with no key behaves as it always did.
Generations started this way stream progress to websocket subscribers and write a run report, exactly like ones started from the page.
from src.plugin_api.generation import (
GenerationRequest, list_generation_files, resolve_media_ref, submit_generation,
)
async def upscale_last_result(user, preset_id, generation_id):
first = list_generation_files(user, generation_id)[0]
media = resolve_media_ref(
user, {"kind": "history", "generation_id": generation_id, "file_id": first["id"]}
)
form_data = {"image": media["value"], "image__origin": media["origin"]}
return await submit_generation(
user, GenerationRequest(preset_id=preset_id, mode="img2img", form_data=form_data)
)Preparing a request from a saved session#
A plugin frontend can turn a saved session into the same GenerationRequest the Generate page
would send, without a Generate tab: window.__potionui.generation.prepareRequest(input).
| Input | Meaning |
|---|---|
presetId, mode | The preset and the mode to run. |
session | One mode's saved settings, as a session stores them (prompt, promptSegments, promptTabs, promptRelay, videoDirector, variables, formData, selectedVariant, ...). |
overrides | Optional changes on top of the session: formData is merged field by field, every other key replaces the session's value. |
presetVars | The preset's vars (from GET /api/presets/{id}), which decide multi-prompt, Prompt Relay, promptless and optional-prompt modes and the Video or Music Director. |
tabId | Optional; becomes the request's tab_id. |
random, now | Optional sources for chip shuffles and shuffled variables, for repeatable results. |
It returns {ok: true, request, variableRolls, submittedPromptTemplate, shuffled, director}, or
{ok: false, code, reason} where code is no_preset, no_prompt or director and reason
is a message when there is one. Chip shuffles and shuffled variables are resolved in the call, so
each call is a fresh roll. Submit the request with submit_generation (or
POST /api/generations/start); the server still binds and checks it like any other request.
Following a generation's progress#
A plugin frontend follows a running generation with
window.__potionui.generation.subscribe(generationId, handler). It returns an unsubscribe
function; call it when the generation is over or when your page unmounts.
Read the generation's current state with GET /api/generations/{id}/status before you
subscribe: events start when you subscribe and what happened before is not replayed. An
unknown id, or one that belongs to another user, produces no event at all, not even an error.
const unsubscribe = window.__potionui.generation.subscribe(generationId, (event) => {
if (event.type === 'generation_status') {
showProgress(event.message, event.progress);
return;
}
unsubscribe();
if (event.type === 'generation_complete') loadResults(generationId);
else if (event.type === 'generation_error') showError(event.data?.message ?? event.message);
else showCancelled();
});handler receives only these four events, and only for generationId:
event.type | What it carries |
|---|---|
generation_status | Progress while it runs: generation_id, status ('running'), progress (a number, or null while the stage has no fraction), message, current_step. |
generation_complete | data: the generation's status record (data.id, data.status, ...). Read the files with list_generation_files or the history API. |
generation_error | The failure: data.generation_id and data.message, or the same fields at the top level, depending on where it failed. |
generation_cancelled | data: the generation's status record. |
Other messages of the generation socket (previews, artifacts, timers, the subscription acknowledgement or a subscription error) are not passed on. The server only streams a user's own generations; administrators may follow any.
All plugin subscriptions share one connection to the app's generation websocket
(/ws/generation), opened on the first subscribe and closed when the last subscriber
unsubscribes, so subscribing to many generations does not open many sockets. The core pages
(Generate, History) keep their own connections. The socket reconnects on its own after a drop
and subscribes to every followed generation again. The generation protocol has no unsubscribe
message: unsubscribe() stops calling your handler, and the server stops sending once the
shared connection closes. A handler that throws is logged and does not stop the other
handlers.
subscribe is absent on hosts that predate it; feature-detect it with
window.__potionui.generation.subscribe?.(...) and fall back to polling
GET /api/generations/{id}/status if you need to.