wax

Writing a plugin

Wax plugins are sandboxed WebAssembly components. This guide goes from an empty folder to a working plugin, then covers the whole interface.

How plugins work

Quick start

This plugin stars any new mail whose subject mentions "urgent".

1. Make the crate. Put it in plugins/ so it can find the interface:

mkdir -p plugins/urgent/src

plugins/urgent/Cargo.toml:

[package]
name = "wax-urgent"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
crate-type = ["cdylib"]

[dependencies]
wit-bindgen = "0.63"

[profile.release]
opt-level = "s"
lto = true
strip = true

# Built on its own, not as part of the app.
[workspace]

2. Implement the world. plugins/urgent/src/lib.rs:

wit_bindgen::generate!({ world: "plugin", path: "../../wit/plugin.wit" });

use wax::plugin::types::Permission;

struct Urgent;

impl Guest for Urgent {
    fn manifest() -> Manifest {
        Manifest {
            id: "urgent".into(),
            name: "Urgent".into(),
            version: env!("CARGO_PKG_VERSION").into(),
            permissions: vec![Permission::ReadEnvelopes, Permission::ModifyMail],
            network_hosts: vec![],
            scan_existing: false,
        }
    }

    fn on_message_received(message: Envelope, reason: CheckReason) -> Vec<Action> {
        if reason != CheckReason::Arrived {
            return vec![];
        }
        if message.subject.to_lowercase().contains("urgent") {
            vec![Action::Star(true)]
        } else {
            vec![]
        }
    }

    // The rest of the world. Return "nothing" for the parts you don't use.
    fn commands() -> Vec<Command> { vec![] }
    fn run_command(_id: String, _choice: Option<String>, _message: Option<Envelope>) -> Result<Vec<Action>, String> {
        Err("no commands".into())
    }
    fn panel() -> Option<Panel> { None }
    fn get_sender_view(_account: String) -> Option<SenderView> { None }
    fn on_sender_key(_account: String, _who: Sender, _key: String) -> Result<Vec<Action>, String> {
        Ok(vec![])
    }
}

export!(Urgent);

3. Build and install.

scripts/build-plugins.sh urgent

This builds plugins/urgent for wasm32-wasip2 and copies it to ~/.config/wax/plugins/urgent/plugin.wasm. If the crate has a config.example.toml, the script also copies it to config.toml the first time.

4. Switch it on. Within two seconds, Wax notices the new folder. Open Settings → Plugins, check what it asks for and choose On.

On disk

~/.config/wax/plugins/<id>/
  plugin.wasm    the component
  grants.toml    on/off and what you allowed (written by Wax and Settings)
  config.toml    the plugin's own settings, edited by you
  storage.toml   the plugin's key-value store (needs `storage`)

grants.toml looks like this:

enabled = true
permissions = "read-envelopes modify-mail"

Wax reloads the plugins when any plugin.wasm or grants.toml changes. A plugin can only be granted permissions its manifest asks for.

Life of a call

Wax compiles each plugin once at load. Every call (manifest, on-message-received, get-sender-view and the rest) then runs on a new instance. Nothing survives between calls: statics and globals start fresh each time. Keep settings in config.toml (read with config()) and anything you learn in storage (storage-get and storage-set).

Export When Wax calls it Needs
manifest At load, and whenever the plugins reload —
on-message-received Each new Inbox message that sender rules didn't file, before it's shown or announced; and for checkers, existing mail too (see below) read-envelopes
get-sender-view When you open the Sweep (g w); the first running plugin that returns a view wins read-envelopes
on-sender-key When you press one of your view's keys on a sender row read-envelopes
commands At load, and each time one of your commands' menus opens (so choices can show current times) —
run-command When you press a command's key in the list, click its reader button, or pick from its menu —
panel Not called yet; return None —

