@chat-leo/chatleolib
v2.2.0
Published
ChatLeo library for web integration
Readme
chatleolib
Core library of ChatLeo: login, real-time connection, state (ChatStore) and uploads. It is normally loaded by <chatleo-component>; an application shell can also drive it directly with ChatLeoLib.getInstance() and setServerUrl() (see below).
Real-time transport
The library talks to the server through a Transport (src/transport/):
| Transport | Protocol |
|---|---|
| WsV2Transport | ChatLeo Protocol v2 over WebSocket (chatleo-v2) — the default |
| SocketIoTransport | Socket.IO (socketio-v1) — legacy compatibility mode |
Configuration
import { ChatLeoLib } from '@chat-leo/chatleolib';
ChatLeoLib.transport = 'v2'; // 'v2' (default) | 'socketio' | 'auto'or, per component, <chatleo-component transport="socketio"> (takes precedence over the static setting).
v2(default) — ChatLeo Protocol v2 only. The endpoint comes from discovery, or<serverUrl>/v2/wsif the server has no discovery document. If the WebSocket cannot be established, login still succeeds and the connection keeps retrying in the background.socketio— legacy Socket.IO atserverUrl. Nothing else is requested (no discovery document); keep this for Socket.IO-only deployments during the transition.auto— after login the library fetchesGET /.well-known/chatleo(cached for the session). If it listschatleo-v2, v2 is used at the advertised URL (REST calls stay onserverUrl, even if the WebSocket lives on another host). If the document is missing, invalid or does not offer v2, Socket.IO is used. If v2 cannot be established after 3 attempts the library logs a warning and falls back to Socket.IO when the document lists it.
The default changed from socketio to v2, so default logins now fetch the discovery document once; a missing or failed document keeps the client on v2 at <serverUrl>/v2/ws rather than switching to Socket.IO. Set the value before the first login. Servers must offer v2, or hosts must pin socketio/auto; rolling back to the previous behaviour is configuration-only.
Reliable sending and unread state
sendChatMessage()shows the message immediately withdelivery: 'pending'and returns the generatedclient_id. On ack the message becomessentand takes the serverid/seq; broadcasts that arrive first are merged byclient_id, so nothing is shown twice.- Failed sends stay in an
Outboxand are retried automatically after reconnect with the sameclient_id(10 s ack timeout, exponential backoff, 5 attempts).forbidden,read_only,not_foundandinvalidare permanent. On failure the message hasdelivery: 'failed'anderror; components emitmessageRetry/messageDiscard, which map tochatStore.retryMessage()/discardMessage(). - When the server sequences messages, reconnect catch-up uses one
POST /api/v1/syncrequest with per-room cursors. Missing sequences are fetched withafter_seq, scroll-back usesbefore_seq, and unread counts/read markers come from the server (POST /rooms/:id/read,room-readevents). Opening the active room reports the read marker after a 2 s debounce while the tab is visible. - Servers without sequencing keep the previous behaviour (active-room re-fetch, local unread counting) while still showing pending/sent state.
What differs between protocols
Sending, receiving, room events, presence, read state and catch-up sync behave identically (the same behaviour tests run against both). Only v2 additionally provides:
- Resume — on every reconnect the library sends its per-room cursors so the server replays missed messages;
room.resynctriggers a REST catch-up. - In-band token refresh — a refreshed access token is sent as
auth.refreshon the open connection instead of reconnecting. - Activity and streams —
ChatStoredispatchesactivityandstreamUpdatedevents (typing / thinking / tool use of agents, and messages that are produced incrementally). With Socket.IO these events are never produced.
chatStore.addEventListener('activity', (e) => {
const { roomId, senderId, kind, state, expiresAt, data } = (e as CustomEvent).detail;
});
chatStore.addEventListener('streamUpdated', (e) => {
const { streamId, roomId, text, status } = (e as CustomEvent).detail; // status: streaming | ended | aborted
});
chatStore.getActivities(roomId); // currently active activities
chatStore.getStreams(roomId); // streams in progressTesting
pnpm --filter @chat-leo/chatleolib testbehaviour.socketio.test.ts and behaviour.v2.test.ts run one shared scenario suite (src/testing/behaviourSuite.ts) against a fake Socket.IO server and a fake v2 server. src/testing/FakeV2Server.ts can be reused to test other v2 clients.
Calls (protocol v2 only)
Calls require protocol v2. On Socket.IO the library reports calls as unavailable, ignores call events and refuses the call REST actions; chat keeps working. ChatStore exposes activeCall(roomId) and incomingCall, and dispatches callChanged / callRinging. ChatLeoLib.ensureCallsAvailable() checks the discovery calls feature; startCall, joinCall, declineCall, leaveCall, endCall and refreshCallToken call /api/v1/.../calls. joinCall returns {sfu_url, token, room_id, mode, ice_servers}, which maps directly to call-core's ConnectionCredentials. Call state also comes from active_call in the room list and sync response, so a client that missed live events still shows a running call.
Push notifications
ChatLeoLib.push exposes state(), enable(), disable() and syncOnLogin(); the component uses pushState, enablePush and disablePush. Push requires the server's push discovery feature and a served worker (chatleolib/dist/chatleo-push-sw.js, or import chatleolib/push-sw into an existing worker). Subscriptions always go through the ChatLeo server; the PulseLeo SDK is loaded lazily. See docs/push.md.
Application shell without an embedded component
A host that owns the session at the shell level — no chat page and no <chatleo-component> in
the DOM — drives the shared instance directly, points it at the server and signs in:
import { ChatLeoLib, ChatLeoLoginError } from '@chat-leo/chatleolib';
const lib = ChatLeoLib.getInstance(); // the one instance the page (and its components) share
lib.setServerUrl('https://chat.example.com'); // origin of the ChatLeo server
try {
const profile = await lib.signIn({ ticket, transport: 'auto' });
} catch (e) {
if (e instanceof ChatLeoLoginError) {
// e.reason: 'invalid_credentials' | 'invalid_ticket' | 'unreachable' | 'server_error'
}
}setServerUrl()is required before the first sign-in when no component providesserver-url. It accepts an origin URL (https://chat.example.com) — REST and discovery endpoints are resolved from it — and rejects paths, queries, hashes and non-http(s) schemes.- A programmatically set URL wins over the DOM scan: a
<chatleo-component>mounted later uses the configured server even if itsserver-urlattribute differs (or is absent). - Re-setting the current URL is a no-op. Changing it while signed in throws — call
logout()first, because the session's tokens, transport and rooms belong to the previous server. - A session returned by
lib.getSession()can be persisted and restored on the next load withlib.restoreSession(session); its server URL is re-applied and stays sticky. - Components discovered later are bound to the same instance and join the existing session;
mount
<chatleo-component chatLeoLib={lib}>when a chat view is needed.
