Skip to content

Worked examples

The best way to learn the plugin SDK is to read a real plugin. This page walks through @lore/branch-explorer, the first-party plugin that ships as the default Explorer view on the Branches tab, and highlights the patterns you will reuse in your own plugins.

All paths below are relative to the plugin's directory in the Lore Desktop repository, packages/plugins/@lore/branch-explorer/.

@lore/branch-explorer

What the user sees: a sidebar listing every branch (grouped by category), a graph visualization of revision history, context menus for switching, merging and archiving branches, and a New Branch modal.

What it does

The plugin wraps the shared branch visualizer library (@lore-vcs/branch-visualizer) inside the plugin host. It subscribes to the host's branch and revision data, translates visualizer commands into host mutations, and streams revision history on demand. Because it runs in-process, it short-circuits many commands that would otherwise round-trip to Lore, and serves them directly from the host's already-loaded state.

Manifest: grants in practice

The manifest in package.json declares a 15-entry access array. Reading it alongside the source shows read, mutate and stream grants side by side:

{
  "plugin": {
    "main": "dist/main.js",
    "renderer": "dist/renderer.js",
    "access": [
      "data:app.language",
      "data:repository.branches",
      "data:repository.archivedBranches",
      "data:repository.currentRevision",
      "data:repository.revisions",
      "call:repository.create",
      "call:repository.users",
      "call:repository.refreshBranches",
      "call:repository.switch",
      "call:repository.archive",
      "call:repository.restore",
      "call:repository.merge",
      "call:repository.syncToRevision",
      "call:repository.fetchRevisions",
      "call:repository.revisionHistory"
    ]
  }
}

Two prefixes appear here:

Prefix Purpose Examples in this plugin
data: Read host state and subscribe to changes app.language, repository.branches, repository.revisions
call: Invoke a host command, either as a one-shot call that may mutate state or as a stream of results repository.create, repository.switch, repository.archive (one-shot); repository.fetchRevisions, repository.revisionHistory (streamed)

The last two call: entries, repository.fetchRevisions and repository.revisionHistory, are consumed with commands.stream() rather than commands.call(). Both require a call: grant. The host enforces the same permission for streaming and one-shot invocation.

Every grant maps to a concrete call site in the source. If a grant were removed, the host would reject the corresponding data.get, data.on, commands.call or commands.stream call at runtime. See Access and grants.

The mutation path

A UI action becomes a repository mutation through commands.call. The pattern is always the same: the component calls commands.call with the host command name and an arguments object, awaits the result, and handles errors.

Creating a branch

The New Branch modal (src/components/NewBranchModal.tsx) collects a name and a base branch, then calls the host's repository.create command:

// src/components/NewBranchModal.tsx
await commands.call("repository.create", {
  branch: trimmedName,
  baseBranch,
});

The host creates the branch and auto-switches the working tree onto it. The plugin does not need to refresh its branch list, because the data.on subscription (covered below) delivers the updated list automatically.

Switching, merging, archiving

The page component (src/pages/branchExplorerPage.tsx) serializes mutations behind a mutatingBranchId guard so only one runs at a time:

// src/pages/branchExplorerPage.tsx
const handleSwitchBranch = useCallback(
  async (branch: BranchInfo) => {
    if (branch.isCurrent || mutatingBranchId) return;
    setMutatingBranchId(branch.id);
    try {
      await deps.commands.call("repository.switch", {
        branch: branch.name,
      });
    } catch {
      // Failure is surfaced by the host (showProgress).
    } finally {
      setMutatingBranchId(null);
    }
  },
  [deps, mutatingBranchId]
);

The same shape repeats for every mutation in the same file: repository.archive, repository.merge, repository.restore and repository.syncToRevision.

Adapter-level mutations

The adapter layer (src/adapter/mutations.ts) handles mutations triggered by the graph visualization rather than the sidebar. The visualizer identifies branches by id, but the host's repository.archive command keys by name, so the adapter resolves the id first:

