ConvoKit DocsCurrent releases
Package documentationapp.convokit:convokit-androidLatest documented release
ConvoKit API with emoji reactions
Android SDK

Build native Kotlin chat with coroutines and Flow.

The Android SDK supports API 23+ with conversations, messages, attachments, and realtime events. Keep the ConvoKit client secret on your backend.

Publishedapp.convokit:convokit-android:0.10.0

Native Android, distributed from a public Maven feed

Add the ConvoKit repository and dependency below. No registry login or GitHub token is required. The example shows a working integration.

Add the repository

Register the unauthenticated ConvoKit feed once.

kotlin
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven("https://maven.convokit.app/")
}
}

Add the dependency

Requires Android API 23+, Kotlin 2.1+, and Java 17.

kotlin
dependencies {
implementation("app.convokit:convokit-android:0.10.0")
}

The client secret never belongs in an APK

Android receives only the public client ID and a short-lived user token from your authenticated backend. Room membership is also a backend authorization decision—not proof supplied by knowing an ID.

Configure and connect

Inject your token endpoint through TokenProvider. The SDK uses https://api.convokit.app automatically.

kotlin
val convoKit = ConvoKitClient(
clientId = "your-public-client-id",
tokenProvider = TokenProvider { appUserId ->
// Call your authenticated backend. Return only the scoped user token.
yourApi.issueConvoKitToken(appUserId).token
},
)
lifecycleScope.launch {
convoKit.connectUser(currentUser.id)
}

Server token endpoint

Keep client credentials on the server.

javascript
// app is your existing Express app.
// Supply middleware that verifies your product session and sets req.user.
// For cookie sessions, also enforce your product's CSRF protection.
import { requireProductUser } from './your-auth.js'
const clientId = process.env.CONVOKIT_CLIENT_ID
const clientSecret = process.env.CONVOKIT_CLIENT_SECRET
if (!clientId || !clientSecret) throw new Error('Configure ConvoKit server credentials')
async function callConvoKit(path, body) {
const response = await fetch('https://api.convokit.app/api/v1/' + path, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-client-id': clientId,
'x-client-secret': clientSecret,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
})
if (!response.ok) throw new Error('ConvoKit request failed')
return response.json()
}
app.post('/api/convokit/token', requireProductUser, async (req, res) => {
res.set('Cache-Control', 'no-store')
const id = req.user?.id // Trusted session identity, NEVER a request-body ID.
if (typeof id !== 'string' || !id) {
return res.status(401).json({ error: 'Sign in first' })
}
if (req.body?.appUserId !== undefined && req.body.appUserId !== id) {
return res.status(403).json({ error: 'User does not match your session' })
}
try {
await callConvoKit('user', { id, name: req.user.name })
const result = await callConvoKit('auth/token', { appUserId: id })
if (typeof result?.data?.token !== 'string' || !result.data.token) {
throw new Error('Invalid token response')
}
// The customer-facing endpoint returns { token }, not ConvoKit's envelope.
return res.json({ token: result.data.token })
} catch {
return res.status(502).json({ error: 'Chat token temporarily unavailable' })
}
})

Conversations

Create, list, rename, archive, restore, and leave rooms.

kotlin
val room = convoKit.createConversation(
CreateConversationInput(
participants = listOf(currentUser.id, teammate.id),
title = "Launch room",
description = "Release coordination",
),
)
val rooms = convoKit.getConversations(limit = 25)
val sameRoom = convoKit.getConversation(room.id)
convoKit.updateConversationTitle(room.id, "Production launch")
convoKit.archiveConversation(room.id)
convoKit.unarchiveConversation(room.id)
convoKit.leaveConversation(room.id)

Inbox previews and unread counts

  • listInbox returns an InboxPage of rooms newest activity first (latest surviving message, then creation time).
  • Each InboxEntry carries the conversation beside latestMessage, unreadCount, unreadCountCapped, your readPosition, lastReadAt and activityAt.
  • unreadCount counts messages from other users after your read position and is exact up to 1,000; a capped count is a lower bound.
  • limit defaults to 30 and must be 1..100; cursor is omitted when null.
