SpaceMIX v0.1.0

Frame protocol

stablefor bothsince protocol 1

How an extension's sandboxed frame is created and loaded, its sandbox and CSP, every postMessage message, the bridge methods and subscription channels, timeouts, errors and PROTOCOL_VERSION.

Every extension runs in its own sandboxed iframe. The only way out of it is postMessage to the window that hosts it. This page describes that wire: packages/sdk/src/protocol.ts (the types), packages/sdk/src/runtime.ts and apps/desktop/frame/main.tsx (the frame side), and apps/desktop/src/lib/extensionHost.ts (the host side).

Extension code doesn't speak this protocol. The frame runtime, which SpaceMIX ships, speaks it, and gives the extension host from @spacemix/sdk. Use host; don't post messages to window.parent yourself. The protocol is documented because it defines what host can do, what the timeouts and errors are, and what a different host would have to implement.

PROTOCOL_VERSION

const PROTOCOL_VERSION = 1;

The frame runtime sends ready with protocol: PROTOCOL_VERSION. The host answers with init, which carries the host's protocol. The runtime refuses an init whose protocol is different and posts failed:

This extension frame speaks protocol 1; SpaceMIX sent 2.

The host doesn't check the protocol in ready today. Both sides normally come from the same SpaceMIX build, but not always: in a browser the frame document is fetched from the active server (<server>/api/ext-frame), which can run a different version from the page hosting it. Additive changes keep PROTOCOL_VERSION at 1 (see Contract).

The frame

Where it comes from

The frame document is served by the SpaceMIX core, without a session (it holds no data; the host posts the bundle in):

Window URL
A browser <active server>/api/ext-frame?theme=<light|dark>
The desktop app's dev window /api/ext-frame?theme=…
The bundled desktop app spacemix-widget://localhost/ext?theme=… (Windows: http(s)://spacemix-widget.localhost/ext?theme=…)

The document is an inline script and stylesheet (the runtime, built from apps/desktop/frame/ into src-tauri/frame-dist/) and an empty <div id="root">. An inline script sets data-theme on <html> from the theme query parameter before anything paints.

Sandbox

<iframe sandbox="allow-scripts allow-forms" allow="clipboard-write" referrerpolicy="no-referrer" src="…">
  • sandbox="allow-scripts allow-forms": the frame has an opaque origin (null). No allow-same-origin, so localStorage, sessionStorage, IndexedDB and cookies throw or are empty. No allow-popups, so window.open does nothing; no allow-modals, so alert, confirm and prompt don't show; no top navigation. allow-forms is there only so a <form onSubmit> handler runs; the CSP blocks the submission itself.
  • allow="clipboard-write", plus ; autoplay * for an extension with camera, microphone or screen (so a call's remote audio plays). Camera and microphone are not in allow: browsers refuse capture to an opaque origin, so the host captures for the frame (see Media).
  • referrerpolicy="no-referrer".
  • The extension's frame is not in the React tree: all frames live in one fixed-position container that the host moves over the view's slot.

The probe frame the Studio uses to read a bundle's manifest has sandbox="allow-scripts" only.

Over HTTP (/api/ext-frame) the document also sandboxes itself, with the same flags, in a second policy: see Content Security Policy.

Content Security Policy

The frame document is served with:

default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline';
img-src data: blob: http: https:; media-src data: blob: http: https:; font-src data:;
frame-src <own origin> http: https:; connect-src 'none'; form-action 'none'; base-uri 'none'

Over HTTP a second policy is sent with it, sandbox allow-scripts allow-forms (sandboxed in src-tauri/src/server.rs). The app's page is on the same origin as this route, so the document is sandboxed whoever loads it, opened directly or embedded without the attribute, and never runs as that origin. The desktop app's spacemix-widget: scheme doesn't send it.

What that means for extension code:

  • No fetch, XMLHttpRequest, WebSocket, EventSource or navigator.sendBeacon (connect-src 'none'). Use host.net.fetch.
  • No external scripts, stylesheets or fonts. Fonts only as data: URLs.
  • Images, audio and video can load from http: and https: URLs and from data: and blob:.
  • Nested frames can load the server's own origin and any http:/https: site (an extension can embed a site of the user's own, like a WordPress editor). Over the desktop scheme, frame-src names spacemix-widget: and http(s)://spacemix-widget.localhost instead of the origin.

"No network" therefore means no scripted network access from the frame; it does not mean no request ever leaves it. Images and nested frames are requests.

