omni_adapter (Dart / Flutter)

Join a Connect Omni stage from Dart or Flutter and exchange real-time messages with ProtoPie prototypes. Same wire contract as the TypeScript, Python, C#, Kotlin and Swift adapters — one credential, dotted channels, JSON-string convention.

First time? The step-by-step guide for a first connection (the adapter key, the install and the adapter name, in all six languages) is docs/getting-started.md, shipped in the adapter's npm and NuGet packages. Everything a Dart or Flutter program needs is also in this README and in llms.txt.

For AI assistants — the full usage guide llms.txt ships in the package root (next to pubspec.yaml in the pub cache, ~/.pub-cache/hosted/pub.dev/omni_adapter-<version>/llms.txt; on Windows under %LOCALAPPDATA%\Pub\Cache). Must-know rules for Dart:

  • Credential: only a cst_… adapter token (Share → Adapter keys → Create key, then Copy) or a bare ck_… key with url + stageId; never hard-code it — read it with const String.fromEnvironment('CONNECT_TOKEN') (--dart-define / -D; works everywhere) or, in a pure Dart program, Platform.environment (never on the web). Whitespace around it → ConfigError.
  • Close on exit: await client.close() on SIGINT/SIGTERM (pure Dart), or unawaited(_client?.close()); in dispose() (Flutter) — the client ends at the call and waits up to 1 s for the server to confirm the leave. An unclean exit leaves the old seat in the member list for a few seconds.
  • Lifecycle events: client.onEvent('stateChange' | 'error' | 'memberJoin' | 'memberLeave' | 'history' | 'ended' | 'queueOverflow', (payload) { … }) — not client.on('error', …), which subscribes to a stage channel named error. Callbacks run synchronously in the zone you called connect() from — keep them short (heavy work janks a Flutter UI).
  • latest() is not a delivery check: it folds your own sends in. To confirm a publish use ack: true (a server ack, not a delivery receipt) or watch the channel from a second connection.
  • exclusiveName standby: only instances on the same adapter key; while standby new sends are dropped (or, acked, fail with Standby), and becoming standby drops whatever was queued — nothing stale goes out on promotion. Read client.standby.
  • 60 messages a second per connection: the adapter paces sends to the server's limit; a faster source fills the queue and loses its oldest values — throttle() it. close() drops queued fire-and-forget sends.
  • send / sendJson throw synchronously for a bad channel or value and after the session ended — not as a Future error, so .catchError and unawaited(...) don't see it. Put the call inside try (with await, a plain try/catch catches both).
import 'package:omni_adapter/omni_adapter.dart';

// dart run -DCONNECT_TOKEN=cst_… bin/main.dart · flutter run --dart-define=CONNECT_TOKEN=cst_…
const token = String.fromEnvironment('CONNECT_TOKEN'); // Stage → Share → Adapter keys → Create key, then Copy

Future<void> main() async {
  final client = await connect(ConnectOptions(
    secretKey: token,
    displayName: 'Flutter Panel',
    receives: const ['panel.value'],
    sends: const ['panel.slider'],
  ));

  client.on('panel.value', (msg) => print('${msg.channel} = ${msg.value}'));
  await client.send('panel.slider', 0.42, ack: true);
  await client.close();           // when you are done — leaves the stage
}

Works in Flutter on web as well as mobile and desktop: the package never imports dart:io directly (only the optional hostname label does, behind a conditional export).

Install

dart pub add omni_adapter        # Flutter: flutter pub add omni_adapter

which adds the dependency to pubspec.yaml and fetches it:

dependencies:
  omni_adapter: ^0.1.0

Working from a checkout of the adapter repository instead (contributors with access to it)? Use a path dependency — omni_adapter: {path: <repo>/dart}, where <repo> is the checkout — then dart pub get (or flutter pub get).

Three runtime dependencies, on purpose: socket_io_client (the server speaks Socket.IO), http (one POST) and web_socket (socket_io_client 3.1.6 already depends on it; the adapter imports one error type from it — see below). Flutter apps need only network access — see Flutter for the per-platform settings (Android INTERNET and cleartext, the macOS sandbox entitlement).

Server requirements

Joining, sending, receiving and the roster work on any Connect Omni server, but some features need an adapter-enabled server (or web build): ck_ adapter keys, strictRouting, exclusiveName, providesView, screen broadcast, remote input and the Engine profile. The minimum server for each feature is in the compatibility matrix, docs/COMPATIBILITY.md in the adapter's npm and NuGet packages. On an older server a ck_ key makes connect() fail with AuthRevoked (the server reads it as a bad share token, 401), the Engine profile fails with JoinTimeout (no host hands the page a port), and the declarations fail silently: the server strips them, so strictRouting falls back to broadcast, exclusiveName instances stay independent and a providesView adapter never appears as a screen candidate.

The credential