kotlin
val page = convoKit.listInbox(limit = 30)
page.entries.forEach { entry ->
// A count (or a capped count) is a number; a marker alone is a dot, never an invented count.
val badge = when {
entry.unreadCountCapped || entry.unreadCount > 99 -> "99+"
entry.unreadCount > 0 -> entry.unreadCount.toString()
else -> null
}
val dot = entry.isUnread && entry.unreadCount == 0 && !entry.unreadCountCapped
renderRow(entry.conversation.displayTitle, entry.latestMessage?.text, badge, dot, entry.activityAt)
}
// Walk older rooms with the opaque cursor until it is null.
val older = page.nextCursor?.let { convoKit.listInbox(cursor = it) }
// Refetch on both app-wide signals; throttle the activity one.
viewModelScope.launch {
convoKit.realtime.onInboxChanged(convoKit.clientId).collect { reloadInbox() }
}
viewModelScope.launch {
convoKit.realtime.onInboxActivity(convoKit.clientId).collect { scheduleReload() }
}

Mark unread

  • markConversationUnread flags a room for the connected user only: other members, webhooks and read events never see the marker, and unreadCount is untouched.
  • InboxSummary carries isUnread (true for a count, a capped count or the marker), unreadMarkedAt and privateStateVersion; render a numberless dot when the count is 0, never an invented count.
  • Capture membership?.privateStateVersion from getConversation once per open and send it through the three-argument markConversationRead with every acknowledgement of that open, so a mark made later survives a delayed read; clearConversationUnread with ifVersion clears an empty room the same way.
  • Marker changes reach your other devices through onInboxActivity; against an older backend membership is null and the mark and clear calls fail with status 404.
kotlin
// Flag the room for the current user only; other members never see the marker.
val state = convoKit.markConversationUnread(room.id)
// state.unreadMarkedAt, state.privateStateVersion
// Capture the version once, when the room opens (null on an older backend).
val opened = convoKit.getConversation(room.id).membership?.privateStateVersion
// Every acknowledgement of that open carries it: the marker clears only while
// the version is still current, so a mark made after the open survives.
convoKit.markConversationRead(room.id, newestRendered.id, opened)
// An empty room has nothing to acknowledge: clear the marker conditionally instead.
val result = convoKit.clearConversationUnread(room.id, ifVersion = opened)
// result.cleared is false, not an error, when nothing was marked or the version moved on.

Messages

Send text and paginate room history.

kotlin
val sent = convoKit.sendMessage(
SendMessageInput(
conversationId = room.id,
text = "The release is ready.",
),
)
val history = convoKit.getMessages(room.id, limit = 20, offset = 0)
val sameMessage = convoKit.getMessage(sent.id)