The envelope a plugin gets has the sender, subject, date and flags, plus to (To and Cc recipients) and labels (Gmail's labels for the message; system ones start with a backslash, like \Important). Message text isn't included; that will come with read-bodies.

A message a plugin moves or archives never appears in the Inbox or as a notification. The actions themselves then run in the background over IMAP, labels and flags first, then the move or archive. Wax waits for every plugin before showing new mail, so keep on-message-received quick.

Checking mail that's already there

on-message-received gets a check-reason saying why it's being called:

Reason When Actions Wax carries out
arrived New mail, before it's shown All you're granted
existing The first sweep of mail already in your folders add-label, warn
opened A message is opened that this version of the plugin hasn't checked (in any folder, Spam included) add-label, warn
not-spam You move a message out of Spam, or let its sender back in from Screened Out; labels go on before it moves add-label, warn
marked-spam You report a message as spam (!) or block its sender none: it's for learning

For anything but arrived, Wax quietly drops every other action, so an old message is never moved or archived by a plugin. Plugins that only sort new mail (filter rules, the Screener) return nothing unless the reason is arrived.

Set scan-existing: true in the manifest to get the sweep. When the plugin is switched on, or a new version of it loads, Wax checks every cached message outside Spam, Trash and Drafts, once each (duplicates across labels count once), with progress in the status bar. The plugin can read-message mail from the last 90 days; older mail is checked on its envelope alone. Settings → Plugins has Check existing mail to run it again for anything not yet checked. Wax remembers which version checked which message, so bumping your version rechecks everything.

warn(text) keeps a warning with the message: it shows as an amber ⚠ banner above the message whenever it's opened, in any folder. It needs no permission.

plugins/phishing uses all of this. plugins/spam learns from marked-spam and not-spam, keeps what it learned in storage, and moves new mail to [Gmail]/Spam once it is sure.

plugins/screener is a complete example: it holds mail from strangers in the Lobby using knows-sender, and remembers when each account was switched on in storage.

Permissions

Permission Lets the plugin Status
read-envelopes Get messages' senders, recipients, subjects, flags; call senders Works
modify-mail Return label, move, archive, read, star and file-sender actions Works
storage Use storage-get and storage-set Works
read-bodies Call read-message and message-text for the new mail being handled Works
network Call http-get for hosts in network-hosts Answers "not available yet"
compose Return open-draft Not carried out yet
read-drafts Get check-draft calls with the message being written Works

Ask for the least you need. Settings shows each request in plain words, and an action you weren't granted is refused and reported.

Actions

Action Effect Status
add-label(name) Adds a label, creating it if needed Works
remove-label(name) Removes a label Works
move-to(name) Labels it and takes it out of the Inbox Works
archive Takes it out of the Inbox Works
mark-read(bool) Read or unread Works
star(bool) Star or unstar Works
notify(text) Shows text in the status bar (needs no permission) Works
warn(text) Keeps a warning shown above the message in the reader (needs no permission) Works
file-sender(decision) Files all of a sender's mail, past and future (sender views only) Works
snooze-until(time) From a command: out of the Inbox under a Snoozed label until the RFC 3339 time, then back unread Works
follow-up(time) From a command: at the time, back to the Inbox unless someone else wrote in the thread since Works
open-draft(draft) Open a prefilled draft Not yet

Host functions

All live in wax::plugin::host.

Function Does Needs
log(text) Reports a line in the status bar and in Settings → Problems (at most 20 per call) —
config() Your config.toml as text, or "" —
utc-offset() Seconds east of UTC on this Mac now, for local times —
senders(account, limit) Senders by volume from the local cache, with their rule read-envelopes
knows-sender(message) Whether you know its sender: your own address, a colleague at your work domain, someone you've written to, someone with a sender rule, or other mail from them (not the Lobby, Spam, Trash or this batch) read-envelopes
storage-get(key), storage-set(key, value) Your key-value store storage
read-message(account, mailbox, id) The message's text, links (shown text and URL), headers and attachment names; fetched once per message. Only for the messages on-message-received is checking (in a sweep, those from the last 90 days) read-bodies
message-text(account, mailbox, id) Just the text, as above read-bodies
http-get(url) HTTPS GET Not yet

config.toml is yours to define; Wax doesn't parse it. The built-in plugins use one setting per line with # comments. That's a good habit: people edit these files by hand.

Checking what you write

A plugin granted read-drafts gets check-draft(text) with the message's Markdown a moment after you stop typing. Return a draft-issue for each thing worth a look: start and end are byte offsets into text, kind is spelling or grammar, message is shown when it's pointed at, and suggestions are replacements, best first. Wax shows them under the message; clicking one replaces that span, and a spelling issue can be added to ~/.config/wax/dictionary.txt, which Wax checks before showing anything. Names of the people the message is addressed to never count as typos. Return an empty list if you don't check drafts.

plugins/spelling carries a whole English dictionary inside its .wasm, suggests fixes for typos, and catches a few grammar slips.

Commands

A command acts on the selected message. Wax offers it as a key in the message list and, with in-message-toolbar, a button in the reader.

Command {
    id: "snooze".into(),
    title: "Snooze".into(),
    keybinding: Some("z".into()),
    in_message_toolbar: true,
    scope: CommandScope::Any,
    choices: vec![CommandChoice { id: "tomorrow".into(), title: "Tomorrow".into(), detail: "Thu 8 AM".into() }],
    text_hint: Some("or type a time: fri 9am".into()),
}

Sender views

A sender view is a keyboard-driven list of senders, like the Sweep. The plugin supplies the rows and the keys. Wax draws the list, moves with j/k and the arrows, and closes with esc. Wax also holds each decision for the undo window (⌘Z), then writes the sender rule and moves the mail.

fn get_sender_view(account: String) -> Option<SenderView> {
    let rows = wax::plugin::host::senders(&account, 500).unwrap_or_default();
    Some(SenderView {
        title: "Sweep".into(),
        keys: vec![ViewKey { key: "r".into(), label: "Reading".into(), about: "newsletters".into(), color: 0x4f8ff7 }],
        rows,
    })
}

fn on_sender_key(_account: String, who: Sender, key: String) -> Result<Vec<Action>, String> {
    if key != "r" { return Ok(vec![]); }
    Ok(vec![Action::FileSender(SenderDecision {
        email: who.email,
        name: who.name,
        count: who.count,
        destination: Some("Reading".into()), // None keeps them in the Inbox
    })])
}

See plugins/sweep for the full version, which reads its keys from config.toml.

Testing

Plain logic (parsing your config, matching rules) can be unit tested with cargo test in the plugin's folder. This works as long as the code under test doesn't call host functions. plugins/sweep does this.

The whole plugin can be tested against the real host. Build it, then follow the tests at the bottom of src/wasm_host.rs: copy the .wasm into a scratch folder with a grants.toml, load it with Host::load_from, and call arrived, sender_view or sender_key. plugins/test-runaway is a plugin that misbehaves on purpose: it proves loops and memory grabs are stopped.

scripts/build-plugins.sh sweep && cargo test wasm_host

When something goes wrong

Versions

The interface is versioned (wax:plugin@0.6.0) and still changing: a plugin built against one version won't load in a Wax built with another. When it changes, rebuild against the new wit/plugin.wit.

Checklist

Edit this page on GitHub