Architecture
A contributor's map of Airpost: the crate graph, the processes, the engine protocol, the store, the task pipeline, the desktop's main and renderer split, plugin loading, and how to trace a feature end to end.
This page is for people changing Airpost’s code. For the user-level picture (what runs where and why), see the concepts section. Here you get the pieces you touch when you change something, and the files they live in.
Airpost is one sync engine and several clients. The engine (apps/engine, the airpost-engine binary) is the only process that touches mail. Every other program speaks the engine protocol and owns only its own surface. Airpost is a fork of Mailspring (the desktop app) and Mailspring-Sync, which was ported from C++ to Rust as the engine. Upstream Mailspring-Sync is still the reference for the engine’s behaviour, and C++ paths in comments (MailSync/...) are relative to it.
Engine and backend
The split between the engine and the backend is a trust boundary.
Engine (apps/engine) | Backend (apps/backend) | |
|---|---|---|
| Serves | One person: their accounts on one device, or on their own server, headless | Many users: self-hosted for a team or family |
| Holds | IMAP, SMTP and OAuth credentials, the mail database, bodies, attachments, search | Users, device tokens, plugin metadata, tracking events, shared pages and assets |
| Never holds | Other users’ data | Mail credentials or mail content |
| Reachable from | The local user only (Unix socket, peer uid check); remote clients only through apps/gateway | The public internet |
The engine and the backend share only the wire types in crates/airpost-wire, which depends on nothing but serde and serde_json. If you find yourself wanting the backend to import an engine crate, the change is in the wrong place.
Crate graph
One Cargo workspace at the repository root covers the apps and the crates. The graph below is the runtime [dependencies] of each Cargo.toml (dev-dependencies left out). airpost-core sits under almost everything and is omitted from the arrows to keep the graph readable.
Three things follow from the graph:
airpost-ipcdepends on serde, serde_json and schemars only. The CLI, the MCP server, the gateway and third-party tools use it without pulling in the engine.- The clients (
cli,mcp,gateway) never depend onairpost-storeorairpost-sync. They read through the protocol, not the database. - Workers in
airpost-syncreachairpost-tasksthroughairpost_sync::TaskRunnerFactory, which the engine binary fills withairpost_tasks::Tasks. That seam is whyairpost-syncdoesn’t depend onairpost-tasks.
apps/engine/CLAUDE.md has a table of what each engine crate owns. The Repository layout page has the short version.
Process model
No client embeds another, and there is no orchestrator. The desktop starts an engine when none is running; a headless install runs the engine and gateway as launchd or systemd units (deploy/systemd) or in a compose file (deploy/server).
Engine modes
airpost-engine takes --mode (parsed in apps/engine/src/cli.rs):
| Mode | What it does |
|---|---|
serve | Every account in one process, added and removed by the parent over stdin. Listens on <config-dir>/run/engine.sock unless --socket names another path. With --detached there is no parent channel, and the socket takes the parent methods from local connections |
sync | One account per process, the C++ engine’s model. Used by the harness and for A/B runs |
test | Checks an account’s IMAP and SMTP settings and prints the result |
reset | Deletes one account’s rows |
migrate | Creates or upgrades airpost.db. serve runs it before it accepts connections |
install-check | Checks the install |
import-legacy | Imports from a database moved aside as airpost.legacy.db |
Inside serve, each account has named threads (background, foreground, calContacts, metadata, metadataExpiration, calendar, from airpost_core::constants::thread). An account’s threads are spawned with WorkerContext::spawn so their log lines go to that account’s file. A failure on an account’s thread stops that account only and sends account.state stopped; a panic on an engine-wide thread (stdin, socket, signals) aborts the process.
Credentials
The engine holds account passwords, OAuth refresh tokens, integration keys and the Airpost server token (crates/airpost-secrets). It keeps them as one keyset in one item: the macOS Keychain (service “Airpost Engine”), the Linux Secret Service, or secrets.enc in the profile, AES-256-GCM with a key from AIRPOST_ENGINE_KEY_FILE or systemd’s $CREDENTIALS_DIRECTORY. There is no plaintext backend. A keyset that is stored but can’t be read is an error, not an empty keyset. There is no secrets.get method: a client can store and delete a secret and ask whether one exists, never read it back.
The desktop still has its own keyset too: the credentials key in config.json, encrypted with Electron safeStorage (keychain item “Airpost Safe Storage”) by the main process (apps/desktop/src/main/profile/key-manager.ts). Older profiles kept account secrets there. On upgrade, credentials.import moves them into the engine and sets credentialsMovedToEngine. A copy of the old blob stays under credentialsBeforeEngine for one release so a downgrade still works. After the move, credentials holds only integration keys the desktop still reads.
The engine protocol
The protocol lives in crates/airpost-ipc. It is JSON-RPC 2.0 over newline-delimited JSON: one message per line, UTF-8, \n after each (frame.rs). A line longer than MAX_LINE_BYTES is a framing error and ends the connection. PROTOCOL_VERSION is 1; additive changes (a new method, a new optional field) keep it.
A connection goes like this:
- The client sends
hellowithprotocol: 1and a free-formclientstring such asairpost-cli/0.1.0.hellomust be the first request, or the answer isHELLO_REQUIRED. - The engine answers with its version, pid, accounts,
featuresandcapabilities. Clients gate behaviour onfeatures, never on the engine version string. - The client calls
subscribe(optionally withaccounts,classesand asincecursor) to start receivingdeltanotifications. - From then on the client sends requests and reads responses and notifications on the same socket.
The gateway sets relayed: true, scopes and device on the hello it sends for a remote device. The first hello fixes them for the connection, and the engine checks crates/airpost-ipc/src/policy.rs again on every relayed connection, so a compromised gateway can’t widen a device’s rights by itself.
Method groups
Method names are constants in the method module of crates/airpost-ipc/src/lib.rs. Use the constant (method::THREADS_LIST), not the string.
| Group | Methods |
|---|---|
| Connection | hello, subscribe, engine.status, engine.logs.tail |
| Reads | folders.list, labels.list, threads.list, threads.get, messages.get, search, contacts.search, counts.get, tasks.get, tasks.list, metadata.list, query |
| Live queries | query.subscribe, query.setWindow, query.unsubscribe, notification query.changed |
| Tasks | task.queue, task.cancel, sync.wake, bodies.fetch, calendar.sync |
| Intents | threads.archive, threads.trash, threads.spam, threads.notSpam, threads.move, threads.label, threads.markRead, threads.star, threads.removeFromView, threads.snooze, threads.unsnooze, categories.markRead, categories.create, categories.rename, categories.delete, categories.empty |
| Undo | undo.apply, undo.redo, undo.list, undo.record, notification undo.changed |
| Drafts | draft.create, draft.update, draft.delete, draft.validate, draft.send, draft.cancelSend |
| Files | files.get, files.read, files.put |
| Templates | templates.list, templates.get, templates.save, templates.delete |
| Calendar and contacts | events.expand, events.subscribe, events.unsubscribe, events.create, events.update, events.rsvp, notification events.changed, contacts.get, contacts.create, contacts.update, contacts.import, contacts.export |
| Accounts | account.list, account.add, account.remove, account.test, account.reset, account.discover, account.oauth.begin, account.oauth.complete, account.setSecrets, account.update, account.reorder, notification account.changed |
| Secrets and server | secrets.set, secrets.delete, secrets.has, server.set, server.clear |
| Engine lifecycle | engine.shutdown, engine.resetDatabase, engine.setLogLevel, credentials.import |
| Other | messages.unsubscribe, settings, rules, AI and integration methods (see the rest of the method module) |
Every method has a class in policy.rs: open to any connection, local clients and admin-scoped devices only, or stdin only. A method the table doesn’t name is local-only by default, so a new method is closed to remote devices until you say otherwise.
Deltas
A delta notification carries DeltaParams (methods.rs):
{"jsonrpc":"2.0","method":"delta","params":{
"accountId":"a1b2c3d4","seq":1042,"modelClass":"Thread",
"type":"persist","modelJSONs":[{"id":"...","unread":false}]}}
type is persist, unpersist or metadata-expiration. seq lets a client resume with subscribe { since } after a reconnect.
Error codes
Standard JSON-RPC codes plus Airpost’s, from the code module:
| Code | Name |
|---|---|
| -32700, -32600, -32601, -32602, -32603 | Parse error, invalid request, method not found, invalid params, internal error |
| -32000 | UNSUPPORTED_PROTOCOL |
| -32001 | UNKNOWN_ACCOUNT |
| -32002 | TASK_REJECTED |
| -32003 | HELLO_REQUIRED |
| -32004 | NOT_FOUND |
| -32005 | ACCOUNT_STOPPED |
| -32006 | ACCOUNT_EXISTS |
| -32007 | WRONG_CHANNEL (a stdin-only method on the socket) |
| -32008 | FORBIDDEN_RELAYED |
TypeScript types
The Rust types are the source of truth. crates/airpost-ipc/src/bin/airpost-ipc-schema.rs emits one JSON Schema document, and packages/client (@airpost/client) generates the TypeScript the desktop and web use from it:
cd packages/client
npm run generate # regenerate after changing a type in airpost-ipc
npm run check # fails if the generated files are stale
You can poke the protocol by hand with the CLI’s raw call:
make airpost ARGS="rpc engine.status"
make airpost ARGS="rpc folders.list '{\"accountId\":\"<id>\"}'"
The store
crates/airpost-store owns the SQLite database, airpost.db in the profile. The base schema is V12_SCHEMA in schema.rs: the final schema the C++ engine reaches, replayed statement for statement so a database created here has the same sqlite_master as one from Mailspring-Sync. PRAGMA user_version is 12 for that schema and goes up by one with each entry of MIGRATIONS.
Most model tables share one shape: an id, an accountId, a version, the model’s full JSON in data, and a few columns pulled out of it for indexes. Models wrap their JSON and expose typed accessors over it, so keys the engine doesn’t know survive a save.
| Table | Holds |
|---|---|
Thread, ThreadCategory, ThreadReference, ThreadCounts | Threads, which folders or labels each is in, header references for threading, unread and total counts per category |
Message, MessageBody, MessageFolder, MessageOrphan | Messages, their bodies, every server copy of a message (folder, UID, flags), messages waiting for the orphan sweep |
Folder, Label | Categories, with path and role |
File | Attachments |
Contact, ContactBook, ContactGroup, ContactContactGroup | Contacts and CardDAV books and groups |
Calendar, Event, EventSearch | Calendars, events, and the FTS5 index over them |
Task | Queued and finished tasks, with status |
ModelPluginMetadata, DetatchedPluginMetadata | Plugin metadata on threads and messages |
Account, _State | Account rows and engine key-value state |
DraftTombstone | Drafts deleted locally, so sync doesn’t bring them back (migration 14) |
Migration 13 adds a lookup index on ThreadReference. To change the schema:
- Add an entry to
MIGRATIONSincrates/airpost-store/src/schema.rswith the nextversion. - Bump
SCHEMA_VERSIONinairpost_core::constants. - Add what the migration creates to
crates/airpost-store/tests/fixtures/migrations.json.tests/schema.rscompares a migrated database againstv12_schema.jsonplus that file.
Never edit a migration that has shipped. A database from a newer build is refused, and a C++ engine’s database is moved aside to airpost.legacy.db rather than upgraded. apps/engine/tools/schema_check.py check <airpost.db> compares a real database against the expected schema.
Stores are !Send: one Store per thread. Writes that emit deltas run in store.transaction("<function_name>", |s| ...), which batches the deltas until commit.
The task pipeline
Every write a client asks for is a task or an intent. Clients never write the database.
crates/airpost-tasks/src/lib.rs holds TaskProcessor. A task goes local to remote to complete or cancelled:
- Local phase:
perform_localsaves the task, runsperform_local_by_class, which matches on the task’s class name (ChangeUnreadTask,ChangeStarredTask,ChangeFolderTask,ChangeLabelsTask,SyncbackDraftTask,DestroyDraftTask,SyncbackMetadataTask,ChangeRoleMappingTask, the contact and event tasks, and so on), and sets the status toremote. Each run records its own undo data. - Remote phase: the account’s foreground worker picks up
remotetasks and runs the matching remote function against the server (SendDraftTaskgoes throughperform_remote_send_draft, flag changes throughapply_*_in_imap_folder). - Failure: there are no automatic retries. A failure ends the task as
completewitherrorset.SendDraftTaskcan be deferred until the account is online. - Cancel:
task.cancelflags the task; its remote phase ends it ascancelledif it hasn’t started.
Intents (threads.archive and the rest) are the engine deciding which tasks a mail action means. On Gmail an archive removes the inbox label; elsewhere the copies move to Archive, else All Mail. The engine resolves that, queues the tasks, and records an undo entry. Undo is the engine’s log (undo.*), and apps/engine/src/undo.rs with crates/airpost-tasks/src/undo.rs implement it.
An unknown class is logged and ignored in the local phase. A plugin that queues its own task class needs engine support for that class, or it has to be expressed as SyncbackMetadataTask on plugin metadata.
The desktop: main process and windows
The desktop (apps/desktop) is Electron with TypeScript and React 17, compiled at runtime, no bundler.
| Runs in | Code |
|---|---|
| Main process only | src/main/, src/engine/supervisor/, src/config/migrator.ts, src/config/persistence-manager.ts |
| Both | src/intl/, src/platform/, src/config/, the root files of src/engine/ (protocol.ts, process.ts, channels.ts) and a few single files listed in the main-process override in .eslintrc |
| Windows only | Everything else: src/engine/client/, src/data/, src/components/, src/features/, src/packages/, plugins/ |
import/no-restricted-paths in .eslintrc enforces the split in both directions, so npm run lint fails on a window import from main code.
The two processes talk to the engine on different channels:
- Main process to engine, stdin and stdout (
engine/supervisor/supervisor.ts,engine/supervisor/host.ts,EngineServeProcessinengine/process.ts). Calls that carry credentials or manage the engine:account.add,account.remove,account.test,account.reset,engine.resetDatabase,engine.setLogLevel,engine.shutdown. Windows reach these over Electron IPC (engine/channels.ts). - Each window to engine, the Unix socket (
engine/client/connection.ts, on@airpost/client’sSessionandunixTransport).hello,subscribe,task.queue, reads and deltas.
The windows’ database is read-only. DatabaseStore.inTransaction() throws. Reads go to the engine’s query method (data/database/engine-reads.ts). core.engine.reads: "sqlite" is a kill switch that reads a read-only better-sqlite3 connection to airpost.db instead.
User action → Actions.queueTask() → EngineBridge → task.queue → engine
│
▼
UI updates ← QuerySubscription ← query.changed (live queries)
← DatabaseStore.trigger() ← delta notifications
EngineBridge in the main window listens to Actions.queueTask and sends tasks on its connection. Mail actions come from TaskFactory, the perspectives and the pickers as an IntentTask (src/data/tasks/intent.ts), which the bridge runs as the intent RPC. TaskQueue (data/stores/task-queue.ts) follows the Task table through a live query and offers waitForPerformLocal and waitForPerformRemote. QuerySubscription (data/query/subscription.ts) is a live query when the engine has the live-queries feature: the engine sends rows and query.changed, and the subscription doesn’t read change records at all.
How plugins load
PackageManager (src/packages/manager.ts) builds a list of package directories at startup:
- The bundled roots from
src/packages/bundled-packages.ts:src/features,plugins/,themes/. <config-dir>/packages, unless the app runs in safe mode.<config-dir>/dev/packages, in dev mode only.
In spec mode it uses tests/support/fixtures/packages instead. Built-in features and bundled packages are discovered as one list sorted by directory name, and later directories override earlier ones, so a user package with the same name replaces a built-in one.
For each window, activatePackages(windowType) activates every package whose windowTypes names that window (or all). Packages with syncInit activate at once; the rest activate after 2.5 seconds. Before activating, the manager:
- skips an optional package listed in
core.disabledPackages, - checks the plugin API range in
engines.airpost(orengines.mailspring) against the app’s plugin API version, and refuses a package that lists neither.
A built-in feature in src/features/<dir>/ has no package.json. Its entry in src/features/index.ts gives the package name, windowTypes, syncInit and a lazy require of its index.ts, and PackageManager wraps it in a BuiltinFeature. The directory name is the mailspring://<dir>/ asset host, so don’t rename one. tests/packages/builtin-features.test.ts pins the activation order, which is also the order toolbar buttons and composer extensions register in.
Plugins reach the app through the plugin API modules in src/packages/api/ (mailspring-exports, mailspring-component-kit, mailspring-store, mailspring-observables), which keep their Mailspring names for compatibility. App code imports the defining modules by relative path instead. See Plugins.
Service plugins are different: they are separate programs the engine supervises, not desktop code. See Service plugins and examples/service-plugin.
Tracing a feature end to end
Take starring a thread, and follow it through every layer.
- The button. Find the UI in
apps/desktop/src/features/orplugins/. Search both: a lot of the app is a bundled plugin. The star button infeatures/thread-list/toolbar-buttons.tsxcallsTaskFactory.taskForInvertingStarred(data/tasks/factory.ts), which returnsIntentTask.forThreads(Method.ThreadsStar, ...), and queues it withActions.queueTask. - The bridge.
EngineBridgesends the intent as an RPC on the main window’s socket connection. Turn on the dev tools (Developer > Toggle Developer Tools) and$mgives youmailspring-exportsto inspect stores and queue tasks by hand. - The method. Look up
THREADS_STARin themethodmodule ofcrates/airpost-ipc/src/lib.rsand its params,ThreadsStarParams.policy.rssays who may call it. - The dispatch. In
apps/engine/src, grep formethod::THREADS_STAR. Intents are inintents.rs; reads are inread_api.rs(for examplemethod::FOLDERS_LIST); drafts, PIM, templates and accounts have their own*_api.rs. - The task. The intent turns into
ChangeStarredTask. Its local phase ismessages::apply_starredincrates/airpost-tasks/src/messages.rs, its remote phaseapply_starred_in_imap_folder. - The deltas. The local phase saves
MessageandThreadrows in a store transaction, which emitsdeltanotifications. Watch them withmake airpost ARGS="watch --class Thread,Message,Task". - The server. The engine’s log for the account shows
Running ChangeStarredTask performLocal:and the remote phase.make airpost ARGS="logs -f"follows it. - The UI update. The thread list’s live query gets
query.changedand re-renders.
The same path works for any other feature: start from the method constant and grep for it in apps/engine, apps/cli, apps/mcp, apps/desktop/src and packages/client.