Everything needs ONE value, issued by the stage owner: open the stage → Share → "Adapter keys" → Create key, then Copy → a cst_… token that bakes in the server URL, stage id and the adapter key (ck_…). A bare ck_… key also works with url + stageId; anything else (a share token, for instance) is rejected with ConfigError before any network call, and so is whitespace around the value (a newline from a file or an environment variable).

Treat both as secrets and keep them out of your source. Read the token with const String.fromEnvironment and pass it at build/run time:

const credential = String.fromEnvironment('CONNECT_TOKEN');
// flutter run --dart-define=CONNECT_TOKEN=cst_…
// dart run -DCONNECT_TOKEN=cst_… bin/main.dart

Keep the const: String.fromEnvironment is only guaranteed to work as a constant (most ahead-of-time compiled targets have no defines at run time). A --dart-define keeps the token out of your source and repository, but the value is compiled into the app — anyone with the build can extract it, and a Flutter web build carries it as plain text in main.dart.js for every visitor to read. Give such builds only to people you would give the key to, and use a key you are ready to revoke (Share → Adapter keys). A pure Dart program can read Platform.environment['CONNECT_TOKEN'] (dart:io) instead — never on the web, where dart:io does not exist.

API

// Publish — values are primitives only (String/num/bool/null)
await client.send('door.open', true);
await client.send('door.open', true, ack: true);          // wait for server ack
await client.sendJson('robot.status', {'pose': [1, 2]});   // JSON-string convention
await client.sendTo(participantId, 'cmd.stop', 1);         // unicast

// Receive
client.on('actuator.cmd', (msg) => msg.value);             // exact channel
client.on('robot.*', (msg) => msg.channel);                // wildcard (1+ segments)
client.onJson('robot.status', (value) => value);           // parsed JSON

// State
client.latest('sensor.temperature');                       // last value (history-seeded; 1000 most recently updated channels)
client.latestJson('robot.status');
client.historyJson('chat.message'); // this channel's history, JSON-parsed
client.history('chat.*');                                  // replay ring ≤1000, NOT storage
await client.members();                                    // roster (providesView, standby, receives, sends, …); member.declaresChannel('robot.status')
await client.listeners('robot.status');                    // who will receive it: .declared / .broadcast (self excluded); records no-listener when nobody declared it
client.state;                                              // idle|connecting|connected|reconnecting|ended
client.standby;                                            // one-active-per-name (below)

// Lifecycle
client.onEvent('stateChange', (s) => print(s));
client.onEvent('memberJoin', (m) => print(m));
client.onEvent('ended', (reason) => print(reason));
await client.close();

// High-rate values — coalesced to hz per second, the last value is sent
final push = client.throttle('nav.position', hz: 10);
push(0.5);                                                 // a bad channel or value throws ValidationError here

// WebRTC ICE deployment config (screen adapters) — hand it to your platform
// WebRTC plugin (e.g. flutter_webrtc). Without it the peer gathers host
// candidates only and connects inside the same NAT only. Cached on success only;
// on failure it returns a still-cached list, else the public STUN list (when only
// the authenticated route failed), else [] — and the next call asks again. Never
// hard-code STUN/TURN URLs.
final iceServers = await client.fetchIceServers();

Lifecycle events come only through onEvent — client.on('error', …) (or any other name) subscribes to a stage channel of that name. Every handler takes one Object? payload:

Name Payload When
'stateChange' String — idle connecting connected reconnecting ended every state transition
'error' AdapterError a server-pushed or transport error (rejoin refusals included)
'memberJoin' Member a participant joined
'memberLeave' String (participant id) a participant left
'history' List<StageMessage> the history snapshot was re-seeded (every (re)join that carries one)
'queueOverflow' PublishInput the offline queue dropped its oldest item
'ended' String? (reason) the session is over — the last event

An unknown name is accepted and simply never fires. Handlers see only events that happen after you register them — read client.state for the current state. A handler that throws is logged (warn) and does not stop delivery to the others.

Errors at the call site are synchronous. send, sendTo and sendJson check the channel and the value — and whether the session already ended (SessionEnded) — before they return a Future, and throw right there:

// ✗ the ValidationError escapes — catchError only sees errors inside the Future
unawaited(client.send('', 1).catchError((Object e) => print(e)));

// ✓ try around the call (with await, this catches network-side failures too)
try {
  await client.send('panel.tap', 'A', ack: true);
} on AdapterError catch (e) {
  final why = e.hint ?? e.message; // AckTimeout carries neither a hint nor more than its code
  print('panel.tap failed: ${why == e.code ? e.code : '${e.code}: $why'}');
}

sendJson takes JSON-compatible values — Map with String keys, List, String, finite num, bool, null, or an object with toJson(). Anything else (a DateTime, a Set, NaN, a circular reference) throws AdapterError('ValidationError') synchronously, like send. The throttled push(value) checks the channel and the value like send and throws ValidationError at the call site — but, unlike send, it does not throw after close(); a value that passes is delivered fire-and-forget, and a delivery failure is not reported to you.