// src/adapter/mutations.ts
async function archiveBranch(
  commandId: string,
  id: string,
  deps: ArchiveBranchHandlerDeps
): Promise<void> {
  const branches = await deps.data.get("repository.branches");
  const match = branches?.find((b) => b.id === id);
  if (!match) {
    deps.log.warn(/* ... */);
    return;
  }
  await deps.commands.call("repository.archive", { branchName: match.name });
}

This is a common pattern: read host state to translate between the shapes your UI uses and the shapes the host commands expect.

The streaming path

Revision history can be large: hundreds of revisions per branch, delivered incrementally. The plugin uses commands.stream instead of commands.call so it can process revisions as they arrive rather than waiting for the full result.

Streaming revisions for a branch

In src/adapter/shortCircuits.ts, the revision-history handler streams revisions for a known branch:

// src/adapter/shortCircuits.ts
const handle = deps.commands.stream("repository.fetchRevisions", streamArgs, {
  next(item) {
    const revisions = item.revisions;
    for (const r of revisions) {
      deps.emit(commandId, buildRevisionHistoryEntry({ /* ... */ }));
      deps.onEntry?.(r.revision, branchId);
    }
  },
  error(err) {
    // Log and emit a failed COMPLETE.
    deps.emit(commandId, buildComplete(2));
  },
  complete() {
    deps.emit(commandId, buildComplete());
  },
});

The stream call returns a StreamHandle with a cancel() method. The handler tracks active handles so a superseding request for the same command id cancels the previous one, which prevents stale data from arriving after fresh data.

repository.fetchRevisions takes these arguments:

  • branchIds: the branches to walk.
  • revision: the hash to start from. Omitted means the branch tip.
  • length: the page size. The default is 25, and it is ignored when date is set.
  • date: a lower bound. The walk stops at revisions created before it.
  • onlyBranch: when true, a spine-only walk that stops at the fork point.

