Airpost
Plugins

Plugins overview

How desktop plugins are structured, discovered and loaded, and what they can and can't do.

A plugin is a package that the desktop app loads into its windows. It can add React components to named slots in the UI, hook into composing and reading mail, call the engine, and ship styles, keymaps and menus. Logic that has to run while the app is closed goes in a service plugin.

To install a plugin someone else wrote, see Plugins. This section is for writing one.

Plugins are fully trusted code. They run in the app’s windows with Node and can reach everything the app can: files, the network, the engine socket, your mail. Nothing in the plugin API is a security boundary.

Package layout

my-plugin/
├── package.json          # Required: metadata
├── lib/
│   └── main.ts           # Required: exports activate() and deactivate()
├── styles/               # Optional: CSS, loaded automatically
├── keymaps/              # Optional: keyboard shortcuts, loaded automatically
├── menus/                # Optional: menu definitions, loaded automatically
├── assets/               # Optional: images, sounds
└── tests/                # Optional: Jasmine tests (*.test.ts)

In dev mode (npm start in apps/desktop, which passes --dev, or any build launched with --dev) the app compiles .ts and .tsx on the fly and caches the result in the profile. Packaged builds don’t ship the TypeScript compiler: a regular install that hits a .ts, .tsx or .jsx file shows a “Plugin must be compiled” dialog instead (src/platform/compile-cache-ts-unsupported.js). So develop in TypeScript under --dev, and compile to plain CommonJS JavaScript before you share the plugin, leaving mailspring-exports, mailspring-component-kit, react and the other app modules as external imports.

Stylesheets load from styles/: index.css alone if there is one, otherwise every file sorted by name. Write plain CSS that reads the theme tokens and the core values in static/styles/variables.css (var(--spacing-standard), var(--font-size-small)). LESS still compiles for compatibility with Mailspring plugins, but is removed at plugin API 2.0.

package.json

{
  "name": "my-plugin",
  "version": "1.0.0",
  "displayName": "My Plugin",
  "description": "What the plugin does",
  "main": "./lib/main",
  "license": "GPL-3.0-only",
  "engines": {
    "airpost": "^1.39.0"
  },
  "windowTypes": {
    "default": true,
    "composer": true,
    "thread-popout": true
  },
  "isOptional": true
}
FieldRequiredDescription
nameYesPackage id, kebab-case. Also the host in airpost-asset://<name>/... URLs
versionYesSemantic version
mainYes, except themesEntry point
engines.airpostYesSemver range of plugin API versions the plugin works with. engines.mailspring is read too
displayName, descriptionNoShown in Preferences > Plugins
windowTypesNoWhich windows load the plugin: default (main window), composer, thread-popout, emptyWindow, or all
isOptionalNoThe user can turn it off
syncInitNoActivate during startup instead of after the delay
themeNo"ui" for a theme
airpost.engineMethodsNoLocal-only engine methods the plugin calls (see Engine)
airpost.serviceNoA background program the OS runs beside the engine (see Service plugins)

Lifecycle

lib/main.ts exports activate() and deactivate(). Unregister everything in deactivate() that you registered in activate().

import { ComponentRegistry, ExtensionRegistry } from 'mailspring-exports';
import MyButton from './my-button';
import MyExtension from './my-extension';

export function activate() {
  ComponentRegistry.register(MyButton, { role: 'Composer:ActionButton' });
  ExtensionRegistry.Composer.register(MyExtension);
}

export function deactivate() {
  ComponentRegistry.unregister(MyButton);
  ExtensionRegistry.Composer.unregister(MyExtension);
}

The loading sequence is:

  1. The package manager discovers packages in each directory below.
  2. It keeps those whose windowTypes match the current window.
  3. It checks that the plugin API version satisfies engines.airpost. A missing or unsatisfied range is logged and the package is skipped.
  4. Packages with syncInit: true activate immediately; the rest about 2.5 seconds later.
  5. For each package it loads keymaps, stylesheets and menus, requires main, and calls activate().

Where plugins are found