Prototypes and the Console send every value as a string ("42", not 42) — or null when the message carries none — so convert before comparing; values from other programs keep their type.

The server never echoes your own publishes; latest() still folds them locally, so it is not a delivery check. Acks: ack: true waits for the server's ack (not a delivery receipt) and fails with AckTimeout after ackTimeout (default 15 s) — a timeout does not prove the server didn't get it. An acked send already on the wire when the connection drops or you close() ends in AckTimeout at once (it is not re-sent); one still waiting in the offline queue stays queued across a reconnect and fails with SessionEnded at close(). Attach handlers to acked sends before await client.close() — a rejection that nobody handles becomes an uncaught error in your zone. Print the code and e.hint ?? e.message: several codes carry no hint (AckTimeout, SessionEnded, most ValidationErrors, some ConfigErrors), and an error without a message of its own has the code as its message (AckTimeout) — so also say which call failed.

Offline queue and rate limit. While disconnected, reconnecting or backing off, sends queue (queueLimit, default 1000; overflow drops the oldest, fires queueOverflow and fails a dropped acked send with QueueOverflow) and flush in order once sending can resume, as fast as the rate limit below allows — plain items without waiting for acks, an acked item only after its server answer; a plain send returns as soon as it is queued. A plain send is at-most-once, direct or queued: it asks for no ack, so a server rejection of it — the rate limit included — is never seen, and one lost to a drop right after it went out is not retried. A queued acked send that already went out once before a drop and is later failed with QueueOverflow, Standby or SessionEnded may have reached the server too — on a queued acked send, none of these codes proves non-delivery. When an acked send meets the server's rate limit (TooManyRequests), the adapter backs off (1 s, doubling, up to 60 s) and re-sends from the queue silently — no send-dropped in diagnostics(), nothing thrown. Recognise it as: connected, queuedCount > 0, not standby, no send-dropped. close() drops queued fire-and-forget sends (queued acked sends fail with SessionEnded): to be sure the last values went out, await an acked send or wait until queuedCount is 0 first.

Rate limit — 60 messages a second. The server accepts at most 60 messages a second per connection and silently drops fire-and-forget messages above that, so the adapter paces every send — direct or queued — with a token bucket (60 per second, bursts of up to 30); a send with no token free waits in the queue. Keep a source above 60/s up and the queue fills: the oldest items are dropped (a queueOverflow event for each, one queue-overflow line in the diagnostics ring per episode) and the newest value still goes out. After a disconnect, a sender at 60/s or more stays behind by up to queueLimit ÷ 60 seconds (the queue drains at 60 a second, so a full default queue of 1000 takes about 17 s) — throttle it or lower queueLimit. Acked sends go one per round trip, so never use ack: true for a high-rate stream.

Roster. await client.members() returns a List<Member> (you included) and await client.listeners(channel) a Listeners with channel, declared and broadcast (lists of Member, you excluded). Re-read members() after every (re)connect — joins and leaves that happened while you were disconnected are not replayed as events. members() and listeners() are server round trips: they fail with NotConnected while the client is not connected.

Console output. By default the adapter prints every log line — debug ones included — as [omni-adapter] … with print. Pass logger: (level, message) { … } to route them into your app logger, or logger: (level, message) {} to silence them.

Option Default Notes
displayName 'Omni adapter' 1–64 chars. A screen layer finds an adapter by this name — keep it stable
receives / sends — Channel declarations (max 32, each ≤512 chars; receives may use wildcards unless strictRouting is on). Backstage port chips + flow pulses
strictRouting false Server delivers only declared receives (+ messages targeted at you). Requires exact names
providesView — none|web|stream — stream makes this adapter selectable by an Adapter Stream layer (by display name); web marks a web page (a Web View layer shows a page by its URL)
exclusiveName — One active per name (below)
autoRejoin true Wait for a closed stage to reopen and rejoin (below)
reconnection true socket.io level reconnect (dropped socket, live session)
queueLimit 1000 Offline outbound queue cap (oldest dropped first)
ackTimeout 15 s How long a send(..., ack: true) waits before AckTimeout. Must be above zero and at most 2^31−1 ms (about 24.8 days) — anything else fails with ConfigError
osHostname the machine's host name Machine label shown in the stage. Filled in from Platform.localHostname wherever dart:io exists (Dart VM, Flutter mobile/desktop); empty on the web. The other five adapters never fill it in for you
usePolling false Pin to HTTP long-polling — Flutter web only. On native platforms socket_io_client 3.x has no polling transport and the connection never succeeds (connect() logs a warning)
logger print (level, message) — every log line, debug included; route it into your app logger, or pass a no-op to silence it
onLog — (LogEntry entry) — every diagnostics-ring entry as it is recorded (entry.code: state, standby, active, send-dropped, …)

