Inbox
A shared inbox for support conversations from an in-app widget, Slack, WhatsApp, SMS and other channels, with assignment, internal notes, read receipts, bot handoff and realtime updates.
The inbox SQL module stores inboxes per organization,
takes its contacts from the contacts block (each
conversation's contact is a person) and keeps its conversations and messages on the
messaging core: each conversation is a core
conversation of kind inbox, each message and note a core message, and the
inbox adds its own fields (status, assignee, bot mode, direction, delivery)
in inbox_conversations and inbox_message_details. createInbox from
better-supabase/blocks/inbox reads and writes them, and the React hooks
keep a list, a thread and an in-app widget current over Supabase Realtime.
The hooks are a registry item: install them with
npx shadcn add @better-supabase/use-inbox, which writes
hooks/use-inbox.ts into the app. Channel messages reach the same
tables through the Chat SDK adapters.
pnpm better-supabase add inboxThe module needs the access contract, the messaging block, the attachments block and the contacts block. With the jobs module installed, an inbound message to a bot conversation queues a bot job and an outbound message on a channel queues a delivery job; without it, nothing is queued and the app delivers the messages itself. With notifications installed, assignees and mentioned staff get a notification, and with the outbox every change emits a block event.
Permissions
Staff need a tenant permission for each action. The roles in your access contract grant them like any other permission.
| Permission | Allows |
|---|---|
inbox.read | Listing conversations, reading messages and notes, seeing a contact's reads |
inbox.reply | Sending replies and internal notes, reacting, typing pings |
inbox.assign | Assigning, changing the status, snoozing and handing off to staff |
inbox.manage | Creating inboxes and teams, members, templates and purgeContact |
Under the provider access model, an operations entry inbox.command.<name>
replaces the key for the assign, set_status, set_bot_mode and reply
commands; without one, the key above applies after the rename in
blocks.inbox.permissions.
A contact who is a signed-in user reads only their own conversations and
never sees internal notes. Inboxes with settings.widget = true let such a
visitor open a conversation; other inboxes take new conversations only from
staff and the service.
Paging conversations
conversations.page pages conversations by keyset (ADR 1077), with facets and count, and conversations.getConversation returns a not_found error for an unknown id. status is open by default (["all"] reads every status). Sorts are lastMessageAt (the default) and createdAt, inboxId, teamId, contactId, status, assignee, priority, sla, slaMinutes and tagId filter by a list of values, and q searches the subject, the preview and the contact. priority takes low, normal, high or urgent. sla takes the first response states ok, due, breached and met, judged against slaMinutes (one value, 60 by default). tagId keeps the conversations that carry any of the tags and needs the tags block. The facets are status, inboxId, priority and sla. The organization comes from organizationId or the block's tenant option. conversations.list and conversations.get keep working and are deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Paging inboxes and templates
inboxes.page and templates.page page the organization's channel accounts and message templates by keyset, each with facets and count, and inboxes.getInbox and templates.getTemplate return a not_found error for an unknown id. Both sort by name (the default) or createdAt. inboxes.page filters by channel, botMode and archived (archived inboxes are hidden unless archived is ["true"]) and searches the name and the address. templates.page filters by channel, language and inboxId and searches the name and the body. The organization comes from organizationId or the block's tenant option. Both run as the caller, so the read policy of each table decides which rows come back.
const inboxes = await inbox.inboxes
.page({ organizationId, filters: { channel: ["whatsapp"] } })
.orThrow();
const macros = await inbox.templates
.page({ organizationId, q: "follow", limit: 20 })
.orThrow();Creating the client
createInbox takes a block transport. Use the
caller's client in server actions so RLS and the permission checks apply,
and a service transport for bots and channel webhooks:
Server code calls the inbox instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useInbox } = defineDataHooks(
"inbox",
(db: AppDb) => db.inbox,
);const rows = await db.inbox.list({ limit: 50 }).orThrow();"use client";
import { useInbox } from "@/lib/supabase/hooks";
const rows = useInbox({ limit: 50 });rpcTransport(supabase) calls the same functions over the Data API when
the block schema is exposed. Every method returns a Result, so database
errors come back as a DbError instead of an exception.
Inboxes and contacts
const help = await inbox.inboxes
.create({
tenant: organizationId,
name: "Help",
channel: "widget",
botMode: "human",
settings: { widget: true },
})
.orThrow();
await inbox.inboxes.setMember(help.id, agentId, "agent").orThrow();
const contact = await contacts
.savePerson(organizationId, { name: "Ada", email: "ada@example.com" })
.orThrow();
await contacts
.addIdentity(contact.id, { channel: "whatsapp", address: "+31612345678" })
.orThrow();A conversation's contact is a person of the contacts
block, and contactId is the person's id. A person's addresses on channels
(an email address, a WhatsApp number) are its identities, and
contacts.findByIdentity finds the person behind one. When a message
arrives on a channel, conversations.open and the Chat SDK adapters find
the person by identity, user or email and create one when there is none, so
a WhatsApp number and a signed-in user with the same email end up as one
person.
inboxes.setup creates an inbox with its members and a team in one call: setup({ tenant, name, channel?, members?, team? }) creates the inbox, adds each member ({ userId, role: "agent" | "lead" }) and, with team: { name, userIds? }, creates the team and puts its users on it. The first failing step ends the setup and its error is returned. What the earlier steps created stays, so run inboxes.update or inboxes.setMember to finish it.
const { inbox, team } = await inbox.inboxes
.setup({
tenant,
name: "Support",
members: [{ userId: lead, role: "lead" }],
team: { name: "Tier 1", userIds: [lead] },
})
.orThrow();Conversations and messages
const conversation = await inbox.conversations
.open(help.id, { contact: contact.id, subject: "Billing", message: "Hi" })
.orThrow();
await inbox.messages
.send(conversation.id, { body: "How can we help?" })
.orThrow();
await inbox.messages
.note(conversation.id, "Refund approved", { mentions: [leadId] })
.orThrow();
await inbox.conversations
.assign(conversation.id, { assigneeId: agentId })
.orThrow();
await inbox.conversations.resolve(conversation.id).orThrow();| Method | Does |
|---|---|
conversations.list(tenant, filter) | Conversations by status, inbox, assignee, team, contact or search text |
conversations.get(id) | One conversation with lastReadAt for the caller and contactReadAt |
conversations.assign, setStatus, snooze, resolve, reopen | Routing and status; a contact's new message reopens a resolved conversation |
conversations.handoff(id, reason), setBotMode | Moves a bot conversation to staff and tells them |
conversations.markRead, typing, events, counts | Read state, typing pings, the conversation's history, open and unread counts |
messages.send, note, list, get, edit, remove, react | Messages and notes; remove leaves a tombstone |
messages.createUpload, confirmUpload | A file upload: an attachment row, then its id in attachments |
files.pending, stored, failed | Service only: channel files to fetch, upload and confirm |
templates.upsert, delete, page, getTemplate | Approved channel templates, such as WhatsApp's, and their keyset page |
purgeContact(contactId) | Erases a person and their conversations; returns attachment paths to delete |
A note is a message with kind: "note": staff with inbox.read read it,
and a contact never does. Each message has the core fields (mentionIds,
sentAt, editedAt, deletedAt, attachments, reactions), and a
contact's messages have no authorId; the contact is the conversation's
contactId.
messages.react needs the reactions block and
stores the reaction on the core message (subject type message), so
reactions in the inbox, in channels and on comments share custom emoji,
events and counts. Without the block it fails with the hint
INBOX_REACTIONS_MISSING.
contactReadAt is the last time the contact read the conversation, only
for staff, so a thread can show a read receipt. A message body is limited
to maxBodyLength characters (20000 by default).
Files are rows of the attachments block on the message, readable by the
staff and the contact of that conversation once the scan marks them clean.
A file a contact sends on a channel arrives as a URL; the message keeps a
pending attachment, and the chat-sdk importFiles (or your own loop over
files.pending) fetches it, uploads it and confirms it.
purgeContact deletes the person, their identities and their conversations,
and returns the { bucket, path } of each
stored file; remove them from Storage afterwards, since a SQL function
can't delete Storage objects.
Bots and outgoing messages
Each inbox and conversation has a botMode: bot, human (staff answer)
or paused (nobody answers, for example while a contact is blocked). When
a contact writes in bot mode the module queues a job on inbox_bot, and
a staff reply on a channel inbox queues one on inbox_outbound. The job
handlers in Chat SDK adapters run the bot and post the
reply on its channel. A staff reply or handoff switches the conversation
to human, so the bot stops answering.
Reply drafts
inbox.drafts keeps an unsent reply per staff member and conversation in
inbox_drafts, so a reply survives a reload or a switch to another
device. upsert replaces the caller's open draft on the conversation or
starts one; send posts it as the caller, with any last edits, and marks
it sent; discard marks it discarded.
await inbox.drafts
.upsert(conversationId, { body: "Thanks, we are on it." })
.orThrow();
const [draft] = await inbox.drafts.list(conversationId).orThrow();
const message = await inbox.drafts.send(draft.id).orThrow();The service role files an AI draft with suggest(conversationId, input, { model }). It has no author: every staff member who can reply on the
conversation sees it in list, and one of them sends or discards it, so
a model proposes a reply and a person decides. A draft holds a message
or an internal note (kind: "note"), its format, attachments, mentions
and the message it replies to.
Snooze and scheduled replies
Snooze a conversation until a time in the future, or schedule a staff reply to go out later:
const tomorrow = Temporal.Now.instant().add({ hours: 24 });
await inbox.conversations.snooze(conversation.id, tomorrow).orThrow();
const scheduled = await inbox.messages
.schedule(conversation.id, { body: "Following up as promised." }, tomorrow)
.orThrow();
await inbox.messages.reschedule(scheduled.id, tomorrow.add({ hours: 1 }));
await inbox.messages.cancelScheduled(scheduled.id);| Method | Does |
|---|---|
conversations.snooze(id, until) | Hides the conversation until until; a past time fails with 22023 |
messages.schedule(id, input, at) | A staff reply for later: messages only, no notes, at in the future |
messages.scheduled(conversationId?) | The caller's scheduled replies, soonest first |
messages.reschedule(id, at), cancelScheduled(id) | Moves or deletes the caller's scheduled reply |
publishDue(maxRows?) | Service only: sends the replies whose time came, as their authors |
wakeSnoozed() | Service only: reopens the conversations whose snooze ended |
Only the author sees a scheduled reply before it is sent, and it needs
inbox.reply. When it is due, publishDue sends it through the same path
as messages.send (deliveries, the outbound job, the bot hand-off) as the
author; a reply whose author has lost inbox.reply is dropped. Waking a
conversation sets it to open, logs unsnoozed in its events, emits
inbox_conversation.unsnoozed and notifies the assignee, or the inbox's
members while nobody is assigned (inbox.snooze_ended).
With the jobs block, snoozing and scheduling each
queue a delayed job on inbox_schedule (scheduleQueue) for the right
time: { type: "inbox.wake", conversation_id } or
{ type: "inbox.publish", scheduled_id }. A handler calls wakeSnoozed()
or publishDue() on a service client; a job left by a reschedule finds
nothing due and does nothing. Without jobs, run both from a cron;
maintain() in the Chat SDK adapters calls
them.
import "server-only";
import { jobs } from "@/lib/jobs";
import { serviceInbox } from "@/lib/inbox";
export const GET = jobs.drainRoute({
secret: process.env.CRON_SECRET,
handlers: {
inbox_schedule: async () => {
await serviceInbox.wakeSnoozed().orThrow();
await serviceInbox.publishDue().orThrow();
},
},
});Realtime
Changes broadcast without row data on private topics. A thread uses the
messaging topic messages:<conversationId>, whose pings name the message
that changed, and typing pings carry { conversationId, userId, typing }.
The lists use inbox:org:<organizationId>. useInbox reloads the list
through your server action when a broadcast arrives; useConversation and
useInboxWidget fetch only the pinged message through get and reload the
whole thread only after a reconnect.
Set blocks.inbox.options.realtimeColumns (for example ["status", "botMode"]) to add the new values of those columns, under columns, to the
conversation broadcast, and to skip updates that change none of them. New
timeline events broadcast event.created with { conversation_id, event_id, type }. conversations.setActiveStream({ conversationId, streamId }) marks
the stream that is writing a bot reply, like runs.claim in ai-chat: a
second stream is refused with INBOX_STREAM_ACTIVE, and streamId: null
releases it. Subscribers receive a stream ping.
"use client";
import { useInbox } from "@/hooks/use-inbox";
import { loadConversations } from "./inbox-actions";
export function ConversationList({
organizationId,
}: {
organizationId: string;
}) {
const { items } = useInbox({
organizationId,
load: () => loadConversations({ status: "open" }),
});
return (
<ul>
{items?.map((row) => (
<li key={row.id}>{row.subject}</li>
))}
</ul>
);
}| Hook | Returns |
|---|---|
useInbox({ organizationId, load }) | items, status, error and refresh for a conversation list |
useConversation({ conversationId, load, get }) | The messages as items, who is typing and a setTyping |
useInboxWidget({ open, send, load, get }) | An in-app widget: submit, reset and the open conversation |
useInboxWidget keeps the open conversation id under storageKey in the
client's storage port: localStorage on the web, and the store passed to
nativePorts({ storage }) on React Native (see
block controllers). Without a storage
port it forgets the conversation on reload. Throttle setTyping yourself;
a ping counts for typingMs (5000 by default).
Each hook wraps a controller from better-supabase/blocks/inbox
(createInboxController, createConversationController and
createInboxWidgetController) that a plain TypeScript UI can use directly.
Vue, Svelte and Solid run them with useBlockController from
better-supabase/vue, /svelte and /solid; see
Block controllers.
Vue
useBlockController from better-supabase/vue runs createInboxController,
createConversationController or createInboxWidgetController with its
options; auth and ports come from
app.use(betterSupabase(bsb)) unless you pass them. state is a shallow ref
of the snapshot and actions are the controller's actions. The work starts
on mount, and the controller is disposed with the component.
<script setup lang="ts">
import { createInboxController } from "better-supabase/blocks/inbox";
import { useBlockController } from "better-supabase/vue";
const { organizationId } = defineProps<{ organizationId: string }>();
const { state } = useBlockController(createInboxController, {
organizationId,
load: () => loadConversations({ status: "open" }),
});
</script>
<template>
<ul>
<li v-for="row in state.items ?? []" :key="row.id">{{ row.subject }}</li>
</ul>
</template>loadConversations stands for your server call, as in the React example.
Svelte
useBlockController from better-supabase/svelte runs any of the three
controllers with its options; auth and ports come from
setBetterSupabase(bsb) unless you pass them. It returns a readable
store of the snapshot, read with $, with the actions on .actions. The
work starts on mount, and the controller is disposed with the component.
<script lang="ts">
import { createInboxController } from "better-supabase/blocks/inbox";
import { useBlockController } from "better-supabase/svelte";
let { organizationId }: { organizationId: string } = $props();
const inbox = useBlockController(createInboxController, {
organizationId,
load: () => loadConversations({ status: "open" }),
});
</script>
<ul>
{#each $inbox.items ?? [] as row (row.id)}
<li>{row.subject}</li>
{/each}
</ul>Solid
useBlockController from better-supabase/solid runs any of the three
controllers with its options; auth and ports come from
<BetterSupabaseProvider client={bsb}> unless you pass them. state() reads
the snapshot through from, and actions are the controller's actions. The
work starts on mount, and the controller is disposed with the owner.
import { For } from "solid-js";
import { createInboxController } from "better-supabase/blocks/inbox";
import { useBlockController } from "better-supabase/solid";
export function Component(props: { organizationId: string }) {
const { state } = useBlockController(createInboxController, {
organizationId: props.organizationId,
load: () => loadConversations({ status: "open" }),
});
return (
<ul>
<For each={state().items ?? []}>{(row) => <li>{row.subject}</li>}</For>
</ul>
);
}Default data
inbox declares tenant defaults: seed_inbox_defaults creates a "Help" inbox on the in-app channel with staff answering. Call it through seed_tenant_defaults when an organization is created. It keeps an inbox that already has the name, so running it twice changes nothing. Conversation statuses (open, pending, snoozed and resolved) are a check constraint and not rows, so there is nothing to seed for them.
Block events
With the outbox installed the module emits inbox_message.received,
inbox_conversation.opened, inbox_conversation.assigned,
inbox_conversation.resolved, inbox_conversation.reopened and
inbox_conversation.unsnoozed, each with
the conversation, organization, inbox, contact, assignee and status.
Options
| Option | Default | Meaning |
|---|---|---|
blocks.inbox.options.topic | inbox | The prefix of the organization topic |
blocks.inbox.options.bucket | inbox-files | Where files from before 0.14 live, for imports |
blocks.inbox.options.maxBodyLength | 20000 | The longest message body |
blocks.inbox.options.botQueue | inbox_bot | The job queue for bot replies |
blocks.inbox.options.outboundQueue | inbox_outbound | The job queue for channel deliveries |
blocks.inbox.options.scheduleQueue | inbox_schedule | The job queue for snooze wake-ups and scheduled replies |
blocks.inbox.options.realtimeColumns | none | Conversation columns to broadcast with columns |
blocks.inbox.options.notify | true | Notifications for assignments and mentions |
Example
The Next.js example has a staff inbox at /inbox with status and assignee
filters, assignment, internal notes, read receipts and typing, and a Help
sheet in the header where a signed-in user opens a conversation with the
useInboxWidget hook. The assistant answers in the Help sheet until a
staff member replies. See apps/examples/nextjs/src/features/inbox and
Build a unibox inbox.
Hooks
createInbox takes hooks, keyed by method name, that run your code
before and after a call: refuse it with a DbError, rewrite its arguments
or observe the result (see extending blocks). Methods in a group take their hooks under the group's name,
such as hooks: { conversations: { resolve: { before } } }.
Without the client
db.inbox is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import "server-only";
import { createInbox, sqlTransport } from "better-supabase/blocks/inbox";
export const inboxFor = (claims: Record<string, unknown>) =>
createInbox({ transport: sqlTransport(postgres.asUser(claims)) });
export const serviceInbox = createInbox({
transport: sqlTransport(postgres.asService()),
});Reply and take over
conversations.reply({ conversationId, input, resolve }) sends the reply and, with resolve: true, resolves the conversation after a successful send. conversations.takeOver({ conversationId, assigneeId }) switches a bot conversation to human mode and assigns it. Both call the hooked methods, so hooks see every step.
Last updated on
Push notifications
Push tokens per device with RLS, Expo device registration, and a sender for the Expo Push API that prunes dead tokens.
Comments
Comments on any record as its conversation on the messaging core, with replies, mentions, resolved threads, pins, edit history, anchors, files and comments turned into tasks.