Lifecycle

  1. Created. The host creates the frame the first time it is needed: the view is opened; the assistant, a widget or host.tools.call calls one of its actions; the host needs its MCP servers (extensions with a net: permission, whenever tools are listed); someone signs in and the extension has events; the Studio previews it. Each window or browser tab runs its own instance. A paid extension turned off until it's paid for gets no frame.
  2. ready. The runtime installs the host modules as globals, then posts ready.
  3. init. The host answers every ready with init (and, as a fallback, sends one init on the iframe's load event if no ready was heard). init carries the approved manifest, the bundle, the CSS, the theme, env, visible, focused and route.
  4. Load. The runtime checks protocol, connects host, sets the theme, appends the CSS, runs the bundle as an inline <script>, checks the module, mounts <View /> in an error boundary, and posts loaded with the module's manifest (JSON-cloned). Any failure in this step posts failed with the error.
  5. Ready. The host checks that the module's id and version match the installed package, else fails with The package's code is <id>@<version>, but it's installed as <id>@<version>. Then the frame is shown (it is transparent until this point) and calls, routes and targets flow.
  6. Kept. The frame stays alive, hidden, when the user switches to another view, and receives visible: false.
  7. Dropped. On uninstall, when the installed package's hash changes (an update or a dev rebuild), when the store's Reload is used, when a Studio preview is rebuilt, when the person loses access to the extension, or when a paid extension is turned off until it's paid for (its Studio previews too). Pending calls reject with <Name> was reloaded., subscriptions end, and media sessions close. The next use creates a fresh frame.

Only one init is acted on per frame; later ones are ignored by the runtime.

Messages

Every message is an object with op: true and a type. Both ends check isOp(message) and the sender: the frame accepts messages only from window.parent; the host identifies frames by their contentWindow (the origin is null for all of them). Anything else is ignored, so a widget frame nested inside an extension's frame can't be mistaken for the extension.

Host to frame: HostToFrame

type Fields Meaning
init init: FrameInit Start: see FrameInit.
theme theme: ThemeState The app switched light/dark. The runtime sets data-theme on <html>.
visible visible The view was shown or hidden (host.view.onVisible). Sent only after the frame is ready.
focus focused SpaceMIX's window gained or lost the user's attention (focused and not hidden). Sent to every frame on each change (host.view.onFocus).
route route Back/Forward or a link moved the view to another route (host.view.onRoute). Never an echo of the frame's own view.navigate.
target target A notification target (host.view.onTarget, useLinkTarget). Sent once the frame is ready; the runtime holds it until the view is visible and something listens. Only the latest undelivered target is kept.
call id, kind: "action", name, args, via? Run a declared action. The frame answers with call-result under the same id. via is the ActionVia for host.tools.call, and for a call through the SpaceMIX API (extension: "ai.spacemix.api").
call id, kind: "mcp" Resolve the module's mcp(host). The answer's result is McpServer[] ([] without mcp).
res id, ok: true, result / ok: false, error The answer to a req.
event sub, payload A push on subscription sub.
probe id, js Sent instead of init to a one-shot probe frame: run the bundle, mount nothing, answer probe-result.

Frame to host: FrameToHost

type Fields Meaning
ready protocol The runtime is loaded and listening.
loaded manifest The bundle ran and the view is mounted.
failed error The bundle couldn't run or mount, or the protocol didn't match. The frame's status becomes failed and waiting calls reject with error.
req id, method, args A host API call. See Requests.
call-result id, ok: true, result / ok: false, error The answer to a call.
error message An error the extension's code threw outside a call: render, effect, timer, unhandled rejection. Shown in the frame's status and the console.
focus-check none The frame's own window gained or lost focus; the host re-checks attention and may send focus.
shortcut key, meta, shift Ctrl/⌘ + K ("k", command palette), Ctrl/⌘ + N ("n", new chat) or Ctrl/⌘ + J ("j", show or hide the chat window) without Alt was pressed in the frame. The runtime calls preventDefault and the host handles it.
probe-result id, ok: true, manifest / ok: false, error The answer to probe.

FrameInit

interface FrameInit {
  protocol: typeof PROTOCOL_VERSION;
  manifest: ExtensionManifest;
  js: string;
  css: string;
  theme: ThemeState;
  env: HostEnv;
  visible: boolean;
  focused: boolean;
  route?: string;
}

interface ThemeState {
  mode: "light" | "dark";
}

manifest is the package's manifest with permissions replaced by the approved list. env is host.env: desktop, platform ("macos", "windows", "linux", "ios", "android"; "web" in a browser), me (id, name, email; empty strings if the session can't be read) and serverName. route is optional: a host that doesn't send it means "". Today's host always sends it.

Requests