Error codes

Every failure is an AdapterError with .code (branch on it), .message and usually .hint. Errors throw from the call that caused them; later failures arrive on onEvent('error', …).

Code Meaning adapter behaviour
AuthRevoked Adapter key rejected, revoked or expired — or, with stage-locked in the message, the stage is closed to guests (adapters join as guests) Terminal — auto-rejoin gives up (ended: "rejoin-abandoned: AuthRevoked"); issue a new key, or ask the stage owner to reopen the stage to guests
ProtocolVersionMismatch / ClientAheadOfServer Wire version gate Terminal — upgrade one side
ValidationError Bad channel/value (thrown synchronously), or the server rejected the join body (400) Local checks throw before any network call; a join 400 names the fields (see below)
RoomEnded No live session connect() throws it at once; after a successful join, auto-rejoin keeps waiting
SessionEnded The client has ended (closed, or the session is over for good) send throws synchronously; queued acked sends fail
StageFull Participant cap reached Surfaced from the join; rejoin keeps waiting
StageArchived The stage is archived Surfaced from the join — ask its owner to restore it
TooManyRequests Server rate limit (60 messages a second per connection), seen only on acked sends Backoff and retry from the queue — not thrown
TooManyRequests from connect() The server refused the join (429): too many failed join attempts from this network address — 20 within 5 minutes, usually another program here still using a revoked or mistyped token — or more than 60 joins a minute with one adapter key (a restart loop); servers without the per-key join limit also refuse a sixth join from one address within a minute Thrown from connect(), not retried — wait up to 5 minutes, and fix the program that causes it
KeyMaterialUnavailable from connect() The server (503) cannot read the stored material of an older adapter key on this stage — a server-side key change left it behind; after 30 of these from one address within a minute, a correct key gets the same answer until the minute ends Thrown from connect(), not retried (a joined client keeps retrying while it rejoins) — ask whoever runs your Connect to revoke the old keys
AckTimeout No server ack within ackTimeout, or the connection closed with the ack pending Fails that acked send (at once when the connection closes) — the server may still have it
Standby An acked send while this instance is standby, or a queued acked send discarded when it became standby Not sent
QueueOverflow Queue cap hit (sending faster than 60/s, or a long disconnect) Oldest item dropped (an acked one fails), plus queueOverflow
NotConnected / JoinTimeout / ConfigError Unreachable server (or members()/listeners() while not connected) · connected but never admitted · bad options Surfaced to the caller — ConfigError before any connection is attempted
Unauthorized / NotSupported The server refused a roster request · the call is not available on this transport or server (ensureStreamLayer() on a server without the route — its other errors are RoomEnded, TooManyRequests, ValidationError, NotConnected and SessionEnded after close(); an error of its 401 re-validation passes through as connect() would report it, for example AuthRevoked) Thrown from that call

When the session closes

The adapter does not die. It goes to reconnecting, checks at a widening interval whether the stage reopened (2s → ×2 → 60s) and rejoins on its own; sends queue while it waits and flush on return. So ended means finished for good: you called close(), or rejoining was abandoned because waiting cannot help — a revoked adapter key ends with rejoin-abandoned: AuthRevoked rather than retrying forever. Turn it off with autoRejoin: false for a one-shot script.

A server-side disconnect does not crash your program

