Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Writing plugins

A plugin is a directory, usually a git repository, with a manifest, views and a backend:

my-plugin/
  mochi-plugin.toml     what it is, what it runs, what it offers
  settings.toml         its commented [module.<id>] section, for users
  qml/                  its views
  src/, Cargo.toml      the backend's source, for a Rust backend

The repository has example plugins to copy:

ExampleShows
examples/plugins/pomodoroA Rust backend: a countdown bubble updated every second, island notices, actions with arguments, a control center card with buttons, watching the media module’s state
examples/plugins/meteoA Rust backend fetching from the web on a timer, settings with a place and units, a control center card and a forecast view. Mochi has a weather module of its own; this is the same idea as a plugin
examples/plugins/emojiA Rust backend that is a launcher provider: an emoji picker with no views
examples/python/helloA Python backend with a small SDK of its own: see Making an SDK

To work on a plugin, list it with a path: source and install it, which runs its build:

# ~/.config/mochi/plugins.toml
[plugins.pomodoro]
source = "path:~/code/mochi-pomodoro"
mochi plugins install pomodoro   # builds it; mochid reloads

Views hot-reload as you save them. After rebuilding the backend, mochi reload restarts it: mochid restarts a plugin whose manifest or backend changed.

The manifest

mochi-plugin.toml at the plugin’s root names the plugin, its backend, its actions and what it offers. The smallest one, for a plugin of views only:

[plugin]
id = "clock"
name = "Big clock"
version = "0.1.0"
api = 1

[views]
overrides = ["idle/Pill"]

A plugin with a backend adds [backend] with the program and the command that builds it, and usually [[actions]] and [[contributions]]. Plugin manifest lists every key.

Views

Views are QML files in the views directory, loaded the same way as a builtin module’s: see Writing views. An activity or bubble names a view by its file name without .qml, and a view gets the payload property. import qs.island gives the theme, Daemon and the controls. A view reads its plugin’s state with Daemon.state("<id>") and runs its actions with Daemon.command("<id>", "<action>", [args]).

A control center card or page gets the plugin’s published state as its payload, and a card can set hidden: true to step aside. The control center draws the card’s frame and title, so the view only draws what goes inside, filling the width it’s given.

Replacing builtin views

overrides = ["idle/Pill"] puts the plugin’s qml/overrides/idle/Pill.qml in place of the idle module’s Pill.qml, while both modules are enabled. The file sits in the idle module’s directory, so it can use that module’s other files and gets the same payload as the view it replaces. Without the plugin, the builtin view is back. An override that fails to load, with a QML error for example, gives way to the builtin view, and mochid’s log has the error. When two plugins replace the same view, the one whose id sorts first wins.

The backend in Rust

Depend on mochi-sdk, and hand your function to mochi_sdk::run. It gets a ModuleCtx with the same calls as a builtin module’s:

use mochi_sdk::{ActivitySpec, ModuleCtx, ModuleEvent, json};

fn main() -> std::process::ExitCode {
    mochi_sdk::run(run)
}

async fn run(mut ctx: ModuleCtx) -> Result<(), mochi_sdk::Error> {
    while let Some(event) = ctx.next_event().await {
        match event {
            ModuleEvent::Command(command) if command.action == "say" => {
                ctx.present(
                    ActivitySpec::new("Hello")
                        .timeout(std::time::Duration::from_secs(3))
                        .payload(json!({ "text": "Hi" })),
                );
                command.reply(Ok(()));
            }
            ModuleEvent::Command(command) => command.reply(Err("no such action".into())),
            _ => {}
        }
    }
    // mochid closed the connection: time to go.
    Ok(())
}

The Rust SDK covers settings, activities, bubbles, state, calls, the compositor, logging and testing.

A backend in any language

A backend is any program that speaks the plugin protocol: JSON lines over file descriptor 3. This one, in sh, answers an action with an activity. For more than a few lines, a small library helps: Making an SDK explains how to write one, with a complete one in Python.

