The reference chat client connects directly to AppEngine with a customer or guest JWT. This is separate from the server-held application credential described in Overview. A Socket.IO deployment can use a compatible reverse proxy, but a per-request HTTP SDK proxy does not implement the realtime protocol. Do not expose the application secret to make chat connect.
Video tutorials for this topic
The reference implementation is the chat-client project — a React widget embedded into a host page.
Connecting
Socket.IO, on the /chat namespace:
import io from 'socket.io-client';
const socket = io(`${appengineHost}/chat`, {
transports: ['websocket'],
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 1000,
reconnectionDelayMax: 10000,
auth: {
token,
orgId,
configId,
deviceId: getDeviceId(),
context: {
currentUrl: window.location.href,
device: /mobile/i.test(navigator.userAgent) ? 'mobile' : 'desktop',
language: navigator.language,
deviceId: getDeviceId(),
chatSessionId: existingChatSession,
},
},
});transports: ['websocket'] skips the HTTP long-polling handshake. Credentials go in auth, which Socket.IO sends on the connection handshake — not in the URL, where they would end up in proxy logs and browser history.
context.chatSessionId requests session resumption. Persist the ID returned by successful authentication, scoped to organization and identity; the server may replace an expired guest session. The guest thread is customer:{chatSessionId}:{email}, while a signed-in customer uses customer::{email}. Guest sends also need chatSessionId in their message payload.
Authenticating
Connection and authentication are separate. connect means the socket opened; the server then emits authenticate with the verdict:
socket.on('connect', () => {
// transport is up — not yet authorised
});
socket.on('authenticate', (res) => {
if (res?.success) {
onAuthenticated(socket, res); // res.chatSessionId
} else {
socket.close();
clearSession();
}
});Do not send messages on connect. Wait for a successful authenticate — anything emitted before it is unauthenticated and will be rejected.
Event vocabulary
Session and transport
| Event | Meaning |
|---|---|
authenticate | Auth verdict; carries chatSessionId |
connect_error, error | Transport or server error |
token_expired | Credential expired — re-authenticate |
session-expiring, session-expired | The conversation is ageing out |
disconnect | Socket closed; transport failures may retry, server-initiated disconnect needs explicit recovery |
account_locked | Stop the session and use the supported account recovery flow |
service_unavailable | Retryable server lookup failure, not proof of an invalid account |
Conversation
| Event | Meaning |
|---|---|
message | A complete message |
chat-stream | AI chunk, tool-use, tool-result, end or error event |
status, update | Typing and state changes |
Routing to a human
| Event | Meaning |
|---|---|
queued, queue-update | Waiting for an agent, and position |
agent-assigned, agent-changed | An agent picked the conversation up |
chat-transferred | Handed to another agent |
chat-ended | Conversation closed |
presence-change | Agent availability changed |
Proactive engagement and broadcast
| Event | Meaning |
|---|---|
engage | Server-initiated outreach |
broadcast-started, broadcast-ended | A live broadcast |
webrtc-offer, ice-candidate | WebRTC negotiation for audio/video |
The handshake is the reference client authentication path. Manual authenticate remains supported when credentials were omitted from the handshake. Other client-to-server operations include:
| Event | Body and result |
|---|---|
chat-message | {message, chatId, chatSessionId?, files?} → {success, messageId, chatId, routedTo?}; guest sends require their session ID |
list-chats | {chatSessionId?, filter?, search?} → {success, chats} |
chat-history | {chatId, chatSessionId?} → {success, history} |
join-chat | {chatId} → {success} |
shareStatus | {from, to, status: 'typing', type: 'typing'} → typing relay |
updateMessageStatus | {uid, status: 'read', from, to} → persisted message status and relay |
close-chat | {chatId, reason?, sendTranscript?, transcriptEmail?} → close result |
broadcast-join | Join the current broadcast; inspect success |
A send acknowledgement is not proof that the recipient read the message. On timeout, reload history before offering a resend; the handler does not establish a general client idempotency key. History currently contains the latest 100 persisted messages, oldest first, including files and metadata.
Streaming replies
Handle chat-stream.event before changing the UI. Append only chunk.data, show tool activity separately, stop waiting on end/error, and reconcile the terminal sk when present. The stream may use the customer's message ID, so create a separate provisional AI row rather than overwriting the question. After reconnect, merge persisted history by server message ID and retire incomplete drafts. message events and final stream data may describe the same reply.
Reconnection
Reconnection is automatic and bounded — ten attempts with a growing delay, capped at ten seconds. Two things are your responsibility:
- The current auth object is re-sent. Automatic retries do not refresh it. Update
socket.author recreate the socket with the fresh token before explicitly reconnecting. The widget re-runs guest authentication and rebuilds its socket; a signed-in host must use its own supported customer refresh flow. - Attempts are finite. After ten failures the socket stops trying. Surface that to the visitor rather than leaving a dead widget that looks live.
Embedding
The source project is private; its README package-install examples are not a verified published SDK. The global loader exposes AppmintChat.init({containerId, orgId, configId, appId, apiHost, assetBaseUrl}). configId selects the chat configuration; appId is the app credential the widget signs in as, by App ID (username) or record id. The widget signs that app in with POST /profile/app/attest {appId, platform: "web", domain} and then makes the visitor a guest with the app token; the page's website must be on the app's Allowed domains (Web: the site chat widget). A guest's history is returned only with the chat's own chatSessionId, which the widget keeps in the browser. apiHost selects REST/socket origin, while assetBaseUrl selects JavaScript/CSS assets. The loader mounts React but does not require a React host. No documented destroy API is exposed; test repeated SPA mounts and listener cleanup.
The source-only Flutter package appmint_flutter_chat speaks the same handshake but its current controller targets signed-in customers. It uses customer::{email} and does not send the guest chatSessionId on messages. Its automatic reconnect reuses auth, and history loading occurs in start(); arrange explicit refresh/recovery rather than assuming complete replay.
Other namespaces
/workspace takes staff/customer handshake {token, orgId} and emits ready, with access-checked subscribe: {workspaceId} acknowledgements using ok, not success. Workspace typing and socket read are ephemeral. Persist read progress through POST /workspace/:id/read and recover items through REST after reconnect.
/live-calls takes a staff handshake and returns a visibility-filtered calls snapshot. listen: {callSid} returns the current call and transcript lines. Its Redis transcript is capped at 400 lines and removed at call end; audio is live base64 8 kHz mu-law. whisper, takeover and hangup acknowledge accepted control, not confirmed remote execution. Takeover also requires a registered softphone.
For the full implementation and verification lesson, see AppEngine Realtime. These contracts were checked against local source on 7 October 2026; no new live delivery is claimed.