DirectoryContents
The app’s src/features/, plugins/, themes/Built-in features, bundled optional plugins, bundled themes
<profile>/packages/Plugins you install. Skipped in safe mode
<profile>/dev/packages/Loaded only in dev mode

The profile is ~/Library/Application Support/Airpost on macOS, ~/.config/Airpost on Linux and %APPDATA%\Airpost on Windows (Airpost-dev when running with --dev). A user package with the same name as a built-in feature replaces it.

Build a plugin from zero

This walkthrough builds thread-stats: a banner above the message list that counts the messages and senders in the open thread, a toolbar button that stars the selected threads, a config option, a Preferences tab and a keyboard shortcut. Every API it uses is in mailspring-exports or mailspring-component-kit.

1. Create the folder

Run the app from source once (make desktop in the repository root uses the .dev/profile profile), then create the plugin in the dev packages directory so it only loads in dev mode:

mkdir -p .dev/profile/dev/packages/thread-stats/{lib,styles,keymaps}
cd .dev/profile/dev/packages/thread-stats

With an installed build, use <profile>/dev/packages/ and start the app with --dev.

2. package.json

{
  "name": "thread-stats",
  "version": "0.1.0",
  "displayName": "Thread Stats",
  "description": "Counts messages and senders in the open thread.",
  "main": "./lib/main",
  "license": "GPL-3.0-only",
  "isOptional": true,
  "engines": { "airpost": "^1.33.0" },
  "windowTypes": { "default": true, "thread-popout": true }
}

^1.33.0 because the Preferences building blocks used in step 6 arrived in 1.33.0.

3. The banner

MessageListHeaders components get thread and messages as props (src/features/message-list/message-list.tsx). Create lib/banner.tsx:

import React from 'react';
import { localized, Thread, Message } from 'mailspring-exports';

export default class ThreadStatsBanner extends React.Component<{
  thread?: Thread;
  messages?: Message[];
}> {
  static displayName = 'ThreadStatsBanner';

  render() {
    const { messages = [] } = this.props;
    if (!AppEnv.config.get('thread-stats.showBanner') || messages.length < 2) {
      return null;
    }
    const senders = new Set(messages.map(m => (m.from[0]?.email || '').toLowerCase()));
    return (
      <div className="thread-stats-banner">
        {localized('%@ messages from %@ senders', messages.length, senders.size)}
      </div>
    );
  }
}

4. The toolbar button

ThreadActionsToolbarButton components get items (the selected threads), selection and thread (src/features/thread-list/injects-toolbar-buttons.tsx). Create lib/star-button.tsx:

import React from 'react';
import { Actions, ChangeStarredTask, Thread } from 'mailspring-exports';
import { IconButton } from 'mailspring-component-kit';

export default class StarAllButton extends React.Component<{ items: Thread[] }> {
  static displayName = 'StarAllButton';

  _onClick = () => {
    const threads = this.props.items;
    const starred = !threads.every(t => t.starred);
    Actions.queueTask(new ChangeStarredTask({ threads, starred }));
  };

  render() {
    return <IconButton variant="toolbar" icon="toolbar-star.png" label="Star all" onClick={this._onClick} />;
  }
}

The task goes to the engine; the thread list updates when the engine’s delta comes back. Nothing writes to the database from the window.

icon is a RetinaImg image name from the app’s static/images/ (here toolbar/toolbar-star@2x.png). For your own image, pass iconUrl="airpost-asset://thread-stats/assets/star.png" instead. The icon is drawn as a mask in the button’s text colour.

5. Config, command and activation

Create lib/main.ts:

import {
  ComponentRegistry,
  PreferencesUIStore,
  localized,
} from 'mailspring-exports';
import ThreadStatsBanner from './banner';
import StarAllButton from './star-button';

// Read by src/packages/resources.ts: becomes the schema under "thread-stats".
export const config = {
  showBanner: { type: 'boolean', default: true, title: 'Show the thread stats banner' },
};

let tab = null;
let commands = null;