#!/bin/sh
read -r hello <&3
printf '{"type":"hello","api":1}\n' >&3
while read -r line <&3; do
    case "$line" in
    *'"type":"command"'*)
        id=${line#*\"id\":}
        id=${id%%,*}
        printf '{"type":"present","id":1,"spec":{"compact":"Hello","timeout_ms":3000}}\n' >&3
        printf '{"type":"reply","id":%s}\n' "$id" >&3 ;;
    esac
done

A flake for Nix users

You don’t need one: Mochi builds Rust, Node, Python and Go plugins with Nix from their lock files by itself, see Building with Nix. List the programs your backend runs in [backend] needs, so they’re there wherever it’s built.

A flake is for a build Mochi’s builder can’t guess, like extra native libraries. mochi plugins install uses it when Nix is installed, and home-manager can take its package. Copy this next to mochi-plugin.toml and adjust it; mochi.lib.buildPlugin is the same builder:

# A flake for a plugin's repository, for a build Mochi can't guess by
# itself, like extra native libraries: copy it next to mochi-plugin.toml.
# Without one, Mochi builds Rust, Node, Python and Go plugins with Nix from
# their lock files anyway. With it:
#
# - `mochi plugins install` builds it with `nix build` when Nix is
#   installed, instead of the manifest's `build` command.
# - home-manager can take the package as
#   `programs.mochi.plugins.<id>.package = inputs.<plugin>.packages.${pkgs.system}.default;`
#
# `mochi.lib.buildPlugin` follows the plugin's lock file, so there's no
# hash to update, and puts the backend at the manifest's `exec`.
{
  description = "A Mochi plugin";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    mochi = {
      url = "github:Davidutz19/mochi";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };

  outputs =
    { nixpkgs, mochi, ... }:
    let
      systems = [
        "x86_64-linux"
        "aarch64-linux"
      ];
      forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
    in
    {
      packages = forAllSystems (pkgs: {
        default = mochi.lib.buildPlugin pkgs {
          src = ./.;
          # Native libraries the backend links, if any.
          # buildInputs = [ pkgs.alsa-lib ];
        };
      });
    };
}

A flake for a plugin in another language works too, as long as its default package has the backend at the manifest’s exec, or in bin/ by the same name.

The mochi-sdk dependency must be a git one, like mochi-sdk = { git = "https://github.com/Davidutz19/mochi", tag = "v0.4.7" }, not a path to your own checkout, or the plugin only builds on your machine.

Publishing a release

Releases work for the most people: nothing to build, so no compiler, no libraries and no Nix needed, and Mochi patches release binaries to run on NixOS too. Building from source depends on each machine having your plugin’s build environment, and Mochi’s Nix build covers the usual builds of Rust, Node, Python and Go, not every plugin. Publish releases if your plugin compiles to a binary, and always if it’s in a language Mochi can’t build with Nix, see Which source to pick.

For a git-release: source, attach an archive to a release on GitHub, on a Forgejo or Gitea like Codeberg, or on a GitLab, named as [release] asset says with {id}, {version}, {tag} and {arch} (x86_64 or aarch64) filled in. On GitLab, a release’s assets are links: give the link that name, and point it at the archive, in the project’s package registry for instance. The archive holds the plugin as it should be installed: the manifest, the views and the built exec, at its root or in one directory. mochi plugins install reads the manifest from the tagged commit first, to show what it will install, then downloads the asset.

The same archive works without a forge too: put it anywhere over HTTPS, and users list it with its hash, as source = "https://example.org/clock-1.0-x86_64.tar.gz#sha256=<hash>", the hash being what sha256sum prints for the file. An archive pins one architecture and one version, so mochi plugins update never moves it; git-release: picks the asset for each machine and finds new releases.

This GitHub Actions workflow does it on every tag: copy it to .github/workflows/release.yml in the plugin’s repository. It reads the manifest, builds the backend on x86_64 and aarch64, packs the manifest, settings.toml, the views and the built exec, and attaches the archive to the tag’s release. A Rust backend is built as a static binary for the musl target rather than with build, so it runs on any Linux, NixOS included, with no loader or libraries to find; the binary is the one named like exec’s file. For another language it runs build; make the binary static if the language can, like Go with CGO_ENABLED=0. On another forge, its CI or a release made by hand attaches the same archive.

# A GitHub Actions workflow for a plugin repository, for `git-release:`
# sources. Copy it to .github/workflows/release.yml. Pushing a tag like
# v0.1.0 builds the backend on x86_64 and aarch64, packs what
# `mochi plugins install` needs, and attaches it to the tag's release under
# the name `[release] asset` gives.
#
# A Rust backend, one with a Cargo.toml, is built as a static binary for
# the musl target instead of with the manifest's `build`: it needs no
# loader and no libraries, so it runs on any Linux, NixOS without nix-ld
# included. The binary is the one named like `exec`'s file, `meteo` for
# `bin/meteo`. Each architecture builds on its own runner, so the Rust
# toolchain links it with the runner's `cc` and the musl that comes with the
# target; musl-tools gives `musl-gcc` for crates that compile C.
#
# It reads everything from mochi-plugin.toml, so it needs no changes for a
# Rust backend. For another language, `build` runs as it is: add the steps
# that install its tools before "Build", and build it static if the
# language can, like Go with CGO_ENABLED=0.
name: Release

on:
  push:
    tags: ["v*"]

permissions:
  contents: write

jobs:
  release:
    strategy:
      matrix:
        include:
          - arch: x86_64
            runner: ubuntu-24.04
          - arch: aarch64
            runner: ubuntu-24.04-arm
    runs-on: ${{ matrix.runner }}
    env:
      TARGET: ${{ matrix.arch }}-unknown-linux-musl
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ env.TARGET }}

      - name: Install musl
        run: sudo apt-get update && sudo apt-get install -y musl-tools

      - name: Read the manifest
        id: manifest
        env:
          TAG: ${{ github.ref_name }}
          ARCH: ${{ matrix.arch }}
        run: |
          python3 - >> "$GITHUB_OUTPUT" <<'PY'
          import os, tomllib
          manifest = tomllib.load(open("mochi-plugin.toml", "rb"))
          plugin = manifest["plugin"]
          asset = manifest["release"]["asset"]
          for key, value in {
              "{id}": plugin["id"],
              "{version}": plugin["version"],
              "{tag}": os.environ["TAG"],
              "{arch}": os.environ["ARCH"],
          }.items():
              asset = asset.replace(key, value)
          backend = manifest.get("backend", {})
          print(f"id={plugin['id']}")
          print(f"asset={asset}")
          print(f"exec={backend.get('exec', '')}")
          print(f"views={manifest.get('views', {}).get('dir', 'qml')}")
          print(f"build={backend.get('build', '')}")
          PY

      - name: Build
        if: steps.manifest.outputs.build != ''
        env:
          MOCHI_PLUGIN_DIR: ${{ github.workspace }}
          BUILD: ${{ steps.manifest.outputs.build }}
          EXEC: ${{ steps.manifest.outputs.exec }}
        run: |
          if [ ! -f Cargo.toml ]; then
            sh -c "$BUILD"
            exit
          fi
          # C code in the dependencies compiles against musl too.
          export "CC_$(echo "$TARGET" | tr - _)=musl-gcc"
          name=$(basename "$EXEC")
          cargo build --release --locked --target "$TARGET" --target-dir target --bin "$name"
          install -Dm755 "target/$TARGET/release/$name" "$EXEC"
          # A dynamically linked binary fails the release.
          linked=$(file "$EXEC")
          echo "$linked"
          case "$linked" in
            *static*) ;;
            *) echo "$EXEC isn't static" >&2; exit 1 ;;
          esac

      - name: Pack
        env:
          ID: ${{ steps.manifest.outputs.id }}
          ASSET: ${{ steps.manifest.outputs.asset }}
          EXEC: ${{ steps.manifest.outputs.exec }}
          VIEWS: ${{ steps.manifest.outputs.views }}
        run: |
          # The plugin as it should be installed, in one directory.
          mkdir -p "pack/$ID"
          for path in mochi-plugin.toml settings.toml README.md LICENSE "$VIEWS" "$EXEC"; do
            if [ -n "$path" ] && [ -e "$path" ]; then
              cp -r --parents "$path" "pack/$ID/"
            fi
          done
          tar -czf "$ASSET" -C pack "$ID"
          tar -tzf "$ASSET"

      - name: Attach to the release
        env:
          GH_TOKEN: ${{ github.token }}
          TAG: ${{ github.ref_name }}
          ASSET: ${{ steps.manifest.outputs.asset }}
        run: |
          # Both jobs race to make the release; the second just uploads.
          gh release create "$TAG" --title "$TAG" --notes "" --verify-tag 2>/dev/null || true
          gh release upload "$TAG" "$ASSET" --clobber