When the server cuts the connection itself — an adapter key revoked or expired, or a key check that refuses a reconnect — socket_io_client 3.1.6 tries to close a WebSocket the server already closed and drops the resulting WebSocketConnectionClosed error. Unhandled, that error ended a pure Dart program and reached Flutter's PlatformDispatcher.onError. The adapter runs the library's internal work (connection, timers, WebSocket listener) in a zone of its own that swallows exactly that error and logs it at debug through logger; the disconnect itself is handled as above (rejoin, or rejoin-abandoned: AuthRevoked). The error is matched by its type (WebSocketConnectionClosed from package:web_socket, ^1.0.1), not by its text, so the match survives --obfuscate and dart2js minification, and another exception whose message merely starts the same way is not swallowed. Nothing else changes:

  • Any other error raised inside the library still reaches the uncaught-error handler of the zone you called connect() from (runZonedGuarded, Flutter's handlers, …).
  • Your callbacks (on, onJson, onEvent, onSignaling, …) run in the zone you called connect() from, so a Future you create in a callback and await elsewhere in your app delivers its error normally.

Names and closing

The same adapter key is never renamed — a restart keeps its name. Another program connected under the same displayName with a different key makes yours join as name (2); for a providesView: 'stream' adapter, so does an Adapter Stream layer with that name that is bound to another adapter key that is still valid — usually a rotated key whose old copy was never revoked: revoke it. A person who takes a program's name is the one renamed. (Older servers, from before same-key name sharing, renamed a restart that came within a few seconds of an unclean exit to name (2).) An unclean exit (a crash, a kill, Ctrl+C without close()) leaves the old seat in the member list for a few seconds. Call close() on exit — it ends the client at the call and sends the leave, waiting up to 1 s for the server to confirm it. In a pure Dart program:

for (final signal in [
  ProcessSignal.sigint,
  if (!Platform.isWindows) ProcessSignal.sigterm, // SIGTERM can't be watched on Windows
]) {
  signal.watch().listen((_) async {
    await client.close(); // sends the leave
    exit(0);
  });
}

In Flutter, close it in dispose() — see Flutter.

One active per name

Two instances sharing a displayName mean a screen layer cannot tell them apart and the prototype receives both their values interleaved. Pass exclusiveName: true and the server keeps the newest connection active and marks the rest standby. A standby client keeps receiving (so it stays warm), stops sending (so values do not double), logs why, and is promoted automatically when the active one leaves — standby is a spare. The instances must use the same adapter key — a copy with a different key joins as name (2) instead, and its exclusiveName is dropped.

While standby, new sends are dropped (fire-and-forget, debug log only) or fail with Standby (ack: true) — never deferred. When an instance becomes standby — after a reconnect or when presence changes — everything it had queued is dropped the same way (the standby entry in diagnostics() ends with — dropped N queued sends), so a later promotion sends nothing stale. After each (re)connect the adapter needs one roster round trip to judge standby; sends made meanwhile are held (sharing queueLimit), then queued if this instance is active (or the judgment failed) or treated by the standby rule. There is no standby-change event: read client.standby when you need it, or watch the diagnostics ring for the codes standby / active (reading client.standby inside a memberJoin handler is too early — the roster check behind it is still running):

final client = await connect(ConnectOptions(
  secretKey: token,
  displayName: 'Wall Sensor',
  exclusiveName: true,
  onLog: (entry) {
    if (entry.code == 'standby' || entry.code == 'active') {
      print('this instance is now ${entry.code}');
    }
  },
));

Leave it off for crowds that share a name on purpose (20 visitor phones at a booth).

Flutter

  • Token — --dart-define=CONNECT_TOKEN=… read with const String.fromEnvironment('CONNECT_TOKEN'); the value is compiled into the app (see The credential).

  • Connect and close with the widget. dispose() is synchronous: call unawaited(_client?.close());, then super.dispose(). A connect that completes after the widget is gone must close the client it got — nobody else will, and it keeps its guest seat — so check mounted right after the await:

    import 'dart:async';
    
    import 'package:omni_adapter/omni_adapter.dart';
    import 'package:flutter/material.dart';
    
    const token = String.fromEnvironment('CONNECT_TOKEN'); // --dart-define=CONNECT_TOKEN=cst_…
    
    class StagePage extends StatefulWidget {
      const StagePage({super.key});
      @override
      State<StagePage> createState() => _StagePageState();
    }
    
    class _StagePageState extends State<StagePage> {
      ConnectClient? _client;
      String _status = 'connecting';
    
      @override
      void initState() {
        super.initState();
        unawaited(_join());
      }
    
      Future<void> _join() async {
        try {
          final client = await connect(ConnectOptions(secretKey: token, displayName: 'Flutter Panel'));
          if (!mounted) {
            unawaited(client.close()); // the widget went away while connecting
            return;
          }
          client.onEvent('stateChange', (state) {
            if (mounted) setState(() => _status = '$state');
          });
          setState(() => _client = client);
        } on AdapterError catch (e) {
          if (mounted) setState(() => _status = '[${e.code}] ${e.hint ?? e.message}');
        }
      }
    
      @override
      void dispose() {
        unawaited(_client?.close()); // dispose() is synchronous — never await here
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) => Text(_status);
    }
    
  • Callbacks run synchronously on the UI isolate (in the zone you called connect() from) — setState there is fine; heavy work janks frames, so hand it off.

  • Android — add the INTERNET permission, and allow cleartext traffic for a plain http:// server.

  • macOS — the app is sandboxed: add com.apple.security.network.client to both macos/Runner/DebugProfile.entitlements and Release.entitlements. Without it the join fails with NotConnected (Operation not permitted).

  • Plain http:// on iOS/macOS — the adapter connects through dart:io sockets, which App Transport Security does not govern: a macOS build reached a plain-http:// host name with no ATS exception (iOS not verified).

  • Web — no dart:io (Platform.environment, exit, ProcessSignal). usePolling: true works only here; on native platforms the connection is never admitted.

Rules that prevent most bugs

  1. Values are primitives. Objects throw before the network round-trip — use sendJson (prototypes parse the JSON string).

  2. No self-echo. The server never sends your own publishes back. latest() still folds them locally; UI lists need optimistic appends. latest() remembers the 1000 most recently updated channels — like the history ring, older ones fall out.

  3. A live session must exist. An Editor or the Owner has to open the stage in Connect (people who joined through a share link cannot start one), or the adapter key was created with Let adapters start a session turned on (Share → Adapter keys) so it can start one. connect() fails with RoomEnded at once when there is none; after a successful join, autoRejoin (the default) waits out a closed session and joins the next one.

  4. Each connection consumes one guest seat of the stage cap. Reuse one client; don't connect per message. Call close() on exit (in dispose() in Flutter) — see Names and closing.

  5. Cloud URL shape: the API base is …/api/connect, not the web UI base …/connect. The Share-dialog token is always correct; doctor flags a hand-typed UI base.

  6. History is a ring (≤1000, reseeded per reconnect) — not storage, and state, not triggers (the snapshot never re-fires on() handlers; see below).

  7. Errors are AdapterError with .code and usually .hint — a one-line next action. Print e.hint ?? e.message in error paths (several codes carry no hint); the hint is usually the whole fix. When the server rejects the join body, ValidationError carries the fields it named (up to three, then (+N more)) instead of a bare (400):

    AdapterError(ValidationError): token/validate rejected the request body (400):
    clientType — Invalid literal value, expected "adapter"
     — Server and adapter disagree on the request shape — usually a version skew.
    Update whichever is older, then retry.
    

    A rejected field almost always means a version skew, not a bad token.

Examples

  • example/ — pure Dart: quickstart, sensor bridge (throttle + auto-rejoin), screen adapter (providesView / exclusiveName / signalling), roster bridge (bidirectional + members()).

Two more examples are full apps with their own platform folders, so they are not part of the published package:

  • example_flutter/ — a Flutter app that draws received values, sends slider/button values, and shows connection and standby state. Verified as a web build (that build is also the CI guard that keeps dart:io out of this package).
  • example_aaos/ — an Android Automotive OS head-unit app: real vehicle signals (speed/gear/night/temperature) from the Car API to the stage, HMI commands (hmi.ambient, hmi.notice) back, and a drive-cycle simulator fallback on non-automotive devices.

Remote input (standalone servers) — no registration code needed

Pass onRemoteInput to startScreenBroadcast (below) and the helper carries the coc.input channel wiring, the holder gate, the direction whitelist, the [0,1] clamp, pointer-id validation and cancel synthesis — still with no WebRTC dependency in this package. Injecting the pointer into your UI is your code: what a pointer means is the app's decision.

Remote input runs on standalone servers — the only servers that run adapters. The stage arms it for Editors as soon as your screen streams — no registration code — so onRemoteInput is all you need. Standalone servers send lease-holder notices (key adapters are registered automatically on join and told the holder): input is accepted only from the Editor holding the lease — the Connect editor claims it automatically on the first pointer-down — and PIN or share-link viewers never control. Older servers that predate the notices never announce a holder; then the gate stays permissive and accepts every viewer's input. The core also carries a registration/lease API for registration-code deployments (the first holder notice switches the gate to strict with no change to your code): registration (client.submitRegistrationCode(code) → registrationId + a succession deviceSecret — a secret; client.resumeRegistration(deviceSecret: …) re-binds after reconnects) and the operation-lease holder notice (client.onRemoteInputHolder(...)), whose local ttlMs expiry you should still honour.

example_aaos/ remains the reference for injection — including a physical-safety gate that blocks new pointers while the vehicle is moving — and it runs on this helper (startScreenBroadcast), so it doubles as the recommended wiring. Standalone servers only.

Screen broadcast (Adapter Stream)

Put your own rendered screen on a stage's Adapter Stream layer. The helper owns the signalling choreography and adds no dependency — you inject one session per viewer, built on whatever WebRTC stack you already use.

final broadcast = startScreenBroadcast(
  client: client,
  createSession: (viewer, sendIceCandidate, iceServers, wireInput) async {
    // flutter_webrtc lives in YOUR app — that is why `flutter build web`
    // still works for this package
    return openSession(viewer, sendIceCandidate, iceServers, wireInput);
  },
  onRemoteInput: (pointer, viewer) => inject(pointer),   // optional
);
broadcast.viewerCount;
await broadcast.stop();

Two rules the helper encodes because both fail silently — negotiation reports success and the picture never appears:

  1. Announce on every connect ({"kind":"ready"}, reconnects included). The server builds its peer list from sockets already in the room and only tells existing viewers about a late arrival when that arrival says ready. The helper re-announces on every connected transition (not the current-state value — a fast reconnect collapses into no re-announce if you watch the value).
  2. Attach the track to a stream (addTrack(track, stream)) so the answer carries msid. That part is your session's job; without it the viewer's ontrack fires with an empty streams array.

The adapter only ever answers — the viewer sends the offer. Declare providesView: 'stream' at connect time and give the adapter a stable display name: on a server with adapter stream layers the server then creates and binds the Adapter Stream layer itself when the adapter joins — in the first group placed on the stage, matched by the name the server gave the adapter (client.me?.displayName, which may read name (2); the participant id changes every run), and a deleted layer comes back on the next join. Without the declaration no layer is created and the helper records stream-undeclared once in client.diagnostics(). When your session factory returns null (nothing to send yet), the viewer gets no answer; call broadcast.sourceChanged() once the source exists so that viewer offers again — it is for when the source starts or changes, not per frame (calls are coalesced to at most one announcement per second). await client.ensureStreamLayer() is optional — an idempotent call that returns the layer: renamed is true when the server gave another name than requested (another program on a different key uses this name, or you rotated keys without revoking the old one — rename one, or revoke the old key; a layer under the original name will not show this adapter), and the client logs a warning. Errors: NotSupported (server too old), RoomEnded (no live session), TooManyRequests (429), ValidationError with the server's message, NotConnected (5xx, network, ack timeout, or a server failure while re-validating the key after a 401), SessionEnded after close(); any other error of that re-validation passes through as connect() would report it (for example AuthRevoked). The helper keeps one session per viewer receiver: the web keeps one receiver per (viewer page × adapter participant) and sends its receiverId, so two tabs of the same guest each get their own session instead of closing each other's — your factory is called once per receiver, with the same participant id, and viewerCount counts receivers. Answers and ICE echo the viewer's negotiationId and receiverId. A viewer keeps at most maxReceiversPerViewer (4) sessions: a fifth receiver evicts first one whose session has not sent its answer yet (an answered session stays live while it renegotiates), then the least recently negotiated session — the helper cannot see an injected connection's state, so report closures, or a vanished tab (a PIN or share-link guest's refresh keeps the participant id) holds a slot and a live tab that never renegotiates can be the one evicted. To close a session as soon as its connection fails, pass it back — broadcast.sessionClosed(session) when flutter_webrtc reports RTCPeerConnectionStateFailed or RTCPeerConnectionStateClosed (an unknown or already replaced session is ignored). When the adapter comes back with a new participant id (a rejoin into a new session, the 6-hour guest-token revalidation), the sessions from before the drop are closed. Viewer ICE that arrives early (before the offer, or before your session's answer() returns) is queued and handed to the session afterwards — candidates waiting for an offer expire after 10 s, and at most 4 receivers per viewer (64 in all) can wait. The ICE-server lookup gives up after 5 s and uses the last known servers; a failed lookup is never cached, so the next viewer asks again.

Pass onRemoteInput to the same call to accept viewer pointers (standalone servers). The helper carries the holder gate, the direction whitelist, the [0,1] clamp, pointer-id validation and cancel synthesis when the holder changes; injecting the pointer into your UI is your code — what a pointer means is the app's decision.

Diagnostics — doctor as a library call

final results = await runDoctor(credential);   // List<CheckResult>
print(formatDoctorReport(results));

Print the report when connect fails — it names the one step that is wrong:

try {
  final client = await connect(ConnectOptions(secretKey: token, displayName: 'Wall Sensor'));
  // …
  await client.close();
} on AdapterError catch (e) {
  print('[${e.code}] ${e.hint ?? e.message}');
  print(formatDoctorReport(await runDoctor(token)));
}

Eight checks run in order and stop at the first failure (the point is to name one cause, not list a cascade): credential · url shape · server reachable · adapter screens · remote input · stage session · socket join · screen adapters. adapter screens and remote input only warn or skip — they never stop the run — and screen adapters appears only after a successful join on a server that knows screens. Only ✖ lines need fixing (△ and · are information). The join step takes a guest seat for a moment (as omni-adapter doctor) and leaves. The credential is masked in the report. HTTP and the connect step are injectable, so you can unit-test the whole thing.

For a support ticket, buildReport(credential, diagnostics: client.diagnostics()) bundles the doctor run with the client's diagnostics ring — without diagnostics: the bundle's list is empty — and formatReport(bundle) renders it (the credential appears only as a fingerprint).

The terminal omni-adapter CLI stays TypeScript/Python: the same check from a terminal is npx --no-install omni-adapter doctor "$CONNECT_TOKEN" in a Node project that has the TypeScript adapter installed, or python -m omni_adapter doctor "$CONNECT_TOKEN" with the Python one.

Engine profile (Flutter web) — no credential, no seat

Running inside a stage-canvas layer that hands the page a MessagePort — a Connect Omni Web View layer (Add → Web View: any page URL; its Stage messages rules list the channels the page may receive and send) or an Engine Layer iframe — the adapter borrows the host's authenticated connection: no cst_ token in the page and no guest seat. Here connect() does not detect the layer for you (that is TypeScript-only): assemble an EngineTransport yourself, hand it to a ConnectClient, and inject the parent-window bridge (EngineHostWindow / EnginePortHandle) — that keeps the browser-only APIs (window.parent.postMessage, MessagePort transfer) out of this package, which is what lets it stay usable on every other Flutter target.

final engine = EngineTransport(
  window: bridge,                      // your EngineHostWindow over window.parent / MessagePort
  displayName: 'Panel',
  receives: const ['panel.value'],     // explicit subscribe — the only inbound channels
  sends: const ['panel.level'],        // announced to the host (engine:message-declare) — information, not permission
);
final client = ConnectClient(engine);  // no credential, no seat
await client.open();
client.on('panel.value', (msg) => print(msg.value));
await client.send('panel.level', 0.5);

// Engine control lives on the transport — there is no client.engine in Dart.
await engine.acquireControl();         // presenter lease
await engine.setState({'page': 2});    // shared state

The adapter owns the protocol: the two-step handshake (identity echo, then the port that arrives with the second host-init) or the Web View layer's one-step adapter-view:init handoff (port in the first message; the layer's Receive rules cap subscribe and its Send rules cap publish — exposed as allowedReceives and allowedSends; allowedChannels, both together, is deprecated. A subscription outside Receive is dropped without an error and a send outside Send is refused. Channels the page declares but the rules lack show up in the layer's Stage messages as ones "This page asked for", for the designer to add with Add. Saving changed rules closes the port and reloads the page, so your bridge should call notifyPortClosed() on the port's close event), explicit subscribe (receives, max 32 — that declaration is the inbound), request/response correlation, and the presenter lease / shared state / session snapshot operations.

