@blario/react-native
Blar agent SDK for React Native. It mirrors the web widget's agent: it parses the React component tree into the
web dom_state v3 snapshot, hands out its own per-capture ids (btn-N, inp-N, scr-N) and resolves an id back
to its component to act on it.
Pure JS/TS, no native code. Works on the old architecture and on the New Architecture.
Install
npm install @blario/react-native react-native-webview
With Expo, let it pick the versions that match your SDK:
npx expo install @blario/react-native react-native-webview @react-native-async-storage/async-storage react-native-safe-area-context
Needs react >= 18.2 and react-native >= 0.74. react-native-webview runs the chat (the web widget) and is the
only peer you need to get started; the rest are optional and the SDK works without them:
| Peer |
Without it |
@react-native-async-storage/async-storage |
the contact is kept in memory, so every launch is a new anonymous contact |
react-native-safe-area-context |
fixed fallback insets are used instead of the device's |
react-native-view-shot (or @shopify/react-native-skia on iOS) |
a screenshot request answers sdk_error |
react-native-screens |
on iOS the agent layer is drawn in the root tree instead of its own window |
expo-haptics or react-native-haptic-feedback |
no buzz when a confirmation appears |
expo-keep-awake or react-native-keep-awake |
the screen may sleep during an agent run |
Native peers need a rebuild of the app (npx expo prebuild / pod install) unless Expo Go already ships them. The
package ships its TypeScript source, which Metro compiles with the rest of your app, plus type declarations in dist/.
Then wrap the app as shown in Connect to the Blar backend.
Versions
Versions follow semver and each one is published to npm when it reaches main. While the major is 0 a minor release
may change the API, and the ^0.2.0 range npm writes by default stays within one minor. The latest dist-tag is the
newest stable release and next the newest prerelease (0.3.0-beta.0), installed with
npm install @blario/react-native@next. SDK_VERSION is the installed version, and it is what the SDK reports to the
backend.
Integrate
import { BlarProvider } from '@blario/react-native';
import { createNavigationContainerRef, NavigationContainer } from '@react-navigation/native';
const navigationRef = createNavigationContainerRef();
export default function App() {
return (
<BlarProvider navigationRef={navigationRef} relayUrl="ws://localhost:8790">
<NavigationContainer ref={navigationRef}>{/* app */}</NavigationContainer>
</BlarProvider>
);
}
navigationRef is optional. Without it navigate only reaches routes of the navigators on the focused path.
Screenshots use react-native-view-shot when it is installed, otherwise @shopify/react-native-skia
(makeImageFromView) on iOS. Android requires view-shot: Skia's Android capture can raise a fatal native error
when a view unmounts during capture. With no supported capture module, a screenshot answers sdk_error.
Android on the New Architecture needs view-shot 4 or later: 3.x fails every capture there, while actions keep working.
Each module is resolved once when the SDK loads:
- view-shot leaves a host
Modal out (it is a separate window), so the response carries partial: true and
omitted: ['modal'] while one is open.
- Skia on iOS walks the view tree. A host
Modal is presented by its own view controller, outside the captured
view, so it is reported as omitted, as with view-shot. A capture narrower than maxWidth is sent at its own width,
never upscaled.
Neither includes the status bar, the chat or the agent layer.
The implicit ws://localhost:8790 relay is available only in development when no backend settings are provided.
Production requires both publishableKey and apiBaseUrl, or an explicit relayUrl. Invalid or partial backend
settings disable the SDK while the host app keeps rendering. API URLs must use HTTP(S); relay URLs must use WS(S).
Surrounding whitespace and scheme/host casing are normalized, and API base URLs must have no query or fragment.
Installed from npm, Metro needs no configuration. Only a linked checkout (the example app's file:.. dependency) needs
the SDK folder watched and a single copy of react/react-native (see its metro.config.js).
Connect to the Blar backend
<BlarProvider
publishableKey="<publishable-key>"
apiBaseUrl="https://api.blar.io"
user={{ externalId: 'u-1', email: 'ana@x.cl', name: 'Ana', country: 'CL', getIdentityToken: () => fetchToken() }}
language="es"
debug
>
language is 'es' or 'en' and defaults to 'es'; unsupported runtime values also fall back to 'es' for the
SDK's own texts and the chat's language. With publishableKey and apiBaseUrl the provider uses the backend
transport. It mirrors the web widget: contacts/load/ then contacts/identify/ with X-Publishable-Key,
X-Source-Id and the identity proof (X-Identity-Token / X-Identity-Signature, refreshed once through
getProof / getIdentityToken), the session socket /sessions/chat/<id>/?publishable_key&source_id&tab_id with the
proof as a subprotocol, ping/pong with {visibility, hidden_ms, lag_ms, sdk_version}, reconnect with backoff,
response replay after a reconnect, and a presence heartbeat every 30 s while the app is active and touched in the last
3 minutes. source_id persists in AsyncStorage when installed, otherwise in memory. enabled={false} keeps the SDK
off; changing it on a mounted provider starts or stops the socket, the agent and the chat.
Identity tokens must have three nonempty base64url JWT segments; identity signatures must be hexadecimal.
Malformed static values or provider results are treated as proof failures and never sent in native headers.
import { Blar } from '@blario/react-native';
await Blar.setUser({ externalId: 'u-1', email: 'ana@x.cl' });
await Blar.logout();
Blar.isConnected();
await Blar.getMessageMetadata({ includeTextDom: true });
Risky actions (irreversible, destructive, or confirmation_required) ask for confirmation in a native panel on the
status card; a decline or a 60 s timeout answers user_cancelled.
Drive the app with the real on-site agent
npm run harness -- --key <publishable-key> --external-id <id> --email <email> --base http://localhost:55180 "crea un cliente llamado Ana Díaz"
harness/tap-confirm.sh Confirmar 240 # approves the confirmation on the emulator (adb + uiautomator)
The harness identifies the same contact as the app (--external-id and --email, or BLAR_EXTERNAL_ID and BLAR_EMAIL;
--name and --country are optional), posts the message through
/api/ai/contact-sessions/<id>/widget/messages/create/ without a tab_id, so the app's socket answers as the holder,
and prints the conversation as it grows.
Chat and nudges
With the backend transport the provider also renders the chat. It needs react-native-webview (a peer dependency)
and optionally react-native-safe-area-context for insets.
<BlarProvider
publishableKey="<publishable-key>"
apiBaseUrl="https://api.blar.io"
user={user}
language="es"
strings={{ agentThinking: 'Pensando…' }}
chat={{ launcher: { visible: true, side: 'left', offsetY: 88 }, primaryColor: '#7C3AED' }}
>
Blar.open();
Blar.close();
Blar.getUnreadCount();
Blar.onUnreadCountChange((count) => setBadge(count)); // returns a function that stops listening
Blar.isChatOpen();
An app that hides the launcher and opens the chat from its own button shows the unread count on it with
useBlarUnreadCount(). It adds the AI's replies that arrived while the chat was closed to support's unread messages,
which the backend counts against what the contact read and pushes on the contact socket
(/contacts/socket/, contact_state.unread_count), so a reply from support reaches the badge even when the chat was
never opened. A contact whose conversation went to support is not given a new AI session at launch: the chat opens on
support, and writing to the AI again starts a session from there.
- The web support widget runs inside a
react-native-webview with its home menu (progress checklist, past conversations, release notes), served from a generated HTML
shell on the API origin. The bundle is generated, not committed (src/chat/widget-bundle.generated.ts is git-ignored): build
support-widget.min.js in web-sdk/, then run npm run embed-widget before npm run typecheck or the example
app (the unit tests do not need it). Or pass chat.scriptUrl to load it from a CDN instead.
- A drag down from the widget's header closes the sheet. The header is page content, so the sheet only watches the
touches that cross it (
onTouchMove, never the responder) and the page reports the header's height (header
message); a tap on its buttons still reaches the page.
- One contact, one session, one executor: the page seeds the widget with the native
tab_id, identifies with the same
identity and source, and boots it with agentExecution: false, so it ignores every agent command and only the native
runtime executes. Messages the user sends carry Blar.getMessageMetadata() (platform, screen path, text tree). The
widget's onSessionChange reports a new conversation and the native socket follows it. When the page leaves its
session (an escalation, a new or an ended conversation), native ends any run there and drops the socket until the
page reports the next one. Its onClose closes the sheet, and the chat reopens when the sheet does.
- The chat page never navigates away: a link it opens (a message link, an attachment, "Powered by Blar") goes to the
system browser through
Linking, and frames inside the page load as usual.
- Replying works as in WhatsApp: drag a message to the right and let go, or hold it, and the composer quotes it. This is
the widget's own touch gesture, so it needs no native code.
- Assistant messages that arrive while the sheet is not open raise the unread badge.
- Nudges arrive as native bubbles with the same sender, message, progress and actions as the web widget. Accepting
calls
POST /api/activation/nudges/open/ and opens the chat on the nudge session (openSession, without reloading
the page); No declines (dismiss with decision: "decline", which also turns off the feature offered) and Later calls snooze. A bubble has no ×: it is answered or left. A heartbeat that reports a pending
nudge refreshes the session so the bubble shows without waiting for a restart.
- The at-risk question («¿Qué te está frenando con ?») is a nudge whose answers come from the backend, shown two
to a row as on the web. The SDK declares it can draw it (
blocker_question: true on load and identify); a contact
on an SDK that does not gets step guidance instead. One tap calls POST /api/activation/nudges/answer/ and opens the
chat, where the agent asks what comes next, and an answer given in the chat takes the bubble down.
strings overrides any of the confirmation, chat, nudge and agent mode texts; es and en defaults ship in the
package.
Agent mode
A run looks and behaves like the web widget's agent mode (web-sdk/src/managers/agent-mode-state.ts,
web-sdk/src/agent/agent-mode-ui.ts), driven by AgentModeController: