Building plugins
Votion ships a plugin framework that lets you add routes, sidebar regions, settings panels, database tables, access rules, MCP tools, REST endpoints and more without forking the app. Projects, Calendar, Contacts, CRM, Billing, Mail and Daily Notes — core-looking features — are themselves just bundled plugins built on this same framework, so everything described here is the real thing, not a restricted subset.
Trust model — read this before writing any code
A plugin runs fully trusted, in-process, with no sandbox. Once enabled, a plugin's entry.api module executes inside the same Node process as the rest of the API, with the same database credentials and the same privileges as core code. It is not isolated in a worker, a VM, or a separate container, and nothing in the framework checks what a plugin's code actually does once it runs.
The only security boundary is: only an instance admin can upload or enable a plugin (middleware.admin() on every /api/admin/plugins/* route). There is no per-hook permission prompt and no capability scoping yet — a plugin's declared hooks list in its manifest is informational only, shown on the admin screen, and is not enforced.
Practically: treat installing a plugin exactly like installing server software. Only install plugins you trust, and only an admin account should ever be able to reach the upload screen.
What a plugin is
A plugin is a zip file containing:
manifest.json
api/entry.js # optional — runs in the API process
web/entry.js # optional — runs in the browser
migrations/*.js # optional — this plugin's own schemaNothing is bundled or compiled. api/entry.js is loaded with Node's native import(), and web/entry.js is served as-is and loaded with the browser's native import() — there is no build step for either, and no package manager runs on your plugin's code at install time.
Manifest format
manifest.json sits at the root of the zip:
{
"id": "hello-plugin",
"name": "Hello Plugin",
"version": "1.0.0",
"description": "Framework smoke test — exercises most of the framework's hooks.",
"hooks": [
"route",
"sidebarSlot",
"pageOverlay",
"settingsPanel",
"schema",
"accessControl",
"mcpTool",
"apiRoute",
"searchTabs",
"pageData",
"pageLifecycle"
],
"entry": {
"api": "api/entry.js",
"web": "web/entry.js"
},
"migrationsDir": "migrations"
}| Field | Required | Notes |
|---|---|---|
id | yes | Lowercase slug: ^[a-z][a-z0-9-]{1,63}$. Becomes the key your data is namespaced under everywhere (plugin_data[id], /api/plugin-api/<id>/..., your own DB tables). |
name | yes | Non-empty display string, shown on the admin screen. |
version | yes | Semver, \d+\.\d+\.\d+ (e.g. 1.0.0). A bundled plugin (apps/api/plugins-bundled/) is only re-copied into storage when this version goes up, so bump it with every change to its files — otherwise a running instance keeps serving the old copy. |
description | no | Short, plain text: the admin screen and two lines in Settings › Plugins & Features. |
about | no | The long description for the About section of your settings page. A small Markdown subset, nothing else is interpreted: blocks separated by a blank line, a block of - lines is a list, **bold**, and [label](href) where href is https://… or a docs path starting with / (opened on the instance's docs site). |
setup | no | What an instance needs before members can use your plugin — a Setup section with a Ready / Not set up tag per item. { description?, items: [{ id, title, env?, steps?, readyHint?, notReadyHint? }], links?: [{ label, href }] }. An item is Ready when every env variable (uppercase names) is set on the API server; an item without env reads "No setup needed. Members connect their own accounts." steps ({ title, description? }, {webOrigin} is replaced by WEB_ORIGIN), env, description and links reach instance admins only; everyone else reads notReadyHint (default "<title> isn't set up on this instance yet.") plus "Ask an admin to set this up." |
requires | no | Ids of plugins this one builds on, e.g. ["contacts"] for the bundled CRM. In a workspace your plugin can only be switched on while each of them is on, and they can't be switched off while yours is on (the API answers 409 with "CRM needs Contacts. Turn on Contacts first."). If one of them is turned off anyway (on the instance), your plugin counts as off in every workspace: no routes, nav rows, MCP tools or hooks. Bundled plugins are installed after the plugins they require. |
hooks | no | Array of strings. Informational only — reserved for a future permission prompt, not enforced today. |
entry.api | no | Relative path to a module exporting register(api: PluginServerApi): void | Promise<void>. No leading /, no .. segments. |
entry.web | no | Relative path to one self-contained ES module exporting register(api: PluginWebApi): void. Served at GET /api/plugins/:id/web; this is the only file of your web bundle the browser can load — inline everything else you need. |
migrationsDir | no | Relative path to your migrations directory. Defaults to migrations. |
devSeed | no | Sample data for development: { "entry": "api/dev_seed.js", "after"?: ["crm"] }. entry is a relative path to a module exporting seed(ctx); after lists plugins whose seed runs first when they are seeded too. Never runs in production — see Development seed data. |
shortcuts | no | Keyboard shortcuts your web half handles: [{ "id": "go", "label": "Go to Projects", "chord": { "mod": true, "alt": true, "key": "P" } }]. id is a lowercase slug, unique in the manifest; the full id is <pluginId>.<id> (e.g. projects.go). chord needs "mod": true (Cmd on macOS, Ctrl elsewhere) plus optional shift / alt and a key of 1–10 characters. chord is optional: leave it out (or set it to null) for a shortcut with no default binding, e.g. { "id": "go", "label": "Go to Notes" } — Settings › Keyboard shortcuts shows it as — with a Record link, and it only fires once a member records a combination. While your plugin is installed and enabled, the shortcut is listed in Settings › Keyboard shortcuts, members can remap it (PATCH /api/auth/me/shortcuts with shortcutId: "projects.go") and the collision check counts it. GET /api/plugins returns it as shortcuts: [{ id: "projects.go", label, chord }] (chord: null when it has no default). Remaps of a shortcut that no longer exists are ignored and dropped on the member's next remap. |
translations | no | The manifest's texts in other languages, by language code. Every field is optional; anything left out reads in English. { "de": { "name": "Kalender", "description": "…", "about": "…", "setup": { "description": "…", "items": { "<item id>": { "title"?, "readyHint"?, "notReadyHint"?, "steps"?: [{ "title", "description"? }] } }, "links": { "<href>": "<label>" } }, "shortcuts": { "go": "Gehe zu Kalender" } } }. Settings › Plugins & Features, the permissions panel and Settings › Keyboard shortcuts show them in the interface language; steps replace the English steps one for one. GET /api/plugins answers with names and shortcutLabels (by full shortcut id) per language, so a language switch needs no reload. |
A plugin needs neither entry — a pure-data plugin with only migrations and no hooks is valid — but most plugins ship at least one.
The reference implementation: hello-plugin
apps/api/plugins-examples/hello-plugin/ is the framework's own smoke test. It exercises most of the hooks below end to end: every web-side route, sidebar-slot, page-overlay, settings-panel and open-route hook, and the server-side access-control, MCP tool, API route, search-scope, page-data (single and bulk), page-lifecycle, listing-open-route, permissions and view-action hooks. It does not register the four row-level write guards, the scheduled-job hook, the preset hook, or the web-side nav-item, database-toolbar-slot and workspace-toggle hooks — those are illustrated below from the bundled plugins (Projects, Billing, Daily Notes …) or with generic snippets instead, named at each one. Most code snippets on this page are copied verbatim from hello-plugin's api/entry.js and web/entry.js — copy that directory as your starting point rather than starting from nothing.
entry.web — browser-side hooks
entry.web's register(api) is called once per page load, after apps/web/src/plugins/loader.ts dynamically import()s your bundle. Your module does not import 'vue' — it reads window.__votionVue instead, so your components share the host app's one Vue instance:
export function register(api) {
const { h } = window.__votionVue
// ...
}window.__votionHost — the browser host API
window.__votionVue is Vue itself — h, ref, computed, every other named export of the vue package, nothing app-specific. window.__votionHost is a second, deliberately small global sitting next to it: a hand-picked set of the host app's OWN already-loaded components, composables, stores and lib helpers, exposed so a plugin can build a full page surface that looks and behaves like a real Votion page instead of reimplementing any of this from scratch (the bundled plugins are the real examples — their screens lean on the V* UI kit (VButton, VSelect, VCardDialog …), usePageChrome, and the spaces/session/pages stores, all read off this object). It is populated once per page load, before any plugin's entry.web can run, the same ordering guarantee window.__votionVue gets.
Every member is a REFERENCE to the host app's own existing instance, not a copy bundled into your plugin — exactly the same "one shared copy, not two" reasoning window.__votionVue itself follows. Check host?.version (currently '1.1.0') before relying on a member, the same way you'd defensively check for any optional browser API; it only bumps on a breaking change to an existing member's own signature, never for an addition.
const host = window.__votionHost
const { PageHeader } = host.components
const { useComments } = host.composables
const { useSession } = host.stores
const { apiRequest } = host.lib| Group | Members |
|---|---|
components | PageEditor, PageHeader, PageView, DatabasePage, CellEditorSheet, EmojiGlyph, RouterLink |
composables | useComments, useIsDesktop, useHasCommentMargin, usePageChrome, usePageVimNav, startPageCollab, useSidebarSection |
router | useRouter |
stores | usePages, useSession, useSpaces |
lib | apiRequest, ApiError, authHeader, getAuthToken, docToText |
constants | MD_QUERY, COMMENT_MARGIN_QUERY |
Since 1.1.0 the same object also carries every export of @votion/host (below) at its top level (host.VButton, host.useSpaces), and three members for the plugin machinery: injectStyle(id, css) (one <style> per plugin, replaced on a second call; SDK bundles call it themselves), extensions and services. The groups above stay for existing plugins. Nothing else is on it: plugins, bundled ones included, offer their parts through services and extensions, never as members of their own on window.__votionHost. The per-plugin members bundled plugins used to read (host.contacts, host.calendar, …) were never part of this API and are gone; the documented members did not change, so version stays '1.1.0'.
PageEditor is the real TipTap/ProseMirror editor plus its Yjs/Hocuspocus collab wiring, and startPageCollab is the composable that drives it — reimplementing either inside a plugin bundle would run a second, independent ProseMirror schema and a second Yjs client against the same document, which corrupts collaborative state rather than merely wasting memory the way a second Vue copy would. RouterLink and useRouter are the host app's own already-injected vue-router instance, not a second router a plugin would otherwise have to bundle itself. apiRequest / ApiError / authHeader / getAuthToken are the same fetch wrapper core code uses to call the REST API — reach for these from a plugin component instead of hand-rolling fetch() and reimplementing auth-header handling.
Building entry.web with the plugin SDK
A plain entry.js like the one above works, and is all hello-plugin needs. For a plugin with Vue single-file components, TypeScript and Tailwind classes, write the source under web/src/ and let the plugin SDK (apps/web/plugin-sdk/) build it into the one file the API serves. Every bundled plugin with a UI (Calendar, Contacts, CRM, Mail, Projects, Billing) is built this way, so a third-party plugin built with the SDK gets exactly what they get. hello-plugin keeps a plain entry.js; Daily Notes has no web half at all (it only ships a preset).
my-plugin/
manifest.json "entry": { "web": "web/dist/entry.js" }
web/src/index.ts export function register(api) { … }
web/src/style.css the plugin's stylesheet (below)
web/src/types.ts what other plugins may import, type-only
web/src/**/*.vue components// web/src/index.ts
import { useSpaces, VButton, type PluginWebApi } from '@votion/host'
import './style.css'
import MyPage from './MyPage.vue'
export function register(api: PluginWebApi): void {
api.registerRoute({ path: 'my-plugin', name: 'my-plugin', component: MyPage })
}Build it from apps/web (inside the web container):
npm run build:pluginsbuilds everyplugins-bundled/*/web/src/index.tsintoweb/dist/entry.js;npm run build:plugins -- calendarbuilds one,-- --dir <path>builds the plugins in another directory (your own).npm run dev:pluginsrebuilds on every change (theweb-pluginscompose service runs it); reload the page to pick the new bundle up.- A plugin with its own
vite.config.jscanexport default definePluginConfig({ id, root })fromapps/web/plugin-sdk/index.mjs.
What the build does:
vue,vue-router,piniaand@votion/hoststay out of the bundle. Each import becomes a read offwindow.__votionVue,window.__votionVueRouter,window.__votionPiniaorwindow.__votionHost, so your components share the app's one Vue, one router, one Pinia and one toast queue. Import the package itself, never a subpath (vue/dist/…fails the build).@votion/testis for specs only and fails the build too. Every other dependency (icons, date helpers) is bundled into yourentry.js.- Everything is one file. Dynamic imports and assets are inlined; the API serves only
entry.js. - Styles are scoped and injected. See Styling below.
web/dist/ is build output: it is git-ignored, the Docker image and CI build it, and the API answers GET /api/plugins/<id>/web with 404 (and logs "run npm run build:plugins") while it is missing. The upload route takes a built zip, so ship web/dist/entry.js in it; web/src/ may stay out.
@votion/host — the host API as a module
@votion/host is window.__votionHost as named imports. In the bundle it is the virtual module described above; in vitest and vue-tsc it resolves to apps/web/src/plugins/sdk/host.ts, so specs run against the real components and the type checker knows every prop. The list is the public API: additions only, and every name is listed here.
| Area | Exports |
|---|---|
| UI kit | VAddressField, VBanner, VButton, VCardDialog, VCheckbox, VDialog, VEmptyState, VIconButton, VInlineError, VPopoverSheet, VRadioCard, VScopeChip, VSearchField, VSelect, VShareRow, VSheetHeader, VSwitch, VTag, VTooltip; isSelectMenuOpen, SELECT_MENU_ATTR, VSELECT_SEARCH_THRESHOLD; TOUCH_BUTTON_PHONE, TOUCH_BUTTONS, useTouchButtons |
| Shared components | CellEditorSheet, DatabasePage, EmojiGlyph, MoveToPicker, PageEditor, PageHeader, PageView, PickerOverlay, PluginEmptyState, PluginNavRow, PluginPhoneHeader, RedirectStatus, ShareAccessMenu, ShareDialog, SpaceBadge, SpaceIcon, TimeZoneList, UserAvatar |
| Settings rows | PermissionRow, SettingsAccountRow, SettingsLockedValue, SettingsRow, SettingsSection, SetupStep |
| Database pieces | ChartView, ConfirmDialog, DatabaseTable, MonthCalendar, PropertyValue, SettingsChoiceList, SettingsPanelHeader, ViewSettingsRow (a view-settings row, not Settings › SettingsRow), SettingsToggleRow, ViewIconButton, ViewTypePicker |
| Database helpers | todayDateString, chipClass, memberDisplayName, optionsOf, todayIso, addDaysIso, daysBetween, moveRange, resizeRange, snapToDays, dateEndDay, dateStartDay, deviceTimeZone, parseTypedTime, timeZoneOffsetLabel, withDays, usesPropertyValue, PROPERTY_TYPE_LABELS, propertyTypeIcon, isRestricted, RELATED_PAGES, relationIdsOf, useSettingsPanelFrame, VIEW_TYPE_ICON, VIEW_SCOPE |
| Composables | useAnchoredPanel, useComments, COMMENT_MARGIN_QUERY, MD_QUERY, useHasCommentMargin, useIsDesktop, startPageCollab, usePageChrome, usePageOverlay, usePageVimNav, PHONE_HEADER_TARGET, usePhoneHeader, usePluginSettingsSubpage, useResponsiveColumns, useSettingsModal, useSidebarSection, showToast, useToasts, useTopRightAnchor |
| Stores | usePages, useSession, useSpaces |
| Lib | addSchemaChangeInterceptor, ApiError, apiRequest, authHeader, getAuthToken, SchemaChangeCancelled, schemaChangeOf, APP_META, standaloneReturnUrl, addressLabel, plainAddress, toAddressValue, docsUrl, docToText, EVENT_TONES, resolvePageRoute, useTimeZone, useWeekStart |
| Translations | registerMessages, useI18n, locale, LANGUAGES, intlLocale, formatDate, formatNumber, formatCurrency, catalogProblems (see Translations) |
| Plugin framework | registerPageSection, extensions, services, plugins (activeInSpace(id), setSpaceDisabled(ids)) |
VTooltip is core's hover/focus label: wrap one trigger element, <VTooltip label="…"><button …/></VTooltip>. It shows below the trigger by default; placement="left" puts it beside the trigger (the reason a disabled menu item is off), gap sets the distance in px. It never shows on touch, so a phone sheet states such a reason as text instead.
VAddressField is the Address field: an input with Google Places suggestions ("Powered by Google") that falls back to plain text when the workspace has no Google Maps key (Settings › Integrations) or Google fails. The key stays on the server; the field asks /api/spaces/:id/places/*, so your plugin needs no key and no network code of its own. Bind it with v-model to an AddressValue | null:
interface AddressValue {
label: string // always: the address as shown, or the text as typed
lat?: number // lat and lng come together, from a pick or a location
lng?: number
placeId?: string // Google's place id of a picked suggestion
parts?: {
street?: string
houseNumber?: string
postalCode?: string
city?: string
region?: string
country?: string
countryCode?: string // ISO 3166-1 alpha-2
}
}The database Place property stores the same shape, so a value can move between a plugin field and a Place cell unchanged. Store it as JSON in your own table; toAddressValue(raw) reads it back (a bare string from an older text column becomes { label }), addressLabel(raw) gives the text to show, plainAddress(text) builds a typed value. Props: spaceId (defaults to the current workspace), id, label (accessible name, default "Address"), placeholder (default "Search address…"), disabled. Typing without picking saves { label } on blur or Enter; the × clears to null.
<script setup lang="ts">
import { ref } from 'vue'
import { VAddressField, type AddressValue } from '@votion/host'
const address = ref<AddressValue | null>(null)
</script>
<template>
<label for="client-address" class="text-caption text-ink-secondary">Address</label>
<VAddressField id="client-address" v-model="address" />
</template>useResponsiveColumns(container, columns, { nameMin, gap, reserve }) is the list-column rule every fixed-column list follows (Notion's): the Name column keeps at least nameMin px (default 200), and when the list is narrower than Name plus every column, the columns with the highest priority drop first — equal priorities from right to left. columns is { id, width, priority, minRow? }[] (width in px, lower priority stays longer; minRow keeps a column — and every column that drops before it — out of rows narrower than that many px, for a frame that drops it before the rule would); gap is the space each column adds, reserve what the row needs besides (padding, a trailing ⋯). A ResizeObserver on container (a template ref of the list) drives it, so it follows the sidebar, a docked panel and the window. It returns visible (the ids that fit, in the given order), shows(id) and gridTemplate (minmax(0,1fr) plus the visible widths, for grid-template-columns; append a trailing column yourself). Until the list is measured every column shows. The phone layout (a meta line under the name) is the list's own; database table views scroll sideways instead.
<script setup lang="ts">
import { ref } from 'vue'
import { useResponsiveColumns } from '@votion/host'
const list = ref<HTMLElement>()
const columns = useResponsiveColumns(
list,
[
{ id: 'status', width: 120, priority: 1 },
{ id: 'updated', width: 100, priority: 2 },
],
{ gap: 12, reserve: 20 },
)
</script>
<template>
<div ref="list">
<div v-for="row in rows" :key="row.id" class="grid gap-3 px-2.5"
:style="{ gridTemplateColumns: columns.gridTemplate.value }">
<span>{{ row.name }}</span>
<span v-if="columns.shows('status')">{{ row.status }}</span>
<span v-if="columns.shows('updated')">{{ row.updated }}</span>
</div>
</div>
</template>Types travel with it (PluginWebApi, PropertyDef, RowData, PageMeta, VSelectOption, CalendarColor, ServiceMap, ExtensionPoints, …); see sdk/host.ts for the full list.
Specs import test helpers from @votion/test (testId, openSelect, pickOption, pluginRegistry, createPluginWebApi, extensions, services, exposeHostApiForPlugins, …; apps/web/src/plugins/sdk/test.ts).
Translations: registerMessages and useI18n
Core and every plugin share one message catalog. Each plugin owns a namespace — its plugin id — and ships its strings as plain objects: English is the source, other languages translate a subset, and any key a language lacks reads in English. The interface language is the user's own (Settings › Appearance › Language), else the workspace's (Settings › General), else English; it can change while your screens are open, and t is reactive, so templates and computeds follow it. Bundled plugins use exactly this API.
// web/src/messages.ts
export const messages = {
en: {
pipeline: { title: 'Pipeline', empty: 'No deals yet.' },
leads: { one: '{count} lead', other: '{count} leads' },
},
de: {
pipeline: { title: 'Pipeline', empty: 'Noch keine Deals.' },
leads: { one: '{count} Lead', other: '{count} Leads' },
},
}// web/src/entry.ts — register once, before your screens render
import { registerMessages } from '@votion/host'
import { messages } from './messages'
registerMessages('my-plugin', messages)<script setup lang="ts">
import { useI18n } from '@votion/host'
const { t, formatDate } = useI18n('my-plugin')
</script>
<template>
<h1>{{ t('pipeline.title') }}</h1>
<p>{{ t('leads', { count: rows.length }) }} · {{ formatDate(updatedAt, { dateStyle: 'medium' }) }}</p>
</template>registerMessages(namespace, { en, de?, … })adds or replaces your catalogs (merged per language).coreis reserved.useI18n(namespace)returnst(key, params?),locale(the active code, read-only),intlLocale()and the formatters.{name}in a message is filled fromparams; a message written as{ one, other }(pluszero,few, … if a language needs them) is a plural picked byparams.count.formatDate(value, options?),formatNumber(value, options?)andformatCurrency(value, currency, options?)format in the interface language's locale.intlLocale()gives the BCP 47 locale for your ownIntlcalls. Time zone and week start stay withuseTimeZoneanduseWeekStart.LANGUAGESlists the languages Votion has a catalog for (code, its ownname,intl). A language your plugin does not translate yet shows your English.- Never translate what people typed — page titles, database and option names, record values. Pass them in as params.
- Lint your catalogs in a spec:
expect(catalogProblems(messages)).toEqual([])fails on a key English lacks, other placeholders than English, or a plural only one language has.
Text you hand the host once at registration — registerNavItem's and registerSettingsPanel's label, registerSpaceToggle's label / description / section, registerViewType's label / hint, registerPropertyType's hint — may be a function instead of a string (label: () => t('nav.label')). The host calls it on every render, so your sidebar row and settings name follow a language switch without a reload; a getter (get label() { return t('nav.label') }) works the same way. A plain string is read once and stays as it is.
Core's own strings and the German glossary are described in Translations. Mails, notifications and other text your api half writes for people use the server half: Translations on the server.
Styling
web/src/style.css is compiled with Tailwind against the app's theme, so the app's tokens and utilities (bg-surface, text-ink-secondary, menu-item, the dark: and phone: variants) mean the same in your components:
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities) source(none);
@import '@votion/sdk/theme.css';
@source './';The build scopes the result to your plugin: every element of your templates that has a class gets data-vp="<plugin id>", and every utility selector only matches inside it (.p-4:where([data-vp="calendar"])). The CSS is inlined into entry.js and handed to window.__votionHost.injectStyle(id, css) when the module loads, before register() runs; a rebuild replaces the plugin's one <style> element. What that means for you:
- Your classes never restyle core or another plugin, and theirs never depend on yours.
- A class you pass to a host component (
<VButton class="ml-2">) still works: the attribute goes through to its root element. - A class you set from script (
el.classList.add) or in a string the host renders for you lacks the scope attribute and stays unstyled. Bind classes in templates. - The utilities layer is scoped; the theme layer (CSS variables) is not emitted twice, it is the app's.
Control sizes and the touch: variant. Every control — text input, select, button, icon button — is at least 44px tall on a touch screen from the tablet up (icon buttons get a 44 × 44 hit area); phones (below 48rem) already use 44. A mouse at any width keeps the desktop size. The theme's touch: variant matches exactly that case: width ≥ 48rem and a coarse pointer (@media (width >= 48rem) and (pointer: coarse)), never width alone. Write the desktop size and add the touch height next to it:
<input class="h-8 w-full rounded-md bg-input px-2.5 max-md:h-11 touch:h-11" />
<button class="inline-flex size-7 items-center justify-center touch:size-11">…</button>Use the same property as the desktop class (h-* → touch:h-11, min-h-* → touch:min-h-11, size-* → touch:size-11), grow a fixed-height wrapper with it, and leave label size and padding alone. The host components (VButton, VIconButton, VSelect, VSearchField, VCheckbox, VSwitch) and the menu-item / menu-input / menu-select utilities already do this. A menu-* class with your own lg:min-h-* override needs touch:min-h-row-touch (or touch:min-h-11) next to it, since your lg: class sorts after the utility's touch rule. Search fields are controls too — the sidebar's included, they are 44px on touch. Exceptions: list and table rows, calendar/grid cells and inline in-cell editing keep their drawn sizes; colour swatches and cover/preset tiles stay small but at least 32px on touch (md:size-7 touch:size-8 on a 44px phone swatch), with their grid gaps unchanged; and touch: never matches inside the docked View settings panel (.votion-dock), which keeps desktop sizes on tablets.
Services and extension points — plugins working together
A plugin never imports another plugin's code. Two registries in the host carry everything plugins offer each other, and both are typed by declaration merging from the offering plugin's web/src/types.ts:
- Services — one object per plugin, for calls.
api.provide(service)in yourregister()offers it under your id; others callservices.get('<id>')(undefined while that plugin is off or not loaded yet) orservices.whenProvided('<id>', cb)(returns a cancel). Look it up when you need it, never at import time. - Extension points — lists an owner renders, for contributions.
api.registerExtension(point, entry)addsentry(id, optionalorder, lower first, default 100, plus the point's own fields) under your id and returns the undo; the sameidagain replaces the entry. The owner readsextensions.list(point), which is reactive and only holds entries of plugins that are on in the current workspace (extensions.all(point)ignores the switch).
// calendar/web/src/types.ts — what Calendar offers
export interface CalendarService { openEventEditor: … }
declare module '@votion/host' {
interface ServiceMap { calendar: CalendarService }
}
// another plugin
import type {} from '@votion-plugin/calendar/types' // types only
import { services } from '@votion/host'
await services.get('calendar')?.openEventEditor({ title: 'Review' })@votion-plugin/<id>/… resolves to that plugin's web/src/ for the type checker; importing a value from it is a lint error (votion/plugin-boundary), so the bundle never contains another plugin's code. The same rule keeps a plugin's relative imports inside its own web/src/.
Services offered today:
| Id | Members |
|---|---|
calendar | openEventEditor(prefill) — the full event editor, prefilled; resolves with the created event or null |
contacts | searchContacts(spaceId, q, { scope?, limit? }) — the workspace's contacts plus the member's own private ones; contactEmailSuggestions(spaceId, q, limit?) — { name, email } per address of those contacts; shareContact(spaceId, contactId, mode?) — makes a private contact a workspace contact ('keep_syncing' or 'copied'); initialsOf(contact), roleLine(contact); ContactAvatar (props initials, color?, size? 24/32/40/72, tile?) and SourceBadge (prop source) — components to render with <component :is>, without a class (wrap them instead, so they keep Contacts' styles). Types: @votion-plugin/contacts/types (ContactsService, Contact, …) |
projects | ensureArea() — loads the workspace's Projects area; isAreaTask(databaseId) — whether that is the area's Tasks database (false, and starts loading, until the area is there); NewProjectDialog (prop onCreated?(projectId), emits close; call ensureArea() first) and ProjectBadge (props title, color?, size?) — components to render with <component :is> |
mail | canCompose(spaceId) — whether the member has a mailbox there; compose(to) — opens a new mail to [{ name, email }] (then navigate to /mail); unreadCount(spaceId) — the Inbox's unread count |
Extension points offered today (the owner renders them; entries show only while their plugin is on):
| Point | Owner | Entry fields |
|---|---|---|
contacts.contactSection | Contacts › a contact's page, right column | component (props contact, spaceId) |
crm.customerSection | CRM › a customer's page | column? ('side'/'main'), component (props customer, spaceId) |
crm.customerAction | CRM › page head buttons | label, primary?, run(customer, { spaceId, anchor, router }) |
crm.customerField | CRM › New/Edit customer dialog | component (props customer, spaceId; may expose afterSave) |
crm.customerProjectLine | CRM › a customer's project rows | rows(projects, { spaceId, customer }) → { [projectId]: { subline, budget, hours, amount } | null }, lowest order wins per project |
projects.subline | Projects › All projects | label(projectId), summary?(activeIds), load?() |
projects.overviewBlock | Projects › a project's overview, after the metric cards | component (props projectId, projectTitle) |
projects.settingsTab | Projects › project settings | label, component (props projectId, projectTitle, narrow; emits close) |
gantt.sprints | core Gantt view | sprint bands for a database (apps/web/src/database/views/viewExtensions.ts) |
workload.context | core Workload view | areas, capacity and its panel (same file) |
Server-side extension points: registerExtension(point, entry) and extensions(point, spaceId)
The API process has the same pattern for services a plugin offers other plugins' server code. The owner of a point names it, documents the entry shape and reads it; any plugin — bundled or third-party — fills it. No plugin imports another, and load order does not matter.
api.registerExtension(point, entry)addsentry(id, optionalorder, lower first, default 100, plus the point's own fields — usually functions) under your plugin's id and returns the undo. The sameidat the same point again replaces the entry. Call it inregister().await api.extensions(point, spaceId)returns the entries of every plugin that is on in that workspace, lowestorderfirst, each with itspluginId. While the offering plugin is off (in the workspace or on the instance) its entries are left out, so an empty list is the consumer's cue to fall back to its own behaviour. Ask on every request, never cache the list, and treat an entry that throws as absent.
// the offering plugin — api/entry.js
export function register(api) {
api.registerExtension('contacts.companySource', {
id: 'my-plugin.companies',
label: 'My CRM',
order: 20,
available: async (spaceId, userId) => true,
search: async (spaceId, userId, q, limit) => [],
// … the rest of the point's fields
})
}
// the owner of the point
const [source] = await api.extensions('contacts.companySource', spaceId)
const options = source ? await source.search(spaceId, userId, q, 20) : [] // [] = free textServer-side points offered today:
| Point | Owner | Entry fields |
|---|---|---|
contacts.companySource | Contacts › a contact's Companies field | label ("CRM companies"), available(spaceId, userId) → boolean, companiesOf(spaceId, userId, contactIds) → Map<contactId, [{ id, name, role, archived?, href }]>, search(spaceId, userId, q, limit) → [{ id, name, detail, href }], create(spaceId, userId, name) → { id, name, href }, setCompanies(spaceId, userId, contactId, companyIds) (links exactly these; links that stay keep their role). The first source whose available answers true wins; without one, companies are free text. CRM's crm.companies is the worked example (plugins-bundled/crm/api/companies.js). |
registerRoute(route: RouteRecordRaw)
Registers a Vue Router route (merged into the app's router). Give it a component and, if other hooks need to key off it, a name:
const HelloPage = {
name: 'HelloPluginPage',
render() {
return h('div', { class: 'p-6', 'data-testid': 'hello-plugin-page' }, [
h('h1', { class: 'text-h2 font-semibold text-ink' }, 'Hello Plugin'),
h('p', { class: 'mt-2 text-ui-sm text-ink-secondary' },
'This route, this sidebar region, and this page are all registered by a plugin.'),
])
},
}
api.registerRoute({ path: '/hello-plugin', name: 'hello-plugin', component: HelloPage })registerSidebarSlot(matches, component)
Swaps the sidebar's page-tree scroll region for your own component while matches(route) is true for the current route — the same "swap, don't remove the chrome around it" contract every plugin-owned sidebar region should follow. With { replacesNav: true } the shortcuts zone steps aside as well, but the quick nav (Home, every plugin's nav row, Trash) always stays on top with a divider under it, so your sidebar starts with its own title and needs no way back to Home:
const HelloSidebar = {
name: 'HelloPluginSidebar',
render() {
return h('div', { class: 'p-3 text-ui-sm text-ink-secondary' },
'Hello Plugin sidebar slot.')
},
}
api.registerSidebarSlot((route) => route.name === 'hello-plugin', HelloSidebar)registerPageOverlayHook(fn)
fn(page) => { badge?, badgeIcon?, breadcrumb?, locked?, hideComments?, lockMessage?, notice? } | null. Called for every page opened in the editor overlay; return null/ undefined for pages you have nothing to say about. This is display/UX only — pair it with the server-side registerAccessControlHook below for real enforcement:
api.registerPageOverlayHook((page) => {
if (typeof page.title !== 'string' || !page.title.includes('[locked]')) return null
return { badge: '👋 Hello Plugin', locked: true }
})badge is a short label shown as a pill above the page title; badgeIcon (optional, an emoji such as '✅') is shown in front of it. locked: true makes the editor read-only and shows a lock banner; lockMessage overrides its default copy, and hideComments: true hides the comments button/section independently of locked. notice: { title, message, action?: { label, run } } shows an info banner above the page without locking anything (Projects' "You can view this project · Request access"). The page object also carries access (the caller's level: full, edit, comment, view) and pluginData (the page's plugin_data, keyed by plugin id) to decide on. breadcrumb: { crumbs: [{ label, to, icon? }], typeLabel?, typeIcon? } replaces the page-tree ancestors in the full page's top bar with your own links, followed by the page's title and a type badge (which then takes the place of badge above the title). On a phone the bar shows only the type badge and the last crumb. Projects uses it for "Projects / Votion 1.0 / Block editor 2.0".
registerPageOpenRouteHook(fn)
fn(page) => { name, params } | null. Resolves where page should navigate to, for every call site that opens a page by its own metadata (the sidebar tree, search results, Home's recently-changed list, ...) instead of the generic /p/:pageId viewer. Return null/undefined for a page you don't claim. page carries an openAs field when the matching server-side registerPageListingOpenAsHook (below) already attached one for this page — read it, or compute your own destination from any other field on page; both are valid (hello-plugin's own web/entry.js has a worked example of each):
// Reading the server's own openAs contribution:
api.registerPageOpenRouteHook((page) => {
if (!page.openAs) return null
return { name: page.openAs.route, params: page.openAs.params ?? {} }
})
// Or computing your own destination purely client-side:
api.registerPageOpenRouteHook((page) => {
if (typeof page.title !== 'string' || !page.title.includes('[hello-route]')) return null
return { name: 'hello-plugin', params: {} }
})A database page always opens its table view regardless of this hook — no plugin can claim that. The first registered hook to return a non-null result wins, same "first match wins" rule registerPageOverlayHook already uses.
registerSettingsPanel({ id, label, component, ownHead?, description?, banner? })
Adds your plugin's settings page. It is a sub-page of Settings → Workspace → Plugins & Features, not a navigation entry: your row in the list gets a Settings button, and the page opens under a "Plugins & Features / Your plugin" breadcrumb. The host draws the head — your plugin's name, version, Disable and "Settings of the … plugin for this workspace." — and renders component below it (after any workspace toggles). Pass ownHead: true when your component draws its own title and description (the bundled Billing page does); the host then draws only the breadcrumb. description replaces the default line under the title with your own (the bundled Projects page says who may change its settings). It can also be a function (space) => string that gets the current workspace ({ id, name }, or null) — the bundled Mail page uses it to name the workspace. banner: { title, body? } draws an Info banner under that line, above About — the bundled CRM uses it for "Required plugin: Contacts". Deep links still work by panel id: openSettings('hello-plugin').
api.registerSettingsPanel({
id: 'hello-plugin',
label: 'Hello Plugin',
component: HelloSettingsPanel,
})label may be a function (() => t('plugin.name')) so the name follows the interface language — see Translations.
registerNavItem({ label, to, icon, testid, visible?, isActive?, count?, meta? })
Adds a row to the sidebar's quick nav (Home, the plugin rows, Trash, in AppShell.vue). With more than three entries the quick nav shows the first three plus the current section and collapses the rest under "More", so isActive matters: the active row is always shown. icon is a Vue component you render yourself — entry.web has no bundler, so you cannot tree-shake an icon library import; inline a small render function instead:
api.registerNavItem({
label: 'Hello Plugin',
to: '/hello-plugin',
icon: HelloIcon,
testid: 'sidebar-hello-plugin',
isActive: () => activeSection.value === 'hello-plugin',
})visible/isActive are re-evaluated on every render; omit either to always show the item / never highlight it. label may be a function too (label: () => t('nav.label')), re-read on every render, so the row follows a language switch.
A row can show something on its right, like the sidebar's Mail and Calendar rows do:
count: () => number— a number in faint meta text (Mail's unread count).0shows nothing, 100 and more read 99+; it never cuts.meta: () => string— a short text ("10:00 Design review", "2 leads"). It takes at most half the row and ends in "…" when it doesn't fit; the label never shrinks below 64 px.''shows nothing.
Both are re-evaluated on every render; count wins when you set both.
shortcut: 'go' binds one of your manifest's shortcuts (by its id) to the row: pressing it opens to. The row's icon is also your plugin's icon in front of its section in Settings › Keyboard shortcuts, unless you register one with registerIcon.
registerShortcutTarget(shortcut, to)
Binds one of your manifest's shortcuts to a path when your plugin has no nav row to bind it through, e.g. a shortcut that opens one of your plugin's own routes:
api.registerShortcutTarget('go', '/notes')No bundled plugin uses it today — each binds its shortcut through its nav row's shortcut: 'go'.
registerIcon(icon)
Your plugin's own icon, a Vue component like a nav row's icon. Core draws it 16 px, in the secondary text colour, in front of your section's title in Settings › Keyboard shortcuts. Optional: without it, the icon of your nav row is used (the one your shortcut opens, else the first); with neither, the section has no icon.
registerSpaceToggle({ label, testid, description?, section?, checked, onToggle, error? })
A plugin's own workspace-level on/off switch, drawn as a switch row on that plugin's settings sub-page of Settings → Workspace → Plugins & Features (a plugin with a toggle gets the Settings button even without a panel), under the section heading when given. Only the workspace's owner/maintainer can flip it. Reach for this when your plugin has a workspace-scoped on/off concept (no bundled plugin registers one today):
const { apiRequest } = window.__votionHost.lib
const lockBySpace = reactive({}) // spaceId -> boolean, loaded from your own settings route
api.registerSpaceToggle({
label: 'Lock archived notes',
testid: 'settings-feature-toggle-my-notes',
section: 'Notes',
description: 'Makes every archived note read-only for everyone in this space.',
checked: () => lockBySpace[useSpaces().current?.id] === true,
onToggle: async () => {
const spaceId = useSpaces().current?.id
if (!spaceId) return
const next = await apiRequest(`/api/plugin-api/my-notes/spaces/${spaceId}/settings`, {
method: 'PUT',
body: JSON.stringify({ lock_archived: lockBySpace[spaceId] !== true }),
})
lockBySpace[spaceId] = next.lock_archived
},
error: () => '', // non-empty shows an Error banner on the sub-page
})The switch's state is the plugin's own: keep it in your own table (migrationsDir) behind your own GET/PUT settings route (registerApiRoute) — core stores nothing for it.
checked and error are re-evaluated on every render, the same imperative-call contract visible/isActive above already use — error's non-empty return shows as an Error banner on the sub-page. description is optional: it sits under the label and is what the Settings search matches instead of the generic "Plugin vX.Y.Z." text. Most plugins never register this at all — most plugins have no workspace-level toggle, only the instance-admin enable/disable control every plugin row already gets for free.
Plugin-owned schema (migrationsDir)
Your migrationsDir holds plain Lucid migration files — the same up()/down() class shape node ace migration:run already uses for core migrations, run through the real MigrationRunner:
// migrations/1700000000000_create_hello_plugin_notes_table.js
import { BaseSchema } from '@adonisjs/lucid/schema'
export default class extends BaseSchema {
tableName = 'hello_plugin_notes'
async up() {
this.schema.createTable(this.tableName, (table) => {
table.uuid('id').primary().defaultTo(this.raw('uuid_generate_v7()'))
table
.uuid('user_id')
.notNullable()
.references('id')
.inTable('users')
.onDelete('CASCADE')
table.text('message').notNullable()
table.timestamp('created_at').notNullable()
})
}
async down() {
this.schema.dropTable(this.tableName)
}
}Rules that matter:
- Ids are UUIDs. Every core id is a UUIDv7 string, so a column pointing at a core row is
table.uuid(...), neverinteger. Give your own tables the sameuuid_generate_v7()default core uses, and treat ids as opaque strings: never parse, compare or sort them as numbers. - Your own tables only. Foreign-key into core tables (
pages.id,users.id, …) — never add a column onto a core table. Core's schema is not yours to change. - Tracked in a shared
plugin_schema_migrationstable, never core'sadonis_schema— your migration file's recorded name already embeds your plugin's directory, so two plugins' migrations can't collide. - Migrations run on install (
up) and on uninstall (down, every batch this plugin ever ran) — not on enable/disable. Disabling a plugin leaves its tables and data in place; only removing it rolls the schema back. - If your table needs to track something like a core page's
trashed_at(e.g. for a partial unique index your own table can't express against a core column), seeregisterPageLifecycleHookbelow — that is the one way a plugin learns a core page was trashed or restored.
entry.api — server-side hooks
entry.api's register(api) is called once, the first time your plugin is enabled in a given process's lifetime (not re-run on every request, and not re-run just because the plugin was disabled and re-enabled without a process restart):
export async function register(api) {
// ...
}Plugins per workspace — api.isEnabledInSpace(spaceId): Promise<boolean>
An instance admin installs and enables a plugin for the whole instance; each workspace's owner or a maintainer can then switch it off for their workspace under Settings › Plugins & Features (stored in space_plugins, no row = on). While it is off in a workspace, the host skips the plugin there on its own: page data and bulk page data hooks, the listing "open as" hook, view actions and plugin property types, and in the browser its nav items, sidebar and top-bar slots, settings panel, database toolbar slots, page overlays, open routes and empty states. Your own registerApiRoute handlers, MCP tools and scheduled jobs are not workspace-scoped by the host — call api.isEnabledInSpace(spaceId) before touching a workspace's data.
registerAccessControlHook(fn: (page) => Promise<boolean | { message: string }>)
Returning true or { message } locks page for writes; false leaves it alone. Every enabled plugin's hook is checked (the first lock wins), and the same result gates both the REST write path and the realtime collab-auth path — a plugin's lock can't be forgotten on one of the two:
api.registerAccessControlHook(async (page) => {
if (typeof page.title !== 'string' || !page.title.includes('[locked]')) return false
return { message: 'This page is locked by Hello Plugin.' }
})What a lock does:
GET /api/pages/:idstill answers and carriesplugin_lock: { plugin_id, message }(nullwhen no plugin locks the page) — the page view shows it read-only with that message.- Meta
PATCH /api/pages/:id, contentPUT /api/pages/:id/contentand permanentDELETE /api/pages/:idanswer 403 with codeE_PAGE_PLUGIN_LOCKEDand yourmessage. Trash, restore, move and duplicate are not blocked. - A realtime collab connection to the page is read-only.
A bare true uses the message "This page is read-only."
registerMcpTool(fn: (server, client) => void)
Registers tools on the per-request MCP McpServer, right after core's own tools — a plugin's tools appear over the same /api/mcp endpoint, no separate transport. client is an InternalApiClient: call it to act as the caller, the same way core's own tools stay inside the REST API's own permission checks:
api.registerMcpTool((server, client) => {
server.registerTool(
'hello_plugin_add_note',
{
title: 'Add a Hello Plugin note',
description: "Appends a note to this plugin's own table, owned by the caller.",
inputSchema: { message: z.string().min(1).max(500) },
},
async ({ message }) => {
const me = await client.get('/api/auth/me')
await db.table('hello_plugin_notes').insert({ user_id: me.id, message, created_at: new Date() })
return { content: [{ type: 'text', text: 'Note added.' }] }
}
)
})registerApiRoute(method, pattern, handler)
Your plugin's own REST endpoints, reachable at /api/plugin-api/<your-plugin-id>/<pattern>. method is one of GET / POST / PATCH / PUT / DELETE; pattern is relative to your own prefix (no leading prefix, :name segments allowed) and doesn't need a leading slash. handler receives the real Adonis HttpContext — ctx.auth, ctx.request, ctx.response, ctx.params all work exactly as in a core controller:
api.registerApiRoute('GET', '/notes', async (ctx) => {
const user = ctx.auth.getUserOrFail()
const rows = await db.from('hello_plugin_notes').where('user_id', user.id).orderBy('created_at', 'desc')
return { notes: rows }
})
api.registerApiRoute('DELETE', '/notes/:id', async (ctx) => {
const user = ctx.auth.getUserOrFail()
await db.from('hello_plugin_notes').where('id', ctx.params.id).where('user_id', user.id).delete()
})Return a value to send it as JSON (same convention as a core controller's return value), or call ctx.response.json() / .created() / .noContent() yourself and return nothing — never both. The single /api/plugin-api/:pluginId/* route this dispatches through requires middleware.auth() (any signed-in user) and nothing stricter by default; add your own checks in the handler for anything tighter.
registerSearchTabs(tabs) — hook search.tabs
Adds tabs to Votion's Search. The tab row is core's All · Workspace · Private, then every tab an enabled plugin registers, sorted by order. A plugin switched off in a workspace (or on the instance) has no tabs. Each tab is { id, label, icon, order, kind? } plus exactly one search provider:
id— stable, sent as?tab=and as each hit'ssearch_type. Notall,workspaceorprivate, and not another plugin's id.icon— a Lucide icon name in kebab case (square-check,contact,mail…); shown in the "More" menu and on hit rows.order— Projects uses 20–23, Contacts 40, Calendar and CRM 50, Billing 60–61, Mail 70.kind— the singular label on the right of a hit row ("Task"). Without it, a claimed page shows the tab label as its path ("Customers").pages({ spaceId, userId })— page-backed: the page ids the tab claims (database rows too). Core searches them with its own ranking, read gate and snippets, and keeps them out of the Workspace and Private tabs.meta(pages)may return aMapof page id to the hit row's details (search_meta).search({ spaceId, userId, q, limit })— own data: return hits{ id, title, route: { name, params }, icon?, meta?, snippet?, updated_at? }(or{ hits, total }).qmay be empty — list the tab then.routenames a route your web half registered. Check your own permissions here; return[]for nothing.
meta (both kinds) can carry status: { name, color }, subtitle, project: { id, title }, lead: { id, name }, date, start/end and current; the row shows the status tag, then the rest joined with " · ".
api.registerSearchTabs([
{
id: 'hello-plugin-marked',
label: 'Marked',
icon: 'sparkles',
order: 900,
pages: async ({ spaceId, userId }) => markedPageIds(spaceId, userId),
},
{
id: 'notes',
label: 'Notes',
kind: 'Note',
icon: 'file-text',
order: 901,
search: async ({ spaceId, userId, q, limit }) =>
(await findNotes(spaceId, userId, q, limit)).map((note) => ({
id: note.id,
title: note.title,
route: { name: 'hello-note', params: { noteId: note.id } },
meta: { subtitle: note.author },
})),
},
])GET /api/spaces/:id/search-tabs lists the row ({ tabs: [{ id, label, icon, order, kind, plugin_id }] }). GET /api/spaces/:id/search?q=&tab= answers one tab with { tab, hits, total }; tab=all (the default) with a query answers { tab: 'all', groups: [{ tab, hits, total }] } (each tab's first five hits, empty tabs left out), without a query the recent page listing. A failing provider leaves its tab empty instead of failing Search. This replaces the former registerSearchScope and registerSearchTypes.
registerPageDataHook(fn: (page) => Record<string, unknown> | null | undefined)
Contributes to one page's GET /api/pages/:id response, merged under plugin_data[your-plugin-id]. Return null/undefined for a page you have nothing to add for — it's omitted from the response entirely, not sent as an empty object:
api.registerPageDataHook((page) => {
if (typeof page.title !== 'string' || !page.title.includes('[hello-data]')) return null
return { marked: true, titleLength: page.title.length }
})registerBulkPageDataHook(fn: (pages) => Map<number, Record<string, unknown> | null | undefined>)
The bulk counterpart of registerPageDataHook, for the sidebar tree listing (GET /api/spaces/:id/pages), which loads many pages per request and can't afford one hook call per page. Called once with the whole page set already loaded; return a Map keyed by page id, and omit any page id you have nothing to add for:
api.registerBulkPageDataHook((pages) => {
const result = new Map()
for (const page of pages) {
if (typeof page.title === 'string' && page.title.includes('[hello-bulk]')) {
result.set(page.id, { bulkMarked: true })
}
}
return result
})registerPageLifecycleHook(fn: (pageIds, event: 'trashed' | 'restored') => Promise<void> | void)
Fires when a page subtree your plugin cares about is trashed or restored, with the whole affected subtree's ids. This exists because a plugin's own table can't read a core column like pages.trashed_at directly inside its own partial unique index — if you need that guarantee, mirror trashed_at onto your own table and keep it in sync here:
api.registerPageLifecycleHook(async (pageIds, event) => {
await db.table('hello_plugin_lifecycle_events').insert(
pageIds.map((pageId) => ({ page_id: pageId, event, created_at: new Date() }))
)
})There is no hard-delete event — a plugin's own row is expected to carry references pages(id) on delete cascade, so Postgres removes it the instant the page itself is gone; nothing left to clean up.
registerPageListingOpenAsHook(fn: (pages) => Map<number, { route, params? } | null | undefined>)
The server-side half of "open this page on my own route, not the generic viewer". Called once, batched over the WHOLE page set already loaded for the request, by every generic page-listing endpoint: GET /api/spaces/:id/recent-pages, GET /api/spaces/:id/pages (the sidebar tree), GET /api/spaces/:id/pages/search, and GET /api/spaces/:id/trash. Return a Map keyed by page id, omitting any page id you don't claim — the result rides along as an open_as field (null for a page no plugin claims) next to plugin_data on every row:
api.registerPageListingOpenAsHook((pages) => {
const result = new Map()
for (const page of pages) {
if (typeof page.title === 'string' && page.title.includes('[hello-listing-route]')) {
result.set(page.id, { route: 'hello-plugin' })
}
}
return result
})route is a route NAME your plugin's own registerRoute (hook 1) registered — never a path. The matching client-side registerPageOpenRouteHook (above) is what actually turns this into a navigation; this hook only tells the client which page is claimed and by what route. A page can only ever open one way — the first enabled plugin's hook to claim a given page id wins, unlike plugin_data (registerBulkPageDataHook), which deliberately lets every enabled plugin add its own key to the same page at once.
registerTreeHiddenPagesHook(fn: (spaceId) => Promise<string[]> | string[])
Hook 24. Returns root page ids whose whole subtree stays out of the workspace's sidebar tree listing (GET /api/spaces/:id/pages). The pages are still ordinary pages: links, the row API and MCP see them. Search leaves them out, except the rows a plugin's Search tab claims (registerSearchTabs). Projects uses it for its area (a hidden root page with the Projects, Tasks, Milestones and Sprints databases), which has its own sidebar.
Scoping a database's rows (?scope=)
GET /api/databases/:id/rows?scope=<relationPropertyId>:<pageId> lists only rows whose relation holds that page, on top of the view's own filters, so removing a filter never shows other rows. A malformed scope answers 422 E_VIEW_INVALID. In the web app, provide VIEW_SCOPE (apps/web/src/database/viewScope.ts) around a DatabaseTable: it sends the scope with every listing and seeds new rows with defaults. Projects pins a project's views to its tasks this way.
Properties whose config.fixed is true cannot be deleted, trashed or changed to another type (422 E_PROPERTY_FIXED); renaming still works.
registerPermissionDefinitions(defs: { id, label, description?, defaultRole }[])
Declares one or more named permissions your plugin cares about, surfaced on Settings → Plugins & Features → Plugin permissions (every member sees it; owners and maintainers change it), one list per plugin under your manifest's name. defaultRole is one of 'owner' | 'maintainer' | 'member' — the role your permission is granted to when nobody has overridden it for this workspace.
api.registerPermissionDefinitions([
{
id: 'add-note',
label: 'Add a note',
description: 'Lets a member use hello_plugin_add_note / POST /notes.',
defaultRole: 'member',
},
])A workspace owner/maintainer can change the lowest role holding it, and add exceptions for one custom group or one named user, from that same page, independent of this declaration. Check whether the caller currently holds a permission with api.hasPermission(permissionId, userId, spaceId) (below); it resolves any override first and falls back to your declared defaultRole when none exists.
registerSuggestedGroups(names: string[])
Suggests one or more workspace-scoped group names your plugin would find useful (e.g. a CRM plugin suggesting 'Sales'). Each shows as a one-click "+ name" chip in Settings → Workspace → Groups, for every workspace where a group of that name doesn't already exist. Clicking it creates a real, empty group an owner/maintainer then populates like any group they made by hand — installing or enabling your plugin never creates a group, or adds anyone to one, on its own.
api.registerSuggestedGroups(['Note Takers'])api.hasPermission(permissionId: string, userId: number, spaceId: number): Promise<boolean>
Resolves one of your own declared permissions (above) for one user in one workspace: an explicit workspace override if the owner/ maintainer set one (by role, by one of this workspace's custom groups, or by that one user specifically), otherwise your declaration's defaultRole. Call this from your own route/hook instead of re-deriving role checks by hand:
api.registerApiRoute('POST', '/spaces/:spaceId/notes', async (ctx) => {
const user = ctx.auth.getUserOrFail()
const spaceId = Number(ctx.params.spaceId)
const allowed = await api.hasPermission('add-note', user.id, spaceId)
if (!allowed) {
return ctx.response.status(403).json({ message: 'You do not have the add-note permission' })
}
// ...
})registerRowCreateGuardHook(fn: (database, userId) => Promise<boolean> | boolean)
Lets your plugin add an extra restriction on top of the generic page-access check before a row may be created in database (any database page, not just your own — check database.id against whatever you consider yours and return false for everything else). Return true to deny the request (the caller gets a 403); false means "no objection from me". Every enabled plugin's hook is OR'd together, the same restriction-only contract registerAccessControlHook already uses — a hook can only add a denial, never grant access beyond what core's own check already allows:
api.registerRowCreateGuardHook(async (database, userId) => {
if (database.id !== myTasksDatabaseId) return false
return !(await api.hasPermission('create-task', userId, database.spaceId))
})registerRowWriteGuardHook(fn: (database, row, touchedPropertyIds, userId) => Promise<boolean> | boolean)
The same restriction-only contract as the row-create guard above, checked before PATCH /api/rows/:id/properties writes any cell. touchedPropertyIds is every property id this one request would write or clear (plus the title property's id when the title itself changed), letting you tell a narrow edit (e.g. only a board's grouping property) apart from a broader one:
api.registerRowWriteGuardHook(async (database, row, touchedPropertyIds, userId) => {
if (database.id !== myTasksDatabaseId) return false
if (await api.hasPermission('edit-task', userId, database.spaceId)) return false
const canMoveOnly = await api.hasPermission('move-task', userId, database.spaceId)
return !(canMoveOnly && touchedPropertyIds.every((id) => id === myStatusPropertyId))
})registerPropertyOptionGuardHook(fn: (database, property, userId) => Promise<boolean> | boolean)
The same restriction-only contract, checked before any of the four select/multi-select option routes (create/reorder/rename-or- recolour/delete an option) mutate property's option list:
api.registerPropertyOptionGuardHook(async (database, property, userId) => {
if (property.id !== myStatusPropertyId) return false
return !(await api.hasPermission('manage-lanes', userId, database.spaceId))
})registerRowValueGuardHook(fn: (database, row, property, newValue, userId) => Promise<string | null | undefined> | string | null | undefined)
A different shape from the three guards above: not "allow or deny", but "is this specific new VALUE acceptable". Checked on every cell write registerRowWriteGuardHook already let through, once per property actually present in the write (a cleared relation never reaches this hook — clearing can't violate a value-level invariant the way setting one can). Return an error message string to reject the write with that message; null/undefined means no objection. row is the pre-write row on a PATCH, or null on a CREATE (a freshly created row is always plain and non-private, since core's generic row-create route accepts no privacy flags yet):
api.registerRowValueGuardHook(async (database, row, property, newValue, userId) => {
if (property.name !== 'Project' || property.type !== 'relation') return null
if (!Array.isArray(newValue) || newValue.length === 0) return null
const targets = await Page.query().whereIn('id', newValue)
for (const target of targets) {
if (await isPrivate(target)) {
return 'Project must not be set to a Private project while this task is visible to the whole workspace'
}
}
return null
})Typical use: an invariant between two related rows, e.g. "a task visible to the whole workspace must never point at a Private project". Same OR'd-across-plugins discipline as the other guards, except first-REJECTION-wins instead of first-true-wins, since a message (not a boolean) is what every caller after the first needs to see.
Combine these four — row-create, row-write, property-option and row-value — with registerPermissionDefinitions to gate your own databases by workspace-level grants, with no new permissions UI of your own: every declared permission already surfaces on the generic panel the previous section describes. The bundled Projects plugin declares its six grants (create project; create task/milestone/sprint; move task; edit task; start/close sprint; manage project settings) this way.
A hook that queries your own tables must not let a DB error abort the caller's transaction, not just avoid throwing. isRowCreateBlocked/ isRowWriteBlocked/isPropertyOptionMutationBlocked/ firstRowValueGuardError (and isPageLocked for registerAccessControlHook) run inside whatever transaction the caller's own request (or, in tests, the per-test transaction) already has open — these guard calls are never the ones that opened it. A bare try/catch around your own query stops the JS exception, but Postgres has already marked that WHOLE transaction aborted the instant the query errored (error 25P02): every later query on it — yours or anyone else's — then fails with "current transaction is aborted", 500ing requests that have nothing to do with your plugin. Run the risky query inside its own db.transaction(...) instead of directly on the shared connection; when a transaction is already open this nests as a SAVEPOINT, so a failure rolls back only your lookup and leaves the caller's transaction perfectly usable:
async function scaffoldRoleFor(databaseId) {
try {
return await db.transaction(async (trx) => {
return await trx.from('my_plugin_table').where('database_id', databaseId).first()
})
} catch (error) {
logger.warn({ err: error, databaseId }, '[my-plugin] lookup failed — treating as "not ours"')
return null
}
}Use this pattern whenever a guard looks up plugin-owned state: a missing row is legitimately possible (plugin state is a process-wide singleton that outlives any one test's own rolled-back transaction), and without the SAVEPOINT isolation above, a failure like that cascades into unrelated Database rows/views specs across a whole test run.
registerScheduledJob(fn: () => Promise<void> | void)
Registers a function the existing automations scheduler (start/automations_worker.ts's scheduleTick) calls once per tick, currently every ~60s, for every currently-enabled plugin. This exists so a plugin that needs its own periodic background sweep doesn't start a second setInterval of its own — register into that already-running tick instead:
api.registerScheduledJob(async () => {
const stale = await db
.from('hello_plugin_notes')
.where('created_at', '<', DateTime.utc().minus({ days: 30 }).toJSDate())
if (stale.length === 0) return
await db.from('hello_plugin_notes').whereIn('id', stale.map((row) => row.id)).delete()
})The hook takes no arguments and the ticker carries no schedule concept of its own beyond "call every registered job once per tick" — if your job needs calendar/clock-based timing (e.g. "only once per UTC day"), compute that yourself on every call — re-derive "today" from DateTime.utc() on every tick, or keep your own last-run time in your own table; the framework tracks no last-run time for you. One plugin's job throwing is caught and logged by the ticker and never stops any other plugin's job from running on the same tick — but it does mean a failure inside your own job is your own job's responsibility to notice (log it, don't silently swallow it).
Translations on the server: registerMessages and translate
Your api half has its own catalogs for what it writes for people — mails, Inbox and push notifications, texts it stores for someone to read. They work like the web half's (see Translations), in a separate namespace that is always your plugin id: English is the source, other languages translate a subset, a missing key reads in English, {name} placeholders come from params, and { one, other } is a plural picked by params.count. MCP tool descriptions stay English; API error messages follow the request (below).
api.registerMessages(catalogs)adds or replaces your catalogs ({ en, de?, … }, merged per language). Call it once inregister(api).api.translate(language, key, params?)gives one message inlanguage. Any language your catalogs have works, even one Votion's interface does not offer yet — Billing writes its invoice mails in French and Italian because the invoice follows the client's language. An unknown or empty language reads in English.api.languageForUser(userId, spaceId?)is the language to write to a member in, by the rule core's mails and push notifications follow: their own (Settings › Appearance › Language), else the workspace's (spaceId, the workspace the message is about — Settings › General), else English.api.translatorForUser(userId, spaceId?)istranslatebound to that language:t(key, params?), witht.languagethe code it picked.api.languageForRequest(ctx)is the language of the request a route handler answers: itsAccept-Language(the web app sends the interface language on every request), else English — the rule core's API errors follow. Clients that send none (MCP, scripts) get English.api.translatorForRequest(ctx)istranslatebound to that language, for what a route answers that people read: summaries ("Every weekday"), labels, rows it adds to another plugin's page, and error messages with values in them (throw invalid(t('errors.tooLong', { max }))).
Fixed English is matched by text. You never pass a language for the text you register once or throw as a plain sentence: core looks the exact English up in your en catalog and answers with the same key in the request's language — the way core's own API errors work. That covers the label / description of registerPermissionDefinitions, the names of registerSuggestedGroups, the label / kind of registerSearchTabs, the label of registerViewAction, the message a registerRowValueGuardHook rejects with, and the message of a 4xx error a registerApiRoute handler throws (new Exception('Customer not found', { status: 404 })). Text without an entry, and a message with values in it, stay as written; use translatorForRequest for those. Keep such strings anywhere in your catalog (permissions.manage, errors.notFound, …); a sentence used twice needs one entry.
// api/entry.js
const messages = {
en: {
reminder: {
title: 'Reminder: {title}',
startsIn: { one: 'starts in {count} minute', other: 'starts in {count} minutes' },
},
},
de: {
reminder: {
title: 'Erinnerung: {title}',
startsIn: { one: 'beginnt in {count} Minute', other: 'beginnt in {count} Minuten' },
},
},
}
export async function register(api) {
api.registerMessages(messages)
api.registerScheduledJob(async () => {
for (const due of await dueReminders()) {
const t = await api.translatorForUser(due.userId, due.spaceId)
await notify(due.userId, `${t('reminder.title', { title: due.title })} · ${t('reminder.startsIn', { count: due.minutes })}`)
}
})
}In a route, translate for the request:
api.registerApiRoute('GET', 'events/:id', async (ctx) => {
const t = api.translatorForRequest(ctx)
const event = await findEvent(ctx.params.id)
// Matched by text: reads "Termin nicht gefunden" when the catalog has it.
if (!event) throw new Exception('Event not found', { status: 404 })
return { ...event, repeats: t('recurrence.weekdays') }
})Never translate what people typed (titles, names, record values) — pass them in as params. Text meant for someone outside the workspace (a client, a guest) follows that person's language when you know it — Billing uses the invoice's language — and api.translate with that code.
registerViewAction({ key, label, icon, appliesTo, visibility, handler })
Renders one more icon-button in the view toolbar's existing Filter / Sort / Automations row (apps/web/src/database/DatabaseTable.vue) for every database appliesTo matches and every caller visibility admits. Exists because the Button property's own automation chain is scoped to ONE row — a view action needs to query/mutate an arbitrary collection and run real control flow (e.g. "close sprint": roll every open task forward, create the next sprint, navigate to it):
api.registerViewAction({
key: 'say-hello',
label: 'Say hello',
// Resolved against a small fixed icon map in DatabaseTable.vue
// (VIEW_ACTION_ICONS) — an unrecognised name falls back to a
// generic icon rather than failing to render.
icon: 'sparkles',
// Which databases show the button at all. Takes the already-loaded
// Page, same shape as registerRowCreateGuardHook/
// registerRowWriteGuardHook above — a plugin's own per-space
// database id (e.g. a bootstrap-created Sprints database) does not
// exist yet at register() time, so this cannot be a fixed id.
appliesTo: (database) => database.title.includes('[hello-view-action]'),
// Whether THIS caller sees the button at all — reuses a declared
// permission the same way a row guard would.
visibility: (ctx) => api.hasPermission('use-view-action', ctx.userId, ctx.spaceId),
// Runs in-process with full db access when the button is clicked.
// Its return value rides back to the client verbatim under `result`.
handler: async (ctx) => {
await db.table('hello_plugin_notes').insert({
user_id: ctx.userId,
message: `Hello from view action — database ${ctx.databaseId}`,
created_at: new Date(),
})
return { message: `Hello from view action — database ${ctx.databaseId}` }
},
})ctx ({ userId, spaceId, databaseId }) is the same shape for both visibility and handler — plain ids, not loaded models; load whatever you need yourself, the hello-plugin worked example above does. appliesTo and visibility are re-checked server-side on every trigger, not only when the toolbar renders the button — a stale or tampered client render is never itself the access check, the same discipline the row/property guard hooks above already hold every write path to. The trigger route (POST /api/databases/:id/view-actions/:pluginId/:key/trigger) answers 404 when the plugin is disabled, the key is unknown, or appliesTo no longer matches, and 403 when appliesTo passes but visibility doesn't — the same split a caller who can't see a page at all vs one who can see it but not write to it already gets elsewhere in this API.
registerDatabaseToolbarSlot(matches, component) (web only)
A browser-side-only sibling of registerViewAction above, for the same view toolbar. Reach for this one instead when the action needs to collect input from the caller BEFORE it does anything — registerViewAction's trigger route fires its handler immediately, with no request body, which is right for a one-click action but has no way to show a form first. This hook hands the toolbar a whole plugin-owned component instead, exactly like registerSidebarSlot above — the component decides its own look, state, and which of your entry.api routes it calls directly via apiRequest (never a new core endpoint):
const HelloToolbarButton = {
name: 'HelloToolbarButton',
setup() {
const open = ref(false)
return () =>
h('button', { onClick: () => { open.value = !open.value } }, 'Say hello')
},
}
api.registerDatabaseToolbarSlot(
(database) => database.title === 'Hello Plugin Database',
HelloToolbarButton,
)matches receives the already-loaded database's { id, title } — plain fields, not a full Page model, same "hand over the minimum" shape ViewAction#appliesTo above already uses. Unlike appliesTo, there is no server-side re-check here: this hook contributes UI only, so your component is responsible for its own gating (e.g. fetching a permission check from your own entry.api route on mount) and for only ever calling routes that enforce themselves — e.g. fetch a can-create-… check to decide whether to render at all, then POST to your own gated creation route either way.
registerPropertyType({ type, available? }) (server) and registerPropertyType({ type, section, hint?, available?, cell }) (web)
A plugin-owned database property type — the bundled Billing plugin's Time tracking is the worked example. The type itself still has to be known to core (listed in PROPERTY_TYPES, the database check constraint, and its label and icon in the web's propertyOps.ts), so a column keeps rendering its header while the plugin is off. The plugin adds what only it can:
- Server:
available(spaceId)decides whether a new property of this type may be created (or a property changed to it) in that workspace. Core asks it onPOST /api/databases/:id/propertiesand on a type change and answers422 E_PROPERTY_TYPE_UNAVAILABLEwhen no enabled plugin offers the type. Existing columns are never touched. - Web: the type picker shows the type under the plugin's own
section({ key, label }) with thehintline under it, whileavailable()is true; Table rows and the row page rendercell(propsrowId,databaseId,property,readOnly,rowTitle?,variant: 'table' | 'row'). A plugin type is created, never converted into.
// entry.api
api.registerPropertyType({
type: 'time_tracking',
available: async (spaceId) => (await loadSettings(spaceId)).enabled,
})
// entry.web
api.registerPropertyType({
type: 'time_tracking',
section: { key: 'billing', label: 'Billing' },
hint: 'Start and stop a timer per row. Added by the Billing plugin.',
available: () => billingOnForCurrentSpace(),
cell: TimeTrackingCell,
})registerViewType({ type, label, hint }) (web only)
Offers one of the core's plugin-motivated view types in + Add view and in a view's Layout picker, as a menu row with hint as faint text on the right. The view itself is core — only the picker entry belongs to the plugin, so it disappears while the workspace has the plugin off and existing views keep rendering.
api.registerViewType({ type: 'gantt', label: 'Gantt', hint: 'Projects' })No bundled plugin calls it: Gantt and Workload are core view types, and core lists them in both pickers itself (under Burndown), whether Projects is on or not. Projects only feeds them, through the gantt.sprints and workload.context extension points (sprint lanes, areas and capacity); without Projects they render without those.
registerTopbarSlot(component) (web only)
A chip in the pinned top bar — on desktop before Share, on phones under the floating top row (mounted with variant: 'mobile'). The component renders nothing when it has nothing to show; the Billing plugin's running-timer chip is the worked example.
registerDatabaseEmptyState(fn) (web only)
Replaces the plain "No pages yet" of a database your plugin owns with its own empty state. fn receives { id, title, pluginData } — pluginData is the database schema's plugin_data, i.e. what your server-side registerPageDataHook returned for the database page itself — and returns null for any other database, or a plain descriptor the core draws in its own style (centred emoji, title, one line of text, an optional button that navigates):
api.registerDatabaseEmptyState((database) => {
if (database.pluginData['my-notes']?.notes_database !== true) return null
return {
emoji: '🗒️',
title: 'No notes yet',
description: 'Create the first note for your team.',
action: { label: 'New note', icon: 'plus', to: { name: 'my-notes-new' } },
}
})The first plugin that returns a descriptor wins. No bundled plugin registers one today.
registerDatabaseChrome(fn) (web only)
Trims the database toolbar for a database your plugin owns. fn receives the same { id, title, pluginData } and returns null, or { phoneAutomations: false } to drop the phone toolbar's one-tap ⚡ (Automations stays in the ••• View options sheet). Any plugin saying false wins. No bundled plugin registers one today.
registerSchemaChangeInterceptor(fn) (web only)
Steps in before a property or option change made through the core menus (create, rename, retype, delete a property; add, edit, delete or reorder an option). fn receives { databaseId, action, propertyId, optionId, body } and returns nothing (the request goes as it is), { path, after } (send it to another path, then run after with the answer) or { handled: true, response } (answer it yourself). Throw SchemaChangeCancelled to drop it. Projects uses it to ask "Change the template too?".
registerPropertyOptionsHook(fn) (web only)
Narrows and orders the options of a select, multi-select or status property for the page in view. fn receives { databaseId, pageId, propertyId, type } — pageId is the row page or peek shown, or the page a scoped view is pinned to — and returns null or { visibleIds, order? }. Every picker, cell editor, filter value list, board column and the core option editor then offer only those options, in that order. A plain database (no page) is never narrowed. The hook runs inside the surfaces' computeds: read reactive state for answers that arrive later. Projects uses it so a project offers only its template's Status options.
Both hooks are skipped while the plugin is off in the workspace.
registerPropertyMenuHook(fn) (web only)
Says where a property on a row page comes from, for its property menu. fn receives { pageId, databaseId, propertyId } and returns null or an origin: templateName ("From template …"), hideLabel, or locked: true with hidden, showLabel, lockedNote(name) and setHidden for a fixed property whose menu offers only Hide / Show. The first hook with an answer wins; it may read reactive state. Projects uses it for sprint and milestone pages. Skipped while the plugin is off.
registerExtension(point, entry) and provide(service) (web only)
api.registerExtension(point, entry) adds entry to another plugin's (or core's) extension point under your plugin's id and returns the undo; api.provide(service) offers your service to other plugins under your id. See Services and extension points above for both registries and the points and services that exist.
registerPreset(manifest: PresetManifest) — Templates picker
Declares one ready-made "template" your plugin ships: a set of databases (with their properties, including relations to each other) plus an optional page tree, that a workspace member can instantiate with one click from the workspace's Templates picker. The bundled Daily Notes plugin is nothing but a preset — its whole server entry is api.registerPreset(dailyNotesPresetManifest) and it has no web half. Its manifest (plugins-bundled/daily-notes/api/preset.js) is a real, currently-shipping worked example for the row-template, pageType, view and icon/cover fields quoted below: a single bare database with no page tree at all (pages: [] is a legal manifest whenever at least one database is declared — see validatePresetManifest), carrying its own icon/cover directly and a manifest-declared default row template whose title resolves {{date}}. The page-tree fields below (pages[], children, a content database block) are illustrated with a separate, generic example instead, since Daily Notes has none.
Not every feature fits the declarative shape below — a plugin whose provisioning needs a button-triggered automation chain, or a non- default view (Board/Calendar/Burndown), still registers a manifest (for the id/name the picker lists and the eager validatePresetManifest check), but passes a second argument: registerPreset(manifest, instantiate), where instantiate is your own (options: {spaceId, userId, isPrivate}) => Promise<{databaseIdsByKey, pageIdsByKey, rootPageIds}>, called INSTEAD of the generic clone engine. No bundled plugin uses this escape hatch today.
manifest is validated eagerly, at register() time — a malformed manifest fails loudly at boot, not at the first user's instantiate click:
api.registerPreset({
id: 'notes-bundle',
name: 'Notes',
defaultVisibility: 'workspace',
icon: '🗒️', // optional, picker row and preview (≤ 32 chars)
summary: 'Notes for the team', // optional, one line under the name (≤ 500)
description: 'A shared notes database with a dashboard.', // optional, preview text (≤ 500)
databases: [{ key: 'notes', name: 'Notes', properties: [] }],
pages: [{ key: 'dashboard', title: 'Notes dashboard', children: ['notes'] }],
})icon, summary and description only feed the Templates picker. Its preview draws a miniature of your first database's first view (Board, List, anything else as a table).
Every cross-reference inside a manifest — a relation's toKey, a page's children entry, a content block's databaseKey (below) — is a bundle-local key you make up, never a real database/page id (no id exists yet when your plugin registers its manifest). Keys share one namespace across databases and pages. A workspace member clicking "Use template" in the picker calls the generic clone engine (app/lib/presets/clone_engine.ts's instantiatePreset), which creates every declared database/property/view/page in one transaction and resolves every bundle-local key to the real id it minted in that same call — so instantiating the same manifest twice in one workspace produces two fully independent copies with no shared backing object between them, and a failure partway through leaves nothing behind.
A PresetDatabaseSpec (databases[]) needs a key and a name; its properties[] are plain { name, type } (every PropertyType except 'title' — every database gets an automatic title property for free, named titleName or "Name" by default). A relation-typed property needs relation: { toKey } naming another database inside this same bundle — an out-of-bundle toKey is rejected at validation time, not instantiation time. Add twoWay: true plus backPropertyName to also mint a mirrored relation property on the target database, pointing back:
databases: [
{ key: 'projects', name: 'Projects', properties: [] },
{
key: 'tasks',
name: 'Tasks',
properties: [
{
name: 'Project',
type: 'relation',
relation: { toKey: 'projects', twoWay: true, backPropertyName: 'Tasks' },
},
],
},
],A PresetPageSpec (pages[]) needs a key and a title. children nests other bundle keys (databases or pages) directly under this page, in display order — a key may be claimed by at most one parent (a flat forest, not a DAG), and every database/page key nobody claims as a child lands as a top-level sibling of the workspace's existing root pages.
content is a plain TipTap document for the page body (defaults to an empty doc when omitted). To place a view of one of this same bundle's own databases on the page — the inline/linked database block (apps/web/src/editor/databaseBlock.ts's database node) — write attrs.databaseKey instead of a real attrs.databaseId (which can't exist yet when you're writing the manifest):
pages: [
{
key: 'dashboard',
title: 'Projects dashboard',
children: ['projects', 'tasks'],
content: {
type: 'doc',
content: [
{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Projects' }] },
{ type: 'database', attrs: { databaseKey: 'projects' } },
{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Tasks' }] },
{ type: 'database', attrs: { databaseKey: 'tasks' } },
],
},
},
],The clone engine resolves every databaseKey to THIS instantiation's own freshly created database id (and mints a fresh block uid) before the page is written, so two instantiations in the same workspace each get a dashboard bound to their own two databases, never the other instantiation's. Validation rejects a content database block with an unknown databaseKey, no key at all, or one that already carries a literal databaseId — a manifest can never know a real id in advance, so a hardcoded one is always a mistake, caught at validation time.
On-create automations
A PresetDatabaseSpec may also declare automation — an action chain that fires once for every row ever created in this instantiation's own copy of the database, using the same trigger/action machinery a hand-built database automation already uses (there is no separate "preset automation" runtime — once instantiated, it is indistinguishable from one built by hand in the Automations panel). No bundled preset currently ships one — Daily Notes used this for its row title until a manifest-declared row template (below) replaced it, because an automation and a template both setting one title is a real defect, not a feature. The capability itself is unchanged and still available to any preset:
databases: [
{
key: 'notes',
name: 'Notes',
properties: [],
automation: {
trigger: 'on_create',
actions: [
{
kind: 'set_property',
databaseKey: 'notes', // must be this SAME database's own key
property: 'title', // 'title', or the name of a declared property
valueTemplate: '{{today}}',
},
],
},
},
],trigger only ever accepts 'on_create' today — nothing else describes an event a freshly-instantiated, still-empty database can have had yet. Each set_property action's valueTemplate is resolved through the same {{...}} token grammar a live automation's action config already supports ({{trigger.title}}, {{trigger.property:<id>}}, {{var.<name>}}, and {{today}}/{{date}} — documented synonyms, the server's current UTC calendar date as 'YYYY-MM-DD'). property addresses 'title' (the database's own automatic title property) or the name of one of that SAME database's declared properties[] entries — validation rejects a databaseKey outside the bundle (the same bundle-closure rule a relation's toKey already gets), a databaseKey other than the declaring database's own (cross-database targets aren't supported yet), and a property name that doesn't exist.
Row templates
A PresetDatabaseSpec may also declare templates[] — real, saved database-row templates, written at instantiation time the same way a member's own "+ New template" creates one by hand. This is the mechanism the shipped Daily Notes preset uses for its own default template today:
databases: [
{
key: 'notes',
name: 'Notes',
properties: [{ name: 'Tags', type: 'multi_select' }],
templates: [
{
key: 'today-template', // bundle-local, scoped to this database's own list
title: 'Daily Note {{date}}', // a TITLE TEMPLATE, resolved per row
icon: '📝',
isDefault: true, // becomes this database's own default_template_id
pageType: 'daily-note', // optional, inherited by every row made from it
},
],
},
],Each template needs a key (unique within its own database's templates[] — never referenced by anything else in the manifest, so it needs no bundle-wide uniqueness) and a title. icon/cover/ content follow the same shape a PresetPageSpec's own fields do; content defaults to an empty document when omitted. properties[] seeds literal cell values by the owning database's own property name — [{ property: 'Tags', value: ['standup'] }] — never the title property, which only ever comes from the dedicated title field. At most one template per database may set isDefault: true; that one becomes the database's own default_template_id, the same field PATCH /api/databases/:id/default-template already writes by hand.
A template's title is a TITLE TEMPLATE, not a literal string: when a member creates a row from it (explicitly, or through a database's own default), the title is resolved through the exact same {{...}} token grammar an automation's valueTemplate already uses — {{date}} (and its synonym {{today}}) resolves to the server's current UTC calendar date at the moment the ROW is created, never at manifest-instantiation time. This is what lets Daily Note {{date}} read as a different, correct date every day without any automation at all. The template PAGE itself still shows the raw, unresolved string — that is where a member edits it — while the Templates menu's own list previews it resolved.
A template row is written directly, never through the generic row-create route, and is guaranteed not to queue any of the database's own on-create automation events — a template is not data.
Page types (pageType)
A PresetDatabaseSpec and a PresetRowTemplateSpec may each declare pageType — an optional label that marks what kind of page this is, so your plugin (or anyone reading the API) can recognise its pages later without keeping its own id table:
databases: [
{
key: 'notes',
name: 'Daily Notes',
pageType: 'daily-notes', // lands on the database page itself
properties: [],
templates: [
{ key: 'today-template', title: 'Daily Note {{date}}', isDefault: true, pageType: 'daily-note' },
],
},
],- Format. Lowercase letters, digits and dashes, starting with a letter or digit, at most 64 characters (
/^[a-z0-9][a-z0-9-]{0,63}$/).validatePresetManifestrejects anything else atregister()time. Leaving it out means no page type (null). - Where it lands. The
pages.page_typecolumn of the database page (database spec) or of the template row (template spec). - Inheritance. A row created from a template — picked explicitly or through the database's default template — gets the template's page type. Duplicating a row or a whole database keeps the page types of the copied pages, and Save as template on a row keeps the row's page type on the new template. A row created without a template has none.
- In the API. Every page payload built by
serializeMeta(page tree, page, row and duplicate responses) carries it aspage_type(nullwhen unset). There is no REST or MCP field to set or change it — only a preset puts it there. - Behaviour. None. Core attaches no behaviour to a page type: it does not lock, hide, route or style a page by it. It is a stable label for your plugin's own hooks (an access-control hook, a page overlay, a search tab) to key off.
The bundled Daily Notes preset uses daily-notes for its database and daily-note for its default template, so every note made from that template is a daily-note page.
Views, icons and covers
A PresetDatabaseSpec and a PresetPageSpec may each declare icon (an emoji, or an uploaded-file URL — same shape a real page's icon already has) and cover (an image URL), landing verbatim on the created page/database once instantiated:
databases: [
{ key: 'notes', name: 'Notes', properties: [], icon: '📓' },
],
pages: [
{ key: 'dashboard', title: 'Notes dashboard', icon: '🏠', cover: 'https://example.com/cover.png' },
],A PresetDatabaseSpec may also declare views[] — the tab strip the database opens with. Omitting views entirely keeps today's unchanged default: one Table view and one List view, named "Table" and "List". Declaring views replaces that pair completely with exactly what you list, in order:
databases: [
{
key: 'notes',
name: 'Notes',
properties: [{ name: 'Tags', type: 'multi_select' }],
views: [
{
type: 'list',
name: 'Recent',
icon: '🕐',
openMode: 'center',
sorts: [{ property: 'Name', direction: 'desc' }],
},
{ type: 'list', name: 'All', icon: '📋', openMode: 'center' },
],
},
],Each view needs a type — one of the same set the view-type picker offers today (table, calendar, gallery, feed, chart, board, list, timeline, map, burndown) — validated eagerly, the same "fails at register() time, not at a user's instantiate click" rule every other part of this manifest already follows. name defaults to the type's own default name (e.g. "List") when omitted; icon is the same per-view emoji override the view tab bar already supports. openMode picks how a row opens from this view — 'full_page' (default), 'peek', or 'center'.
sorts, filters and hiddenProperties each name a property by its manifest name — the automatic title property's own name (titleName, or "Name" by default) or any entry of this SAME database's properties[] — never a numeric id, which doesn't exist until instantiation. Validation rejects a name that doesn't resolve on this database, naming the property and the database, before anything is written:
views: [
{
type: 'table',
sorts: [{ property: 'Name', direction: 'asc' }],
filters: [{ property: 'Tags', operator: 'is_not_empty' }],
hiddenProperties: ['Tags'], // everything else on this view stays visible
},
],settings is type-specific (the same shape the view's own settings panel reads/writes) and is passed through as-is — no by-name property resolution — shallow-merged on top of that type's own defaults (the same defaults a hand-created view of the same type gets), so you only need to name what differs from the default:
views: [{ type: 'list', settings: { show_page_icon: false } }],A list view's right-aligned secondary-property pill(s) are the one setting that genuinely needs a by-name spelling of its own: defaultViewSettings can only ever default to the single first non-title property, with no way to name two or three specific properties in a chosen order — which a hand-created List view's own settings panel lets a member do by hand (capped at 3 pills). Declare secondaryProperties (by manifest name, same contract as sorts/ filters/hiddenProperties above) instead of guessing at real property ids inside settings by hand; it resolves into settings.secondary_property_ids at instantiation time and overrides any raw settings.secondary_property_ids you also wrote:
views: [
{ type: 'list', name: 'Recent', secondaryProperties: ['Tags', 'Updated'] },
],Reading back which real ids your instance created
instantiatePreset computes a full bundle-local-key → real-id map and persists it — your plugin can read it back later through api.getPresetInstances(manifestId, spaceId), without needing your own bespoke tracking table:
const instances = await api.getPresetInstances('notes-bundle', spaceId)
// -> [{ id, manifestId, spaceId, databaseIdsByKey: { notes: 42 }, pageIdsByKey: {}, rootPageIds: [...], createdAt }]Every instantiation of your manifest in that workspace gets its own entry, oldest first — instantiating the same manifest twice in one workspace is two independent rows here too, matching the clone engine's own "no shared backing objects" guarantee. This is the same record a guard hook can resolve a bare database id back through, instead of keeping a hand-rolled per-plugin table.
A workspace member only ever reaches this through GET /api/spaces/:spaceId/presets (lists every enabled plugin's presets with icon, summary, description and a preview of board/list/table) and POST /api/spaces/:spaceId/presets/:presetId/instantiate (is_private in the body picks Workspace vs. Private visibility, defaulting to your manifest's own defaultVisibility) — presets_controller.ts is the real route if you need the exact request/response shape.
Building on other bundled plugins
Bundled plugins are plugins like yours: they offer each other (and you) their parts through the same two registries, services and extension points (see Services and extension points above), never through imports. In the browser that is the way in: api.registerExtension for a point, services.get for a service, both empty while the providing plugin is off.
Every bundled plugin's browser part is an SDK bundle, so in the browser services and extension points are the only way in; there are no per-plugin members on window.__votionHost. Server side, a few plugins expose plain globals (globalThis.__votionProjects, globalThis.__votionCrm, globalThis.__votionBilling, …). They are not part of the plugin API: check that they exist, and expect them to be missing while the plugin that provides them is off. New server-side services go through Server-side extension points instead.
Projects — a property on every project (globalThis.__votionProjects)
const property = await globalThis.__votionProjects?.ensurePluginProperty(spaceId, {
pluginId: 'crm',
key: 'crm.customer', // one property per key and workspace
name: 'Customer',
type: 'select',
config: { options: [] },
})Creates the property once in the workspace's Projects database, marks it template-managed and adds it to every project template, so it shows on every project and a change inside a project asks the usual template scope question. A second call returns the same property. While your plugin is off the property is hidden on projects; its values stay. Guard its options with registerPropertyOptionGuardHook if your plugin owns them. CRM's Customer property is the worked example.
CRM — the customer page
Server side, one provider per plugin feeds the customer list and page:
globalThis.__votionCrm?.registerCustomerProvider({
pluginId: 'billing',
id: 'crm.billing',
order: 30,
totals: async (ctx) => new Map(), // customerId → { open_cents } (list "Open")
metrics: async (ctx) => [], // { id, label, value, detail, order, revenue }
connection: async (ctx) => null, // { label, icon, summary } (Connected plugins)
data: async (ctx) => ({ invoices: [] }),// customer.plugins[pluginId]
activity: async (ctx) => [], // { id, kind, title, detail, at, href }
})ctx has spaceId, userId, customer, customers, contactIds, projectIds, canSeeRevenue and language — the request's language ('en' without one, e.g. for MCP): write labels, summaries and Activity rows in it with api.translate(ctx.language, key, params). Metrics with revenue: true are dropped without See revenue; withhold amounts elsewhere yourself. Providers are only asked while their plugin is on, and one that throws is skipped. A plugin that may load before CRM registers into globalThis.__votionCrmProviders (a Map by id) instead. Activity is derived: CRM stores only its notes.
In the browser, api.registerExtension(point, entry) adds to the page (the entry shapes are typed in @votion-plugin/crm/types, with the customer shapes Customer / CustomerDetail; pluginId is filled in for you):
'crm.customerSection'—{ id, column?, order?, component }: a card in the right column ('side', default) or after Activity ('main'); propscustomerandspaceId.'crm.customerAction'—{ id, label, primary?, order?, run }: a button in the page head;run(customer, { spaceId, anchor, router }). Billing registers New invoice (billing.new-invoice, primary); CRM has none of its own, so without Billing there is no such button.'crm.customerField'—{ id, order?, component }: a field in the New customer / Edit customer dialog; propscustomer(null while creating) andspaceId. ExposeafterSave(customer)to act once the customer is saved.
Each shows only while its pluginId is on in the workspace. Billing's own parts — the crm.billing provider (metrics, Invoices, project rows, Activity), the Billing client card and field and New invoice — are the worked example (plugins-bundled/billing/api/crm.js, plugins-bundled/billing/web/src/crm/).
Contacts — the contact page
api.registerExtension('contacts.contactSection', { id, order?, component }) adds a card to the right column of a contact's page; props contact and spaceId. CRM's Customer is order 10, the Projects card 20, Billing's Invoices 30. A card shows only while its pluginId is on, and never on a private contact; render nothing for a contact it has nothing for. The entry and contact shapes are typed in @votion-plugin/contacts/types.
To pick, share or draw contacts, use the contacts service (see Services offered today): CRM's Add contact searches with searchContacts, shares the pick with shareContact and draws each row with Contacts' own ContactAvatar and SourceBadge; Billing's invoice recipient searches the same way, and Mail's recipient field suggests contactEmailSuggestions.
Projects — All projects
api.registerExtension('projects.subline', { id, order?, label, summary?, load? }) puts a plugin's word at the start of a project's line on All projects — label(projectId) returns it or null; the lowest order with an answer wins (CRM 10, Billing 20). summary(activeProjectIds) adds a part to the header (“2 billed to customers”); load() is called when the page opens.
Projects — a project's page, its tasks and the projects service
api.registerExtension('projects.overviewBlock', { id, order?, component }) adds a block to a project's Overview after the metric cards; api.registerExtension('projects.settingsTab', { id, order?, label, component }) a tab to Project settings (per project, never inherited from the template). Billing's Billing block and tab are the worked example. A task's page takes sections through registerPageSection; ask services.get('projects')?.isAreaTask(databaseId) in applies to show yours only on Projects tasks (Billing's Time). Projects loads after plugins whose id sorts before it, so look the service up when you use it, never in register(). Its types: import type { ProjectsService } from '@votion-plugin/projects/types'.
Billing — invoices and clients
Server side, the Billing plugin exposes globalThis.__votionBilling while it is loaded. Each call checks that Billing is on in the workspace and that userId holds Create invoices:
const billing = globalThis.__votionBilling
if (billing) {
// A draft with lines (same body as POST /spaces/:id/invoices); returns the invoice row.
const draft = await billing.createInvoiceWithLines(spaceId, userId, {
client_id: clientId, // or recipient: { name, address, country }
project_id: projectId, // optional
lines: [{ description: 'Website relaunch', quantity: 18.5, unit: 'h', rate_cents: 9500 }],
})
// The client linked to a CRM customer (billing_client.crm_customer_id), or null.
const client = await billing.findClientByCrmCustomer(spaceId, crmCustomerId)
// Create a client, and link or unlink one to a CRM customer (1:1).
const created = await billing.createClient(spaceId, userId, { name: 'Hoffmann Bau', country: 'DE' })
await billing.linkClientToCrmCustomer(spaceId, userId, created.id, crmCustomerId)
}The draft's number is reserved from the workspace's number format; tax treatment and totals follow the client (see the Billing guide). In the browser, Billing provides the billing service while it is loaded — the pieces CRM's customer page draws the way Billing does:
import { services } from '@votion/host'
import type { BillingService } from '@votion-plugin/billing/types'
const billing: BillingService | undefined = services.get('billing')
// billing.BudgetBar — props `budget: { label, percent, state }`
// billing.InvoiceStatus — props `status: 'draft' | 'sent' | 'overdue' | …`
// billing.invoiceStatusLabels — 'Draft', 'Sent', 'Partially paid', …Look it up when you render (computed(() => services.get('billing'))), never in register(): Billing may load after you. Billing's own UI lives in plugins-bundled/billing/web/src/ and is built like any other plugin bundle; it fills Projects', CRM's and Contacts' extension points and registers the cell of the core-known time_tracking property type.
Development seed data (devSeed)
A plugin can ship its own sample data so a fresh development instance shows it filled in. just seed (node ace db:seed) first builds the core Kitchensink workspace, then runs the seed of every plugin that is enabled and on in that workspace. Bundled and uploaded plugins use the same mechanism; core never imports your code, it only follows your manifest:
{
"id": "hello-plugin",
"devSeed": { "entry": "api/dev_seed.js", "after": ["contacts"] }
}The module exports one function:
// api/dev_seed.js — only imported while seeding, never by a running server
export async function seed(ctx) {
const base = `/api/plugin-api/hello-plugin/spaces/${ctx.spaceId}`
const note = await ctx.once(
'note:welcome',
async () => {
const row = await ctx.api.post(`${base}/notes`, { title: 'Welcome' })
return { id: row.id }
},
// optional: create it again if someone deleted it by hand
async (value) => ctx.api.get(`${base}/notes/${value.id}`).then(() => true, () => false)
)
ctx.log(`welcome note ${note.id}`)
}What ctx holds:
| Member | What it is |
|---|---|
spaceId | The seeded workspace (Kitchensink). |
owner, member | { id, email, name } of the workspace owner (john.doe) and of a second member (jane.roe), or member: null. |
api.get / post / patch / put / delete(path, body?, { as?, query? }) | This instance's REST API — core routes and every plugin's /api/plugin-api/<id>/…. Paths start with /api/. Requests run as the owner, or as the member with { as: 'member' }, with a short-lived token that is deleted afterwards. Resolves to the response body; a status of 400 or more throws an error naming the method, path, status and message. |
once(key, create, exists?) | Runs create once per workspace and stores what it returns (keep it small: an id) under key; later runs return the stored value instead of creating a duplicate. With exists, a stored record that no longer exists is created again. |
isEnabled(pluginId) | Whether another plugin is on in the workspace — for data that links to it. |
log(message) | A line in the just seed output. |
Rules:
- Development and tests only. The runner refuses to start in production, and the seeder only runs in the
developmentandtestingenvironments. - Write through the API. Create your records with your own routes (and core's), as your UI does — so they pass your validation and permissions. Never write to another plugin's tables; read other plugins through their routes (CRM's customers, Projects' overview).
- Idempotent. Wrap every create in
ctx.once. The keys are stored per plugin and workspace inplugin_dev_seed_records, and removed with the workspace or when your plugin is uninstalled. - Order. Seeds run after every plugin in
requires, then after the plugins indevSeed.afterthat are seeded too. A plugin that is off in the workspace is skipped. If a seed throws, the others still run andjust seedfails at the end, naming it. - Realistic. Use names a real workspace would have (companies, people, projects), not test markers.
- A bundled plugin's files are copied into storage only when its
versiongoes up, so bump it when you add or change the seed.
The bundled plugins' seeds are the worked examples: plugins-bundled/contacts/api/dev_seed.js, crm, projects, billing, calendar and daily-notes (Mail has none: an account needs a real Gmail or IMAP server).
Install, enable, and remove
- Build your zip with
manifest.jsonat its root, alongside yourapi/,web/andmigrations/directories (whichever you use). - Upload it from the workspace switcher's Plugins item (admin-only, next to Invites). This validates the manifest, extracts the zip, and runs your migrations — but installs the plugin disabled. Installing never runs your
entry.apicode. - Enable it from the same screen. This is the moment your
entry.apimodule actually runsregister()for the first time in this process; its hooks become active immediately. If your plugin hasentry.web, every signed-in browser's next page load picks up the bundle atGET /api/plugins/:id/web. - Disable it to turn its hooks off again without touching its data — disabling only removes it from the enabled-set the hooks check against; your tables and rows are untouched.
- Remove it (must be disabled first) to roll its migrations back and delete its extracted files for good.
A broken entry.api module (throws during register()) is logged and left enabled-but-unloaded rather than taking the whole process down — check the server logs and disable/remove it from the admin screen.
Minimal walkthrough
To build the smallest useful plugin:
- Copy
apps/api/plugins-examples/hello-plugin/as your starting point and rename itsidinmanifest.json. - Delete the hooks you don't need from both entry files and from the manifest's
hookslist. - If you need your own data, write a migration for your own table(s), FK'd to
pages/usersas needed. - Zip the plugin's root directory (so
manifest.jsonsits at the zip's top level, not inside a subfolder) and upload it from the workspace switcher's Plugins item. - Enable it, confirm your route/sidebar/settings panel shows up in the browser and your API routes answer at
/api/plugin-api/<your-id>/....
For non-trivial references beyond hello-plugin, read the bundled plugins under apps/api/plugins-bundled/. Daily Notes (daily-notes/) is the smallest: a preset-only plugin whose whole server entry is one registerPreset call — a database with views, an icon/cover, pageTypes and a manifest-declared default row template (api/preset.js). Projects (projects/{api,web/src}) is the largest: an SDK-built web half plus registerPageOpenRouteHook/ registerPageListingOpenAsHook, page overlays, search tabs and the row-level write guards.