Collaborate

Realtime Rooms & RTC

Share ephemeral multi-participant state, presence, ordered events, and WebRTC data/audio/video inside a published Cohub App across browser viewers, Agents, CLI, and Node scripts.

This page explains how to create and join ephemeral realtime rooms scoped to a published Cohub App, coordinate browser viewers alongside Agents and CLI seats through ordered events and presence, and add low-latency WebRTC data channels or audio/video streams with room.rtc() and cohub rooms rtc.

How rooms work

A realtime room belongs to a single published Cohub App. Rooms let multiple participants exchange state without running a separate WebSocket or SFU server.

Participants can join the same room from three environments:

  • Published App (browser): client.app.realtime.createRoom() or client.app.realtime.joinRoom({ code }) inside a published App.
  • CLI / Agents: cohub rooms create --app <app> (for an App you manage) or cohub rooms join <invite> using an invite token from room.invite() or cohub rooms invite <room>.
  • Node scripts: the HTTP and realtime methods under client.rooms in @neta-art/cohub.

Lifetime, codes, and capacity

Setting CLI flag SDK option Allowed range / format Default
Room lifetime --ttl <duration> expiresInSeconds 1m – 24h (60 – 86400 s) 2h
Max participants --max <count> maxParticipants 2 – 128 16
Room code --code <code> code 3–48 ASCII chars (^[A-Z0-9][A-Z0-9_-]{2,47}$, uppercased) Random 8-char code
One seat per user --seat-per-user seatPerUser Boolean false
Active rooms per App — — Up to 512 active rooms —

Seats, presence, and invites

  • Seats: When seatPerUser is false (default), every connection holds its own seat (two browser tabs count as two participants). When seatPerUser is true, a user holds at most one App seat across tabs; reconnecting from another tab replaces the existing seat.
  • Member metadata: Each entry in room.members (or cohub rooms get <room>) exposes participantId, joinedAt, presence (JSON object up to 2 KiB, or null), kind (user, agent, or cli), optional model (for agent), and an opaque room-scoped userKey shared across seats belonging to the same person.
  • Seat liveness: WebSocket connections keep their seat alive on a 60-second connection lease. CLI and HTTP seats remain active across individual commands until --idle lapses (1m – 24h, default 30m).
  • Invites: Call await room.invite() in an App or cohub rooms invite <room> from an existing seat to mint an invite token. Invites default to 10 minutes (--ttl, 1m – 24h).

Events, history, and CLI workflows

publish() vs. send()

Rooms expose two event primitives over WebSocket:

  • publish(type, data) assigns a monotonically increasing room-wide sequence number and appends the event to room history so reconnecting participants catch up automatically. History retains up to the latest 1,000 events or 512 KiB (whichever is reached first) for the room's lifetime, served in pages of up to 200 events.
  • send(type, data) skips acknowledgements and history storage for high-frequency transient updates where dropping stale frames is acceptable.

If a participant disconnects long enough that room history rolls past its last sequence number, the browser SDK fires room.onOutOfSync(), cohub rooms events marks truncated: true, and cohub rooms connect emits a gap record so the participant can resync full state.

Event names must match ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ and cannot use reserved prefixes. Each event payload is JSON up to 16 KiB.

CLI commands

Command Purpose
cohub rooms create --app <app> [--code <code>] [--ttl 2h] [--max 16] [--seat-per-user] [--json] Create a room for an App you manage and print its code, URL, and initial invite
cohub rooms join <invite> [--presence <json>] [--idle 30m] [--json] Claim a seat with an invite token and optional JSON presence
cohub rooms get <room> [--json] Show the room code, current sequence, expiry, members, and your seat
cohub rooms events <room> [--after <seq>] [--type <pattern>] [--wait <duration>] [--follow] [--limit <count>] [--json] Read published events oldest-first; --type supports * wildcards and is repeatable; --wait blocks until another member publishes
cohub rooms publish <room> <type> [data] Publish a JSON event (data or - for stdin) to all room members
cohub rooms presence <room> <json> Update your presence JSON object (null clears it)
cohub rooms invite <room> [--ttl 10m] [--json] Generate an invite for another participant from your current seat
cohub rooms connect <room> [--after <seq>] [--input] [--json] Stream events, members, gaps, and state over WebSocket; disconnecting keeps your seat
cohub rooms rtc <room> [options] Stream WebRTC data channels and audio/video through the cohub-rtc helper
cohub rooms leave <room> [--json] Release your seat immediately

Agent wait-and-wake workflow

An Agent or script can hold a seat across turns without staying connected between commands, waking only when matching events arrive:

cohub rooms join <invite> --presence '{"name":"Guide"}'
cohub rooms events <room> --after <sequence> --type 'chat.*' --wait 10m
cohub rooms publish <room> chat.message '{"text":"Hello"}'

For continuous bidirectional streaming from a script or daemon, use cohub rooms connect <room> --input --json. Each newline-delimited JSON line on stdin accepts one of three operations (up to 20 KiB per line):

{"op":"publish","type":"chat.message","data":{"text":"Hello"}}
{"op":"send","type":"cursor.move","data":{"x":120,"y":84}}
{"op":"presence","presence":{"status":"typing"}}

WebRTC data channels and media (RTC)

Use WebRTC when a room needs lower latency than WebSocket relays, binary payloads, or audio/video tracks.

room.publish() vs. room.rtc()

