AI chat
Chats, projects, participants and a branching message tree (or one linear list) in a canonical message format or the SDK's own parts, with runs, tool approvals, share links, a model catalog per plan and moderation events.
The ai-chat block stores the conversations of an AI assistant: chats and
projects per user and tenant (or per user alone), the people a chat is shared
with, a message tree with edits and regenerations as branches, the run that
writes each answer, tool approvals, share links, the models each plan allows
and moderation events. It doesn't call a model.
The AI SDK adapter generates the answers and stores them
here; another SDK can do the same through the same methods.
better-supabase add ai-chat # adds tenant, access and streams as well| Table | Holds |
|---|---|
ai_projects | Folders of chats with shared instructions, per owner and tenant |
ai_chats | title, model, visibility, pinned, archived_at, temporary, the leaf and the active stream |
ai_chat_participants | Who a chat is shared with: users, teams, customers and external emails, as viewers or editors |
ai_chat_links | The live link of a chat: one salt per chat, rotatable |
ai_messages | The tree: parent_id, role, author_id, parts in the message format below, native, status |
ai_runs | One row per answer: model, status, token usage, the gateway's generation id and cost, the engine |
ai_run_steps | The progress of a long run, one row per step key |
ai_harness_sessions | What a coding-agent harness keeps per chat: resume state, continue state and a lock (experimental) |
ai_sandboxes | Every sandbox or container a chat or harness started: provider, id, status, idle seconds, last use |
ai_tool_approvals | Approval requests for tool calls and the decision |
ai_tool_policies | auto, ask or deny per tool and tenant |
ai_pending_inputs | Questions a run asks the user, and the answer |
ai_message_sources | Cited sources per message |
ai_message_feedback | Thumbs up or down per message and user |
ai_chat_shares | Share links, stored as the SHA-256 of the token |
ai_model_catalog | The models the app offers, with pricing and the plans that may use each |
ai_moderation_events | Flags, redactions and blocks with their category and score |
| Permission | Lets a member | Default roles |
|---|---|---|
ai_chat.read | read the tenant's chats shared with the organization | owner, admin, member |
ai_chat.create | start chats in the tenant | owner, admin, member |
ai_chat.share | share a chat with the organization or by link | owner, admin, member |
ai_chat.moderate | read the tenant's moderation events | owner, admin |
ai_chat.manage | set tool policies, delete any chat in the tenant and read spend per user | owner, admin |
A chat is private (its owner alone), organization (every member holding
ai_chat.read) or shared (its owner, its participants, the members of
participating teams and anyone holding the live link). An organization member
who is not a participant can't read a shared chat. Assistant
messages, runs, approvals and the model catalog are written by the service
role, so a client can't forge an answer.
Server
Server code calls the ai-chat instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useAiChat } = defineDataHooks(
"aiChat",
(db: AppDb) => db.aiChat,
);const rows = await db.aiChat.list({ limit: 50 }).orThrow();"use client";
import { useAiChat } from "@/lib/supabase/hooks";
const rows = useAiChat({ limit: 50 });transport calls as the user and service as the service role. With
better-supabase/postgres, pass sqlTransport(postgres.asUser(claims)) and
sqlTransport(postgres.admin).
| Group | Methods |
|---|---|
chats | create, get, list, update, remove, shareSummaries, purge (expired temporary chats) |
projects | create, update, list, remove |
participants | add, remove, addParty, removeParty, list |
links | create, rotate, revoke, get |
messages | appendUser, saveAssistant, path, siblings, switchBranch |
runs | claim, release, stop, setCost, get, list, usageByUser, attach, steps, pendingApprovals |
sandboxes | register, touch, forChat, list, idle, finishStop, stopIdle, idleStopJob |
approvals | request, decide, list, setPolicy, policies |
inputs | open, answer |
feedback | rate |
shares | create, revoke, list, get (by token, for anyone who has it) |
models | allowed (what the tenant's plans allow), upsert |
moderation | record, list |
Every method returns a Result. Database errors are DbError values, never
exceptions.
Paging chats and projects
chats.page and projects.page page by keyset (ADR 1077), each with facets and count, and chats.get and projects.get return a not_found error for an unknown id. Chats sort by lastMessageAt (the default), createdAt and title, filter by projectId, pinned and archived, and q searches titles and message text. Projects sort by updatedAt and name, and filter by pinned and archived. chats.list and projects.list 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.
Branches
appendUser stores the user's message under the chat's leaf. Sending the
same id again is a no-op, and the same id with other parts is an edit,
stored as a sibling. With trigger: "regenerate-message" nothing is stored
and the leaf moves back, so the next answer becomes a sibling of the old
one. path(chatId) returns the active branch from the root, siblings
the alternatives at one message, and switchBranch shows another branch.
Participants
participants.add(chatId, userId, { role }) shares a chat with one person,
as a viewer (the default) or an editor. Viewers read the chat and its
messages; editors also send messages, stop a reply and switch branches. add with another role
changes it. The chat's owner (holding ai_chat.share when the chat has a
tenant) or the service role adds people. The owner removes anyone, and a
participant leaves with participants.remove(chatId, ownUserId).
await db.aiChat.participants.add(chatId, userId, { role: "editor" }).orThrow();
const people = await db.aiChat.participants.list(chatId).orThrow();In a chat with a tenant, a participant has to hold ai_chat.read there
(AI_CHAT_INVALID otherwise), and counts only while they are a member, so
removing someone from the organization also takes away the chats shared with
them. chats.list returns the chats the caller owns or takes part in. Each
user message records its writer in author_id (authorId on path).
Adding and removing someone sends participant.added and
participant.removed on the chat's topic.
Teams, customers and external people
participants.addParty({ chatId, party, role }) shares a chat with a team
({ kind: "team", teamId }), a customer ({ kind: "customer", userId }) or an
email address ({ kind: "external", email }). Adding a party to a private
chat makes it shared, and so does participants.add.
| Kind | Reads the chat through |
|---|---|
user | their own participant row |
team | membership of the team, checked when they read (the teams module's, or your own) |
customer | guest access to the chat (the guests module); the customer needs no membership |
external | the live link only; the address is stored lowercased and receives nothing from the library |
The teamMembership option names an app function (team uuid, user uuid) returns boolean that answers whether a user belongs to a team. It defaults to
the teams module's members when that module is installed. Without either,
adding a team raises AI_CHAT_INVALID.
participants.list returns the owner first, with the role owner.
chats.shareSummaries(chatIds) returns, for each chat the caller reads, its
users (owner first), the number of teams and whether it has a live link, so a
chat list shows who shares each chat in one call.
await db.aiChat.participants
.addParty({ chatId, party: { kind: "team", teamId }, role: "editor" })
.orThrow();
const [summary] = await db.aiChat.chats.shareSummaries([chatId]).orThrow();
// summary.users[0] is the ownerWithout a tenant
blocks["ai-chat"].options.tenant: false lets chats and projects live
outside a tenant, for apps where each user has their own assistant:
blocks: { "ai-chat": { options: { tenant: false } } },const chat = await db.aiChat.chats.create(null, { title: "Ideas" }).orThrow();
const projects = await db.aiChat.projects.list(null).orThrow();organization_id on ai_chats and ai_projects takes nulls, and any
signed-in user may start a chat without one. A chat without a tenant can't be
shared with an organization (AI_CHAT_NO_TENANT), but its owner can share it
by link or with participants. organizationId is undefined on such chats,
and the AI SDK adapter then skips the quota and the org: gateway tag. A
chat that names a tenant still follows the permissions above.
Modes
A chat has a free mode text, such as ask or agent. Set the modes option
on the block to restrict it to a list: the module adds a check constraint
(bsb_ai_chat_mode_check) so the database refuses any other value, and
createAiChat({ modes }) narrows the mode type of every chat, input and patch
to that list. Run bsb gen after you change the option, since modes is a
client option that the generated blocks.generated.ts carries. A mode name
starts with a lowercase letter and holds lowercase letters, digits, _ and -
(at most 100 characters).
import { createAiChat } from "better-supabase/blocks/ai-chat";
export const chat = createAiChat({
transport,
modes: ["ask", "agent", "plan"],
});
// chat.create({ organizationId, chat: { mode: "agnet" } }) is a type error.Chats created before you set modes keep a null mode, which the constraint
allows.
Message storage
blocks["ai-chat"].options.messages chooses how ai_messages is keyed and
what it stores:
| Key | Values | Default | Sets |
|---|---|---|---|
key | "text", "uuid" | "text" | The type of the message id and of every column that points at a message |
tree | true, false | true | A tree with parent_id, or one linear list per chat ordered by seq |
parts | "canonical", "native" | "canonical" | Parts in the format below, or the SDK's own parts as it sends them |
blocks: {
"ai-chat": {
options: { messages: { key: "uuid", tree: false, parts: "native" } },
},
},With key: "uuid" every message id must be a uuid, or the call fails with
AI_MESSAGE_INVALID; give the AI SDK generateId: () => crypto.randomUUID().
With tree: false an edit replaces the message and drops the ones after it,
and switchBranch fails with AI_CHAT_LINEAR. With parts: "native" the
row keeps the SDK's message as it was sent (format is native), and the AI
SDK adapter reads it back without a conversion. Pass the SDK's message as
native to appendUser and saveAssistant; the AI SDK adapter does.
The key and the storage can't change on an existing install: choose them
before the first better-supabase add ai-chat, or move the rows yourself.
Runs and streams
One answer runs at a time per chat. runs.claim(chatId, streamId) is a
compare-and-set on the chat: it fails while another stream is active,
unless that one is older than staleAfter. The writer appends to the
durable stream, so a reload resumes the answer, and
runs.release ends the run with its status and usage. runs.stop sets the
stream's cancel flag; the writer sees it on its next append.
With the usage block installed, runs.release
records the run's tokens on two meters: ai.input_tokens and
ai.output_tokens (the inputMeter and outputMeter options), once per
run, keyed by the run so a retried release counts nothing twice. With a
meters catalog on usage, only the meters it names are recorded. If the app
already meters tokens itself (meterTelemetry or usageEntries from
better-supabase/ai-sdk), set meterUsage: false so they are not counted
twice.
A run is queued, running, cancel_requested, completed, failed or
cancelled. AI tasks and workflow runs use the same names, and
FINAL_RUN_STATES from better-supabase/blocks lists the three final
ones.
Tool approvals
approvals.request stores a tool call that waits for a decision in
ai_tool_approvals, and approvals.decide records it through
decide_ai_tool_approval. The service role may always decide. Otherwise
the approval's owner, the user whose chat made the call, decides it.
Under the provider access model, the provider's
isApprover template
decides instead, with {kind} 'ai-tool', {subject} the tool's name and
{tenant} the chat's tenant. The approval's owner is then always refused
(AI_APPROVAL_NOT_FOUND), so a second person decides every call. The server side of the same check is the approverOf
runtime hook.
With the approvals
module installed, every waiting tool call also files an approval request
(subjectType ai_tool_approval, action run, the call's input in
payload), so the approvals inbox lists it. Approving or rejecting it there
decides the tool call, and decide_ai_tool_approval closes the request. The
approvers stay the ones above.
Durable runs
A run's engine is ai-sdk for an answer written inside the request and
workflow for one that runs as a workflow
(durable chat), with the engine's own run id in
external_run_id. runs on the chat client reads them:
const { runs } = createAiChat({ transport, service: serviceTransport });
const mine = await runs.list({ active: true }).orThrow();
const steps = await runs.steps.list(mine[0].id).orThrow();
const allSteps = await runs.steps
.listFor({ runIds: mine.map((run) => run.id) })
.orThrow();
const inbox = await runs.pendingApprovals().orThrow();| Method | Does |
|---|---|
get, list | The caller's runs, or one chat's (chatId), newest first |
usageByUser | Runs, tokens and cost per user across an organization (see below) |
attach | Records the engine's run id (service role) |
steps.record, steps.list | Records a step by its key (service role); the same key updates it |
steps.listFor | Steps of many runs in one call, each with its runId |
pendingApprovals | The caller's undecided approvals across chats, with each chat's title |
Members read the runs and steps of the chats they can read; only the service role writes them.
Spend per user
ai_runs is readable by its owner only, so runs.list can't total what an
organization spends. runs.usageByUser is the read that spans it. It needs
ai_chat.manage in the organization (the service role may always call it)
and fails with AI_CHAT_FORBIDDEN otherwise.
const spend = await runs
.usageByUser({
organizationId,
since: Temporal.Now.instant().subtract({ hours: 24 * 30 }),
limit: 20,
})
.orThrow();
// [{ userId, runs, failed, inputTokens, outputTokens, cachedInputTokens,
// costMicroUsd, lastRunAt }], most expensive firstsince counts runs that started at or after it and until runs that
started before it. limit defaults to 50 and is at most 500. A usage key
that is not a number counts as zero, and a run without a cost counts as 0
micro-dollars.
Harness sessions
A coding-agent harness keeps its state per chat in ai_harness_sessions
through createHarnessSessions, on the service role. The block stores the
harness's resume and continue states as JSON without reading them. lock
keeps two turns from driving one sandbox for ttlSeconds, and save with a
holder fails with AI_HARNESS_LOCKED while another holder has the lock.
Members can't read the table, not even for their own chats, because resume
state can hold harness credentials. The store is experimental: its shape
follows the harnesses as they settle.
save with a sandboxId registers the session's sandbox in
ai_sandboxes (provider harness unless sandboxProvider names one), and
sandboxId: null marks it stopped. load returns the running sandbox's id,
so a harness reads and writes sandboxId as before. The
idle-stop job stops harness sandboxes with the rest, skips one
whose session a turn holds the lock of, and marks the session stopped once
its last sandbox stopped.
Sandboxes
ai_sandboxes holds every sandbox or provider container a chat or a harness
session started, so one idle-stop job stops all of them. Register each
sandbox the app starts, and mark it used while it runs:
const { sandboxes } = createAiChat({ transport, service: serviceTransport });
const row = await sandboxes
.register(organizationId, {
provider: "vercel",
sandboxId: sandbox.id,
chatId,
})
.orThrow();
await sandboxes.touch(row.id);forChat(chatId, provider) returns the chat's running sandbox so the next
message reuses it. A sandbox started in another tenant is not reused:
register fails with the hint AI_SANDBOX_FORBIDDEN. Schedule the idle-stop
job every few minutes; it claims sandboxes that nobody used for their
idleSeconds, or that passed expiresAt, and calls your stopper:
import { vercelSandboxes } from "better-supabase/vercel-sandbox";
const vercel = vercelSandboxes({ sandboxes });
export const handlers = { ai_sandbox_idle: sandboxes.idleStopJob(vercel.stop) };Vercel Sandbox also creates, registers and resumes
one sandbox per chat with vercel.forChat. A harness sandbox reaches the
stopper with its harnessId set. A stopper
that throws leaves the sandbox running with the error on the row, and the
next run tries again.
| Option | Default | Sets |
|---|---|---|
sandboxIdleAfter | 600 | Seconds without use before the idle-stop job stops a sandbox |
Share links
shares.create(chatId) returns a token once and stores only its hash. The
link shows the branch it was made from, frozen at that message.
shares.get(token) reads it without signing in; revoke ends it.
Live link
links.create(chatId) returns { chatId, token } for a link that always shows
the chat's active branch, and makes the chat shared. The token is
<chat>.<sha256(salt || chat)>; the salt stays in ai_chat_links.
links.rotate(chatId) gives the link a new salt, so every earlier token stops
working, and links.revoke(chatId) deletes it. links.get(token) reads the
chat without signing in. It fails for an unknown, rotated or revoked token, and
when the chat is private again.
Client
The React hooks are a registry item. Install them with
npx shadcn add @better-supabase/use-ai-chat, which writes
hooks/use-ai-chat.ts into the app.
"use client";
import { useAiChats } from "@/hooks/use-ai-chat";
export function Sidebar({ organizationId }: { organizationId: string }) {
const { items, hasMore, loadMore, create } = useAiChats({ organizationId });
// ...
}| Hook | Returns |
|---|---|
useAiChats(query) | The user's chats, newest first, with loadMore, create, update, remove |
useAiChatTree(chatId) | The active branch, with switchBranch and step between siblings |
useAiModels(organizationId) | The models the tenant may use, for a model picker |
useAiShare(chatId) | The chat's share links, with create and revoke |
The list and the tree load again when the private Realtime topics
ai-chats:{userId} and ai-chat:{chatId} announce a change
(blocks["ai-chat"].options.listTopic and topic). In Server
Components the hooks throw; call the block on the server instead.
Vue
useBlockController from better-supabase/vue runs any of the block's
controllers (createAiChatsController, createAiChatTreeController,
createAiModelsController and createAiShareController) 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 { useBlockController, useSupabase } from "better-supabase/vue";
import {
createAiChat,
createAiChatsController,
rpcTransport,
} from "better-supabase/blocks/ai-chat";
const { organizationId } = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state, actions } = useBlockController(createAiChatsController, {
client: createAiChat({ transport: rpcTransport(supabase) }),
query: { organizationId },
});
</script>
<template>
<ul>
<li v-for="chat in state.items ?? []" :key="chat.id">{{ chat.title }}</li>
</ul>
<button @click="actions.loadMore()">Load more</button>
</template>Svelte
useBlockController from better-supabase/svelte runs any of the block's
controllers (createAiChatsController and the others) 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 { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createAiChat,
createAiChatsController,
rpcTransport,
} from "better-supabase/blocks/ai-chat";
let { organizationId }: { organizationId: string } = $props();
const { supabase } = betterSupabase();
const chats = useBlockController(createAiChatsController, {
client: createAiChat({ transport: rpcTransport(supabase) }),
query: { organizationId },
});
</script>
<ul>
{#each $chats.items ?? [] as chat (chat.id)}
<li>{chat.title}</li>
{/each}
</ul>
<button onclick={() => chats.actions.loadMore()}>Load more</button>Solid
useBlockController from better-supabase/solid runs any of the block's
controllers (createAiChatsController and the others) 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 { useBlockController, useSupabase } from "better-supabase/solid";
import {
createAiChat,
createAiChatsController,
rpcTransport,
} from "better-supabase/blocks/ai-chat";
export function Component(props: { organizationId: string }) {
const supabase = useSupabase();
const { state, actions } = useBlockController(createAiChatsController, {
client: createAiChat({ transport: rpcTransport(supabase) }),
query: { organizationId: props.organizationId },
});
return (
<>
<ul>
<For each={state().items ?? []}>{(chat) => <li>{chat.title}</li>}</For>
</ul>
<button onClick={() => actions.loadMore()}>Load more</button>
</>
);
}Message format
better-supabase/blocks/ai-chat defines the message format the AI blocks
store. A message has an id, a role (system, user, assistant or
tool), a list of parts and optional metadata. The format belongs to
better-supabase, not to one SDK: an adapter for the AI SDK or another SDK
converts its own messages to these parts and back, so the stored history,
search and memory work the same whichever SDK wrote them.
import {
aiMessageSchema,
type AiMessage,
} from "better-supabase/blocks/ai-chat";
const message: AiMessage = {
id: "msg_1",
role: "assistant",
parts: [
{ type: "text", text: "Here is the invoice." },
{
type: "tool-call",
toolCallId: "call_1",
toolName: "getInvoice",
input: { id: 42 },
},
],
};
const result = await aiMessageSchema["~standard"].validate(message);aiMessageSchema is a Standard Schema, so it
works anywhere a Zod or Valibot schema does. isAiMessage(value) is the
type guard. An adapter may also keep its own copy of a message in native
(the AI SDK adapter stores the UIMessage), and reads it back with
path(chatId, { native: true }).
Parts
| Type | Fields |
|---|---|
text | text, state (streaming or done) |
reasoning | text, state |
file | mediaType, url, filename |
tool-call | toolCallId, toolName, input, providerExecuted |
tool-result | toolCallId, toolName, output, isError |
tool-approval | toolCallId, approvalId, state (requested, approved or denied), reason |
source | sourceType (url or document), id, url, title, mediaType |
data | name, id, data |
step | boundary (start or finish), stepId |
Every part can carry providerMetadata, an object the adapter passes
through unchanged. Unknown fields are rejected. An SDK part with no
counterpart becomes a data part, so a conversion never drops content.
JSON Schema
The same format is published as JSON Schema 2020-12 at
https://unpkg.com/better-supabase/schemas/ai-message-v2.json
(AI_MESSAGE_SCHEMA_ID). Use it to validate messages outside TypeScript or
in a jsonb check constraint. The version is pinned as
SPEC_PINS.aiMessage; a change to the format ships as a new schema file and
a new pin, never as an edit to a published version. Version 2 adds the AI SDK 7 tool and approval fields; ai-message-v1.json stays published. See Standards.
Your own fields
Every ai-chat table takes extra columns: a column you add to a table with alter table in your own schema files is a field of the block.
| Option | Table | Write them through |
|---|
The SQL functions return a row's extra columns under fields, and so does
participants.list. A column the table already has is refused.
Columns you add to ai_chats with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createAiChat a Standard Schema
for them as fields: chats.create, chats.update take them next to the block's own keys and
validate them (a bad value is a validation error), and chats.get, chats.list return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createAiChat({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.aiChat is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createAiChat, rpcTransport } from "better-supabase/blocks/ai-chat";
export const aiChatFor = (supabase: SupabaseClient, admin: SupabaseClient) =>
createAiChat({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
});Last updated on