A req is one host API call. method is dotted ("storage.get"), and args are the method's arguments in order. The runtime drops trailing undefined arguments. Arguments and results cross by structured clone: plain data, ArrayBuffer, Uint8Array, File (for fs.import) are fine; functions and DOM nodes are not, and fail with Can't send "<method>" to SpaceMIX: <error>. If a result can't be cloned, the host sends its JSON instead, or The result can't be sent to the extension: <error>.

The host answers every request with res. A request is refused with:

  • an unknown method: SpaceMIX has no "<method>".
  • a missing permission: <Name> doesn't have the "<permission>" permission.

Methods

The methods table in extensionHost.ts. "Needs" is the permission the bridge checks before running the method; see Permissions.

Method Needs host API
storage.get none host.storage.get(key)
storage.set none host.storage.set(key, value)
collection.list none host.collection(name).list(options); the collection name is the first argument of every collection.*
collection.get none .get(id)
collection.create none .create(fields)
collection.update none .update(id, patch)
collection.delete none .delete(id)
fs.roots, fs.list, fs.read, fs.write, fs.mkdir, fs.rename, fs.delete, fs.import fs host.fs.*
git.repos, git.add, git.remove, git.fetch, git.log, git.show, git.diff, git.blame, git.file, git.tree, git.refs, git.grep git host.git.*
chat.people, chat.conversations, chat.history, chat.thread, chat.search, chat.threads, chat.mentions, chat.pins, chat.send, chat.edit, chat.delete, chat.react, chat.pin, chat.markRead, chat.createChannel, chat.openDm, chat.updateChannel, chat.join, chat.leave, chat.invite, chat.archive, chat.prefs, chat.typing chat host.chat.*
notifications.send, notifications.people, notifications.markRead none host.notifications.*
events.emit none host.events.emit
events.catalog, events.list, events.claim events host.events.*
tools.list, tools.call tools host.tools.*
ai.complete, ai.available ai:invoke host.ai.*
mcp.listTools, mcp.callTool any net: host.mcp.*; the server's URL is also checked like net.fetch
net.fetch, net.allowedHosts any net: host.net.*; net.fetch takes a NetWire["request"]
shell.open, shell.openUrl, shell.save, shell.copy none host.shell.*
view.navigate none host.view.navigate(route, { replace })
view.setFullscreen none host.view.setFullscreen(on); on must be a boolean
media.open, media.answer, media.stop, media.constraints, media.devices camera, microphone or screen The runtime's getUserMedia/getDisplayMedia/enumerateDevices (see MediaWire)
widgets.widgets, widgets.frameUrl, widgets.refresh, widgets.purge, widgets.call, widgets.reportError, widgets.openGallery widgets or widgets:view host.widgets.*
widgets.dashboards, widgets.snapshot, widgets.createDashboard, widgets.renameDashboard, widgets.deleteDashboard, widgets.reorderDashboards, widgets.addToDashboard, widgets.removeFromDashboard, widgets.resizeItem, widgets.setLayout, widgets.deleteWidget, widgets.openStudio widgets host.widgets.*
subscribe depends on the channel (channel, params) → a subscription id (number)
unsubscribe none (sub)

The host methods themselves (signatures, behavior, errors) are documented under Host API.

Wire shapes

interface NetWire {
  request: {
    url: string;
    method: string;
    headers: Record<string, string>;
    body: { kind: "text"; text: string } | { kind: "base64"; base64: string } | null;
    timeout: number;
  };
  response: {
    status: number;
    statusText: string;
    headers: Record<string, string>;
    body: { kind: "text"; text: string } | { kind: "base64"; base64: string };
  };
}

type McpServerWire = Pick<McpServer, "name" | "url" | "headers" | "include" | "exclude">;

NetWire is how net.fetch crosses: the runtime encodes the body and wraps the response as a NetResponse. shell.save sends its data in the same body shape. McpServerWire is the server description mcp.* takes; the host keeps only name, url and headers (as strings) for a view's own calls.

MediaWire describes the media.* methods: media.open(constraints, source) → MediaWire["offer"] (source "user" or "display"), media.answer(session, sdp), media.stop(session, mid), media.constraints(session, mid, constraints) → MediaWire["track"], media.devices() → MediaWire["device"][], and the media subscription pushing MediaWire["event"] ({ type: "ended", mid }). Media errors come back as "<DOMException name>: <message>", which the runtime turns back into a DOMException. Stability: experimental (see Media).

Subscriptions

