SpaceMIX v0.1.0

Notifications and events

for bothsince protocol 1

How to tell people what happened (notifications) and other extensions what happened (events), and how to design kinds, targets and payloads.

Two core facilities tell the rest of SpaceMIX that something happened in your extension:

  • Notifications tell people: a line in their notification center (the bell in the sidebar) and a count on your item in the navigation. API: Notifications.
  • Events tell other extensions: an automation, an activity log, a dashboard. API: Events.

Both are declared in the manifest, so the store can show people what an extension sends before they install it, and the host refuses anything the manifest doesn't declare.

Notifications

host.notifications works for every extension; no permission is needed. Each person has their own center and counts, and both update live.

Declare the kinds you send

// manifest.ts
notifications: [
  { name: "direct_message", title: "Direct messages", description: "When someone sends you a direct message." },
  { name: "mention", title: "Mentions", description: "When someone mentions you, @channel or @here in a channel." },
  { name: "digest_ready", title: "Weekly digest", description: "When your weekly summary is ready.", badge: false },
],
  • name: snake_case, unique within the extension. It's the kind you pass to send.
  • title and description: shown in the store under "Notifications it sends". Write the title as a plural noun ("Direct messages", "Tasks assigned to you") and the description as "When …".
  • badge (default true): unread notifications of this kind count on the extension's navigation item. Set false for kinds worth a line in the center but not a number on the icon (a report finished, an update installed). Use badges for things that are waiting for the person, like a message they haven't read. A count that never goes down teaches people to ignore it.

The host refuses a send whose kind the manifest doesn't declare, with an error naming the declared kinds. An extension that declares no kinds can't send.

Sending

What a notification may contain is strict on purpose:

  • kind: one of your declared kinds.
  • text: plain text, 1–280 characters after whitespace is collapsed. Line breaks become spaces. It's shown as text: markdown, HTML and URLs are never interpreted or linked.
  • target (optional): up to 512 characters, opaque to everyone but you and never shown to the user. Use whatever your view understands: a record id, "note:abc", "repo/xyz#main". Make it a /-separated path from the general to the specific (<conversation>/<message>), so markRead can clear a whole branch at once.
  • to (optional): user ids from host.notifications.people(), at most 50. Omit it to notify only the person signed in.

The core stamps which extension sent each notification, so you can't send on another extension's behalf, and clicking one always opens your view, never someone else's or a web page.

// actions.ts, for a hypothetical `assign` action: tell whoever the task now belongs to.
assign: async ({ id, userId }, host) => {
  const task = await host.collection<{ title: string; assignee?: string }>("items").update(String(id), { assignee: String(userId) });
  await host.notifications.send({ kind: "task_assigned", text: `Assigned to you: ${task.title}`, target: task.id, to: [String(userId)] });
  return task;
},

Opening and clearing

When the user opens a notification, it's marked read and your view gets its target through useLinkTarget (from @spacemix/sdk/react), once the view is showing. Each target is delivered once. A target whose record no longer exists should leave the view as it is. A target that maps to a page should navigate() there, so it lands in history:

const [, navigate] = useRoute();
useLinkTarget((id) => navigate(`task/${id}`));

People also see the thing a notification is about without clicking it: they open the conversation from your sidebar, or the task from the board. When they've seen it, mark it read, so the count on your navigation item goes down:

// The conversation is on screen: everything about it has been seen.
useEffect(() => { void host.notifications.markRead({ target: conversationId }); }, [conversationId]);

host.notifications.markRead({ kind: "task_assigned", target: task.id }); // one kind, one record
host.notifications.markRead();                                          // everything from this extension

target matches the target itself and everything under it: "c1" clears "c1", "c1/m9" and "c1/m9/r2", but not "c10". markRead only ever touches your own extension's notifications to the person signed in, and resolves to { marked }, how many changed.

Chat is an extension whose notifications come from the core rather than from send: the chat core notifies people of direct messages, mentions and thread replies itself (kinds direct_message, mention, thread_reply, declared in Chat's manifest like anyone's), with targets <conversation>/<message> or <conversation>/<root>/<reply>.

Events

An event says something happened: a task was completed, a mail arrived, a page was published. Any other extension can act on it. Nothing about events is tied to one consumer.

You get collection events for free. Every collection reports <collection>_created, <collection>_updated and <collection>_deleted whenever it changes, whoever changed it (your view, the assistant, an automation). The payload is the record with its id; _updated also has changed, the names of the fields whose values changed. An update that changes nothing isn't reported. You don't declare or emit these, and you can't.

Declare the events your collections can't express, and emit them with host.events.emit from your view or actions. Good events are things a person would want to react to, named in the past tense: task_completed, mail_received, post_published. Don't declare an event for every field change; that's what _updated is for.

// manifest.ts
events: [
  {
    name: "task_completed",
    title: "Task completed",
    description: "A task was marked done. The payload is the task.",
    schema: {
      type: "object",
      properties: {
        id: { type: "string", description: "The task's id." },
        title: { type: "string", description: "The task's title." },
      },
      required: ["id"],
    },
  },
],

// actions.ts
complete: async ({ id }, host) => {
  const task = await host.collection<{ title: string; done: boolean }>("items").update(String(id), { done: true });
  await host.events.emit({ type: "task_completed", payload: { id: task.id, title: task.title }, summary: `Task “${task.title}” completed`, target: task.id });
  return task;
},

The host checks every emit:

  • type must be one of your declared events.
  • The payload is validated against the event's schema. Undeclared fields are dropped (unlike collection records, where they are an error). An event with no schema takes no payload; sending one is an error. At most 16 KB as JSON.
  • summary follows the notification text rules: one line, 1–280 characters, never interpreted.
  • target is up to 512 characters and means whatever your view's useLinkTarget makes of it.
  • The core stamps the source, the time and the person whose session emitted it, so an extension can't emit on another's behalf.

Events can also come from outside any extension: a script or service with an API key can emit through the SpaceMIX API. Those have source: "api", a free snake_case type and an unchecked payload with payload.via.apiKey naming the key, so test source as well as type, as the example below does.

Receiving events

Receiving needs the events permission, because it means seeing every extension's events and what's in them. The store tells the user so. SpaceMIX starts the frame of every extension with events in the background when someone signs in, so it hears events with its view closed.

Every open window and browser runs your frame, so an event arrives in each of them. Claim before doing anything that must happen once per event, like sending a mail; the core decides atomically:

host.events.subscribe(async (e) => {
  if (e.source !== "ai.spacemix.tasks" || e.type !== "task_completed") return;
  if (!(await host.events.claim(e.id))) return; // another window has it
  await host.notifications.send({ kind: "task_done", text: e.summary ?? "A task was completed" });
});

To catch up after being offline, keep the id of the last event you handled and call host.events.list({ after: lastId }). If a full page comes back, page further back with before set to the oldest id you got until you reach your cursor, then handle the events oldest first. Ids sort by time. The core keeps a capped log; see Events for the limits.

Checklist

  • Every notification kind is declared with a title and description; badge: false on kinds that aren't waiting for the person.
  • Text is one plain line; target is something your view handles with useLinkTarget.
  • markRead runs once the person has seen what a badged notification was about.
  • Things people would want to react to that collections don't already report are declared in events, with descriptions and payload schemas, and emitted with a one-line summary.
  • The README lists the kinds, what their targets mean, and the events.

This page as markdown · All pages as one file