Edit and delete your own messages

  • editMessage(messageId, text, revision) and deleteMessage(messageId) are the author operations: only the sender may call them, while still an active READ_WRITE member (other members' messages and a READ role fail with status 403 and HTTP_ERROR).
  • Every Message carries revision, 0 when sent and +1 on every edit by its author or by your server; isEdited (revision > 0) is the only edited signal, never updatedAt.
  • Send the row's revision with every edit: a stale one fails with status 409 and code REVISION_CONFLICT and nothing is written, so reload with getMessage, show the current text and retry with its revision.
  • A null text clears the caption of a message with attachments; attachments are never changed by an edit, and a text-only message cannot be emptied.
  • Deleting is unconditional and cannot be undone; files already received or downloaded are not retracted.
  • Both calls need the 0.8 backend: an older backend answers an uncoded 404 (HTTP_ERROR), never a deleted message.
  • revision is a trailing defaulted field of the Message data class, so named-argument literals keep compiling while copy() and componentN() changed.
kotlin
// Edit with the revision of the message as the user saw it.
try {
val edited = convoKit.editMessage(message.id, "Can you take another look?", revision = message.revision)
if (edited.isEdited) { /* render "Edited" beside the time */ }
} catch (error: ConvoKitException) {
if (error.code != "REVISION_CONFLICT") throw error
// Someone else changed it first: reload, show the current text, keep the
// draft, and retry with current.revision.
val current = convoKit.getMessage(message.id)
}
// Clear the caption of a message with attachments; the attachments stay.
convoKit.editMessage(photo.id, text = null, revision = photo.revision)
// Delete for every member; other devices learn through onMessageDeleted.
convoKit.deleteMessage(message.id)

Quoted replies and jump to a message

  • SendMessageInput.replyToMessageId quotes a message of the same room and is omitted from the request when null; every Message then carries replyToMessageId (null when the row is not a reply, and a trailing defaulted field so named-argument literals keep compiling).
  • The reference is write-once — no edit changes it — and a retry with the same clientMessageId must repeat the same target or it fails with status 409.
  • A target in another room, or one that is gone, fails with code MESSAGE_NOT_FOUND.
  • Quoted text is never copied onto the reply: getReplyPreviews(conversationId, messageIds) resolves a whole rendered page in one round trip, trimming the ids, dropping duplicates in first-seen order and splitting the distinct list into requests of 50, so you never chunk.
  • An id missing from a resolved result is the only deletion signal and is final; a failed call writes nothing and says nothing about which ids exist, so retry it on the next page.
  • getMessageContext(conversationId, messageId, olderCursor, newerCursor, limit = 30) returns one window of history, newest first, centred on a message or continued from a cursor — exactly one selector and a limit in 1..100 (default 30), both INVALID_ARGUMENT before any request.
  • Both cursors come back on every page and are null at that end of the room; a null newerCursor was only true at query time, so return to live history through the ordinary newest page.
  • Both calls need the 0.9 backend: an older backend answers an uncoded 404 (HTTP_ERROR), which is never "the message is gone" — hide the affordances instead.
  • A room you are no longer an active member of answers a 404 with code CONVERSATION_NOT_FOUND, and a cursor the backend cannot read a 400 with code INVALID_CURSOR.
  • Sending a quote to an older backend is the one silent case: the message is stored without the reference, so the quote disappears when the send is confirmed.
kotlin
// Quote a message of the same room; omit the field for an ordinary send.
val reply = convoKit.sendMessage(
SendMessageInput(
conversationId = room.id,
text = "Tuesday works for me.",
replyToMessageId = quoted.id,
),
)
// One request for the whole rendered page, never one per row. The SDK trims the
// ids, drops duplicates and splits the distinct list into requests of 50.
val quotedIds = page.mapNotNull { it.replyToMessageId }
val previews = if (quotedIds.isEmpty()) emptyList()
else convoKit.getReplyPreviews(room.id, quotedIds)
val previewById = previews.associateBy { it.id }
// An id missing from a RESOLVED result is the only "the quoted message is gone"
// signal: keep the reply and its reference, render an unavailable placeholder,
// and never ask for that id again. A failed call says nothing about the ids.
renderQuote(reply.replyToMessageId, previewById[reply.replyToMessageId])
// Open a quoted message that is older than the loaded history.
try {
val context = convoKit.getMessageContext(room.id, messageId = quoted.id, limit = 50)
showWindow(context.messages) // newest first, centred on the target
// Page back toward the newest message; null means that end of the room.
context.newerCursor?.let { cursor ->
showWindow(convoKit.getMessageContext(room.id, newerCursor = cursor).messages)
}
} catch (error: ConvoKitException) {
if (error.code != "MESSAGE_NOT_FOUND") throw error
// The quoted message was deleted: keep the reply and its reference.
}

Images and files

Upload bytes through signed storage, then attach the URL.

kotlin
val url = convoKit.uploadMessageMedia(
conversationId = room.id,
input = UploadInput(
bytes = selectedBytes,
fileName = "screenshot.png",
contentType = "image/png",
),
)
convoKit.sendMessage(
SendMessageInput(
conversationId = room.id,
text = "Attached for review",
media = listOf(ImageMedia(url = url, name = "screenshot.png")),
),
)

Realtime Flow

Collect typed streams from lifecycle-owned coroutines. An edit arrives on onMessage as an UPDATE carrying the new revision (keep the higher revision when rows meet); a deletion arrives on onMessageDeleted as the message ID.

kotlin
viewModelScope.launch {
// INSERT or UPDATE: an edit arrives as an UPDATE carrying the new
// event.message.revision, so merge by ID and keep the higher revision.
convoKit.realtime.onMessage(room.id).collect { event -> upsertMessage(event.message) }
}
viewModelScope.launch {
// Remove the ID and keep it, so a late row cannot restore the message.
convoKit.realtime.onMessageDeleted(room.id).collect { event -> removeMessage(event.id) }
}
viewModelScope.launch {
convoKit.realtime.onTyping(room.id).collect { event ->
updateTyping(event.userId, event.isTyping)
}
}
viewModelScope.launch {
convoKit.realtime.onReadReceipt(room.id).collect { event ->
updateReadState(event.userId, event.readPosition, event.readAt)
}
}
viewModelScope.launch {
convoKit.realtime.onPresence(convoKit.clientId).collect(::updatePresence)
}

Read receipts

Participants and read events carry readPosition beside the acknowledgement time. Resolve readers with readThrough instead of comparing timestamps, and keep the newest position per user from live events.

kotlin
// Durable state returned with every conversation. The position decides by
// conversation order when present; lastReadAt is the fallback without one.
val readers = room.participants.filter { participant ->
participant.appUserId != message.senderId &&
readThrough(participant.readPosition, participant.lastReadAt, message)
}
// Then merge live receipt events, keeping the newest position per user.
convoKit.realtime.onReadReceipt(room.id).collect { event ->
readAtByUserId[event.userId] = event.readAt
val incoming = event.readPosition ?: return@collect
val current = readPositionByUserId[event.userId]
if (current == null ||
compareValuesBy(incoming, current, { it.createdAt }, { it.messageId }) > 0
) {
readPositionByUserId[event.userId] = incoming
}
}

Typing, presence, and cleanup

  • Publish ephemeral state and dispose on sign out.
  • A read names the newest rendered message; a target that is no longer in the conversation fails with code MESSAGE_NOT_FOUND, so acknowledge the next newest rendered message instead.
  • Pass the privateStateVersion captured when the room opened as the third argument to also clear your own unread marker while it is still current (see Mark unread).
  • Argument checks (a negative privateStateVersion, ifVersion or revision) fail before any request with INVALID_ARGUMENT; backend codes worth branching on are MESSAGE_NOT_FOUND (404), REVISION_CONFLICT (409, editMessage) and INVALID_CURSOR (400), and responses without a JSON code carry HTTP_ERROR with the HTTP status.
kotlin
convoKit.sendTyping(room.id, isTyping = true)
// Name the newest message the user has actually seen.
convoKit.markConversationRead(room.id, throughMessageId = newestRendered.id)
convoKit.updatePresence(isOnline = true)
// On host-user sign out:
convoKit.disconnectUser()

Joining a room by ID

Joining is deliberately not an unrestricted client SDK method. Your backend validates policy and adds membership before Android loads the room. The public example includes this complete flow.

typescript
// Server: enforce your product's room policy, then add membership.
await admin.addConversationMember(roomId, {
appUserId: request.user.id,
role: 'READ_WRITE',
})
// Android: call that join endpoint before loading the room.
yourApi.joinRoom(roomId)
val room = convoKit.getConversation(roomId)

Session and users

connectUser / disconnectUser

Starts or disposes the user session and shared realtime socket.

connected / currentUserId

Reports the active app-user session.

authHeaders / lastUserToken

Exposes authenticated context for advanced REST integrations.

getUsers / getUser

Lists app users with pagination or fetches one by ID.

Conversations

getConversations / getConversation

Lists active or archived rooms in creation order and loads one authorized room. getConversation also fills your own membership (role, lastReadAt, readPosition, unreadMarkedAt, privateStateVersion); capture privateStateVersion when the room opens.

listInbox(limit = 30, cursor = null, archived = false)

Lists the inbox newest activity first with a preview, unread count and read state per entry, paged by an opaque cursor. A limit outside 1..100 fails before any request with code INVALID_ARGUMENT.

createConversation

Creates a room with participants and optional metadata.

updateConversationTitle

Changes or clears the participant-facing title.

archiveConversation / unarchiveConversation

Controls the connected user’s archived state.

leaveConversation

Removes the current user from a room.

markConversationRead(conversationId, throughMessageId, privateStateVersion)

Records the read position through the newest rendered message; the one-argument overload reads through the newest message on the server. Positions never move backward. privateStateVersion, the version captured at open, also clears your unread marker while it is still current; the one- and two-argument overloads send none and leave the marker alone.

markConversationUnread(conversationId)

Marks the room unread for the connected user only and returns a ConversationPrivateState (conversationId, unreadMarkedAt, privateStateVersion). Every call advances the version; the count is untouched.

clearConversationUnread(conversationId, ifVersion = null)

Removes your unread marker without acknowledging a message, only while it still has ifVersion when given. Returns a ClearUnreadResult whose cleared is true or false (a no-op is not an error) with the current private state.

ReadPosition.covers / readThrough

Decides whether a message is read: the position by conversation order when present, otherwise lastReadAt.

Messages and media

getMessages / getMessage

Loads paginated history or one message; every Message carries revision (0 when sent, +1 per edit by its author or your server) and isEdited, plus replyToMessageId when the row quotes another message.

sendMessage

Sends text plus image, file, location, or contact media. SendMessageInput.replyToMessageId quotes a message of the same room and is omitted from the request when null; the reference is write-once, so a retry with the same clientMessageId must repeat it, and a target that is gone or in another room fails with MESSAGE_NOT_FOUND.

editMessage(messageId, text, revision)

Author edit: replaces the text of one of the connected user’s own messages, or clears the caption of a message with attachments with a null text, and returns the updated Message (revision + 1, attachments unchanged). revision is the row’s revision as the user saw it; a stale one fails with status 409 and code REVISION_CONFLICT, so reload with getMessage and retry. Both keys are always sent; a negative revision fails before any request with INVALID_ARGUMENT.

deleteMessage(messageId)

Author delete: removes one of the connected user’s own messages for every member. Unconditional (no revision) and cannot be undone; other devices learn through realtime.onMessageDeleted. A message that is already gone fails with code MESSAGE_NOT_FOUND.

getReplyPreviews(conversationId, messageIds)

Resolves the quoted messages a rendered page points at in one round trip, never one request per row. The ids are trimmed and de-duplicated in first-seen order and the distinct list is split into requests of 50, merged in that order; an empty list, a blank id or an id over 64 characters fails before any request with INVALID_ARGUMENT. Ids that do not exist, were deleted or belong to another room are simply absent from the result — the only deletion signal — while a failed call says nothing about which ids exist.

getMessageContext(conversationId, messageId, olderCursor, newerCursor, limit = 30)

Returns one window of a room’s history as a MessageContextPage (messages newest first, olderCursor and newerCursor always present and null at that end of the room). Exactly one of messageId, olderCursor and newerCursor, and a limit in 1..100, both checked with INVALID_ARGUMENT before any request. A centred window always contains its target; an unknown, deleted or foreign messageId fails with MESSAGE_NOT_FOUND and an unreadable cursor with INVALID_CURSOR.

uploadMessageMedia

Uploads and verifies an attachment before returning its URL.

uploadUserAvatar / deleteUserAvatar

Assigns or clears an app-user avatar.

uploadConversationImage / deleteConversationImage

Assigns or clears a room image.

downloadMedia

Downloads protected media through the authenticated proxy.

Realtime state

realtime.onMessage

Returns a Flow<MessageEvent> of inserted and updated messages for one room; an edit arrives as an UPDATE carrying the new revision, so merge by ID and keep the higher revision.

realtime.onMessageDeleted

Returns a Flow<MessageDeletedEvent> with the IDs of deleted messages for one room; remove the row and keep the ID so a late response cannot restore it.

realtime.onTyping

Returns a Flow of typing state.

realtime.onReadReceipt

Returns a Flow of live read events with the reader, acknowledgement time, and read position.

realtime.onPresence

Returns a Flow of online and last-seen state.

realtime.onInboxChanged

Signals when your custom inbox should reload after membership, metadata, profile or deletion changes, including after reconnecting.

realtime.onInboxActivity

Returns a Flow<Unit> that emits after a message is sent or edited, a read position advances or your own unread marker changes anywhere in the app. Never raised on connection; throttle the reload it triggers.

realtime.connectionStatus / errors

Exposes socket status and non-fatal channel errors.

sendTyping / updatePresence

Publishes the current user’s ephemeral state.

Typed models

Public values use kotlinx-datetime and kotlinx-serialization JSON types.

AppUserID, app ID, name, image, last seen, and timestamps
ConversationMetadata and typed participants with role, lastReadAt, and readPosition; a trailing membership (your own row, null except on getConversation)
ConversationMembershiprole, lastReadAt, readPosition, unreadMarkedAt (Instant?), privateStateVersion; never part of participants or inbox entries
ReadPositionmessageId, createdAt, and covers(message); readThrough(readPosition, lastReadAt, message) applies the shared rule
MessageSender, clientMessageId, text, structured media, timestamps, and a trailing revision (0 when sent, +1 per edit; defaulted, so named-argument literals keep compiling) with the derived isEdited (revision > 0), then a trailing replyToMessageId (the quoted message when the row is a reply, null otherwise; also defaulted)
ReplyPreviewid, conversationId, senderId, text (first 500 characters, null when the quoted message has none), textTruncated, createdAt, revision, mediaCount; resolved by getReplyPreviews and never embedded in a Message
MessageContextPagemessages (newest first) plus olderCursor and newerCursor, each null when the window reached that end of the room
MessageMediaImageMedia, FileMedia, LocationMedia, and ContactMedia
InboxSummarylatestMessage (at most its first 4 media, null for an empty room), unreadCount, unreadCountCapped, readPosition, lastReadAt, activityAt, plus trailing unreadMarkedAt, privateStateVersion and isUnread (derived when omitted, so existing literals keep their badges)
ConversationPrivateState / ClearUnreadResultconversationId, unreadMarkedAt, privateStateVersion; ClearUnreadResult adds cleared
InboxEntry / InboxPageInboxEntry carries conversation (participants limited to 10) beside the summary fields and a summary accessor; InboxPage carries entries and nextCursor (null on the last page)
Realtime eventsMessageEvent (type INSERT or UPDATE, message), MessageDeletedEvent (id, conversationId), TypingEvent, ReadEvent (userId, readAt, readPosition), PresenceEvent, and connection status
ConvoKitExceptionStable code (for example MESSAGE_NOT_FOUND for a read whose target is not in the conversation or for a message the caller cannot see, REVISION_CONFLICT with status 409 for an editMessage whose revision is stale, INVALID_ARGUMENT for an inbox limit outside 1..100, a negative privateStateVersion or ifVersion, or a negative revision, all before any request, or INVALID_CURSOR with status 400 for a cursor ConvoKit did not issue), optional HTTP status, response body, and cause

Session lifecycle

Connect the user before creating subscriptions or SDK-backed UI. Your token provider must fetch fresh tokens from your authenticated backend.

On sign-out or account change, dispose the current UI controllers and subscriptions, then disconnect the client. Create a new adapter or controller after the next successful login, even when signing back in as the same user.

See authentication for the token flow and messaging behavior for read receipts, retries, timestamps, and what the SDK-backed UI handles automatically.