Honest limits (v1): no ring-buffer history replay — but latest() is seeded, because the host replays each subscribed channel's most recent value; members() answers empty (there is no seat); there is no reconnect concept (the host owns the layer's life).

Writing your own transport

To plug in your own transport (a test double, a different channel to the host), extends Transport rather than implements Transport. The base class supplies defaults for the optional members (sendSignaling, fetchIceServers, …), so a member added in a later release is not a breaking change for your class; with implements, every new member is a compile error.

The exported constants (backoffInitial, backoffMax, defaultQueueLimit, …) are read-only reference values that document the library's behaviour — they are not settings.

Not included

The omni-adapter terminal CLI (TypeScript/Python only) — runDoctor above is the same logic as a library call. React bindings and typed channels are TypeScript-only.

Development

cd dart
dart pub get
dart analyze --fatal-infos    # strict casts/inference/raw-types, unawaited_futures = error
dart test                     # unit suites incl. the protocol drift guard
dart format --output=none --set-exit-if-changed lib test

The drift guard (test/protocol_drift_test.dart) reads typescript/src/protocol.ts — the repo's reference copy of the wire contract — and compares key:value pairs, so two event names cannot quietly swap places. It skips when that file is absent (standalone checkout).

Testing without a server — MemoryStage

final stage = MemoryStage();
final sensor = await stage.join(const MemoryJoinOptions(displayName: 'sensor', sends: ['sensor.temperature']));
final panel = await stage.join(const MemoryJoinOptions(displayName: 'panel', receives: ['sensor.*']));
panel.on('sensor.*', (m) => print(m.value));
await sensor.send('sensor.temperature', 23.5, ack: true);   // panel receives it; sensor does not (no echo)

