App development
Build a published Cohub App with runtime context, viewer permissions, AI prompts and generation, Space files, App Actions, surfaces, realtime rooms, and commerce.
This page explains how to build web Apps that use the Cohub runtime once published: initializing the SDK in Bridge or Broker mode, syncing theme and locale, requesting viewer permissions, calling AI and Space files, running owner-funded App Actions, integrating with workspace surfaces, connecting realtime rooms and WebRTC, and metering features with commerce. For publishing workflows, visibility, promotion links, and custom domains, see Apps.
Minimal walkthrough
Runtime APIs (context(), viewer authorization, App Actions, realtime rooms, and commerce) only work inside a published Cohub App. Opening a local file:// page or a bare static asset URL returns null from client.context().
- Create a single-file
index.htmlthat initializes@neta-art/cohub, syncs the host theme, reads runtime context, and reads a file from the App's own Space:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello Cohub App</title>
<style>
body {
background: var(--cohub-bg-primary, #ffffff);
color: var(--cohub-text-primary, #111111);
font-family: var(--cohub-font-sans, system-ui, sans-serif);
padding: 24px;
}
</style>
</head>
<body>
<h1 id="heading">Loading…</h1>
<button id="grant" type="button">Read current Space</button>
<pre id="out"></pre>
<script type="module">
import { createCohubClient } from "https://esm.sh/@neta-art/cohub?bundle&target=es2022";
const isDev =
location.pathname.startsWith("/dev/") ||
location.hostname.includes("dev");
const client = createCohubClient({ env: isDev ? "dev" : "prod" });
client.app.appearance.sync();
const ctx = await client.context();
if (!ctx?.app?.id) {
document.getElementById("heading").textContent =
"Open this page as a published Cohub App.";
throw new Error("Not inside a published app");
}
document.getElementById("heading").textContent =
`App ${ctx.app.id} (${ctx.locale})`;
// Uses the publisher-granted file.view scope on the App's own Space.
const home = client.space(ctx.app.homeSpace.id);
const listing = await home.files.list();
document.getElementById("out").textContent = JSON.stringify(
listing.entries.map((entry) => entry.path),
null,
2,
);
// Viewer grants must be requested from a user gesture.
document.getElementById("grant").addEventListener("click", async () => {
const result = await client.auth.authorize({
target: { kind: "pick-space" },
scopes: ["file.view"],
reason: "List files in the Space you select.",
});
if (result.status !== "granted" || result.target.kind !== "space") return;
const selected = await client.space(result.target.spaceId).files.list();
document.getElementById("out").textContent = JSON.stringify(
selected.entries.map((entry) => entry.path),
null,
2,
);
});
</script>
</body>
</html>
- Publish the file with the minimum App scope it needs (
file.viewfor reading its own Space):
cohub -s <space> apps publish hello-app --file ./index.html --app-scope file.view
- Open the published URL printed by the CLI (
https://cohub.live/<username>/<spaceSlug>/w/hello-app) or preview it inside the Space. Confirm the heading shows the App ID and the file list renders, then click Read current Space to verify the viewer consent flow. Publish a new version withcohub apps publish-version <appId>after each change.
Runtime modes and initialization
Inside a published App, createCohubClient() needs no token: the host supplies short-lived credentials automatically.
- Bridge mode — the App runs inside a Cohub iframe (workspace preview tab, overlay, embed, or public page shell). This is the default mode.
- Broker mode — the App is opened at its standalone origin (
<app-id>.apps.example.comor a bound custom domain) and negotiates auth through a popup broker.
The same initialization code discovers both modes. With a bundler:
import { createCohubClient } from "@neta-art/cohub";
// Browsers do not inject ENV — pass env explicitly so a dev-hosted App
// does not call the production API.
const isDev =
location.pathname.startsWith("/dev/") || location.hostname.includes("dev");
const client = createCohubClient({ env: isDev ? "dev" : "prod" });
const ctx = await client.context();
if (!ctx?.app?.id) throw new Error("Not inside a published app");
Without a bundler, import from an ESM CDN:
import { createCohubClient } from "https://esm.sh/@neta-art/cohub?bundle&target=es2022";
Storefront sign-in
On a bound custom domain or managed standalone host, call await client.auth.signIn({ returnTo: location.href }) from a sign-in button. The viewer confirms their Cohub account once and returns to that App URL, preserving query parameters and hash. The host keeps a first-party, App-scoped session for up to 14 days, and reloads or new tabs restore the viewer through client.context().
- Call
client.auth.signOut()to end the storefront session. - Signing out of Cohub on the web ends that storefront session and any tokens issued through the sign-in window across devices.
- Inside Cohub,
signIn()uses the embedding host's login flow and return location.
Calling your own backend
After obtaining the required viewer grants, call client.auth.getAccessToken() to forward the same bearer credential the SDK uses for Cohub API requests:
const token = await client.auth.getAccessToken();
if (!token) return;
const response = await fetch("https://your-backend.example/api/reply", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ input: "Hello" }),
});
In a published App, this credential is the App session token, not the host's account credential. Pass { forceRefresh: true } to request a fresh token from the same provider. A custom getAccessToken option or sandbox execution token still takes precedence. The method returns Promise<string | null>, propagates provider errors, and never requests new permissions. Verify the credential on your backend, preserve its authorization boundaries, and never put tokens in URLs or logs.
Three architecture decisions
Decide these before writing runtime code:
- Do you need runtime capabilities at all? For a static page, report, or client-only game, publish with empty scopes and no runtime SDK code. Viewers see no consent dialog and incur no usage.
- Who pays for AI?
| Model | Implementation | What the viewer sees |
|---|---|---|
| Viewer pays | Call prompts, completions, decisions, or generation from browser code | One consent dialog (client.auth.authorize) on first use |
| Owner pays | Put the work in an App Action under .cohub/actions/ and invoke client.app.actions.run() |
No viewer permission dialog |
| Hybrid | Free reads in the browser; expensive generation inside an Action metered with commerce credits | Checkout only when purchasing credits |
- Where does data live?
| Storage | Implementation | Retention & consent |
|---|---|---|
| Viewer's Space | client.auth.authorize({ target: { kind: "space" | "pick-space" }, scopes: ["file.edit"] }), then space.files.write() |
One viewer grant, revocable, 14-day expiry |
| App home Space | App Action writes with owner permissions | No viewer grant |
| Ephemeral multi-viewer state | client.app.realtime rooms |
Lives for the room's duration (1 minute to 24 hours) |
Context and theme syncing
client.context() reports who the App is, where it was opened from, and what the host is currently displaying. Treat context as routing information, never as authorization.
const ctx = await client.context();
ctx.app.homeSpace; // Space that owns this App (static)
ctx.viewer; // Current signed-in viewer, or null when logged out
ctx.invocation; // Snapshot of how this open started:
// surface, source, spaceId, sessionId, turnId,
// toolCallId, embedder, file, id
ctx.shell; // Live location currently shown by the host:
// space, session, turn
ctx.locale; // Viewer language, e.g. "zh-CN"
ctx.appearance; // colorScheme, theme, tokens, reducedMotion
ctx.window; // { visible } — false while the tab is hidden
ctx.permissions; // appScopes + viewerGrants for UI state
// Subscribe to shell, sign-in, grant, theme, and visibility updates
const stop = client.app.onContextChanged((next) => render(next));
| Field | Represents | When it changes |
|---|---|---|
ctx.app.homeSpace |
Space that owns the App | Never |
ctx.invocation |
Where this open originated | On each open |
ctx.shell |
What the host currently displays | As the viewer navigates |
Syncing appearance and locale
navigator.language and prefers-color-scheme only match Cohub when the viewer follows OS defaults. Read ctx.locale and ctx.appearance instead, or let the SDK keep <html> synchronized:
const stopSync = client.app.appearance.sync(); // sets --cohub-* CSS vars, color-scheme, and lang
body {
background: var(--cohub-bg-primary, #fff);
color: var(--cohub-text-primary, #111);
font-family: var(--cohub-font-sans, system-ui);
}
The public design tokens are: bg-primary, bg-content, bg-surface, bg-elevated, bg-input, bg-hover, bg-active, text-primary, text-secondary, text-tertiary, text-placeholder, text-disabled, border-primary, border-subtle, brand, brand-hover, brand-soft, brand-muted, brand-border, brand-ring, brand-contrast-fg, error-fg, success, warning, error, info, status-running, selection-bg, overlay-scrim, shadow-subtle, shadow-medium, shadow-strong, font-sans, and font-mono. Always supply CSS fallbacks because tokens are absent outside a Cohub host.
Pause heavy animations or rendering while ctx.window.visible is false; background tabs remain mounted for instant resume.
Permissions
An App's effective permissions on a Space are the union of its App scopes and any active viewer grants (plus offline access for home Space Actions):
| Source | Granted by | Coverage | Lifetime |
|---|---|---|---|
| App scopes | Publisher at publish time (App can / --app-scope) |
App's own home Space only; 8 bounded scopes | While published |
| Viewer grants | Viewer via consent dialog (client.auth.authorize) |
Any permission the viewer holds, on any Space or account | 14 days, revocable |
| Offline access | Viewer via consent dialog (offline: true) |
The App's home Space Actions acting on that Space while the viewer is away | Until revoked |
The eight publisher App scopes are: space.view, session.view, file.view, file.edit, taskrun.view, session.prompt.readonly, session.prompt.fullaccess, and command.execute.
Rule of thumb:
- Reads on the App's own Space → publisher App scopes.
- Other Spaces, writes to viewer Spaces, multimodal generation, and
user.*account data → viewer grants.
Requesting viewer grants
Call client.auth.authorize() from a user gesture with a clear reason. It only opens a consent dialog when new permissions are needed; repeat visits reuse valid grants silently. Always operate on the returned result.target, because the resolved Space may differ from the requested one.
const result = await client.auth.authorize({
target: { kind: "space", spaceId },
scopes: ["file.view"],
reason: "Read the Space you opened this App from.",
});
if (result.status !== "granted" || result.target.kind !== "space") return;
const space = client.space(result.target.spaceId);
Key authorization behaviors:
- Targets:
{ kind: "account" }(account-level scopes only),{ kind: "space", spaceId }, or{ kind: "pick-space" }. - Return shape: includes
status,requestedTarget, actualtarget,resolution, andgrant.status: "cancelled"is a normal user dismissal, not an error. - Silent shell consent: targeting
ctx.shell.space.idis silent when that Space published or installed the App for read-only scopes (space.view,file.view,file.view.filtered,session.view,taskrun.view,checkpoint.view) andfile.edit. Other Apps ask once, then renew read-only grants silently. Revoked grants always ask again. - Fallback and re-prompting: unavailable Spaces may fall back to a viewer-controlled Space unless you pass
fallback: "none". PassalwaysAsk: trueto force the dialog (for example, to switch Spaces). - Incremental consent: reading a grant does not extend its expiry; pass
scopeMode: "extend"to add scopes to a valid grant. - Creating a Space for the viewer:
client.auth.requestCreateSpace({ scopes, space, reason })creates a viewer-owned Space in one consent step. Ifgranted: falseis returned alongside aspace, the Space exists but bootstrap did not finish — resume against that Space instead of creating a second one. - Grant management: viewers inspect and revoke grants via
cohub apps grants <app>andcohub apps revoke <app> <grantId>. An App session cannot manage its own grants.
Joining a Space with an invite
An App can render a custom invite page by inspecting the invite token anonymously and letting the host perform the join:
const invite = await client.invite.get(token);
const result = await client.auth.joinSpace({
invite: token,
scopes: ["file.view"], // optional: authorize on the joined Space in one step
reason: "Join the studio to view shared boards.",
});
if (result.status === "joined") {
// result.space, result.role, result.granted
}
- Call
joinSpace()from a user gesture. The host signs the viewer in if needed, shows one confirmation dialog, and accepts with the viewer's account (App sessions cannot accept invites directly). status: "joined"also covers viewers who already hold that role or higher (skipping the dialog when no scopes are requested).status: "unavailable"means the link expired, was revoked, or hit its usage limit.- Hosts create invite links in Space settings or with
cohub spaces invites create; an App with a viewer'smember.managegrant can callclient.space(id).invitations.create().
API to scope map
| Operation | Required scope | Allowed source |
|---|---|---|
| Read Space configuration | space.view |
App or viewer |
List models (models.list, models.listMultimodal) |
(authenticated only) | — |
| Send prompt (full access) | session.prompt.fullaccess |
App or viewer |
| Send prompt (read-only) | session.prompt.readonly |
App or viewer |
LLM completion (completion, streamCompletion) |
session.prompt.readonly |
App or viewer |
Decision (decision) |
session.prompt.readonly |
App or viewer |
| Read / stream Chat replies | session.view |
App or viewer |
| List / read Space files | file.view |
App or viewer |
| Write / delete / move Space files | file.edit |
App or viewer |
| Run Sandbox shell commands | command.execute |
App or viewer |
| Create multimodal generation task | generation.create |
Viewer only |
| Poll tasks, read task runs | taskrun.view |
App or viewer |
| List viewer's Spaces / Chats / usage / all tasks | user.space.list / user.session.list / user.usage.read / user.taskrun.list |
Viewer only |
| List viewer's Apps / scheduled jobs across Spaces | user.app.list / user.cronjob.list |
Viewer only |
Create a Space (auth.requestCreateSpace) |
Requested scopes on the new Space | Viewer consent |
Join a Space (auth.joinSpace) |
Requested scopes on the joined Space | Viewer consent |
| Create, list, or revoke invite links | member.manage |
Viewer only |
| Commerce, realtime rooms, surface, composer, App Actions, navigation | (runtime only, no scope) | — |
"App or viewer" means publisher App scopes cover the App's home Space, while any other Space requires a viewer grant on that Space.
AI, files, and sandbox
Prompting an Agent
Send a prompt into a Space Chat and stream the assistant's response:
// Requires session.prompt.fullaccess (or session.prompt.readonly with read_only) + session.view
const result = await space.prompt({
accessMode: "full_access", // must match the scope you hold
content: [{ type: "text", text: "Summarize the project structure." }],
sessionId: null, // null creates a new Chat; pass a session ID to continue
});
space.session(result.session.id).subscribeGeneration({
state: (e) => renderPartial(e.state),
finalized: (e) => renderFinal(e.turn.assistantText),
});
space.prompt()returns immediately; stream output viasubscribeGeneration()or pollturns.get().accessModedefaults to"full_access". Holdingsession.prompt.readonlywithout passingaccessMode: "read_only"returns HTTP 403.session.prompt.fullaccessdoes not includesession.view. Pair them so reading the reply does not fail with 403.
LLM completion
For stateless one-shot completions without creating a Chat or Turn (needs session.prompt.readonly):
const result = await space.completion({
messages: [{ role: "user", content: "Summarize in one sentence." }],
});
for await (const event of space.streamCompletion({
messages: [{ role: "user", content: "Summarize in one sentence." }],
maxTokens: 160,
})) {
if (event.type === "delta") renderDelta(event.text);
}
messages accepts full conversation history, plain-string or structured content blocks, and an optional space-relative systemPromptPath. Image blocks support Cohub/Anthropic blocks, OpenAI Chat (image_url), and Responses (input_image); external URLs must be publicly reachable, and data: URLs are sent inline.
Structured decisions
space.decision() evaluates structured questions against text, JSON, or images and returns calibrated probabilities (needs session.prompt.readonly):
const result = await space.decision({
state: { ticket: "I was charged twice. Please refund it." },
questions: {
refund: { type: "noul", instructions: "Is the customer asking for a refund?" },
team: {
type: "choice",
instructions: "Which team should handle this?",
criteria: { billing: "Charges", technical: "Bugs" },
},
urgency: {
type: "score",
instructions: "How urgent is this request?",
criteria: ["Can wait", "Needs attention"],
},
},
});
// result.answers.refund.noul (0..1), team.choice, urgency.score (0..1)
- Supports up to 200 questions per call (
noulyes/no,choiceovercriteriakeys,scoreover at least two orderedcriteria). - For images, pass
stateas an array of text and{ type: "image_url", image_url: { url } }parts (public URLs or PNG/JPEG/WebPdata:URLs).
Multimodal generation
// Viewer grant: generation.create + taskrun.view
const { models } = await client.models.listMultimodal();
const result = await client.generations.createAndWait(
{
spaceId,
model: models[0].id,
content: [{ type: "text", text: "A geometric paper lantern at dusk" }],
parameters: { size: "1024x1024" },
},
{ onPoll: (detail) => updateProgress(detail.run.status) },
);
const url = result.output?.find((block) => block.type === "image")?.source?.url;
Always query client.models.listMultimodal() rather than hardcoding model IDs. generation.create is viewer-grant-only and must be paired with taskrun.view so polling can complete.
Files and Sandbox commands
const space = client.space(spaceId);
// file.view
const listing = await space.files.list();
const file = await space.files.read("data.json");
// file.edit
await space.files.write({
path: "output/result.json",
content: JSON.stringify(data),
encoding: "utf-8",
});
// command.execute — shell command string in the Space Sandbox
const run = await space.runCommand({ command: "node scripts/build.mjs" });
Opening files as a custom editor or viewer
Declare file extensions in <head> to register an App as a file handler:
<meta name="cohub:file-handlers" content=".board" />
Installing the App into a Space registers its declared extensions in .cohub/apps.json unless another installed App already owns them. Users can switch the default via Open with… → Always open .board files this way. Read-only Save previews always use the built-in viewer.
client.app.onLaunch(async ({ file }) => {
await openDocument(file.spaceId, file.path);
});
onLaunch fires when the window opens, when the same file is opened again, and when the file is renamed or moved (save to the new path thereafter). An App published or installed by a Space receives file.view and file.edit on that Space without prompting, making App installation in .cohub/apps.json a Space-wide trust decision.
App Actions
Directory Apps can define server-side entrypoints under .cohub/actions/. When invoked, Cohub downloads the immutable published App version and executes the entrypoint inside the home Space Sandbox as the App owner (usage bills the owner), while commerce entitlements and credit metering apply to the signed-in viewer.
const task = await client.app.actions.run({
action: "summarize",
input: { text: "Long document..." }, // JSON passed on stdin, <= 16 KB
});
const detail = await client.tasks.get(task.taskRunId);
.ts and .js entrypoints run under Node.js native type stripping (no enum, namespace, or parameter properties); other entrypoints run via executable bit or shebang. Inside an Action, read execution identity with getCohubContext():
import { getCohubContext } from "@neta-art/cohub";
const { execution } = getCohubContext();
execution.viewerUserId; // signed-in viewer who triggered the Action
execution.spaceId; // the App's home Space
- Action keys match
[a-z0-9-_]+, with at most one matching entrypoint per key. - Action inputs are stored on the Task Run and visible to the App owner and Space members — never pass secrets in
input. - Actions cannot invoke
client.app.actions.run()recursively. - Space Hooks can invoke a published App Action using
uses: <owner>/<space>/<app>/<action>. - To verify a viewer's order inside an Action, call
client.appCommerce.getOrder(appId, orderId)using the Action credential; the server checks that the order belongs to the bound buyer.
Offline access
An Action runs with the App owner's permissions. To let your home Space Actions operate on another Space while its member is away (syncing, reporting, scheduled updates), request offline access once:
await client.auth.authorize({
target: { kind: "space", spaceId },
scopes: ["space.commerce.view"],
offline: true,
reason: "Sync your shop's orders into the dashboard.",
});
- Offline access accepts Space scopes only and always requires an explicit consent dialog (silent shell consent and silent renewal never create it).
- Interactive grants still expire after 14 days, while offline access lasts until revoked or until the granting member loses the underlying Space permission.
- Members and hosts inspect or revoke offline access in Space settings → Access or via CLI:
cohub -s <space> spaces app-access ls
cohub -s <space> spaces app-access revoke <grantId>
- Only Actions running in the App's home Space can use offline access; browser App sessions and Space Hooks executing the Action in another Space cannot.
- Because any visitor can trigger an Action, verify that
execution.viewerUserIdis authorized for the target Space before reading or mutating it.
Surfaces, window lifecycle, and host integration
Preview tab, Overlay, Background, and Guest page
- Preview tab / window (default): opens inside the workspace, deep-linkable via
?window=app:<appId>. - Overlay: a transparent, chrome-free layer above the workspace and below Cohub's own UI. Declare
<meta name="cohub:surface" content="overlay" />at publish time or open withcohub desktop open <app> --as overlay. Overlays start fully click-through; claim interactive hit regions and optional geometry withclient.app.requestConfigure():
client.app.requestConfigure({
inputRegion: [{ x: rect.left, y: rect.top, width: rect.width, height: rect.height }],
});
Set html, body { background: transparent } and <meta name="color-scheme" content="light dark"> so Chromium does not paint an opaque backdrop. Close programmatically with client.app.requestClose(); viewers can always press Escape.
- Background (New Chat): a workspace App used as the New Chat background receives
shell.surface === "background"andshell.spaceset to the hosting Space. It can attach composer chips, but is not callable via desktop commands and receives no device capabilities. - Guest page: a Space can set one of its published public Apps as its guest page under Space settings → Access or with
cohub spaces config <space> --guest-app <app>. Visitors without access and invite links land there withshell.surface === "guest",shell.space, and (when invited)shell.invite.tokenforclient.auth.joinSpace().
Embedding other Apps
A published App can embed another App in an iframe while keeping each App's bridge, consent dialogs, commerce, and tokens isolated:
<iframe
src="https://cohub.live/alice/studio/w/notes"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads allow-modals"
allow="clipboard-read; clipboard-write; fullscreen; web-share"
></iframe>
const embed = client.app.embed.attach(frame, {
appId: ctx.app.id,
shell: ctx.shell ?? null,
onCloseRequest: () => frame.remove(),
});
client.app.onContextChanged((next) => embed.setShell(next.shell ?? null));
// Call embed.dispose() on teardown
The embedded App sees surface: "embed" and invocation.embedder as navigation hints, never authorization.
Callable surface methods (surface.handle)
Register named methods so the Cohub host — or an Agent running cohub desktop open <app> --call <method> — can drive a running App without DOM injection:
client.app.surface.handle("image.open", async (input, { commandId }) => {
const result = await openImageStudio(input);
await client.desktop.reportResult(commandId, {
status: "applied",
result,
error: null,
});
});
- Only registered methods are callable. Delivery is at-least-once, so handlers should be idempotent.
- Returning from the handler acknowledges receipt; report completion with
client.desktop.reportResult()and persistcommandIdif the flow can cross a reload. - For self-hosted or custom Cohub host origins, explicitly allow them via
client.app.surface.allowHostOrigins(["https://cohub.internal"]).
Window state, shortcuts, drops, composer chips, and navigation
- Window state and close protection:
client.app.window.setState({ title: "Roadmap.board", status: "saving", dirty: true });
client.app.window.onBeforeClose(async () => {
await flushPendingWrites(); // return false or throw to keep the window open
});
While dirty is true, the host keeps the App mounted and holds newer App versions until reload. On tab close or workspace leave, the host calls onBeforeClose() and only prompts the viewer if it fails or exceeds 10 seconds. Still persist drafts locally because closing the browser tab itself cannot wait.
- Shortcuts: after
client.context()succeeds, unhandled Ctrl/Cmd chords forward to Cohub (such as the command palette), while plain typing and editing chords (copy, paste, cut, select all, undo, redo) stay inside the App. Callevent.preventDefault()to claim a chord. - Drops: accept dragged files, Tasks, or Apps with
client.app.onDrop({ accept: ["file", "task"], over, leave, drop }). Coordinates are frame-local CSS pixels; treat droppedrefvalues as untrusted and read them through authorized APIs. - Composer chip: attach one plain-text context chip (label ≤ 120 chars, content ≤ 32 KB) with
client.app.composer.setChip({ key, label, content })and clear it withclient.app.composer.clearChip(key). - Host navigation: open a Space resource (
app,file,session,task,checkpoint,cronjob) in the workspace:
const { handled } = await client.navigation.open(
{ kind: "app", ref: "username/space/app" },
{ call: { method: "focus", input: {} } },
);
Degrade gracefully when handled is false (for example in standalone Broker mode).
Realtime rooms, WebRTC, and devices
Realtime rooms
Share ephemeral multi-viewer state scoped to one published App without setting up your own WebSocket server (for full room lifecycle, CLI/Node seats, and RTC helper setup, see Realtime Rooms & RTC):
const room = await client.app.realtime.createRoom({ seatPerUser: true });
// Or join an existing room by code:
// const room = await client.app.realtime.joinRoom({ code });
room.subscribe("state.updated", ({ data }) => render(data));
await room.publish("state.updated", { value: 42 });
publish()assigns a room-wide sequence number and stores events in room history (latest 1,000 events, up to 512 KB for the room's 1 minute – 24 hour lifetime), replaying missed events on reconnect.room.send()skips acks and history for high-rate updates.- Use
room.history({ after })to catch up on join, androom.onOutOfSync()to resync full state if more events were missed than history holds. room.memberslistsparticipantId,presence,kind(user,agent, orcli),model(foragent), and shareduserKeyfor seats acting for the same person.- Invite an Agent or CLI into a room with
const { invite } = await room.invite()(default 10-minute expiry), or create a room from the CLI withcohub rooms create --app <app>. From the CLI, seats stay active across calls until--idle(default 30 minutes) lapses:
cohub rooms join <invite> --presence '{"name":"Guide"}'
cohub rooms events <room> --type 'chat.*' --wait 10m
cohub rooms publish <room> chat.message '{"text":"Hello"}'
Node scripts can hold the same kind of seat through client.rooms.
Peer channels and media (WebRTC)
Call const rtc = await room.rtc() in the browser when room events need lower latency, binary payloads, or audio/video tracks:
| Property | room.publish() |
room.rtc() |
|---|---|---|
| Ordering | Room-wide sequence | Per sender and channel |
| Delivery | Reliable while connected | reliable (default) or latest (drop stale) |
| Payload | JSON, ≤ 16 KB | JSON or binary (ArrayBuffer), ≤ 64 KB |
| History & replay | Latest 1,000 (≤ 512 KB) | Never stored or replayed |
| Environments | Browser, Node, CLI | Browser |
const rtc = await room.rtc();
const cursor = rtc.channel("cursor", { delivery: "latest" });
cursor.send({ x, y });
cursor.onMessage(({ from, data }) => moveCursor(from, data));
const { mic, cam } = await rtc.publish({
mic: audioTrack,
cam: { track: videoTrack, simulcast: true },
});
rtc.onTracksChanged((tracks) => renderTracks(tracks));
await cam.replace(otherCameraTrack);
await mic.stop();
- Viewers receive at most 16 remote media tracks at once. Filter incoming tracks via
rtc.select((candidate) => nearby.has(candidate.participantId))(ornullfor everyone), inspectrtc.candidates, and pick simulcast layers withremote.setQuality("low" | "medium" | "high"). - Watch
rtc.onStateChange()for reconnects and handleAppRtcError: fall back to room events onRTC_UNSUPPORTED(non-browser or older Gateway) orRTC_UNAVAILABLE(no server relay).
Devices, sensors, and haptics
Declare required hardware permissions in <head> and request them at runtime:
<meta name="cohub:devices" content="camera microphone screen location" />
const status = await client.app.devices.request(["camera", "microphone"]);
if (status !== "granted") return showNotice(status);
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
- For
camera,microphone, andlocation, Cohub prompts per App before the browser does and reloads the App frame on first approval (or when revoked from the Cohub bar).screenis ready immediately because the browser prompts on everygetDisplayMedia()call. status === "unavailable"means the device was not declared in<meta name="cohub:devices">or the surface/host does not support it. Overlays and background surfaces never receive hardware devices.- Motion sensors, gamepads, and screen wake lock require no
<meta>declaration (iOS still requiresDeviceMotionEvent.requestPermission()inside a tap; background surfaces go without). Trigger host haptics withclient.app.devices.haptics("confirm")("tick" | "confirm" | "reject" | "longPress").
Commerce
Sell one-time products bound to an App's runtime identity, backed by feature benefits (access gates) and credit benefits (consumable Space-scoped credits). Requires commerce initialized on the Space.
const { entitlements, credits } = await client.app.commerce.getEntitlements();
const unlocked = entitlements.some((e) => e.benefitKey === "pro" && e.enabled);
if (!unlocked) {
await client.app.commerce.purchase({ productKey: "pro_unlock" });
}
// operationId is the idempotency key per logical charge
const result = await client.app.commerce.consumeCredits({
amount: 10,
operationId: crypto.randomUUID(),
reason: "Export high-resolution image",
});
if (result.status === "insufficient") {
await client.app.commerce.purchase({
productKey: "credit_pack",
returnUrl: "https://shop.example.com/cart#/done",
});
}
// Re-query authoritative state after returning from checkout
const state = await client.app.commerce.getCheckoutState();
if (state.orderId) await client.app.commerce.getOrder(state.orderId);
Key rules:
- User gesture and verification: call
purchase()only from a user's purchase action, never on page load. Returning from checkout is not proof of payment — always re-querygetCheckoutState(),getOrder(), orgetEntitlements(). returnUrlconstraints: must be an absolute HTTPS URL pointing either to the App's exact public page path on Cohub (any query or hash) or to any path on its managed standalone domain or active custom domain. OmitreturnUrlto return to the public page. Checkout addscohub_checkoutand preserves the hash;getCheckoutState().orderIdmay benullacross origins.- Immutable pricing: product prices cannot be edited in place. Create a new versioned product key, rebind the benefit, and archive the old product.
- Space credits vs Cohub Balance: Space credits meter actions inside the Space's Apps; Cohub Balance (
cohubBalanceUsd, whole dollars, immutable) is a separate platform-managed product component. - CLI setup and examples: configure commerce with
cohub -s <space> spaces commerce setup,benefits create,products create, andbind— see Billing, Wallet & Commerce for full Space Commerce setup, or the sample Apps index and whale-shrine for the canonical Action + credits loop.
Boundaries and common errors
client.context()returnsnull: the page is running outside a published Cohub App runtime (for examplefile://, localhost, or a raw CDN file URL). Publish to a Space and open the published URL.- Dev App silently calls production API: browsers do not expose
ENV=dev; always passenv: "dev" | "prod"explicitly tocreateCohubClient(). - HTTP 403 on
space.prompt()despite holdingsession.prompt.readonly:accessModedefaults to"full_access". PassaccessMode: "read_only"to match the read-only scope. - Prompt or generation starts, then fails with 403 when reading output:
session.prompt.fullaccessdoes not implysession.view, andgeneration.createdoes not implytaskrun.view. Request both scopes together. generation.createoruser.*rejected at publish time: these scopes are viewer-grant-only and cannot be configured as publisher--app-scopevalues. Request them viaclient.auth.authorize()from a user gesture.- Popup blocked in Broker mode: call
client.auth.authorize()directly inside the click handler before awaiting other API calls so the popup token exchange does not lose user activation. - Acted on the wrong Space:
ctx.invocationandctx.shellare routing hints, not authorization. Always passresult.target.spaceIdfromclient.auth.authorize()toclient.space(...). - Duplicate charges or duplicate surface effects: generate a stable
operationIdper logical action forconsumeCredits()and makesurface.handle()handlers idempotent against at-least-once delivery. - Secrets leaked in Task Runs or assets: Action
inputis visible to the App owner and Space members on the Task Run, and shipped HTML/JS assets are public to viewers. Never embed tokens or secrets in either. - Space or owner cannot publish: ensure the Space has a slug and the owner has a username before publishing.
Next steps
- Apps — publish files, Boards, directories, and ports, manage versions, promotion links, and custom domains
- Realtime Rooms & RTC — room lifecycle, CLI/Node seats, WebRTC channels, and media tracks
- Billing, Wallet & Commerce — Space Commerce products, benefits, credits, and Space Wallet funding
- Models & Generation — multimodal generation models, pricing, and CLI workflows
- SDK — full
@neta-art/cohubclient modules, transport options, and realtime streams - CLI — command reference for publishing, grants, rooms, and commerce setup
- Files & Sandbox — workspace storage, command execution, and Sandbox lifecycle