export function activate() {
  ComponentRegistry.register(ThreadStatsBanner, { role: 'MessageListHeaders' });
  ComponentRegistry.register(StarAllButton, { role: 'ThreadActionsToolbarButton' });

  tab = new PreferencesUIStore.TabItem({
    tabId: 'ThreadStats',
    displayName: localized('Thread Stats'),
    componentClassFn: () => require('./preferences').default,
  });
  PreferencesUIStore.registerPreferencesTab(tab);

  commands = AppEnv.commands.add(document.body, 'thread-stats:toggle-banner', () => {
    AppEnv.config.set('thread-stats.showBanner', !AppEnv.config.get('thread-stats.showBanner'));
  });
}

export function deactivate() {
  ComponentRegistry.unregister(ThreadStatsBanner);
  ComponentRegistry.unregister(StarAllButton);
  if (tab) PreferencesUIStore.unregisterPreferencesTab(tab.tabId);
  if (commands) commands.dispose();
}

componentClassFn is a function so the tab’s code loads only when the user opens it, the same way plugins/ai and plugins/composer-templates do it.

6. The Preferences tab

Create lib/preferences.tsx:

import React from 'react';
import { SettingsPage, SettingsSection, ConfigSwitchRow } from 'mailspring-component-kit';

export default function ThreadStatsPreferences() {
  return (
    <SettingsPage title="Thread Stats">
      <SettingsSection title="Banner">
        <ConfigSwitchRow
          keyPath="thread-stats.showBanner"
          label="Show the banner above the message list"
        />
      </SettingsSection>
    </SettingsPage>
  );
}

ConfigSwitchRow reads and writes AppEnv.config at keyPath for you.

7. Styles and keymap

styles/index.css, reading theme tokens so it works in every theme:

.thread-stats-banner {
  padding: var(--spacing-half) var(--spacing-standard);
  color: var(--muted-foreground);
  background: var(--secondary);
  border-bottom: 1px solid var(--border);
  font-size: var(--font-size-small);
}

keymaps/thread-stats.json, in the same format as src/features/composer/keymaps/composer.json:

{
  "thread-stats:toggle-banner": "mod+shift+i"
}

8. Load it

Restart the app, or use Developer > Reload. Open a thread with a few messages; the banner appears above the list. Select threads and the star button appears in the toolbar. Preferences now has a Thread Stats tab. If nothing shows, open Developer > Toggle Developer Tools and look for errors from thread-stats; a version range the API doesn’t satisfy is logged and the package is skipped.

The ComponentRegistry can outline every injection point: run $m.ComponentRegistry.toggleComponentRegions() in the console ($m is mailspring-exports) to see where each role renders.

9. Test it

Plugin tests are Jasmine files under tests/ named *.test.ts or *.test.tsx, like plugins/phishing-detection/tests/main.test.tsx. Bundled plugins in apps/desktop/plugins/ run with the app’s suite (npm test in apps/desktop). For a plugin elsewhere, the main process has an application:run-package-specs command (src/main/application.ts) that asks for a directory and runs its specs in a window. TestUtils in mailspring-exports has the helpers the bundled tests use.

10. Ship it

Compile lib/ to JavaScript, keep package.json, styles/ and keymaps/ as they are, and point main at the compiled entry. Users install the folder with Preferences > Plugins > Install from a folder…, which copies it into <profile>/packages/.

Developing a plugin

  1. Run the app from source (see Building from source), or use an installed build.
  2. Put your plugin folder, or a symlink to it, in <profile>/packages/. Preferences > Plugins > Install from a folder… copies a folder there for you.
  3. Restart the app, then use Developer > Reload after each change to renderer code.
  4. Open Developer > Toggle Developer Tools for the console. $m is mailspring-exports.

The bundled plugins in apps/desktop/plugins/ (for example composer-templates, send-later, translation, phishing-detection) are working references.

Optional bundled plugins can be turned off with core.disabledPackages in the config:

{ "core": { "disabledPackages": ["plugin-name"] } }

Limits

  • No marketplace and no update mechanism: plugins are installed and updated by hand.
  • No sandbox: plugins have full access.
  • Composer editor (Slate) plugins are registered in core code only; see Composer plugins.

Next