stage.inject('ui.tap', 1);           // as if a prototype sent it
stage.disconnect(panel); stage.reconnect(panel);   // drop + recover: history snapshot, queue flush
stage.end('host closed the stage');  // everyone gets `ended`

Emulates the wire rules in-process (no self-echo, strict delivery, history ring, exclusiveName standby, listeners()); rejectPublish: injects failures. A harness, not a server — no doctor, no REST (ensureStreamLayer() keeps one in-memory layer per name, memory-layer:<name>, so the screen-layer path can be unit-tested — and, like the server, refuses a member that did not join with providesView: 'stream'), no signaling, and no 60-messages-a-second pacing (the client recognises its MemoryTransport and skips the token bucket).

Testing without hardware — replay · simulate

final records = parseRecording(await File('run.ndjson').readAsString()); // written by `omni-adapter record`
await replay(client, records, speed: 2);
await simulate(client, 'sensor.temperature', waveform: 'sine', min: 18, max: 26, hz: 2, durationMs: 30000);

Both publish through send (rate limit, queue, standby and backoff unchanged), wait for the queue to drain (giving up after 15 s without progress) before returning, stop on ended or shouldStop, and return the partial count. wait/random are injectable for deterministic tests. They only pace the sends — the 15 s no-progress limit runs on the real clock, so a no-op wait does not make it give up early.

History is state, not triggers

history()/latest() are re-seeded from the server snapshot on every (re)join whose joined payload carries one (the stage:joined fallback re-seeds nothing) and the history event fires — but the snapshot is never replayed into on() handlers. A command published while this adapter was disconnected is lost as a trigger and survives only as a last value: read latest() when stateChange reaches connected for state channels; treat trigger channels as at-most-once across a disconnect. Deliberate — replaying into handlers would re-fire a stale command minutes late.

Libraries

omni_adapter
Omni Adapter — Dart / Flutter.