To page back, pass the oldest revision you have received as revision. It comes back as the first item of the next page. There is no end-of-history flag (a short page can also be a failed walk answered from the host's cache), so stop when a page brings nothing older than the anchor.

Falling through to a different stream

When a revision hash cannot be resolved to a branch (cross-branch missing-parent backfill), the handler falls through to a different stream command:

// src/adapter/shortCircuits.ts
const handle = deps.commands.stream(
  "repository.revisionHistory",
  { ...args, length: args.length ?? PARENT_HISTORY_LENGTH_CEILING, stopAtKnown: true },
  {
    next(revision) { /* ... */ },
    error(err) { /* ... */ },
    complete() { /* ... */ },
  }
);

The two-tier routing, trying repository.fetchRevisions first and falling back to repository.revisionHistory, is a practical example of choosing the right command for the job. The first is cohort-batched and efficient for known branches. The second handles the edge case.

Wrapping a stream in a Promise

The adapter also wraps commands.stream in a Promise when it needs a one-shot result (for the tip-confirm poll):

// src/adapter/HostIpcProvider.ts
private readRevisionsViaStream(
  branchId: string
): Promise<readonly Revision[]> {
  return new Promise<readonly Revision[]>((resolve, reject) => {
    let result: readonly Revision[] = [];
    this.deps.commands.stream(
      "repository.fetchRevisions",
      { branchIds: [branchId], length: 1, onlyBranch: true },
      {
        next(item) {
          result = item.revisions;
        },
        error(err) {
          reject(err);
        },
        complete() {
          resolve(result);
        },
      }
    );
  });
}

This is useful when you need the streaming transport (because the host command only supports it) but your consumer expects a single resolved value.

The data path

Subscribing to host state

The plugin subscribes to branch data using data.on, which fires immediately with the current value (replay-1 semantics) and then on every change:

// src/pages/branchExplorerPage.tsx
useEffect(() => {
  const subscription = deps.data.on(
    "repository.branches",
    (list: Branch[] | undefined) => {
      // Undefined until the host's first complete branch list lands.
      if (!list) return;
      setBranches(dedupeBranchesById(list));
    }
  );
  return () => {
    subscription.dispose();
  };
}, [deps]);

The same pattern subscribes to archived branches:

// src/pages/branchExplorerPage.tsx
const subscription = deps.data.on(
  "repository.archivedBranches",
  (list: Branch[]) => {
    setArchivedBranches(dedupeBranchesById(list));
  }
);

Because data.on replays the current value on subscribe, the plugin does not need a separate initial fetch. The subscription doubles as the bootstrap read.

Forwarding the host's language

The same data.on pattern carries the host's UI language and locale. The visualizer hides translated text until a language is pushed into its store, and app.language is replay-1, so the first emission unblocks it:

// src/pages/branchExplorerPage.tsx
useEffect(() => {
  const subscription = deps.data.on(
    "app.language",
    (value: { language: string; locale: string }) => {
      store.dispatch(setLanguage(value));
      void i18nInstance.changeLanguage(value.language);
      void branchExplorerI18n.changeLanguage(value.language);
    }
  );
  return () => {
    subscription.dispose();
  };
}, [deps, store]);

The host serves this key renderer-side from its own i18next instance, so the value is always the language the host UI is actually showing. It is shaped for the visualizer's setLanguage payload, so the plugin forwards it verbatim. It also drives the plugin's own i18next instance (branchExplorerI18n).

Parameterized reads

When the plugin needs revisions for a specific branch (a point-in-time read, not a subscription), it uses data.get with a parameter:

// src/adapter/userRevisionInfo.ts
const revisions = await deps.data.get("repository.revisions", { branchId });

The { branchId } parameter scopes the read to a single branch's revision set. Without it, data.get("repository.revisions") would return the full revision dataset.

Keep-alive pages

The renderer entry (src/renderer.ts) registers the page with keepAlive: true:

// src/renderer.ts
reg.provide(
  "page:main",
  lazySlot(() => import("./pages/branchExplorerPage")),
  {
    nav: {
      scope: "repository-tabs",
      label: "Explorer view",
      icon: "BranchIcon",
      priority: 35,
      contributesTo: "branches",
      defaultView: true,
      description: "Displays branches in a visualizer",
    },
    keepAlive: true,
  }
);

A keep-alive page stays mounted when the user navigates away: the host toggles display: none instead of unmounting. This preserves expensive state (the graph layout, scroll position, in-flight streams) across tab switches. The trade-off is memory, because the page's React tree and adapter remain alive. See Renderer: slots and pages.

The page handles the hidden and visible transition with an IntersectionObserver on the page root (src/pages/branchExplorerPage.tsx). While hidden, platform events queue in a FIFO inside the adapter (src/adapter/HostIpcProvider.ts) and drain when the page becomes visible again. This keeps the visualizer from mis-measuring labels at zero width.

Patterns you will likely need

Two patterns do not appear in @lore/branch-explorer but come up frequently in plugins that fetch external data or react to file changes.

Stale-while-revalidate cache

When your plugin fetches data that is expensive to produce, serve the cached result immediately and refresh in the background:

const cached = readCache(cachePath);
if (cached && dataHandle) {
  // Paint stale data so the UI is not empty while the fetch runs.
  dataHandle.set(cached);
}
// Fire-and-forget — activation must not block on the fetch.
fetchAndUpdate(ctx.log);

Keep the cache outside the repository. ctx.pluginDataPath is the data/ folder inside the plugin's own folder, and os.tmpdir() is a good home for a cache you can rebuild.

Branch names and other user-controlled strings used as index keys should use Object.create(null) to avoid prototype-name collisions:

const index: Record<string, ItemSummary[]> = Object.create(null);

Trailing-edge debounce for file changes

When reacting to file-system changes (for example, re-running a linter), debounce to avoid redundant work:

let debounceTimer: ReturnType<typeof setTimeout> | undefined;

function debouncedLint() {
  if (debounceTimer !== undefined) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    debounceTimer = undefined;
    runLint();
  }, 1000);
}

ctx.events.on("fs.changed", () => {
  if (repositoryRoot) {
    debouncedLint();
  }
});

Clean up the timer in deactivate, because the host cannot see it:

deactivate(ctx) {
  if (debounceTimer !== undefined) {
    clearTimeout(debounceTimer);
    debounceTimer = undefined;
  }
  ctx.log.info("deactivated");
},

Next

Build, pack, and install a plugin covers the CLI and the install flow.