Plugin Actions
Actions are plugin-contributed operations that appear in the UI alongside Resources, Notes, and Groups, collecting user input through typed parameters and running synchronously or asynchronously against specific entity types or content types.
Registering an Action
Register actions during init() using mah.action(table):
function init()
mah.action({
id = "colorize",
label = "Colorize Image",
entity = "resource",
placement = {"detail", "card"},
filters = {
content_types = {"image/jpeg", "image/png"}
},
params = {
{ name = "style", type = "select", label = "Style", options = {"realistic", "artistic"}, default = "realistic" },
{ name = "intensity", type = "number", label = "Intensity", min = 1, max = 100, default = 50 }
},
async = true,
confirm = "This will process the image. Continue?",
handler = function(ctx)
local resource = mah.db.get_resource(ctx.entity_id)
-- process the resource...
mah.job_progress(ctx.job_id, 50, "Processing...")
-- ...
mah.job_complete(ctx.job_id, { message = "Done" })
end
})
end
Registration Fields
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
id | string | Yes | -- | Unique ID within the plugin (normalized to lowercase) |
label | string | Yes | -- | Display label in the UI |
entity | string | Yes | -- | Target entity: "resource", "note", or "group" |
handler | function | Yes | -- | Lua function called when the action runs |
description | string | No | "" | Optional description |
icon | string | No | "" | Optional icon identifier |
placement | table | No | {"detail"} | Where to show: "detail", "card", "bulk" |
filters | table | No | match all | Content-type, category, or note-type filters |
params | table | No | none | User input parameter definitions |
async | boolean | No | false | Run asynchronously via the job system |
confirm | string | No | "" | Confirmation message shown before execution |
bulk_max | number | No | 0 | Maximum entities for bulk execution (0 = no limit of the action's own) |
retry | boolean | No | false | The async handler is safe to run again with the same entity and parameters. Offers Retry on an unsuccessful job and Continue on a partial one. |
cancel | boolean | No | false | The async handler may be stopped partway. Offers Cancel on a running job; see Cancelling a job. |
Registering a duplicate id within the same plugin raises a Lua error.
bulk_max is the action's own policy. Independently of it, the deployment caps
how many entities one run may name (-max-action-entities, default 1000);
exceeding either is a 400. The deployment cap exists because an async action
creates a job, a goroutine and a live-progress notification for every submitted
id before any of them runs.
Action Parameters
Parameters define the input fields shown to the user before the action runs.
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Parameter key passed to the handler |
type | string | Yes | "text", "textarea", "number", "select", "boolean", "hidden", "info", "entity_ref" |
label | string | Yes | Display label |
required | boolean | No | Whether the field must be filled |
default | any | No | Default value |
options | table | No | Choices for "select" type |
min | number | No | Minimum value for "number" type |
max | number | No | Maximum value for "number" type |
step | number | No | Step increment for "number" type |
Parameter names must be unique within an action -- params are addressed by name
in the submitted values, the form, and show_when, so a duplicate has no
coherent meaning and is rejected at plugin load.
Types are enforced
A submitted value of the wrong type is rejected before the handler runs:
"text", "textarea" and "hidden" require a string, "number" a number,
"select" one of its options, and "boolean" an actual true or false.
The boolean check matters more than it looks: everything except false and
nil is truthy in Lua, so an unvalidated [] posted for a confirmation flag
would read as "yes" to a handler gating a delete on it.
Entity Reference Parameters
The entity_ref param type lets a plugin action accept references to one or more resources, notes, or groups as additional input. Use cases: an image-edit action that takes multiple source images, a "merge two notes" action, a "tag groups by another group's tags" action.
Schema
{
name = "extra_images",
type = "entity_ref",
label = "Additional Images",
entity = "resource", -- "resource" | "note" | "group"
multi = true, -- false → single ID; true → array of IDs
required = false,
min = 0, -- multi only; omit for no minimum
max = 9, -- multi only; omit or set to 0 for no maximum
default = "trigger", -- "trigger" | "selection" | "both" | ""
filters = { content_types = {"image/jpeg", "image/png"} }, -- optional; inherits action.filters when omitted
show_when = { model = {"flux2", "nanobanana2"} }, -- standard show_when
description = "Reference images sent alongside the source.",
}
Behavior
- The picker UI opens layered over the action modal. It applies the effective filter (per-param
filtersif set, else inheritsaction.filters). - The handler receives the IDs as
ctx.params.<name>-- a Lua number formulti=false, a Lua table of numbers formulti=true. Server-side validation guarantees every ID exists and matches the filter at request time. defaultcontrols what the picker is prefilled with:"trigger"(default when omitted) -- the entity the action was launched from."selection"-- IDs from the current bulk-selection store."both"-- union of trigger and selection (requiresmulti=true).""-- empty; user picks every entry.
- Trigger and selection are silently ignored if
param.entitydoes not match the action's launch entity type. (Example: an action declaredentity = "resource"with anentity_ref entity = "group" default = "trigger"will open with an empty picker on resource pages, since the trigger resource ID is not a valid group ID.)
Constraints
default = "both"requiresmulti = true.entitymust be one of"resource","note","group". Other values are rejected at plugin load time.
show_when
show_when gates a param on the values of other params. Every key must match
(AND-joined), and an array value means any-of:
show_when = { model = {"flux2", "flux2pro", "nanobanana2"} }
-- Visible when model is any of the listed values.
show_when = { model = "b", advanced = true }
-- Visible only when BOTH hold.
Scalar values use strict equality, except that numbers compare numerically regardless of how they arrived.
It is enforced on the server, not just drawn in the browser
Visibility is resolved from the submitted values before validation runs:
- A hidden param is not validated, so
required = truecombines withshow_when. A mandatory field inside a branch is enforced exactly when the user is in that branch -- previously the pair was rejected at plugin load and the workaround was to mark nothing required and re-check in Lua. - A hidden param's submitted value is dropped before the handler sees it.
The modal already strips hidden params, but a direct API caller does not, so a
handler that assumed
show_whenimplied absence was wrong for that caller. - A param whose controlling param is absent from the request counts as hidden. That is the one point where the server can disagree with the browser, which evaluates against its live form state, and it errs toward not validating rather than toward rejecting a field the user was never shown.
Chaining
A show_when may name a param that is itself gated -- a sub-mode selector shown
only for one model, with fields shown only for one sub-mode -- provided the
dependent repeats the controller's own conditions:
{name = "upscale_mode", type = "select", options = {"factor", "target"},
show_when = {model = "seedvr"}},
{name = "upscale_factor", type = "number",
show_when = {model = "seedvr", upscale_mode = "factor"}}, -- repeats model
Omitting the repeated condition is rejected at plugin load. Without it the dependent could be visible while its controller is hidden, and a hidden controller is stripped from the request -- so the server would see no value for it, conclude the dependent was hidden too, and silently discard what the user typed into a field they were shown.
params = {
{ name = "mode", type = "select", label = "Mode", options = {"simple", "scheduled"}, default = "simple" },
-- Mandatory, but only in the branch that shows it.
{ name = "publish_at", type = "text", label = "Publish at", required = true,
show_when = { mode = "scheduled" } },
}
Action Filters
Filters control which entities see the action. Empty filters match everything.
filters = {
content_types = {"image/jpeg", "image/png", "image/webp"}, -- Resource content types
category_ids = {5, 12}, -- Group Category IDs
note_type_ids = {3} -- Note Type IDs
}
| Filter | Entity | Description |
|---|---|---|
content_types | Resource | Match Resources with these MIME types |
category_ids | Group | Match Groups with these Category IDs |
note_type_ids | Note | Match Notes with these Note Type IDs |
If a filter is set but the entity lacks the filtered field, the action does not match.
Placement
| Placement | Location |
|---|---|
detail | Entity detail page (single entity) |
card | Entity card in list views (single entity) |
bulk | Bulk action bar (multiple selected entities) |
The bulk placement renders a button only on the Resource and Group list pages. The Note list page does not expose bulk plugin actions, so a bulk action declared with entity = "note" shows no button there. Running it directly via POST /v1/jobs/action/run with multiple note IDs still works.
Running an action from a template
A category, resource category or note type template can put one action on the page as its own button with the built-in [action] shortcode:
[action plugin="project-management" name="pm-set-status" label="Mark done" param-status="done"]
- Placement is ignored. It decides where the menus list an action, and
POST /v1/jobs/action/runnever checks it, so a template button works for any registered action whoseentitymatches the entity being rendered. The action'sfiltersstill apply: the button is drawn only on entities they match, and the run endpoint checks them again on the click. - Selection-only actions cannot run from a template. A template has no bulk selection. If an action only makes sense with one, declare its selection parameter
required = true(anentity_refwithdefault = "selection"), so template authors get the error "needs a bulk selection and cannot run from a template" on the page instead of a button that fails. - Template parameters are literal.
param-<name>="…"values are fixed in the template and converted by the parameter's type (number,boolean,selectand the text types).entity_refandinfoparameters cannot be set; anentity_refthat defaults totriggergets the rendered entity. - The button runs with the permissions of whoever clicks it, through the same endpoint, checks and Job handling as the actions menu, and is not drawn for accounts that could not run the action.
Synchronous Execution
Sync actions (the default) run within a single request-response cycle. The handler receives a context table and returns a result table.
Timeout: 5 seconds.
mah.action({
id = "tag-by-type",
label = "Auto-Tag by Type",
entity = "resource",
handler = function(ctx)
local resource = mah.db.get_resource(ctx.entity_id)
-- do something quick...
return { success = true, message = "Tagged" }
end
})
Handler Context (Sync)
| Field | Type | Description |
|---|---|---|
entity_id | number | ID of the target entity |
params | table | User-supplied parameter values |
settings | table | Plugin settings |
ActionResult
| Field | Type | Description |
|---|---|---|
success | boolean | Whether the action succeeded |
message | string | Message displayed to the user |
redirect | string | Optional URL to redirect to after completion |
job_id | string | Optional job ID a sync handler can return as a poll handle |
data | table | Optional additional data |
How the modal reports a sync result
success is honoured, so a handler can refuse and say why:
success = true-- the result is announced in arole="status"box and the page reloads after 1.5s.success = false(includingmah.aborton the sync path) -- themessageis shown as an error in arole="alert"box, the modal stays open, and the page does not reload, so the reason stays readable.- A bulk run answers with one result per selected entity. The modal reports how many failed and lists them by entity ID. If some succeeded, the page reloads when the reader dismisses the result rather than under them while they are still reading it.
Return a message with a refusal -- it is the only thing the user will see:
handler = function(ctx)
if not mah.get_setting("api_key") then
return { success = false, message = "Set the API key in plugin settings first" }
end
-- ...
end
Asynchronous Execution
Async actions (async = true) run in a background goroutine via the job system. The API returns immediately with a job_id.
Timeout: 5 minutes. A handler that runs longer is stopped at its next step,
and its job fails with the class timeout.
A plugin runs one piece of background work at a time in each server process. Its
async actions and its mah.start_job jobs wait in one queue per plugin and start
in the order they were submitted; a schedule run goes ahead of them and waits only
for the work already running, though never twice in a row while an action is
waiting. A job waiting its turn is queued in the Job Center and holds nothing.
The job at the head of the queue starts once one of the process's 3 plugin job
slots is free, the plugin is not busy with a hook, a page or another synchronous
call, and the deployment's job budget (-max-job-concurrency, shared with
downloads, exports and every other kind of Job) has room. A bulk run over 50
resources on one server process is therefore one running Job and 49 queued ones
(with several server processes, up to one running Job per process), and it
occupies one slot per process at a time, so other plugins' work and downloads
keep starting while it drains. Just before a queued action starts, the server checks again that the
account it runs as may still run it on that entity. If claiming the job and
making those checks take longer than 10 seconds together, the job goes back to
queued, shows "Waiting for the account and scope checks", and lets the
plugin's other work go first. It tries again after a wait that starts at one
second and doubles each time, up to 30 seconds, and each attempt is allowed twice
as long as the one before, up to one minute, so checks that are slow but finish
still let it start. It never starts on a check that did not finish, and a check
that could not finish is never recorded as a refusal. The first attempt that
cannot finish adds a start and a return to queued to the job's history; the
attempts after it run the checks before claiming the job, and add nothing to its
history while the checks still cannot finish. Work still queued when its plugin is disabled does not
start: a queued action is blocked for a person to decide about, or runs if the
plugin is enabled again first, and a queued mah.start_job job is cancelled.
A handler that is running when its plugin is disabled is stopped at its next step,
and its job ends interrupted with the reason "The plugin was disabled while this
was running."
mah.action({
id = "process-video",
label = "Process Video",
entity = "resource",
async = true,
handler = function(ctx)
mah.job_progress(ctx.job_id, 10, "Downloading...")
-- long-running work...
mah.job_progress(ctx.job_id, 50, "Processing...")
-- more work...
mah.job_complete(ctx.job_id, { message = "Video processed" })
end
})
Handler Context (Async)
Same as sync, plus:
| Field | Type | Description |
|---|---|---|
job_id | string | Job ID for progress reporting |
Job Progress Control
| Function | Description |
|---|---|
mah.job_progress(job_id, percent, message) | Report progress (0-100). Updates are sent at most every 200ms; a report held back is sent when that window ends, even if the handler is blocked. |
mah.job_progress(job_id, report_table) | Report counts, a unit and metrics. See Counts, metrics and graphs. |
mah.job_complete(job_id, result_table) | Request successful completion; after the handler settles, store final progress at 100%. |
mah.job_fail(job_id, error_message) | Mark job as failed. |
Counts, metrics and graphs
Pass a table as the second argument to report what the job is counting. The Job
then shows the count on its progress bar, a speed and an estimated time left in
the Jobs drawer, on the Job's page and on the /jobs list, and it can draw a
graph for any figure you mark with graph = true.
handler = function(ctx)
local rows = 0
for batch = 1, 20 do
rows = rows + process_batch(batch)
mah.job_progress(ctx.job_id, {
completed = batch, total = 20, unit = "items",
message = "Batch " .. batch .. " of 20",
metrics = {
{ key = "rows", label = "Rows written", value = rows, graph = true },
{ key = "skipped", label = "Skipped", value = skipped, total = 20, unit = "items" },
},
})
end
end
| Field | Type | Meaning |
|---|---|---|
percent | number | 0-100. When it is omitted and completed and total are both known, the percent is derived from them. |
completed | number | The amount done, at least 0. |
total | number | The amount there is, at least 0. |
unit | string | What completed counts, at most 20 bytes. bytes, items, percent, seconds and ms are formatted; any other unit is shown as a number followed by the unit. |
message | string | The line shown above the bar. |
metrics | list | Up to 8 figures shown beside the bar. |
Each metric is a table:
| Field | Type | Meaning |
|---|---|---|
key | string | Required. 1-40 bytes of a-z, 0-9, _ and -, unique within the list. |
label | string | Shown to the reader, at most 60 bytes. Defaults to the key. |
value | number | Required. A finite number of at least 0. |
total | number | Optional. Shown as "value of total". |
unit | string | Optional, at most 20 bytes, formatted like the progress unit. |
graph | boolean | Keep this metric's history and draw it as a graph. At most 3 metrics per report. |
A field the table leaves out keeps the value the previous report gave it, so a
loop can report only what changed. metrics replaces the whole list when it is
present, and metrics = {} clears it. An unknown field, a wrong type or a value
outside these bounds raises a Lua error that names the field.
Reports are throttled like the positional form. A report the throttle holds back is not lost: it is sent with the next report that passes, or when the handler settles, so the Job always ends on the last figures the plugin reported. On success, a counted job's final progress is its total, in its own unit, with its last metrics.
Speed and time left are derived from completed. They are shown only when the
unit is not percent, because a speed in percent says nothing. Labels, units
and the message are redacted of the action's parameter values before they are
stored, exactly as the message always was.
The table form needs no capability beyond the one that gives the plugin
mah.job_progress (actions or jobs): it reports on a job the plugin
already owns.
If the handler returns without calling mah.job_complete or mah.job_fail, an
async job is marked completed with progress 100. The message string becomes
the completion text; a nonempty result table within the size limit is stored as
a sanitized Job summary. A success = false field is ignored on the async path
(unlike the sync path, which honors it). To fail an async action, call mah.job_fail or
mah.abort.
If the result includes a canonical local redirect such as
/resource?id=17, /note?id=17, or /group?id=17, the host also publishes an
entity output. Opening it rechecks access to the target. Older
plugin Jobs that stored only the summary show View result for the target
and View JSON result for the summary.
A job already marked failed or cancelled keeps that outcome. A handler that
calls mah.job_fail and then returns a diagnostic table is not overruled by
that table: it is ignored, and the failure stands.
Cancelling a job
A job whose handler has not started offers Cancel in the Jobs panel and the
Job Center, whatever the action declares: it is queued, or blocked with
nothing running, and none of it has run. It ends cancelled at once and its
handler never runs. A bulk run's queued jobs can be selected and cancelled
together in the Job Center.
A running handler offers Cancel only when the action declared cancel = true
when the job was accepted; the job records it, so every server process answers the
same. A job accepted that way whose action no longer declares cancel = true when
its turn comes is not run: it is blocked with the reason registration-changed.
Cancelling it stops the handler at its next step: between two Lua instructions,
or when a mah.sleep or mah.http call it is waiting in returns early. What the
handler did before that stays done, so declare cancel = true only for a handler
that leaves consistent data wherever it stops, for example one that writes each
item in its own mah.db.transaction. The job ends cancelled, also when the
handler had already called mah.job_complete or finished before the stop reached
it: once a person asks for a cancellation, the job does not end as succeeded.
With several server processes, the process running the handler stops it within
about a second of the request. A job cancelled after it was claimed but before its
handler started never starts, and ends cancelled, also when the account and
scope checks it runs before its handler cannot answer: it does not go back to
the queue to wait for them.
A running mah.start_job job has no registration to declare cancel = true, so
it can be cancelled only before it starts.
Why a job failed
A failed job shows a reason in the Jobs panel, on the Job Center list and on the job's page:
| Cause | Failure code | Class | Reason shown |
|---|---|---|---|
mah.job_fail(job_id, message) or mah.abort(reason) | plugin-action-failed | dependency | The message the plugin gave |
| A Lua error the handler did not catch | plugin-handler-error | internal | The error's own first line, such as plugin.lua:20: attempt to index a non-table object(nil) with key 'time' |
| The handler ran for longer than 5 minutes | plugin-handler-timeout | timeout | the handler ran for longer than 5 minutes and was stopped |
Every value of the job's own parameters in the reason is replaced with
[redacted] before it is stored, as in progress and completion messages, and so
is the current value of every password setting of the plugin; the reason is cut
at 1000 bytes. A Lua error names the plugin's file relative to the
plugin's directory, and its stack traceback goes to the server log only. An empty
message reads "the plugin's handler failed".
When the server stops
A graceful shutdown first ends the plugins' mah.http requests still in flight;
their callbacks do not run. It then gives a running handler 5 seconds to finish by
itself. Then it
is stopped at its next step and has 5 more seconds to unwind, and its job ends
interrupted with the reason "The server shut down while this was running." A
handler waiting inside a call that does not end when it is stopped is not ended
by the shutdown, because nothing proves the call has finished: its job keeps
running, and offers no Retry that could run the work a second time beside it. It
ends when the handler returns, or, if the server exits first, when the next
server process resolves it as after a crash. The plugins' part of a
shutdown takes at most 15 seconds, recording those outcomes included; a job whose
outcome could not be recorded in that time is resolved by the next server
process, as after a crash. Work still waiting for its
turn never started: a queued action stays queued and the next server process
runs it, a queued mah.start_job job is cancelled as not started, and a schedule
run that had not started records nothing and runs at a tick after the restart. A
Retry of a schedule run waits like a queued action: it stays queued until a
server process can run it.
After a crash, the next server process on the same machine, in the same boot
session, interrupts the jobs the crashed process was running on its next pass,
with the reason "The server process running this stopped before it finished." A
job whose process cannot be proved stopped that way, because the machine has
rebooted since or the process ran on another machine, waits for its 2-minute
lease; then it is interrupted if its process is proved gone, and otherwise
blocked for a person to resolve. If recording a finished handler's outcome takes
longer than 5 seconds at shutdown, the next process resolves that job the same
way, as runtime-lost. A queued mah.start_job job that a crashed
process on another host accepted stays queued until someone cancels it, because
only that process could ever run its callback.
Leaving work to continue: continue = true
A handler that cannot finish in one run can say so with the reserved key
continue = true in its result table, whether it passes that table to
mah.job_complete or returns it:
mah.job_complete(ctx.job_id, {
message = "Partial: 120 of 500 items. Run it again to continue.",
continue = true,
})
The Job still succeeds, because nothing failed, but its phase becomes partial,
and the Job Center labels it Partially completed. The continue key itself is
not stored in the Job's result output. When the
action also declares retry = true, the Jobs panel and the Job Center offer
Continue on that Job: a new Job that reruns the same handler with the same
input, linked like a Retry, so at most one continuation of a Job exists. This is
the mechanism for long work that one run cannot finish. It is distinct from
Repeat (an independent rerun that may branch) and from Retry (for
unsuccessful work). A successful action without continue = true offers no
Continue. Without retry = true the phase is still recorded as partial, but
nothing is offered, because a continuation reruns the handler.
The key is read from the final result. A handler that calls mah.job_complete
and then returns a table has its returned table replace the earlier one,
message and continue included, so put continue = true in the returned table
too, or return nothing.
A handler that uses this usually resumes from durable state of its own, such as
its mah.kv queue, so the continuation does not redo what the previous run
finished.
Abort
Call mah.abort(reason) from any handler to abort the action:
handler = function(ctx)
local resource = mah.db.get_resource(ctx.entity_id)
if not resource then
mah.abort("Resource not found")
end
-- ...
end
On the synchronous path this returns { success = false, message = reason }. On the asynchronous path there is no success field: the job is marked failed with its message set to the reason (see Why a job failed).
API Endpoints
List Available Actions
GET /v1/plugin/actions
| Parameter | Type | Description |
|---|---|---|
entity | string | Required: "resource", "note", or "group" |
content_type | string | Optional: filter by content type |
category_id | uint | Optional: filter by Category ID |
note_type_id | uint | Optional: filter by Note Type ID |
curl "http://localhost:8181/v1/plugin/actions?entity=resource&content_type=image/jpeg"
Run an Action
POST /v1/jobs/action/run
Content-Type: application/json
{
"plugin": "image-processor",
"action": "colorize",
"entity_ids": [42],
"params": { "style": "realistic", "intensity": 75 }
}
- Sync actions: Returns
200 OKwithActionResult - Async actions: Returns
202 Acceptedwith{ "job_id": "abc123..." } - Bulk (multiple
entity_ids): Returns{ "results": [...] }for sync actions or{ "job_ids": [...] }for async actions. Respectsbulk_maxand-max-action-entities.
A bulk sync run is not atomic: each entity runs in turn and every write it
made is committed before the next one starts. So a handler that fails partway
through returns 200 with one entry per submitted entity, positionally, the
failed ones carrying success: false and a message -- not a 5xx that would
describe none of what already happened. A single-entity run is different and
keeps its error status, because nothing about it is partial.
Get Action Job Status
GET /v1/jobs/action/job?id={jobId}
curl "http://localhost:8181/v1/jobs/action/job?id=abc123def456"
Returns the current job state including status, progress, message, and result.
Related Pages
- Plugin System -- plugin installation, configuration, and lifecycle
- Plugin Hooks -- hook registration, injections, custom pages, and menus
- Job System -- unified job listing, SSE events, and cleanup behavior
- Plugin Lua API -- full Lua API reference for the
mahmodule