subscribe opens a push channel: request("subscribe", channel, params) resolves to a subscription id, and the host then sends event messages with that sub until unsubscribe. The host also ends every subscription when it drops the frame. An unknown channel fails with There's no "<channel>" to subscribe to.

SubscriptionChannel

Channel Params Needs Payload
stored { key } none The new value of a key in the extension's own storage, or undefined. host.storage.subscribe(key) uses key kv:<key>. Writes made by the same frame through storage.set are not echoed back. Collections don't come through here; see records.
records { name } none { kind: "created" | "updated" | "deleted", id, record? } for one record of the extension's own collection name: record is the record after the change, absent for deleted. The frame's own writes are included. null after a resync, when changes may have been missed and the list should be read again. useCollection(name) uses it.
fs none fs none: something changed through Files
git none git none: a repo was added, removed or changed state
chat none chat a ChatEvent
dragdrop none fs a DragDropEvent; desktop app only, never fires in a browser
widgets none widgets or widgets:view none: widgets or dashboards changed
widget-data { widgetId } widgets or widgets:view a WidgetUpdate; keeps that widget's sources running while open
events none events a SpacemixEvent, for every event any extension emits
media { session } camera, microphone or screen MediaWire["event"]

The stored channel and its kv: key prefix are how the runtime implements storage, and the records channel is how useCollection stays live; neither is a storage API. Use host.storage.subscribe, useStored and useCollection. The prefix may change.

A subscription that the host refuses (missing permission, unknown channel) does not throw in extension code: host.*.subscribe returns its unsubscribe function, and the runtime logs [spacemix] couldn't subscribe to "<channel>": <error>.

Timeouts

What Limit Error
A req from the frame 60 s SpaceMIX didn't answer "<method>" within 60 seconds.
net.fetch none (it may wait on the "allow this host?" prompt)
fs.import, git.fetch, mcp.callTool, tools.call, ai.complete 10 min SpaceMIX didn't answer "<method>" within 600 seconds.
A call from the host (action, MCP resolution) 60 s <Name> didn't finish "<action>" within 60 seconds. / … its MCP servers …
A net.fetch request itself timeout from the request, default 30 s, at most 120 s, enforced by the core The request timed out.
Studio probe 10 s The extension didn't finish loading within 10 seconds.

The host's 60 s limit applies to every action, including one reached through host.tools.call, whose own request may wait 10 minutes: an action that takes longer than 60 s fails either way. A frame that never posts loaded or failed has no load timeout: calls wait on it.

Errors

Every failure crosses as a string: res and call-result carry error: string, and the runtime rejects with new Error(error). There are no error codes. An action handler's thrown message becomes the tool result { error } the model sees, or the rejection of host.tools.call. Media errors are the one structured case ("<name>: <message>").

Write error messages for the person or model reading them; don't parse the host's messages. Their wording is not part of the contract.

Other frame behavior

  • Links. A left click on an <a href> to http:, https:, mailto: or tel: (without download, and not a #fragment of the frame document) is cancelled and sent to host.shell.openUrl, unless the extension's own handler called preventDefault.
  • Errors. window error and unhandledrejection are posted as error. A render error shows the boundary's "ran into a problem" screen with a Try again button.
  • Keyboard. Ctrl/⌘ + K and Ctrl/⌘ + N (without Alt) never reach extension code.
  • Focus. The runtime posts focus-check on the frame's focus and blur.

The blank page

The core also serves an empty page at /api/ext-page (and spacemix-widget://localhost/page) that an extension frame can nest, post code into ({ source: "spacemix-page", code }, once) and so host a site's own app outside the frame's CSP. Its CSP allows remote scripts, styles and fonts over http:/https: but connect-src 'none', and over HTTP it gets the same second policy, sandbox allow-scripts allow-forms. There is no SDK API for its URL; the one extension that uses it (WordPress) derives it from the frame's own location. Stability: internal: not part of the protocol 1 promise.

Stability

PROTOCOL_VERSION, FrameInit, ThemeState, HostToFrame, FrameToHost, SubscriptionChannel, NetWire, McpServerWire and isOp are stable: within protocol 1, messages, fields, methods and channels are only added, never removed or changed. MediaWire and the media.* methods are experimental. Of the runtime's exports (packages/sdk/src/runtime.ts: host, hostIfConnected, request, subscribe, connect), only host is re-exported from @spacemix/sdk and is stable. The others belong to the frame runtime, are reachable only through @spacemix/sdk/runtime (not a host module, see Package format) and are internal, as is install in packages/sdk/src/media.ts, which the runtime calls to put its own getUserMedia, getDisplayMedia and enumerateDevices in front of the browser's.

This page as markdown · All pages as one file