# chatkit **One chat for every bitbaum product.** A composer with a microphone that never goes dead, a thread that does not fight the reader, answers with Copy and Retry, and LLM markdown — the fleet's chat standard as a package, so a fix made once reaches every product. Why it exists: on 2026-09-25 there were 13 chats in 10 repos, each written from scratch, each missing something another had already fixed — most often the microphone. The person using them found every gap by hand. This package is the one place those fixes now live. (Model calls, streaming and transcription stay in [`ai-kit`](https://github.com/bitbaum/ai-kit), server-side; chatkit is the interface that calls them.) ## Install ```sh pnpm add @bitbaum/chatkit ``` **Install releases from npm, never a commit or a branch.** A semver range is what lets a fix reach every product: Renovate/Dependabot opens the bump PR in each app when a release ships. A pinned commit or tag silently freezes the app on whatever it pinned — heidi and substrata kept the broken Android paperclip for days after the fix merged, because one pinned `v0.2.0` and npm had only `0.2.1`. ## Use ```tsx import { ChatStarters, ChatThread, Composer } from "@bitbaum/chatkit/react"; import "@bitbaum/chatkit/styles.css"; } /> send(text, attachments)} // return false to keep the draft placeholder="Ask about any project…" sending={streaming} onStop={stop} voice={{ transcribeUrl: "/api/transcribe" }} attach // only if your API accepts attachments tools={} // app-specific controls go in slots heldAttachments={refs.length} // attachments the APP keeps (shown in `header`) attachmentOnlyText="See attached" // so a message of only those can still send /> ``` For an embedded composer/thread that does not render `ChatApp`, use `@bitbaum/chatkit/styles/chat.css` in place of `styles.css`. It contains the same shared composer, thread, reply, attachment and message styles while omitting the full-screen app's conversation rail and drawer. The narrower stylesheet is generated from `styles.css` during the package build, so shared chat styles have one source and do not drift. ### The whole screen — `ChatScreen` A chat page is the conversation, edge to edge and top to bottom, as in the ChatGPT and Claude apps. The header and the composer float OVER it instead of each taking a strip of the screen: words scroll under both and fade as they pass, the header's buttons are frosted pills (`ck-glass`), and the composer is a see-through pill. The last line of an answer always rests above the composer — the scroller is padded by the measured height of each. ```tsx } composer={} // plus an error or a queue, if you have one footnote="Answers can be wrong." > ``` `fill="viewport"` follows the VISUAL viewport, so the composer rides above the phone keyboard. An app with its own thread pads its scroller with the two measured heights: `padding-block: var(--ck-top-inset) var(--ck-bottom-inset)`. The reading column is `--ck-measure` (48rem) wide with `--ck-gutter` (1rem) to the edge; the page behind it is `--ck-page`. `demo/screen.html` is the reference: look at it at 390px before changing any of this. ### The whole app — `ChatApp` `ChatScreen`, `Composer` and `ChatThread` are the pieces. Until 0.18 every product built the app around them itself — the chat list, New chat, Temporary chat, titles, rename and delete, what a reload reopens — and each did it a little differently (`docs/fleet-chat-matrix.md` has the table). `ChatApp` is that app, once: what a person sees in the Claude or ChatGPT phone app, set by this package and changed only through props. ```tsx import { ChatApp } from "@bitbaum/chatkit/react"; import { httpConversationStore, localConversationStore } from "@bitbaum/chatkit"; const store = signedIn ? httpConversationStore({ baseUrl: "/api/conversations" }) : localConversationStore({ key: "heidi-chat" }); { const answer = await streamFromMyApi({ text, attachments, history, signal, onText: (t) => update({ text: t }) }); return answer; // a string, or { content, replies?, citations?, thinking? } }} composer={{ voice: { transcribeUrl: "/api/transcribe" } }} starters={["Explain this word", "Translate a message"]} />; ``` What it owns, so no product writes it again: - **The header**: frosted pills — Chats (a phone; from `railQuery`, default 64rem, the list is a rail beside the chat instead) · the chat's title · New chat · "…" with Temporary chat, Share this chat (with `onShare`), Rename and Delete. `headerStart` / `headerEnd` take the product's own controls (a model picker, a back link). - **The chat list**: a full-height drawer on a phone (a native ``: Escape, the focus trap and focus restore come from the browser; it opens on its close button, never on the search box, so no keyboard jumps up), a rail on a wide screen. New chat, a search box (every word, accents ignored — or your `search`, e.g. searchkit), Today / Yesterday / Earlier, and rows with ONE anatomy: title, date (or "Answering…"), one "…" that opens Rename · Delete as two equal cells; Delete asks once, in the row. An empty list and a failed load each say so, the second with Try again. - **New chat and Temporary chat.** A temporary chat is never written to the store and ends when it is left; the transport gets `temporary: true` and `conversationId: null`, so a server that persists turns itself knows not to. - **Titles**: the first message names a chat (`deriveTitle`, Heidi's rule); `makeTitle({ text, answer })` renames it after the first answer if you have something better. - **Reload**: the open chat comes back (`rememberKey`, device storage — never a temporary one), unless it was deleted elsewhere. A product that keeps the chat in its URL passes `conversationId` and `onConversationChange` instead. - **Turns**: one per conversation, and a turn keeps running when the person opens another chat (its row says "Answering…"). Stop keeps what had arrived. A failed turn shows Retry. A message sent while an answer runs is queued above the composer, with its own ×, and goes when the answer lands. - **The composer**: attachments ON (Camera · Photos · Files, thumbnails above the text, each with its ×, shown in the sent turn too), the microphone, suggested replies, and the screen's visual-viewport sizing (`fill`). **The transport** is the product's one job: `(turn) => Promise`. `turn` is `{ conversationId, temporary, text, attachments, history, signal, update }`; call `update({ text, status, steps })` as the answer streams (the whole text each time); throw for a failed turn. **The store** is an adapter — six methods, `ConversationStore`: `list() · get(id) · create({ title }) · append(id, message) · rename(id, title) · remove(id)`. Two come with the package: - `localConversationStore({ key })` — the device. Versioned (`:v1`), one key per chat; never throws: storage that is missing, blocked (private mode) or full degrades to memory for the page, and a full quota drops the OLDEST chats first. Pictures are kept by name, not bytes. - `httpConversationStore({ baseUrl })` — the product's server, over Heidi's shape: `GET {base}` → `{ conversations }`, `POST {base}` → `{ conversation }`, `GET {base}/{id}` → `{ conversation, messages }` (404 = gone), `POST {base}/{id}/messages` `{ message }`, `PATCH {base}/{id}` `{ title }`, `DELETE {base}/{id}`. `serverWritesTurns: true` when the product's chat route already stores each turn, so nothing is written twice. Signed out on the device, signed in on the server: pass the store for who is there. `copyConversations(local, server)` moves the device's chats into the account on sign-in. `demo/app.html` is the reference — look at it at 390px and 1440px. `test/browser-app.mjs` drives it at both widths: send, the drawer (focus in and back out), New chat, a temporary chat that leaves no row, a reload that reopens the chat, a picture staged above the text and removed, delete, the queue and Stop — and checks for sideways scroll, 44px targets and cut words at every step. #### What a product adds to it (0.19) The first four products to adopt ChatApp (Heidi, OrangeCat, Solon, Substrata) each listed what it could not do. These close those gaps; every one is optional, and 0.18 code keeps working unchanged. **Send from the page — the handle.** `` gives `ChatAppHandle`: `send(text, attachments?, { newChat?, chips? })`, `fill(text, files?)`, `focus()`, `newChat()`, `openConversation(id)`. `send` behaves exactly like the composer's Send (queued behind a running answer, a chat created when none is open); `File`s are read like the paperclip's, and if one cannot be attached nothing is sent — the words and files go into the box with the reason. Never click `.ck-send` from outside. ```tsx const chat = useRef(null); ; ; ``` **A message the page arrives with.** `initialMessage` is sent once, in a new chat, after the list has loaded (StrictMode's double mount sends it once). `send: false` only fills the box. Clear it from your URL or state yourself. ```tsx ``` **`?q=` links.** `deepLinkParam="q"` reads the parameter into a new chat's box and takes it off the address. A link never sends for someone: only with `deepLinkAutoSend` too. ```tsx // /chat?q=How%20do%20invoices%20expire → the box says it; the person sends. ``` **Why a turn failed, per turn.** Throw `ChatTurnError(message, { kind })` from the transport: that bubble shows `message` and keeps `failure.kind` (for a footer to link the fix). Two failures in one chat keep their own words. Any other error shows the `failed` label, never its raw message — unless `failureMessage(error)` maps it. ```tsx import { ChatTurnError } from "@bitbaum/chatkit/react"; if (res.status === 503) throw new ChatTurnError("The model is not set up here.", { kind: "not-configured" }); (navigator.onLine ? null : "You are offline.")} />; ``` **Retry sends the pictures again.** The files of a failed turn stay with it until its answer lands; Retry re-sends the words and the files. Nothing to configure. **Stop and the half answer.** Stop keeps what had arrived (as the apps do). `stopKeepsPartial={false}` drops it for every turn; a transport decides per turn with `turn.stopKeepsPartial(keep)` — `false` while the text is unchecked. ```tsx transport={async (turn) => { turn.stopKeepsPartial(false); // the gate has not checked this text yet /* … stream … */ turn.stopKeepsPartial(true); return answer; }} ``` **Starters with a language.** A starter is `string | { label, prompt?, lang? } | { text, label?, lang? }`; `lang` goes on the button. ```tsx ``` **The chat list's own line.** `historySlot` sits under the search box, above the chats; `historyEmpty` replaces "No chats yet…". ```tsx Only in this browser · Sign in to keep it} historyEmpty={