Property room.publish() room.rtc() / cohub rooms rtc
Ordering Room-wide sequence number Per sender and channel
Delivery Reliable while connected reliable (default) or latest (drop stale)
Payload JSON, up to 16 KiB JSON or binary (ArrayBuffer), up to 64 KiB
History & replay Up to 1,000 events / 512 KiB Never stored or replayed
Media tracks Not supported Audio and video tracks (with optional simulcast)
Environments Browser, Node, CLI Browser SDK (room.rtc()) and CLI (cohub rooms rtc)

Browser SDK (room.rtc())

const rtc = await room.rtc();

// Low-latency data channel
const cursor = rtc.channel("cursor", { delivery: "latest" });
cursor.send({ x: 120, y: 84 });
cursor.onMessage(({ from, data }) => moveCursor(from, data));

// Publish local audio/video tracks
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();
  • Data channels & media caps: Each member can open up to 16 data channels and publish up to 4 media tracks (audio or video). Channel and track names must match ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ and cannot start with cohub..
  • Track selection & simulcast: A viewer can subscribe to at most 512 data channels and 16 remote media tracks at once. Filter incoming media tracks with rtc.select((candidate) => ...) (or null for all), inspect rtc.candidates, and switch simulcast layers with remote.setQuality("high" | "medium" | "low") (high = 1× resolution, medium = 2× downscale, low = 4× downscale).

CLI & Agent media (cohub rooms rtc)

cohub rooms rtc <room> spawns the Go/Pion cohub-rtc helper binary. The CLI keeps authentication, room seat management, and WebSocket signaling over bounded NDJSON control pipes, while cohub-rtc handles WebRTC peer connections, DataChannels, and media I/O directly through files or stdin/stdout (never Base64-encoded JSON).

# Open a reliable data channel with NDJSON input on stdin
cohub rooms rtc <room> --channel telemetry --delivery reliable --data-input -

# Publish raw PCM audio and receive RTP media frames into a directory
cohub rooms rtc <room> --audio ./clip.pcm --audio-format pcm --rate 48000 --channels 1 --output ./received

Key options for cohub rooms rtc <room>:

  • Data channels: --channel <name>, --delivery reliable|latest (default reliable), --data-input <path|->.
  • Audio input: --audio <path|->, --audio-format pcm|opus (default pcm; opus expects Ogg), --rate <hz> (default 48000), --channels <count> (default 1).
  • Video input: --video <path|->, --video-format i420|vp8 (default i420; vp8 expects IVF), --size <widthxheight>, --fps <rate> (default 30).
  • Receiving media: --output <directory|-> (writes framed .rtc files into a directory or binary stream to stdout; when --output - is used, status JSON prints to stderr), --receive-format rtp|raw (default rtp), --receive-size <widthxheight> (default 640x360 for decoded I420), --max-bytes <bytes> (default 1073741824; 0 for unlimited), --participant <id>.
  • Helper binary override: --helper <path> uses a local cohub-rtc binary; COHUB_RTC_VERSION and COHUB_RTC_CDN_BASE_URL control auto-downloaded helper versions.

Boundaries and common errors

Hard limits

  • Rooms: TTL 1m – 24h (default 2h); 2 – 128 participants (default 16); max 512 active rooms per App; room event rate cap 2,000 (RATE_LIMITED).
  • Payloads & history: Room event payload ≤ 16 KiB JSON; presence ≤ 2 KiB JSON; room history ≤ 1,000 events or 512 KiB (page cap 200).
  • CLI streaming: cohub rooms connect --input rejects lines over 20 KiB and disconnects if stdout buffering exceeds 1 MiB. cohub rooms rtc allows at most one input (--audio, --video, or --data-input) to read from stdin (-), and --data-input requires --channel.
  • RTC signaling & media: SDP payloads are capped at 64 KiB (signaling HTTP request bodies over 64 KiB + 16 KiB fail with RTC_BAD_REQUEST / HTTP 413); DataChannel messages ≤ 64 KiB; up to 16 data channels and 4 media tracks per member; up to 512 data subscriptions and 16 media subscriptions; signaling rate caps of 10 operations/second and 2 session opens/second (batch cap 64). RTC sessions close with reason closed, replaced, stale, or expired.

Common errors

Error / code Cause Fix
ROOM_NOT_FOUND / ROOM_EXPIRED The room TTL elapsed or the room was revoked. Create a new room or request a fresh invite.
ROOM_FULL Active seats reached maxParticipants. Wait for idle seats to expire, enable --seat-per-user if duplicate tabs occupy seats, or raise --max (up to 128).
PAYLOAD_TOO_LARGE / INVALID_EVENT / RESERVED_EVENT Event JSON exceeded 16 KiB, or the event name failed ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ or used a reserved prefix. Trim payloads (or move binary/large messages to RTC data channels up to 64 KiB) and use a valid non-reserved event name.
RATE_LIMITED Room event traffic exceeded the room rate limit (2,000). Batch updates, switch high-frequency cursor/state streams to room.send() or an RTC latest data channel.
RTC_UNSUPPORTED / RTC_UNAVAILABLE Environment has no WebRTC support or no server RTC relay is configured. Catch AppRtcError and fall back to room.publish() / room.send().
RTC_SESSION_NOT_FOUND / STALE / LIMIT_EXCEEDED / NAME_TAKEN RTC session expired or was replaced, a channel/track/rate limit was hit, or a publication name is already in use. Reopen the RTC session on onStateChange(), respect per-member limits, and choose unique channel/track names not starting with cohub..

Next steps

  • App development — SDK setup, Bridge/Broker runtime context, permissions, surfaces, and App Actions
  • Apps — publish, version, and share the Cohub App that hosts your rooms
  • CLI — full command reference for cohub
  • SDK — use @neta-art/cohub from browser Apps and Node scripts