Plugin & Add-on Development
Extend OpenDraft through its plugin architecture, and ship optional features — such as an AI assistant — as add-ons the writer chooses to turn on.
For writers: add-ons are optional features you switch on in Tools > System Settings > Add-ons. Each one, including Sidekick, is off until you turn it on. The activation dialog describes what leaves your device and shows any settings. Turning one off removes everything it added and can delete what it stored, such as an API key. The rest of this page is for developers.
Overview
Every feature that is not part of the core editor reaches OpenDraft through one place: the plugin registry in frontend/src/plugins/registry.ts. A plugin is a plain object that lists what it adds — menu items, panels, editor extensions, file formats, reports, grammar checks. The app asks the registry for those contributions wherever it draws a menu, a sidebar or the editor.
- Plugins are always on.
- Add-ons are plugins marked
optIn: true. The registry makes its contributions available while it is on.
Never wire a feature into ScreenplayEditor.tsx, Toolbar.tsx or MenuBar.tsx directly. Anything wired in directly cannot be turned off, cannot be replaced by a plugin, and becomes clutter for writers who do not use it.
AI is always an add-on. Using AI in writing is the writer's choice. Any feature that sends the writer's words to a model — local or hosted — must be an opt-in add-on, off by default, with a clear privacy statement.
Where the Code Lives
| What | Where |
|---|---|
| Plugin registry and types | frontend/src/plugins/registry.ts |
| Core add-ons (one folder each) | frontend/src/addons/<id>/index.ts, default-exporting the plugin |
| List of core add-ons | CORE_ADDONS in frontend/src/addons/index.ts (imported once by App.tsx) |
| Rules every core add-on must pass | frontend/src/addons/boundary.test.ts |
| Settings > Add-ons screen | frontend/src/components/AddOnsSettingsSection.tsx |
The boundary test fails the build if any file outside src/addons/ imports an add-on, or if a core add-on is not opt-in, has no description, or does not say what leaves the device.
The Plugin Object
| Field | Purpose |
|---|---|
id, name, version | Required. id is stable: the writer's on/off choice is remembered by it. |
optIn | true lists the plugin in Settings > Add-ons. |
defaultEnabled | Set to true to start a bundled add-on on. The writer’s saved setting takes priority. |
description | One or two sentences shown in Settings > Add-ons. |
privacy | What leaves the device and where it goes. Shown before the writer turns the add-on on. |
settings | A React component shown when the add-on is turned on and from its Settings… button. |
onActivate() | Runs when the writer turns the add-on on, and at start-up if it was already on. |
onDeactivate({ forgetSettings }) | Runs when the add-on is turned off. Delete stored settings and keys when forgetSettings is true. |
menuItems | Entries in File, Edit, Format, View, Production, Tools or Help. |
panels | Components for the right-sidebar or status-bar slot. Right-sidebar panels get a tab and receive the editor. |
routes | Full pages at a new path, or a replacement for one of the built-in pages that allow it. |
editorExtensions | Tiptap extensions. They take effect the next time a script is opened. |
importers, exporters, reports | Join File > Import, File > Export and Tools > Analytics > Reports. A plugin can add a format but never take over a built-in one. |
grammarProviders | Writing-suggestion checks, merged with the built-in ones. |
sceneActions | Buttons in Scene Details, once under the scene (target: 'scene') or on every shot (target: 'shot'). See Scene actions. |
Scene actions
A scene action is given everything Scene Details knows about the scene, already resolved: the heading, synopsis and number; the location with its type, description, images, the look the scene shows and the setting note; each character with their lines, images and the costumes they wear in order (with when each change happens and each costume’s image); and each shot with the characters it names and the costume each one shows. Images are project asset ids. An add-on that makes a video clip per shot has its references in one object:
pluginRegistry.register({
id: 'my-clips', name: 'My Clips', version: '1.0.0', optIn: true,
privacy: 'Sends the shot text and its reference images to the video service you choose.',
sceneActions: [{
id: 'make-clip',
label: 'Make clip',
target: 'shot',
available: ({ shot }) => !!shot?.text,
run: async ({ projectId, scene, shot }) => {
// scene.location?.look?.image, shot.characters[0]?.costume?.image …
},
preview: ClipThumbnail, // optional: drawn beside the shot
}],
});
run may be async; the button is disabled while it runs, and an error it throws is shown to the writer. available hides the button for a scene or shot it cannot act on. The types are PluginSceneAction and PluginSceneActionContext in frontend/src/plugins/registry.ts.
Rules for Add-ons
- Off by default. Set
optIn: true. Do no work, make no network call and show nothing until the writer turns the add-on on. - Say what leaves the device. Write the
privacyline in plain words. - Ask for settings when turned on. Put addresses, models and keys in the
settingscomponent, not in a separate dialog. - Forget on request. Delete stored settings and keys in
onDeactivatewhenforgetSettingsis true. - Stay out of the way. Use a Tools menu item and a sidebar panel. Do not add toolbar buttons.
- Never change the script without the writer. Show a preview and insert only when the writer confirms, as a normal editor change that Undo reverts.
- Handle failure. Catch errors and show a message the writer can act on, e.g. “Could not reach http://localhost:11434. Is the AI server running?”
Sample: an AI Assistant Add-on
A complete, working add-on that asks a model on an OpenAI-compatible server (Ollama, LM Studio, llama.cpp, or a hosted service the writer chooses) about the script, and inserts the answer as an Action line after the writer reviews it. Use it as the starting point for any AI add-on. It lives in frontend/src/addons/ai-assistant/:
frontend/src/addons/ai-assistant/
index.ts the plugin definition
settingsStore.ts settings kept on this device
client.ts the only code that talks to the AI server
AssistantSettingsForm.tsx shown when the add-on is turned on
AssistantPanel.tsx the right-sidebar panel
1. The plugin definition — index.ts
Everything the app sees of the add-on is declared here. The Tools menu item opens the panel by dispatching plugin-panel:open; it does not reach into the editor.
/** AI Assistant: an opt-in add-on. Off until the writer turns it on. */
import type { OpenDraftPlugin } from '../../plugins/registry';
import { PLUGIN_PANEL_OPEN_EVENT } from '../../components/PluginPanelTabs';
import AssistantPanel from './AssistantPanel';
import AssistantSettingsForm from './AssistantSettingsForm';
import { forgetSettings } from './settingsStore';
const PANEL_ID = 'ai-assistant-panel';
const aiAssistant: OpenDraftPlugin = {
id: 'ai-assistant',
name: 'AI Assistant',
version: '1.0.0',
optIn: true,
description: 'Ask an AI model about your script and insert its suggestions after you review them.',
privacy:
'Sends your question, and the text you select, to the AI server you choose. ' +
'With a local server such as Ollama or LM Studio, nothing leaves your computer.',
settings: AssistantSettingsForm,
onDeactivate: ({ forgetSettings: forget }) => {
if (forget) forgetSettings();
},
panels: [
{ id: PANEL_ID, slot: 'right-sidebar', label: 'Assistant', component: AssistantPanel },
],
menuItems: [
{
id: 'ai-assistant-open',
section: 'Tools',
label: 'AI Assistant',
action: () => document.dispatchEvent(
new CustomEvent(PLUGIN_PANEL_OPEN_EVENT, { detail: { panelId: PANEL_ID } }),
),
},
],
};
export default aiAssistant;
Menu entries and their children accept an optional icon as a string or a React node.
Use an SVG React icon to match the built-in menu style; existing string icons still work.
2. Settings on the device — settingsStore.ts
Settings are stored per device, never inside scripts, and deleted when the writer asks.
/** The assistant's settings, kept on this device only. */
const STORAGE_KEY = 'opendraft:addon:ai-assistant';
export interface AssistantSettings {
/** An OpenAI-compatible server, e.g. Ollama's http://localhost:11434/v1 */
baseUrl: string;
model: string;
/** Only for servers that need one. Stored on this device, never in scripts. */
apiKey: string;
}
export const DEFAULT_SETTINGS: AssistantSettings = {
baseUrl: 'http://localhost:11434/v1',
model: 'llama3.1',
apiKey: '',
};
export function loadSettings(): AssistantSettings {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return { ...DEFAULT_SETTINGS };
const saved = JSON.parse(raw) as Partial<AssistantSettings>;
return {
baseUrl: typeof saved.baseUrl === 'string' ? saved.baseUrl : DEFAULT_SETTINGS.baseUrl,
model: typeof saved.model === 'string' ? saved.model : DEFAULT_SETTINGS.model,
apiKey: typeof saved.apiKey === 'string' ? saved.apiKey : '',
};
} catch (err) {
console.warn('[ai-assistant] could not read settings; using defaults', err);
return { ...DEFAULT_SETTINGS };
}
}
/** Throws with a message the settings form can show. */
export function saveSettings(settings: AssistantSettings): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
} catch (err) {
throw new Error(`Could not save the settings on this device: ${err instanceof Error ? err.message : String(err)}`);
}
}
/** Called when the writer turns the add-on off and asks for its settings to be deleted. */
export function forgetSettings(): void {
try {
localStorage.removeItem(STORAGE_KEY);
} catch (err) {
console.warn('[ai-assistant] could not delete settings', err);
}
}
3. The server client — client.ts
The only code that sends anything off the device, and only when the writer presses Ask.
/** Talks to the OpenAI-compatible server the writer chose. Nothing else. */
import type { AssistantSettings } from './settingsStore';
export interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export async function askAssistant(
settings: AssistantSettings,
messages: ChatMessage[],
signal?: AbortSignal,
): Promise<string> {
const url = `${settings.baseUrl.replace(/\/+$/, '')}/chat/completions`;
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (settings.apiKey.trim()) headers.Authorization = `Bearer ${settings.apiKey.trim()}`;
let response: Response;
try {
response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ model: settings.model, messages, stream: false }),
signal,
});
} catch (err) {
if (signal?.aborted) throw err;
throw new Error(`Could not reach ${settings.baseUrl}. Is the AI server running?`);
}
if (!response.ok) {
const detail = await response.text().catch(() => '');
throw new Error(`The AI server answered ${response.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`);
}
const data = await response.json().catch(() => null);
const text = data?.choices?.[0]?.message?.content;
if (typeof text !== 'string') throw new Error('The AI server sent an answer OpenDraft could not read.');
return text.trim();
}
4. The settings form — AssistantSettingsForm.tsx
OpenDraft shows this inside its own Turn on AI Assistant dialog, under the description and the privacy statement, with its own Turn On and Cancel buttons. Hand OpenDraft your save function with registerSave; return false to keep the dialog open after showing your message.
/** Shown when the writer turns the assistant on, and from Settings → Add-ons. */
import React, { useEffect, useState } from 'react';
import type { PluginSettingsProps } from '../../plugins/registry';
import { loadSettings, saveSettings } from './settingsStore';
const AssistantSettingsForm: React.FC<PluginSettingsProps> = ({ registerSave }) => {
const [settings, setSettings] = useState(loadSettings);
const [error, setError] = useState('');
// Core calls this when the writer presses Turn On or Save.
useEffect(() => {
registerSave(() => {
let url: URL;
try {
url = new URL(settings.baseUrl);
} catch {
setError('Enter the server address, e.g. http://localhost:11434/v1');
return false;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
setError('The address must start with http:// or https://');
return false;
}
if (!settings.model.trim()) {
setError('Enter the name of the model to use.');
return false;
}
try {
saveSettings({ ...settings, model: settings.model.trim() });
return true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
return false;
}
});
}, [settings, registerSave]);
const field = (key: 'baseUrl' | 'model' | 'apiKey') =>
(e: React.ChangeEvent<HTMLInputElement>) => {
setError('');
setSettings((s) => ({ ...s, [key]: e.target.value }));
};
return (
<div>
<div className="settings-row">
<label htmlFor="ai-base-url">AI server address</label>
<input id="ai-base-url" className="settings-input" value={settings.baseUrl} onChange={field('baseUrl')} />
<div className="settings-hint">Ollama: http://localhost:11434/v1 · LM Studio: http://localhost:1234/v1</div>
</div>
<div className="settings-row">
<label htmlFor="ai-model">Model</label>
<input id="ai-model" className="settings-input" value={settings.model} onChange={field('model')} />
</div>
<div className="settings-row">
<label htmlFor="ai-key">API key (only if your server needs one)</label>
<input id="ai-key" className="settings-input" type="password" autoComplete="off" value={settings.apiKey} onChange={field('apiKey')} />
</div>
{error && <p className="addon-error" role="alert">{error}</p>}
</div>
);
};
export default AssistantSettingsForm;
5. The panel — AssistantPanel.tsx
Right-sidebar panels receive the Tiptap editor. The answer is shown first; Insert into script adds it as a normal, undoable edit.
/**
* The assistant's right-sidebar panel. The writer asks; the answer is shown
* first and only goes into the script when the writer presses Insert.
*/
import React, { useEffect, useRef, useState } from 'react';
import type { Editor } from '@tiptap/react';
import { askAssistant } from './client';
import { loadSettings } from './settingsStore';
const SYSTEM_PROMPT =
'You help a screenwriter. Answer in the language the writer uses. ' +
'When asked for script text, reply with that text only.';
const AssistantPanel: React.FC<{ editor: Editor | null }> = ({ editor }) => {
const [question, setQuestion] = useState('');
const [includeSelection, setIncludeSelection] = useState(true);
const [answer, setAnswer] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const abortRef = useRef<AbortController | null>(null);
// Stop a request in flight when the panel closes or the add-on is turned off.
useEffect(() => () => abortRef.current?.abort(), []);
const ask = async () => {
if (!question.trim()) return;
const { from, to } = editor?.state.selection ?? { from: 0, to: 0 };
const selected = includeSelection && editor ? editor.state.doc.textBetween(from, to, '\n') : '';
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setBusy(true);
setError('');
setAnswer('');
try {
const text = await askAssistant(loadSettings(), [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: selected ? `${question}\n\nSelected script text:\n${selected}` : question },
], controller.signal);
setAnswer(text);
} catch (err) {
if (controller.signal.aborted) return;
console.error('[ai-assistant] request failed', err);
setError(err instanceof Error ? err.message : String(err));
} finally {
if (abortRef.current === controller) setBusy(false);
}
};
/** Insert the answer as a new Action paragraph after the current one. */
const insert = () => {
if (!editor || !answer) return;
try {
const { $to } = editor.state.selection;
const at = $to.depth >= 1 ? $to.after(1) : editor.state.doc.content.size;
editor.chain().focus().insertContentAt(at, {
type: 'action',
content: [{ type: 'text', text: answer }],
}).run();
setAnswer('');
} catch (err) {
console.error('[ai-assistant] insert failed', err);
setError('Could not insert the answer into the script.');
}
};
return (
<div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
<textarea
aria-label="Ask the assistant"
rows={4}
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="Ask about your script…"
/>
<label>
<input type="checkbox" checked={includeSelection} onChange={(e) => setIncludeSelection(e.target.checked)} />{' '}
Include the selected text
</label>
<button className="dialog-primary" onClick={ask} disabled={busy || !question.trim()}>
{busy ? 'Asking…' : 'Ask'}
</button>
{error && <p className="addon-error" role="alert">{error}</p>}
{answer && (
<>
<div style={{ whiteSpace: 'pre-wrap', border: '1px solid var(--fd-border)', padding: 8 }}>{answer}</div>
<button onClick={insert} disabled={!editor}>Insert into script</button>
</>
)}
</div>
);
};
export default AssistantPanel;
6. Register it
Add the add-on to CORE_ADDONS in frontend/src/addons/index.ts. Nothing else in the app changes.
import aiAssistant from './ai-assistant';
export const CORE_ADDONS: readonly OpenDraftPlugin[] = [
aiAssistant,
];
Testing Your Add-on
- Run the checks from
frontend/:npx tsc -b,npx eslint src/addonsandnpx vitest run. The boundary test runs with the rest. - Without a model installed, start the stand-in server:
venv/bin/python test-script/mock_ai_server.py, then usehttp://localhost:11435/v1as the server address. It logs each request, so you can see exactly what the add-on sent. - In the app, check that:
- with the add-on off, its menu item and panel tab are absent;
- turning it on shows the description, the privacy statement and your settings form, and that an invalid setting keeps the dialog open;
- the menu item opens the panel, and nothing reaches the script until the writer confirms;
- turning it off with Also delete its saved settings ticked removes the menu item, the panel and the stored settings.
Submitting a Pull Request
- One add-on per pull request, with no changes outside
src/addons/<id>/and the one line inCORE_ADDONS. If the add-on needs a new extension point, propose that in a separate pull request toplugins/registry.ts. - Include unit tests for the add-on's own logic, and screenshots of the turn-on dialog and the panel.
- Describe what leaves the device in the pull request, matching the
privacyline.