What you ask is kept here.

} /> ``` **The product draws the list.** A product whose own sidebar already lists bots, people or rooms can put each one's chats there, in one lane, instead of a second column beside it. `hostList` drops the rail, the drawer and the Chats button; `onListChange` hands over the rows, the load state, the open chat and the chats with a turn running; the handle opens and starts chats. ```tsx const chat = useRef(null); // in the product's sidebar: ``` **Product rows in the attach sheet.** `composer.attachExtras` — `{ id, label, detail?, icon?, onPick }[]` — are rows under Camera · Photos · Files, one anatomy (icon, label, second line), in the same sheet. With `attach: false` the paperclip opens a sheet of only these rows. (`AttachMenu rows` takes the same list.) ```tsx ``` **The product's things on the sent message.** `chipsFor({ text, attachments })` returns `MessageChip[]` (`{ label, href?, kind? }`) shown on the person's message the moment it is sent, and kept with it (`ChatMessageData.chips`). `send(…, { chips })` does the same from the handle. ```tsx held.map((r) => ({ label: r.title, href: r.url }))} /> ``` **A temporary chat ended.** `onTemporaryEnd(chatId)` fires once when a temporary chat is left (New chat, another chat, Temporary off), the page is hidden, or ChatApp unmounts. `turn.chatId` is the same id, so a server row kept for the chat can be keyed by it and deleted here. ```tsx myApi.send({ ...turn, hiddenRowKey: turn.chatId })} onTemporaryEnd={(chatId) => myApi.deleteHiddenRow(chatId)} /> ``` **Footers that know the latest answer, and can send.** `thread.renderFooter(m, { isLatest, index, send, fill })`: put "what next" only under the latest, and let a chip whose label differs from its sentence send in one tap. ```tsx thread={{ renderFooter: (m, { isLatest, send }) => isLatest && }} ``` **After the last turn.** `thread.after` is drawn inside the thread, after the last turn (a pending action, a picker), not over the composer. `demo/app.html?lab=1` is the page these are checked on: StrictMode around ChatApp, the handle on `window.ckChat`. `test/browser-app.mjs` drives it at 390px and 1440px. #### Moving a product onto ChatApp Per product, from the matrix: what goes, what stays. What stays is always the same two things — the transport and the words. **Workarounds 0.19 makes deletable** (each was written in an adoption PR because ChatApp 0.18 could not do it — bitbaum/heidi#226, bitbaum/orangecat#1447, bitbaum/solon#309, bitbaum/substrata#262): - **Substrata** — `lib/chat/drive-composer.ts` (types into the composer and presses Send) goes: `components/portal/chat/useAutoAsk.ts` and `lib/chat/handoff.ts` hand their words and pictures to `initialMessage` (or `ref.send(text, files, { newChat: true })`), and `/chat?q=` becomes `deepLinkParam="q"`. Retry now re-sends the pictures. - **OrangeCat** — in `src/components/ai-chat/ModernChatPanel/index.tsx`, the bridge that sets the composer value and clicks `button.ck-send` goes (`?q=` and `askCat` → the handle), and so does the ephemeral-row cleanup hung on the empty state mounting and `onConversationChange` (→ `onTemporaryEnd`, keyed by `turn.chatId` in `hooks/useCatTransport.ts`). "Your things" moves from a second button into the sheet (`composer.attachExtras`), its staged refs show on the sent bubble (`chipsFor`), `CatAnswerFooter` shows the create links and upgrade nudge only under `isLatest`, and pending actions move from `composer.above` to `thread.after`. `TurnFailure` reads the turn's own `failure.kind` (throw `ChatTurnError`). - **Heidi** — in `app/[locale]/_components/chat/workspace.tsx`, the latest-failure state passed as `thread.labels.failed` goes (throw `ChatTurnError` from `chat-app.ts`'s transport mapping), and so does `turn.update({ text: "" })` before a throw on Stop (→ `turn.stopKeepsPartial(false)` until the variety gate has checked the text). The move and learn chips and the word pick send in one tap again through `renderFooter`'s `send`; the dialect starter gets `lang`; the signed-out "Sign in to keep it" line moves from `startersTitle` to `historySlot`. - **Solon** — nothing to delete. The per-answer "Answered by " fits `thread.renderFooter` (it existed in 0.18; it now also gets `isLatest`). ChatApp's own words still come only in English: pass `labels`. - **Loki** — goes: `ThreadRail.tsx`, the history half of `WorkspaceDrawers.tsx` and `WorkspaceChrome.tsx`, `ThreadTitle.tsx`, `hooks/use-temporary-chat.ts`, `hooks/use-new-chat.ts`, `hooks/use-send-queue.ts` + `QueuedMessages.tsx`, the history-pin storage. Stays: `use-loki-stream` as the transport (its `ephemeral` flag from `turn.temporary`), `ModelPicker` and the project chip in `composer.tools`, the dispatch and handoff cards in `thread.renderFooter`, `httpConversationStore({ baseUrl: "/api/conversations", serverWritesTurns: true })`, `?c=` through `conversationId`. Not in ChatApp yet, so ask for it here first: pinned chats, the "needs me first" line and by-project view, hands-free voice conversation. - **OrangeCat** — goes: `ConversationRail.tsx`, `hooks/useConversations.ts` (incl. its temporary chat), `hooks/useChatHistory.ts`, the header row of `ChatHeader.tsx`. Stays: the Cat's stream as the transport, `ComposerAddMenu` (the person's own things) in `composer.tools` with `heldAttachments`, tool chips and pending actions in `thread.renderFooter`, the quota meter in `headerEnd`. Its conversation routes are not the REST shape above: a six-method store over `API_ROUTES.CAT`, or align the routes. Gains: reopening the chat after a reload, rename, search. - **Heidi** — goes: `conversation-list.tsx`, `new-chat-button.tsx`, the header and drawer state in `workspace.tsx`, the storage half of `use-conversation.ts`, the signed-out draft restore (`use-draft`) → `localConversationStore`. Stays: `transports.ts` (its `Transport` maps onto this one: `onText` → `update`, a `status: "error"` result → a throw), the composer labels and picture limits, the answer view and word pick in `thread.renderFooter`, the model sheet in `headerEnd`. Store: `httpConversationStore({ baseUrl: "/api/conversations", serverWritesTurns: true })` signed in. Gains: a temporary chat. - **Substrata** — goes: the `ChatScreen` + `Composer` + `ChatThread` assembly in `ResearchChat.tsx`, `lib/ask-thread.ts` (the tab handoff → `conversationId` + the device store). Stays: `useChatSession` as the transport, `AskTools` / `ComposerBeside` in `composer.tools` and `footnote`, `chartRenderers`, `AnswerFooter`. Decide: attachments are ON in ChatApp; `/api/chat` takes no files today, so either keep `composer={{ attach: false }}` or accept pictures there. - **Diplodoctor** — goes: the assembly in `app/[locale]/ask/page.tsx`. Stays: the redacting `ask()` as the transport, the labels. Gains: a chat list and reload. Needs: a transcription route (voice is off today) and an API that takes files before `attach` is turned on. - **Causius** — stays as it is for now. A matter is a case with documents, participants and steps, not a chat; its list is the matters page. `ChatThread` + `IntakeComposer` remain the right pieces. - **evig** — goes: the header and Clear in `HirnChat.tsx` and `HirnChatPanel.tsx`. Stays: `/api/hirn/chat` as the transport, the action cards in `thread.renderFooter`, `useChatLabels`. Store: the Hirn history route is per session, not the REST shape — a six-method store, or the device store for the panel. - **Solon** — goes: the header, "New conversation" and the React-state history in `governance-chat.tsx` and `law-chat.tsx`. Stays: the SSE read as the transport, the starters, `renderLink`. Gains: chats that survive a reload (the footnote promises "stays in this tab" and today nothing does). Signed out keeps its own "Sign in to ask Solon" screen instead of ChatApp. ### The microphone `voice` is on by default. Give it a server leg so it works everywhere: - `transcribeUrl`: an endpoint taking `multipart/form-data` `{ audio, locale }` and answering `{ text }` — implement it with `ai-kit`'s `transcribe()`. - or `transcribe: (audio, locale) => Promise` for a custom call. With a server leg, a press **records until the person presses done**, and the server transcribes (one model everywhere, language detected by the model). That is the default since 0.22.0 and every product gets it without a prop: the browser's own recogniser ends the take at the first pause on Android, so a person who stopped to think lost the rest of the sentence, and the same microphone behaved differently from one product to the next. Without a server leg, or with `prefer: "browser"`, the browser's recogniser listens (free, instant). Where it is missing, **or accepts `start()` and then says nothing** — Chromium without Google's speech service does exactly that — the same press records and the server transcribes. The dead recogniser is remembered for 30 days so the next press records immediately. Every failure is shown in words (blocked mic, nothing heard, not available), never as a button that does nothing. `rememberKey: null` stores nothing on the device. ### Which box — `Composer` or `DictationField` One way a person types, everywhere in the fleet. Two exports, one rule: - **`Composer`** — a box that **sends a message in a conversation** (a chat, a messenger, a comment box). - **`DictationField`** — **every other place a person types**: forms, quick-add lines ("Add a task"), titles, notes, a bio. Both carry the same microphone and, when asked (`attach`), the same paperclip: the same Camera · Photos · Files sheet, the same paste-to-attach and drop, the same staged previews with Remove, the same limits and notes, the same app-owned `attachments`, `attachExtras` and `handleRef`, the same submit-key rule. Since 0.43 the whole box lives once (`src/react/typing.tsx`, see "One box" below), so the two cannot drift. Never build a third. ### Any other text box — `DictationField` (0.23) A text box that is not a conversation — a note, a title, a bio, a message to a seller — is still a place a person would rather speak than type. Every such box is this component, not a `