Plugin development
A Marginalia plugin (the user interface calls them extensions) is an OSGi bundle - a JAR with a few extra manifest headers - that Marginalia loads at runtime, without a restart. A plugin can add menu items, tabs, panels and settings to the user interface, keep its own data on books, story parts, lorebooks and user settings, call the model, and take part in generation.
This part of the developer guide explains how plugins work and how to write one. It assumes you can build Marginalia from source (Building from source) and know a little Vaadin Flow (User interface).
How a plugin plugs in
flowchart LR
subgraph Bundle["Plugin JAR (OSGi bundle)"]
Act["BundleActivator"] -->|registers| Ext["MarginaliaExtension"]
Ext --> Dec["ExtensionDecorators"]
Ext --> Lis["generation listeners"]
end
subgraph App["Marginalia"]
Osgi["OsgiService<br/>(Apache Felix)"]
ES["ExtensionService"]
UI["@Extendable UI classes<br/>(instrumented)"]
Gen["StoryGenerationService"]
Ent["entities<br/>attributes JSON"]
end
Osgi -->|onExtensionLoad| Ext
Dec -->|registerDecorator| ES
UI -->|method enter / leave| ES
ES -->|onMethodEnter / onMethodLeave| Dec
Lis -->|addEventListener| Gen
Dec -.->|read / write| EntThere is no plugin API in the usual sense - no list of extension points with stable signatures. Instead, a plugin gets general mechanisms and the whole application to use them on:
Extending the UI puts the first three together: adding components, settings panels, threads and cleaning up on unload. Generation events shows how a plugin changes the prompt sent to the model, on the bundled Author's Note. Example plugin builds a small plugin from scratch and walks through the bundled Chapter Marker and Author's Note.
Plugins are tied to one version of Marginalia
Hooks are attached by class and method name and read local variables and fields by name. Renaming a method or a variable in the application silently disables the part of a plugin that used it (a warning is logged). Build plugins from the same source tree as the application they run in, and test them after every update. Marginalia itself verifies the decorators of an extension before it starts it and refuses ones that ask for classes, methods, arguments, locals or fields that don't exist.
The bundled plugins
The thirty plugins in marginalia/plugins/ are complete, working examples. Each is a separate Maven project.
Users install them as described in Managing extensions.
Asking the user in the middle of a generation
A generation listener can stop the generation and show the user a dialog, and the generation goes on, or ends, by what the user answers. The bundled Prompt Inspector does exactly this: with its check box on, every generation of the user stops just before the request with a dialog that shows the messages about to be sent, and Send sends them while Cancel ends the generation. Three things make it work:
-
The chain waits for you. A listener gets
(event, chain)and the generation does not go on until it callschain.next(). Nothing blocks a thread while it waits, so a listener can start something, return, and callchain.next()later from wherever the answer arrives. It must call it exactly once. -
event.accessUI(action)runs the action on the user's page. The generation runs on a worker thread;accessUIis the way back to the UI that started it (ui.accessand a push), and theUIit hands over is the one to open the dialog on. It returnsfalse, and never runs the action, when the generation has no UI (an agent or a command started it): then nobody can be asked and the listener goes on at once. -
Stopping is cancelling the token.
event.getCancellationToken().cancel()and thenchain.next(): the generation jumps to its cleanup, the request is not sent and the part started for it is removed.
Listeners are global (the generations of all users come through them), so the first thing the listener does is look
whether this user wants to be asked - the Prompt Inspector keeps a boolean in the attributes of the user settings and
reads it with settingService.find(UserSetting.class, currentUser), which works on the generation's thread. The listener,
trimmed:
// onExtensionLoad / onExtensionUnload
inferenceRegistration = storyGenerationService.addEventListener(Events.BEFORE_INFERENCE, this::inspect);
inferenceRegistration.unregister();
private void inspect(GenerationControllerEvent event, EventChain chain) {
boolean asked = false;
try {
if (event.getPayload() != null && isEnabled()) { // this user switched it on
asked = GenerationQuestion.ask(event, chain, log,
(send, cancel) -> new PromptInspectorDialog(format(event.getPayload()), send, cancel));
}
} catch (Exception e) {
log.warn("Failed to show the prompt: {}", e.getMessage(), e); // generate without asking rather than fail
} finally {
if (!asked) {
chain.next(); // nobody was asked: go on
}
}
}
The asking is a class of its own, GenerationQuestion, so that it can be tested without a browser (a fake dialog and a fake
page stand in for the real ones, GenerationQuestionTest). Trimmed, it is:
static boolean ask(GenerationControllerEvent event, EventChain chain, Logger log, ViewFactory factory) {
AtomicBoolean answered = new AtomicBoolean();
AtomicReference<View> view = new AtomicReference<>();
// whatever answers first - Send, Cancel, a stop from elsewhere, the page going away - lets the generation go on, once
Runnable proceed = () -> {
if (answered.compareAndSet(false, true)) {
chain.next();
}
};
Runnable stop = () -> { // a refusal: stop before the request
event.getCancellationToken().cancel();
proceed.run();
};
// the generation was stopped from another window while the question is open: go on, then close it
Runnable unsubscribe = event.getCancellationToken().onCancel(() -> {
try { proceed.run(); } finally { closeQuietly(event, view, log); }
});
if (answered.get()) {
return true; // it was cancelled already: the chain has gone on
}
boolean scheduled = event.accessUI(ui -> { // runs on the thread of the user's page
try {
View shown = factory.create(proceed, stop); // Send -> proceed, Cancel -> stop
view.set(shown);
shown.whenDetached(() -> { // the page was closed or expired with the question open
if (!answered.get()) {
stop.run();
}
});
shown.open();
} catch (RuntimeException e) {
log.warn("Could not show the question: {}", e.getMessage(), e);
proceed.run(); // go on unasked rather than wait for ever
}
});
if (!scheduled) { // an agent or a command: no page to ask
unsubscribe.run();
return answered.get();
}
return true; // the dialog is out, the answer calls chain.next()
}
The dialog is a plain Vaadin Dialog that is given two Runnables (and implements View, which adds whenDetached
over addDetachListener). It is modal and does not close on Esc or a click outside, because the generation is waiting for the
answer; each button runs its callback first and then closes, so that the closing, which detaches the dialog, finds the
question answered.
What to keep in mind when you write one:
-
Always release the chain. Every path out of the listener must end in exactly one
chain.next(): thefinally, the answer, the cancellation. Guard it with anAtomicBooleanwhen several things can answer. -
Give a question that nobody answers a way out. While the question is open the generation is not a thread that waits but a callback nobody has called yet, so there is nothing to interrupt: if the page is closed or expires with the dialog open, no button is ever pressed and the generation would stay parked for ever (its placeholder part in the book, its closures in memory). Treat the dialog going away unanswered as a refusal (a detach listener that cancels the token and releases the chain), and release the chain when the token is cancelled some other way (
getCancellationToken().onCancel(...), which also returns aRunnablethat removes the listener again). The server notices that a page is gone only after a while, so this is not instant. -
Nothing in the way out may throw.
CancellationToken.cancel()runs its listeners one after the other and a listener that throws keeps the rest from running;accessUIthrowsUIDetachedExceptionwhen the page is gone. Release the chain first, then close the dialog, and catch what closing throws. -
The action and the dialog run on the thread of the UI, not in the request scope of the generation. Keep them to showing the dialog and reporting the answer; hand the work on through the chain and do it in the listener.
-
Check that someone can see it.
accessUIreturningfalsemeans no dialog was shown - do not wait. It throwsUIDetachedExceptionwhen the user has closed the page: treat it like a failure and go on or cancel. -
Ask as late as you can.
BEFORE_INFERENCEis the last event before the request, so what the user sees is what the model gets after every other extension has changed it.
The other events and what they carry are in Generation events.
Reading order
- Plugin basics - project layout, the activator and the extension, building and loading.
- Example plugin - build one, load it, see it work.
- @Extendable hooks - the decorator API in detail and its limits.
- Extended attributes - storing data.
- Extending the UI - patterns for menus, tabs and settings, threads and unloading.
- Generation events - changing the prompt and the answer during generation.
- Sharing data between extensions -
IPCService,ToolServiceand calling another extension directly. - Inference providers from a plugin - bringing a model API: factory, settings form, inference service.
- Inherited settings - settings of a plugin that books and folders inherit.
- The text a model reads and anchored passages - keeping the story in one form and giving a model another.
- The text of an export - what an export of a book holds for such a passage.
- Facts for the annotation - offering what a plugin knows to the model that reviews a part.
- Libraries for plugins and translator-common, story-tracker-common and http-hooks - sharing code between plugins.