mirror of
https://github.com/bitbaum/chatkit.git
synced 2026-12-04 08:57:58 +01:00
* feat(field): DictationField with no state in the app — native forms and react-hook-form (0.44.0) - Uncontrolled mode: value/onValueChange optional, new defaultValue; the real text box carries name, so a native form or server action posts typed and said words, and a form reset restores defaultValue. - react-hook-form: forwardRef (ref is the text box), onChange(event) for every change including microphone/Improve/Undo/setText, onBlur(event). - Browser test drives react-hook-form itself (register, Controller, reset) and a native form; docs/roadmap.md records the remaining typing gaps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtoej4Vu1mYafzzcLc * docs(field): say the ref works across the peer React range, not a version Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtoej4Vu1mYafzzcLc --------- Co-authored-by: Claude <noreply@anthropic.com>
1385 lines
71 KiB
Markdown
1385 lines
71 KiB
Markdown
# 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";
|
||
|
||
<ChatThread
|
||
messages={messages} // { id, role, content, speaker?, citations?, failed? }
|
||
live={streaming ? { text: partial } : null}
|
||
onStop={stop}
|
||
onRetry={retryLast}
|
||
empty={<ChatStarters starters={["What can you build for me?"]} onPick={send} />}
|
||
/>
|
||
<Composer
|
||
onSend={(text, attachments) => 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={<ModelPicker />} // 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
|
||
<ChatScreen
|
||
fill="viewport" // or "parent": fill the box you give it
|
||
header={<>
|
||
<button className="ck-glass" aria-label="Chats"><IconMenu /></button>
|
||
<span style={{ flex: 1 }} />
|
||
<button className="ck-glass" aria-label="New chat"><IconPen /></button>
|
||
</>}
|
||
composer={<Composer … />} // plus an error or a queue, if you have one
|
||
footnote="Answers can be wrong."
|
||
>
|
||
<ChatThread … />
|
||
</ChatScreen>
|
||
```
|
||
|
||
`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" });
|
||
|
||
<ChatApp
|
||
name="Heidi"
|
||
store={store}
|
||
transport={async ({ text, attachments, history, signal, update }) => {
|
||
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 `<dialog>`:
|
||
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<answer>`.
|
||
`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 (`<key>: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.** `<ChatApp ref={chat}>` 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<ChatAppHandle>(null);
|
||
<ChatApp ref={chat} transport={transport} />;
|
||
<button onClick={() => chat.current?.send("Check this figure", [], { newChat: true })}>Check this</button>;
|
||
```
|
||
|
||
**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
|
||
<ChatApp transport={transport}
|
||
initialMessage={handoff ? { text: handoff.text, attachments: handoff.files } : null} />
|
||
```
|
||
|
||
**`?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
|
||
<ChatApp transport={transport} deepLinkParam="q" />
|
||
// /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" });
|
||
<ChatApp transport={transport} failureMessage={(e) => (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
|
||
<ChatApp transport={transport}
|
||
starters={["Explain this word", { text: "Grüezi mitenand", lang: "gsw" }]} />
|
||
```
|
||
|
||
**The chat list's own line.** `historySlot` sits under the search box, above
|
||
the chats; `historyEmpty` replaces "No chats yet…".
|
||
|
||
```tsx
|
||
<ChatApp transport={transport}
|
||
historySlot={signedOut && <a href="/login">Only in this browser · Sign in to keep it</a>}
|
||
historyEmpty={<p>What you ask is kept here.</p>} />
|
||
```
|
||
|
||
**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<ChatAppHandle>(null);
|
||
<ChatApp ref={chat} transport={transport} hostList onListChange={setChats} />
|
||
// in the product's sidebar:
|
||
<button onClick={() => chat.current?.openConversation(id)}>{title}</button>
|
||
```
|
||
|
||
**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
|
||
<ChatApp transport={transport}
|
||
composer={{ attachExtras: [{ id: "things", label: "Your things", onPick: openThings }],
|
||
heldAttachments: held.length }} />
|
||
```
|
||
|
||
**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
|
||
<ChatApp transport={transport}
|
||
chipsFor={() => 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
|
||
<ChatApp transport={(turn) => 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 && <button className="ck-reply" onClick={() => send("Make it shorter.")}>Shorter</button> }}
|
||
```
|
||
|
||
**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 <model>" 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<string>` 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 `<textarea>` made by hand:
|
||
|
||
```tsx
|
||
<DictationField
|
||
label="Note"
|
||
value={note}
|
||
onValueChange={setNote}
|
||
voice={{ transcribeUrl: "/api/transcribe" }} // the same server leg as Composer
|
||
improve={{ // optional: writing help
|
||
suggestions: ["Make it tighter", "Fix the grammar"],
|
||
run: async (text, instruction) => (await askYourModel(text, instruction)) ?? null,
|
||
}}
|
||
/>
|
||
<DictationField label="Title" value={title} onValueChange={setTitle} multiline={false} />
|
||
```
|
||
|
||
The microphone is `Composer`'s: Web Speech first, recording when the browser's
|
||
recogniser is silent, a take shown with its timer and kept for a retry when
|
||
transcription fails. Dictation appends to what is there. 16px text, 44px
|
||
targets, a visible label wired to the field.
|
||
|
||
`improve` is chatkit's half of writing help only: how a person asks (one tap on
|
||
a suggestion, or say or type what to change), that it is working, that it
|
||
failed — in words, with their text untouched — and **Undo** until the next edit.
|
||
Chatkit ships no model call and no prompt: `run` is yours (or
|
||
`@bitbaum/writingkit`'s `assist`). Return `null` when it could not be done.
|
||
|
||
Single-line fields (`multiline={false}`) keep the controls beside the text. Colour
|
||
and radius follow the same `--ck-*` variables as the composer. The styles are
|
||
in `styles.css` (not in the embedded `styles/chat.css`: this is not a chat
|
||
surface).
|
||
|
||
#### In a form (0.27)
|
||
|
||
A field in a form needs more than a note box: a name for the post, an error,
|
||
the keys that submit it, and a blur an inline editor can save on. All of it is
|
||
optional; without these props the field is what it was, except that a `hint`
|
||
is now linked to the field with `aria-describedby`, and Enter in Improve's
|
||
"What should change?" box applies the instruction.
|
||
|
||
```tsx
|
||
<form action="/api/listing" method="post">
|
||
<DictationField
|
||
label="Title"
|
||
name="title" // posts with the native form
|
||
multiline={false}
|
||
value={title}
|
||
onValueChange={setTitle}
|
||
error={tried && !title.trim() ? "A title is needed." : null}
|
||
hint="One line, said or typed."
|
||
onSubmit={save} // Enter here; Cmd/Ctrl+Enter in a text area
|
||
/>
|
||
</form>
|
||
```
|
||
|
||
- `name`, `autoFocus`, `readOnly` (no microphone, no Improve: nothing may
|
||
change the text), `id`, `maxLength`, `disabled`, `required`.
|
||
- `invalid` and `error`: `aria-invalid="true"`, the frame in `--ck-danger`, and
|
||
the error in words under the field (`<p class="ck-field-error" role="alert">`).
|
||
`error` implies `invalid`; an empty `error` (`""`, `0`) is no error. The error and `hint` describe the field through
|
||
`aria-describedby` (ids `<id>-error`, `<id>-hint`).
|
||
- `onSubmit`: the submit keys are the package's, so they are the same in every
|
||
app. Cmd+Enter or Ctrl+Enter in a multi-line field, Enter in a one-line one
|
||
(Shift+Enter does nothing there). Never during an IME composition, never
|
||
while disabled or read-only, never while a take is recorded or transcribed.
|
||
With `onSubmit` set, Enter in a one-line field is the package's whether it
|
||
submits or not: the browser's own form post never runs, so a form is not
|
||
sent mid-take without the words. An Enter that ends an IME composition is
|
||
left to the browser.
|
||
- `onKeyDown` runs first, on every key (Escape to cancel an inline editor);
|
||
`event.preventDefault()` there stops `onSubmit`.
|
||
- `onFocus` / `onBlur` belong to the whole field: the text box, the
|
||
microphone, Improve and its panel. Moving between them is not a blur, so
|
||
pressing the microphone does not close an inline editor that saves on blur.
|
||
Leaving while a take is recorded or transcribed is reported once the take
|
||
has ended and its words have gone through `onValueChange`, so a host that
|
||
unmounts the field on blur keeps what was said. Waiting for Improve is not
|
||
a blur either. A switch to another window or app is not a blur. A field
|
||
unmounted by the host while its blur is held reports no blur (the words
|
||
still arrive through `onValueChange`).
|
||
- `inputProps`: what the box itself may also take — `spellCheck`,
|
||
`autoComplete`, `autoCapitalize`, `inputMode`, `enterKeyHint`, `minLength`,
|
||
`aria-*`, `data-*` (`DictationFieldInputProps`). Spread before the managed
|
||
props, so the field's own id, value, class, label wiring, keys and focus
|
||
win; an `aria-describedby` there is joined with the hint and error ids.
|
||
|
||
#### With no state in the app — a native form, react-hook-form (0.45)
|
||
|
||
A form does not have to become client state to get the microphone. Leave
|
||
`value` out and the field keeps its own words, starting from `defaultValue`;
|
||
the real text box carries `name`, so a native `<form>` or a server action posts
|
||
what was typed **and** said, and a form reset puts `defaultValue` back:
|
||
|
||
```tsx
|
||
<form action={saveProfile}>
|
||
<DictationField label="About you" name="bio" defaultValue={profile.bio} />
|
||
<button>Save</button>
|
||
</form>
|
||
```
|
||
|
||
react-hook-form spreads straight onto it — `register()` and a `Controller`'s
|
||
`field` alike. `ref` reaches the text box, `name` is the box's name, and
|
||
`onChange` / `onBlur` get an event whose `target` is the box with the new words
|
||
already in it, also when the words came from the microphone, Improve, Undo or
|
||
`handleRef.setText`:
|
||
|
||
```tsx
|
||
const { register, control } = useForm({ defaultValues: { bio: "", summary: "" } });
|
||
<DictationField label="Bio" {...register("bio", { required: "A bio is needed." })}
|
||
error={errors.bio?.message} />
|
||
<Controller name="summary" control={control}
|
||
render={({ field }) => <DictationField label="Summary" multiline={false} {...field} />} />
|
||
```
|
||
|
||
- `value?` — controlled when given (as before). `defaultValue?` — the first
|
||
words of an uncontrolled field; ignored when `value` is given.
|
||
- `onValueChange?` — every change as text. `onChange?(event)` — every change as
|
||
a `DictationFieldEvent` (`type`, `target`, `currentTarget`): the real React
|
||
event for a keystroke, the same shape for the microphone, Improve, Undo,
|
||
`setText` and a form reset. Either, both or neither.
|
||
- `onBlur?(event)` — still the whole field's blur (the microphone is not a
|
||
blur); it now receives a blur-shaped `DictationFieldEvent` whose `target` is
|
||
the text box. A `() => void` handler keeps working.
|
||
- `ref` — the text box (`DictationFieldElement`), the same element as
|
||
`inputRef`. `DictationField` is a `forwardRef` component, so `ref` reaches
|
||
it on every React the peer range allows.
|
||
- Uncontrolled, something else may write the box (react-hook-form's
|
||
`reset()`, autofill); the field reads it back when focus enters it, so a
|
||
take appends to what is really there. Proven in `test/browser-field.mjs`
|
||
against react-hook-form itself (`demo/field-uncontrolled.html`).
|
||
|
||
#### With the paperclip (0.41)
|
||
|
||
`attach` gives a field the composer's paperclip. Off by default. The app owns
|
||
the staged files with `useAttachments`, reads them at its own submit and
|
||
clears them after:
|
||
|
||
```tsx
|
||
const files = useAttachments(); // same options as `attach`, if any
|
||
const add = async () => {
|
||
await createTask({ title: task, attachments: files.toWire() });
|
||
setTask("");
|
||
files.clear();
|
||
};
|
||
<DictationField
|
||
label="Add a task" multiline={false} value={task} onValueChange={setTask}
|
||
attach // or AttachOptions: limits, sources, readFile, take
|
||
attachments={files}
|
||
onSubmit={add}
|
||
/>
|
||
```
|
||
|
||
- `attach?: boolean | AttachOptions` — the paperclip, exactly as on
|
||
`Composer` (`sources`, `accept`, limits, `readFile`, `take`). Never on a
|
||
read-only field.
|
||
- `attachments?: AttachmentsController` — the staged files, held by the app
|
||
(`useAttachments(options)`): `toWire()` at submit, `clear()` after,
|
||
`attachments` to count them. Give `useAttachments` the same limits and
|
||
`readFile` as `attach`. Without it the field stages into its own, which the
|
||
app cannot read.
|
||
- A screenshot pasted into the field is staged (pasted text stays text); a
|
||
file dropped on it is a file picked; a recording picked through Files is
|
||
transcribed into the words, as in the composer.
|
||
- Labels: `attach`, `attachMenu`, `remove`, `attachNotes` — the composer's.
|
||
- `attachExtras?: readonly AttachExtra[]` (0.43) — the app's own rows in the
|
||
paperclip's sheet, as on `Composer`. With `attach` off the paperclip opens a
|
||
sheet of only these rows. Never on a read-only field.
|
||
- `handleRef?: Ref<DictationFieldHandle>` (0.43) — fill, stage, focus or
|
||
submit from outside: `setText(text)` (kept within `maxLength`),
|
||
`addFiles(files)`, `focus()`, `submit()` (runs `onSubmit` with the submit
|
||
key's checks). The same shape as `ComposerHandle`.
|
||
|
||
#### One box (0.43) — what is shared
|
||
|
||
The rule: **`Composer` sends a message in a conversation; `DictationField` is
|
||
every other place a person types.** They are two shapes of one box, not two
|
||
boxes: everything a person meets while typing is one implementation in
|
||
`src/react/typing.tsx` (internal), and the two exports only fill its slots.
|
||
|
||
- **One frame — `TypingBox`.** The voice bar, the box (a dropped file is a
|
||
file picked), the staged strip, the text, the tools row, the take's
|
||
problem in words under it. `Composer` passes its modes, `header`,
|
||
`footer`, send slot and `above`; `DictationField` its label, error,
|
||
Improve and hint. The tools row is the composer's `ck-tools` in both, so
|
||
the paperclip and the microphone are the same bare icons everywhere (until
|
||
0.42 a field drew them as bordered circles). The frame and the text share
|
||
one set of rules in `styles.css` (`.ck-field, .ck-composer` and
|
||
`.ck-field-input, .ck-input`); each shape keeps only its differences — a
|
||
form field's tighter padding and radius and its focus ring, the composer's
|
||
15rem cap on its text. The class names stay each shape's (`ck-composer…`,
|
||
`ck-field…`): apps theme them, and renaming them would break that.
|
||
- **One text hookup — `useTypingText`.** The box's words and the microphone
|
||
that adds to them: what was said joins the latest words with one space
|
||
(`appendTranscript`), within `maxLength` (`clipToMaxLength`), even when the
|
||
take ends after more typing.
|
||
- **One submit key — `submitKeyAction` (exported from
|
||
`@bitbaum/chatkit`).** A composer: Enter sends, Shift+Enter breaks the
|
||
line. A multi-line field: Cmd/Ctrl+Enter submits. A one-line field: Enter
|
||
submits, Shift/Alt+Enter is swallowed. In every box: never during an IME
|
||
composition, and never while a take is recorded or transcribed (the key is
|
||
swallowed, so nothing is sent without the words). A custom box asks it:
|
||
`submitKeyAction(event, { shape: "composer" | "multiline" | "single", busy, locked })`
|
||
→ `"submit" | "block" | "type"`.
|
||
- **The same controls on both.** The paperclip (`attach`, `AttachOptions`),
|
||
an app-owned `attachments` controller (`useAttachments`), the app's rows in
|
||
the attach sheet (`attachExtras`), and a `handleRef` (`setText`,
|
||
`addFiles`, `focus`, `submit`; `ComposerHandle` and `DictationFieldHandle`
|
||
are one type). On `Composer`, `attachments` lets the app see or stage what
|
||
the composer will send; it still goes out with `onSend` and is cleared
|
||
after. On `DictationField`, `handleRef.setText` keeps within `maxLength`
|
||
and `submit` runs `onSubmit` with the submit key's checks.
|
||
|
||
`VoiceBar`, `VoiceProblem`, `MicButton`, `AttachmentStrip`, `useDictation`
|
||
and `useAttachments` are the same pieces in both. A third box is never built:
|
||
a box that needs something neither shape does is a new slot on this one.
|
||
|
||
### Comments — `CommentThread` (0.23)
|
||
|
||
The conversation under anything: an article, a page, a listing.
|
||
|
||
```tsx
|
||
<CommentThread
|
||
comments={loaded} // oldest first; re-mount with a key to reload
|
||
viewer={user ? { name: user.name } : null}
|
||
signInHref="/sign-in?next=/articles/1" // a signed-out reader is shown the way in
|
||
canRemove={(c) => c.authorId === user?.id || user?.id === article.authorId}
|
||
transport={{
|
||
post: async (text) => (await api.post(text)), // returns the stored comment
|
||
remove: async (id) => { await api.remove(id); },
|
||
}}
|
||
voice={{ transcribeUrl: "/api/transcribe" }}
|
||
timeZone="Europe/Zurich"
|
||
/>
|
||
```
|
||
|
||
The component owns the list, the optimistic removal (rolled back, in words, if
|
||
it fails) and every failure message; the box is `Composer`, so it has the
|
||
microphone, 16px text and Enter-to-send; a refused post keeps the draft in the
|
||
box. To say why a post was refused ("Write a longer comment", a rate
|
||
limit), throw `new CommentRefused(words)` from `post` or `remove`: the thread
|
||
shows those words instead of the generic "try again", which would fail the
|
||
same way forever; any other error shows the label. A comment is shown as text, never as markup, with its line breaks. Times
|
||
render in `timeZone` (UTC by default, so the server's and the browser's markup
|
||
agree), or through your own `formatTime`.
|
||
|
||
### People talking to people — `Messenger` (0.29, 0.31)
|
||
|
||
`ChatApp` is one person and a model. `Messenger` is the other chat a product
|
||
ends up needing: a list of conversations, a thread between several people,
|
||
photos and files — and agents as members of a conversation, never mistaken
|
||
for a person.
|
||
|
||
```tsx
|
||
import { Messenger, type MessengerTransport } from "@bitbaum/chatkit/messenger";
|
||
import "@bitbaum/chatkit/styles/messenger.css"; // or styles.css, if ChatApp is on the page too
|
||
|
||
<Messenger
|
||
viewer={{ id: user.id }}
|
||
transport={transport} // your backend: three methods to start
|
||
agents={[{ id: catId, name: "Cat", mention: "@cat", hint: "Everyone here sees its answer" }]}
|
||
conversationId={id} // keep it in the URL: links and Back work
|
||
onConversationChange={setId}
|
||
composer={{ voice: { transcribeUrl: "/api/transcribe" } }}
|
||
/>;
|
||
```
|
||
|
||
Give it a box with a height (`fill="viewport"` makes it the display and keeps
|
||
the box above the phone keyboard). On a phone it is one screen at a time: the
|
||
list, then the conversation with its own way back. From 48rem of **its own**
|
||
width (a container query) the two sit side by side.
|
||
|
||
**The transport is the whole integration.** `conversations`, `messages` and
|
||
`send` are required; every other method switches a feature on by being there:
|
||
|
||
| Method | With it |
|
||
| --- | --- |
|
||
| `upload(file, about, { progress, signal })` | the paperclip: Camera · Photos · Videos · Files, a tray with progress, Try again |
|
||
| (with `upload`, and a policy that takes audio) | Voice messages: the empty box's send slot records one in place and sends it with one tap; a voice note plays in the thread (0.37) |
|
||
| `subscribe(scope, on)` | messages, read marks, typing and presence from elsewhere (`MessengerEvent`) |
|
||
| `markRead` · `typing` | ticks on the other side; "Maya is typing…" |
|
||
| `markDelivered(conversationId, at)` | the second grey tick: called when messages reach the viewer's device; report `lastDeliveredAt` on participants and push `delivered` events (0.39) |
|
||
| `edit` · `remove` | Edit and "Delete for everyone" on the viewer's own messages (long press, right click, or "…", which Tab reaches); a deleted message leaves "This message was deleted" in its place (`deletedAt`, 0.39) |
|
||
| `hide(message)` | "Delete for me" on any message (0.39) |
|
||
| `transcribe(attachment)` | "Show text" under a voice message: its words, asked for when tapped (0.44) |
|
||
| `forward(message, conversationIds)` | "Forward" on any message: choose up to five conversations; the copy is marked "Forwarded" (`forwarded`, 0.42) |
|
||
| `pin` · `mute` | "Pin" and "Mute" in a conversation's menu; pinned conversations stay at the top, a muted one's unread count is drawn quietly (`pinned`, `muted` on the conversation, 0.42) |
|
||
| `receipts(message)` · `edits(message)` | "Info": who received and read the viewer's message, and when; tapping "edited" shows what a message said before (0.39) |
|
||
| `react(message, emoji \| null)` | six emoji on every message, chips with counts, one per person (0.31) |
|
||
| `people` · `open` | "New": find people, start a conversation |
|
||
| `suggestions()` | who "New" offers before anything is typed: the viewer's agents, recent people (0.33) |
|
||
| `leave` | "Delete conversation" (for the viewer only) |
|
||
| `search(conversationId, query)` | search in the top bar: the matches, and a jump to the one tapped (0.35) |
|
||
| `conversation(id)` | a link to a conversation the list has not loaded |
|
||
| `usage()` | the storage quota checked before an upload starts |
|
||
|
||
Shapes are `@bitbaum/threadkit`'s with a face: a conversation is a `Thread`
|
||
whose participants have a `name`, a message is a `Message` (`threadId`,
|
||
`authorId`, `body`, `createdAt`, `clientId`) that may carry `attachments` with
|
||
a `url`. JSON with ISO dates goes through `reviveMessage` /
|
||
`reviveConversation`. Throw a `MessengerError("…")` when the words are meant
|
||
for the person; anything else is reported in the package's own.
|
||
|
||
What it settles, so no product decides it again:
|
||
|
||
- **An agent is never mistaken for a person.** Its face is a rounded square
|
||
(people are circles), its name carries an "Agent" mark and whom it answered
|
||
for (`onBehalfOf` → "Cat · for Georgy"), its words are in an outlined bubble
|
||
and rendered as markdown; the top bar says "Cat is here" after the person's line ("@maya · Cat is here").
|
||
A message that names an agent (`@cat`, whole word — `@catalogue` is somebody
|
||
else) shows "Cat is thinking…" until it answers, and says so if it never does.
|
||
Alone with an agent (one person, one agent: `soleAgent`) nothing has to name
|
||
it: every message is for it, the empty conversation says "Cat answers every
|
||
message here", and "Ask Cat" is not offered.
|
||
- **Whose message is whose.** The viewer's on the right. Everyone else on the
|
||
left, named as soon as more than one other voice is present. A person's
|
||
words are shown exactly as typed, with `http(s)` addresses made links;
|
||
nothing a person types is ever rendered as markup.
|
||
- **A thread that reads.** Runs of messages share one name and one time, a
|
||
line where each day begins, a "New" line where the unread begin, ticks from
|
||
threadkit's `readState` (an agent in the room does not hold a message at
|
||
unread). Where only agents could read a message, it is read once an agent's
|
||
own read mark is past it (`receiptOf`): move that mark when the agent
|
||
answers. It follows new messages only while the reader is at the end, and
|
||
loading earlier messages keeps their place.
|
||
- **A box of one row**: attach · the words · microphone · send
|
||
(`Composer layout="inline"`), growing upward with the text. Top bar and box
|
||
together are about 120px of a phone; the rest is the conversation.
|
||
- **Files that do not cost more than they must.** What may be attached is
|
||
threadkit's `checkAttachment` (an allowlist, a ceiling per kind, a quota) —
|
||
refused in words before a byte moves. Photos are shrunk in the browser
|
||
(2048px, 1.5 MB by default: `composer.attach`), a film is drawn as its still
|
||
and loads nothing until opened, bytes go wherever `transport.upload` sends
|
||
them — the package has no storage. Pictures open on the whole screen;
|
||
anything else downloads.
|
||
- **A message that did not go is kept**, marked "Not sent." with Try again
|
||
and Delete, and is never shown twice when the stored row and a pushed copy
|
||
both arrive (`clientId`).
|
||
- **Drafts survive** a visit to another conversation and a reload of the tab.
|
||
- **Reply** (0.31): every message can be answered; the answer carries one line
|
||
of the original (`replyTo`), and that line leads back to it. `send` gets
|
||
`draft.replyTo`; store its `id` and return the quote on the message.
|
||
- **Value in a conversation** (0.31): a message may carry a `card` (a payment
|
||
request, money sent, a gift), written by the app for this reader and drawn
|
||
in one shape. The app's own entries in the "+" are `actions`:
|
||
|
||
```tsx
|
||
<Messenger
|
||
actions={[{
|
||
id: "request",
|
||
label: "Request money",
|
||
amount: { unit: "CHF", confirm: "Request" }, // the package asks "how much?"
|
||
available: (c) => c.participants.length === 2,
|
||
onPick: ({ amount, note, send }) =>
|
||
send("", { kind: "request", title: "Payment request", amount: `CHF ${amount}`, note }),
|
||
}]}
|
||
/>
|
||
```
|
||
|
||
The rules are `@bitbaum/threadkit`'s: who may write, how messages merge, and
|
||
— from threadkit 0.1.2 — the attachment policy, the mention matcher and
|
||
`readState`. Those three are exported from here too (`checkAttachment`,
|
||
`DEFAULT_ATTACHMENT_POLICY`, `mentionMatcher`, `readState`), so a server
|
||
checks an upload with the same function the browser used; `src/thread-rules.ts`
|
||
says where they come from and when that copy goes.
|
||
|
||
An app with its own arrangement uses the parts: `useMessenger` (the
|
||
behaviour), `ConversationList`, `MessageThread`, `MessageAttachments`. Every
|
||
word is a label (`labels`, `DEFAULT_MESSENGER_LABELS`); the viewer's bubble is
|
||
`--ck-msgr-own` / `--ck-msgr-on-own`. `demo/messenger.html` is the reference
|
||
at 390px and 1280px, and `test/browser-messenger.mjs` drives it.
|
||
|
||
### Suggested replies
|
||
|
||
The two to four things the person is likely to say next, as buttons under the
|
||
latest answer — one tap sends it. The model writes them in the same turn, so
|
||
there is no second call and no wait:
|
||
|
||
```ts
|
||
import { REPLIES_INSTRUCTION } from "@bitbaum/chatkit";
|
||
const system = `${yourPrompt}\n\n${REPLIES_INSTRUCTION}`; // server side
|
||
```
|
||
|
||
```tsx
|
||
<ChatThread messages={messages} onReply={send} … />
|
||
```
|
||
|
||
Below 40rem the replies are one row that scrolls sideways with a fade, the
|
||
lead reply first and always on screen; wider, they wrap. The Copy · Listen ·
|
||
Share · Retry row under an answer keeps each word on one line and every button
|
||
at the 44px target (0.12.1).
|
||
|
||
That is the whole integration. `ChatThread` takes the `quick_replies` block out
|
||
of every answer (and out of a streaming one before it has finished, so nobody
|
||
watches JSON appear), and shows the buttons under the latest answer only, never
|
||
while a turn runs. Pass `replies` on a message to supply your own instead.
|
||
An app with its own thread uses `extractReplies(text)` and `<ChatReplies>`, so
|
||
the buttons look and behave the same everywhere.
|
||
|
||
The model leads. The instruction asks for replies on EVERY answer, the
|
||
recommended next step first, and the first button is drawn as the lead
|
||
(`ck-reply-lead`): on a phone the answer is read and the next move is one
|
||
tap, the way Grok does it. Only an answer that ends the conversation has no
|
||
buttons.
|
||
|
||
No heading over the buttons (0.15.1). Models like to write their own
|
||
"**Quick follow-up options**" (or "Suggested replies", "Mögliche
|
||
Rückfragen:", …) as the last line above the block; drawn over the buttons it
|
||
reads as an empty section. The instruction tells the model not to, and
|
||
`extractReplies` drops it anyway — decided by shape and position, not a word
|
||
list, so it holds in every language: the last block before the replies, a
|
||
heading or a bold/italic-only line of at most six words with no sentence
|
||
punctuation but a closing colon, plus an `---` beside it. A bold sentence
|
||
("**China holds 99 %.**") stays. While streaming (`{ streaming: true }`, which
|
||
`ChatThread` passes) such a line is held back until the next line shows what
|
||
it is, so it never flashes. `dropReplyLabel(text)` is exported for apps that
|
||
pass their own `replies`.
|
||
|
||
### Voice mode — talking with a chat
|
||
|
||
```tsx
|
||
import { VoiceMode } from "@bitbaum/chatkit/react";
|
||
|
||
<VoiceMode
|
||
open={talking}
|
||
onClose={() => setTalking(false)}
|
||
name="Day Planner"
|
||
dictation={{ transcribeUrl: "/api/transcribe" }}
|
||
onTurn={async (text) => (await send(text)).answer}
|
||
/>;
|
||
```
|
||
|
||
A spoken conversation, full screen: listening → thinking → speaking →
|
||
listening. One big button ends the person's turn (a pause ends it by itself
|
||
where the browser's own recogniser runs) and cuts in while the answer is read.
|
||
Open it from a tap. The microphone and the voice are never both open, and
|
||
neither is open once the call is over; nothing heard twice, a failed
|
||
transcription or an answer that never comes each end the call in words.
|
||
`useVoiceMode` is the loop without the screen; `voiceModeReducer` is its rules.
|
||
|
||
### Under every answer — Copy, Listen, Share
|
||
|
||
`AnswerActions` is the row under an answer, the same in every product:
|
||
|
||
```tsx
|
||
<AnswerActions text={answer} onRetry={retry} speaker={studioVoice} share={{ url }}>
|
||
<YourOwnButton />
|
||
</AnswerActions>
|
||
```
|
||
|
||
Copy copies the markdown. Listen reads the answer aloud as prose (headings,
|
||
emphasis, citations and code fences stripped — `plainTextForSpeech`) with the
|
||
browser's own voice, or with the `speaker` you pass (`{ speak(text), cancel() }`
|
||
— loki hands in its studio voice); while it reads, the row becomes a small
|
||
player: Stop and the time so far. Share opens the system share sheet with the
|
||
answer's prose (or what you pass), only where one exists. A button that does
|
||
nothing is never shown. `ChatThread` renders it under every answer; pass
|
||
`speaker` and `share` through.
|
||
|
||
### Dictation reads Android's cumulative results once (0.15.2)
|
||
|
||
Android's Chrome-family recognisers (Chrome, Brave, Samsung Internet) report
|
||
one utterance cumulatively — "why", "why exactly", "why exactly is", … — often
|
||
every one of them flagged final. The hook appended every final, so Substrata's
|
||
Ask box on Brave typed the sentence once per word (2026-10-25). The transcript
|
||
is now rebuilt from the recogniser's whole results list on every event by
|
||
`heardFromResults` (core, pure), which collapses a growing chain to its last
|
||
link. Desktop finals are untouched: two different phrases stay two, and a word
|
||
the person really repeats as separate results stays repeated. The one
|
||
limitation — "no" then "no no" as two separate results reads as one utterance
|
||
growing — is written down beside the rule. `test/dictation.test.js` holds the
|
||
fixtures; `test/browser.mjs` drives the real composer with a fake cumulative
|
||
recogniser and fails on the old hook.
|
||
|
||
### Charts in answers (0.15)
|
||
|
||
"Who produces gallium?" is answered with a ranked bar chart, not a list.
|
||
chatkit stays dependency-free: it defines the **data contract** and a
|
||
**renderer slot**; the drawing is the app's. Substrata injects
|
||
[`@bitbaum/chartkit`](https://github.com/bitbaum/chartkit), whose components
|
||
take exactly the block's fields, so a block spreads into the matching one:
|
||
|
||
```tsx
|
||
import { BarChart, LineChart, ShareBars, Timeline, StatTiles } from "@bitbaum/chartkit";
|
||
const renderers = {
|
||
chart: (b) =>
|
||
b.chart === "bars" ? <BarChart {...b} /> : b.chart === "line" ? <LineChart {...b} /> : b.chart === "share" ? <ShareBars {...b} /> : b.chart === "timeline" ? <Timeline {...b} /> : <StatTiles {...b} />,
|
||
};
|
||
<ChatScreen renderers={renderers} …> // every answer on the screen
|
||
<ChatThread renderers={renderers} …> // or one thread; Markdown and RichAnswerBlock take it too
|
||
```
|
||
|
||
Without a renderer, or when one returns `null` for a kind it does not draw,
|
||
chatkit draws the **fallback itself**: the caption and a `.ck-table` of the
|
||
data, so a chart is never a blank. A malformed block (a share of 140, a link
|
||
with a script in it) is rejected by the parser and degrades to the same table
|
||
of whatever rows were safe — the renderer never sees it. Copy and Listen read
|
||
the figures as lines.
|
||
|
||
The model writes a chart in the same fenced `chat_ui` JSON as every other
|
||
block. `RICH_ANSWERS_INSTRUCTION` now says when to draw one — ranked
|
||
quantities with 3+ rows → `bars`; shares of one whole → `share`; a quantity
|
||
over time with 3+ points → `line`; 3+ dated events → `timeline`; 2–4 headline
|
||
figures → `tiles` — that every number comes from a tool result, and that each
|
||
row's `href` is copied from the result's page or link.
|
||
|
||
The contract (`ChartBlock`, exported; limits are the parser's):
|
||
|
||
```ts
|
||
{ type: "chart", chart: "bars", caption, unit?, highlight?, rows: [{ label, value, href?, share?, note?, estimated? }] } // ≤ 24 rows
|
||
{ type: "chart", chart: "share", caption, other?, rows: [{ label, share, href? }] } // share 0–100
|
||
{ type: "chart", chart: "line", caption, unit?, series: [{ id, label, points: [{ x, y, href?, note? }] }] } // ≤ 6 series, ≤ 120 points
|
||
{ type: "chart", chart: "timeline", caption, events: [{ date, label, href?, tone?: "up" | "down" | "neutral", kind? }] } // ≤ 24 events
|
||
{ type: "chart", chart: "tiles", caption, tiles: [{ label, value, href?, note? }] } // ≤ 6 tiles
|
||
```
|
||
|
||
An `href` is a same-site path or a web URL, never anything else. The block
|
||
sits in the answer column with the stack figure's margins (`.ck-rich
|
||
.ck-chart`); `test/browser.mjs` renders one through a stub renderer and one
|
||
through the fallback at 320, 390 and 1280px, runs the broken-word scan over
|
||
them and asserts no horizontal overflow.
|
||
|
||
### Words are never cut (0.14.1)
|
||
|
||
A word may wrap onto the next line; it may never be cut in two. `.ck-md` sets
|
||
`overflow-wrap: anywhere` so a long URL cannot push the thread wider, but
|
||
`anywhere` also lowers a table cell's minimum width to one letter, and
|
||
Substrata's three-column answer at 390px read "Te / rm" and "Di / re / ct /
|
||
or / y" (2026-10-22). Tables now keep every word whole: columns share the width
|
||
by wrapping at spaces, and when even the words do not fit the table scrolls
|
||
sideways with a shadow on the edge that has more. The stack figure's tiles
|
||
wrap too: three across becomes two and one, or one under the other, rather
|
||
than cut "Manufacture".
|
||
|
||
`test/browser.mjs` measures it rather than reading the CSS: every word on the
|
||
page is laid out in a `Range` at 320, 390 and 1280px and must sit on one line
|
||
(a word beside a hyphen, slash or dot, and anything over 24 characters, is
|
||
exempt: a URL has to break somewhere). The demo thread carries the table from
|
||
the screenshot, so the check fails on the old stylesheet.
|
||
|
||
The check is exported so any product can run it against its own pages, from a
|
||
Playwright script (never from app code):
|
||
|
||
```js
|
||
import { BROKEN_WORDS_SOURCE } from "@bitbaum/chatkit/audit";
|
||
const broken = await page.evaluate(`(${BROKEN_WORDS_SOURCE})(document.body)`);
|
||
if (broken.length) throw new Error(`words cut across lines: ${broken}`);
|
||
```
|
||
|
||
### The feedback loop (0.14)
|
||
|
||
Two halves, one shape, so a bad answer is found by the product, not by the
|
||
owner tripping over it.
|
||
|
||
- **Under every answer, a thumb up and a thumb down** — pass `onFeedback` to
|
||
`ChatThread` (or `messageId` + `onFeedback` to `AnswerActions`). A thumb
|
||
down opens a sheet: one tap on why (`FEEDBACK_REASONS`: wrong, gave up
|
||
instead of looking, vague, misread, too long, hard to read, other), words
|
||
optional, then Send. The app gets `{ messageId, verdict, reason?, text? }`
|
||
and keeps it with the conversation.
|
||
- **A nightly judge.** A product exports a day of conversations as
|
||
`ChatTranscript[]` (turns with the steps the assistant took, plus the
|
||
thumbs); a reviewer asks a model, with `CHAT_REVIEW_INSTRUCTION` and
|
||
`reviewPrompt(scope, transcript)`, what the person most likely wanted, what
|
||
the product could have given with the tools it has, and what it gave, and
|
||
reads the verdicts back with `parseChatReview` (`score` 1–5, `gaps` from
|
||
`REVIEW_GAPS`: dead_end, wrong_tool, no_web, misread, vague, no_next_step…,
|
||
and one concrete `fix`). In the fleet, Loki runs the judge and files each
|
||
gap into its feedback inbox, where fixes are built.
|
||
|
||
### The next message while a turn runs
|
||
|
||
`queue` keeps Send live while `sending`, beside Stop, and the placeholder
|
||
reads "Queue a message…": the app receives the message through `onSend` as
|
||
usual and sends it on when the turn ends. Without it a send during a turn is
|
||
refused, which holds the next thought until a spinner stops.
|
||
|
||
### Recordings
|
||
|
||
With a server leg, the paperclip also takes a recording that already exists —
|
||
a voice memo from the phone's recorder, a taped meeting. It is dictation that
|
||
happened earlier: the file is posted to `transcribeUrl` under its own name
|
||
(Whisper reads the container from the extension) and the words land in the box
|
||
like a mic take, never staged as an attachment the model would have to read.
|
||
Files are recognised by type and, where a picker hands them over typeless as
|
||
Android does with `.m4a`, by extension. Uploads are capped at
|
||
`MAX_AUDIO_FILE_BYTES` (120 MB — an hour of phone memo with room to spare);
|
||
over it, the person is told in words before any bytes move. Your server leg
|
||
should compress and split long audio before Whisper; loki's does.
|
||
|
||
### Camera, Photos, Files
|
||
|
||
On a touch screen the paperclip opens a sheet with three choices — Camera,
|
||
Photos, Files — each its own file input. One input with a mixed `accept`
|
||
(`image/*,text/*,audio/*`) is what a phone answers with a chooser of capture
|
||
apps (Camera, Camera, Recorder, "Photos & Videos"), where the screenshot you
|
||
came to send is three levels down and the file browser is not offered at all.
|
||
`ATTACH_SOURCE_INPUT` is the SSOT: Camera captures, Photos opens the system
|
||
photo picker, Files asks for documents only (`FILES_ACCEPT`: PDF and text)
|
||
and opens the real document browser. It used to ask for nothing, which Brave
|
||
on Android answered with the capture chooser and no Files at all: an empty
|
||
`accept` means "anything", and anything includes the camera. A picker can
|
||
still hand over other files, so `isTextFile` and `@bitbaum/chatkit/pdf`
|
||
decide afterwards what can be read. With a mouse the
|
||
paperclip opens the file dialog directly — on a desktop all three are the
|
||
same dialog. A box that is not chatkit's composer renders `<AttachMenu
|
||
onFiles={…} />` rather than a bare `<input type="file">`. An app with more to
|
||
bring into a message than files — one of the person's own things, a note the
|
||
model reads every time — passes `extra={(close) => <YourRows />}`: the rows
|
||
sit under the three sources in the same sheet, and the sheet then opens on a
|
||
mouse too, since a file dialog cannot hold them. Labels:
|
||
`labels={{ attachMenu: { title, close, sources: { camera, photos, files } } }}`.
|
||
|
||
A messenger sends films and documents, not prompts: `sources` may name
|
||
`"videos"` (its own input, `video/*`, so no input ever mixes two families),
|
||
`attach.accept` widens what one source asks for (`MESSAGE_FILES_ACCEPT`:
|
||
office documents and archives for Files), and `attach.take` hands every
|
||
picked, pasted or dropped file to the app as it came, with nothing read into
|
||
the page — for a box whose files go to storage. A file dragged onto any
|
||
composer is a file picked.
|
||
|
||
### Picking files anywhere — `@bitbaum/chatkit/attach`
|
||
|
||
An app with no chat still has uploaders (an avatar, product photos, a receipt).
|
||
They need the same thing from a phone, so they use the same piece:
|
||
|
||
```tsx
|
||
import { AttachMenu, shrinkImage } from "@bitbaum/chatkit/attach";
|
||
|
||
<AttachMenu
|
||
sources={["camera", "photos"]} // an image uploader offers no Files
|
||
trigger="Add photo"
|
||
onFiles={(files) => upload(files)}
|
||
/>;
|
||
```
|
||
|
||
`sources` narrows the sheet (one source skips it). `shrinkImage(file, maxEdge,
|
||
maxBytes)` is the in-browser downscale the composer uses. `acceptFamilies` and
|
||
`ATTACH_SOURCE_INPUT` are the rule itself.
|
||
|
||
### PDFs — `@bitbaum/chatkit/pdf`
|
||
|
||
No model on a free chain reads a PDF file. So a PDF someone attaches is read
|
||
in the browser and handed on the way the model already understands:
|
||
|
||
```ts
|
||
import { isPdfFile, readPdf, sheetName, PDF_MAX_BYTES } from "@bitbaum/chatkit/pdf";
|
||
|
||
if (isPdfFile(file) && file.size <= PDF_MAX_BYTES) {
|
||
const r = await readPdf(file, { maxSheets: picturesLeft, assetsUrl: "/pdfjs/" });
|
||
if (r.kind === "text") attachText(file.name, r.text); // "--- page 3 ---" markers kept
|
||
else
|
||
r.sheets.forEach((s) => attachImage(sheetName(file.name, s.firstPage, s.lastPage), s.dataUrl));
|
||
// r.pagesShown < r.pageCount → tell the person which pages went
|
||
}
|
||
```
|
||
|
||
- **A PDF with a text layer** (Word, Docs, a typed report) comes back as text.
|
||
- **A PDF without one** (slides exported as pictures, a scan) comes back as
|
||
pictures of its pages, **four to a sheet** at 784px a page — slide text stays
|
||
legible, and a 20-page deck is 5 pictures. Send them to a model that sees.
|
||
- pdf.js loads only on the first PDF (its own entry point and a dynamic
|
||
import), and the legacy build is used so older iPhones read PDFs too.
|
||
|
||
**One step per app**: pdf.js fetches its worker and image decoders by URL at
|
||
runtime, which no bundler follows. Copy them as the first step of `dev` and
|
||
`build` (pnpm does not run `prebuild` hooks by default):
|
||
|
||
```json
|
||
"build": "chatkit-copy-pdf-assets public/pdfjs && next build"
|
||
```
|
||
|
||
and pass `assetsUrl: "/pdfjs/"`. Keep that folder out of git. Served
|
||
from the app's own origin they pass a strict CSP, and they include the
|
||
decoders without which pages whose pictures are JPEG 2000 — macOS's "reduce
|
||
file size" export — draw blank. `test/browser-pdf.mjs` checks both
|
||
kinds in Chromium; `node test/browser-pdf.mjs your.pdf` prints what any PDF
|
||
turns into.
|
||
|
||
**Attaching a PDF through the composer or `ChatApp`**: the box reads images and
|
||
text itself and refuses everything else. Give it your own reader and a PDF
|
||
picked under Files, pasted, dropped or handed to `ChatAppHandle.send` goes
|
||
through it too:
|
||
|
||
```tsx
|
||
<ChatApp
|
||
composer={{
|
||
attach: {
|
||
maxFiles: 5,
|
||
readFile: async (file, { images, room, progress }) => {
|
||
if (!isPdfFile(file)) return undefined; // chatkit reads everything else
|
||
progress(`Reading "${file.name}"…`);
|
||
const r = await readPdf(file, { maxSheets: Math.min(room, 5 - images), assetsUrl: "/pdfjs/" });
|
||
return r.kind === "text"
|
||
? { attachments: [{ kind: "text", name: file.name, content: r.text }] }
|
||
: {
|
||
attachments: r.sheets.map((s) => ({
|
||
kind: "image",
|
||
name: sheetName(file.name, s.firstPage, s.lastPage),
|
||
mimeType: "image/jpeg",
|
||
dataBase64: s.dataUrl.split(",")[1],
|
||
previewUrl: s.dataUrl, // the thumbnail in the box
|
||
})),
|
||
note: r.pagesShown < r.pageCount ? `Pages 1–${r.pagesShown} of ${r.pageCount}.` : undefined,
|
||
};
|
||
},
|
||
},
|
||
}}
|
||
/>
|
||
```
|
||
|
||
`readFile(file, ctx)` returns the attachments to stage (one file may become
|
||
several), a `note` the person reads under the box, or `undefined` to leave the
|
||
file to chatkit. `ctx` has `limits`, `notes`, `images` (already staged), `room`
|
||
(how many more fit) and `progress(text)` for a slow read. Files are read one at
|
||
a time, so `images` and `room` already count the file before. A thrown error
|
||
becomes "Could not read …"; a note with no attachments keeps the draft and
|
||
shows the reason. The same option is `readAttachmentFiles` for code that reads
|
||
files outside the box.
|
||
|
||
### The check every app runs in CI
|
||
|
||
```sh
|
||
pnpm exec chatkit-check-file-inputs # src app components
|
||
```
|
||
|
||
Fails on any file input whose literal `accept` mixes families (image + text,
|
||
audio + text…) — the exact shape that hid screenshots on Android. One input per
|
||
family, or `AttachMenu`. A real exception carries
|
||
`// chatkit-allow-mixed-accept: <reason>` on the line or the line above.
|
||
|
||
### Screenshots
|
||
|
||
`attach` takes limits: `attach={{ maxImageEdge: 1024 }}` shrinks a picture in
|
||
the browser to 1024px on its longest edge and re-encodes it as JPEG before it
|
||
is staged, stepping quality down until it fits `maxImageBytes`. A phone
|
||
screenshot (~1290×2796, several MB) goes out at a few hundred KB: cheaper for
|
||
whoever pays for the vision model, and the full-resolution screenshot never
|
||
leaves the device. Off by default (`0`).
|
||
|
||
Every reason a file did not attach is a label — `labels={{ attachNotes: {
|
||
imageTooLarge: (name, mb) => … } }}` — so it reaches the reader in their
|
||
language.
|
||
|
||
### The look of an answer
|
||
|
||
`Markdown` renders what a model writes, never as HTML: paragraphs, headings
|
||
with their level, bullet, numbered, nested and task lists, tables (they scroll
|
||
sideways on a phone instead of breaking the page), rules, bold, italic, code,
|
||
links, web images and `[F1]` citation handles. Three things make an answer
|
||
read like the ChatGPT app's rather than a wall of text, and a model does all
|
||
three unprompted:
|
||
|
||
- **A list of named things becomes cards.** `1. **Option.** why` — every item
|
||
opening with a bold lead — renders as a badge (the number, or the emoji the
|
||
lead opens with: `**🤖 Robot.** …`), the name, and the body under it.
|
||
- **A table is a table**, with the header row kept.
|
||
- **Sources are listed once**, under the answer, from the handles the text
|
||
cites and the `citations` map you pass (`{ F1: { label, detail, href? } }`).
|
||
On a mouse they are a row of chips; on a touch screen ONE "Sources · n"
|
||
button opens a sheet with every record — label, detail, link — because a
|
||
row of chips on a phone was a row of cut-off words. `renderCitation`
|
||
replaces the in-text superscript with your own; `renderSources` replaces
|
||
the row with your own; `sources={false}` drops it. `SourcesRow` and `Sheet`
|
||
are exported for an app that lists sources from elsewhere.
|
||
|
||
**0.13 — answers that read like the ChatGPT app's**, measured against it
|
||
screen by screen on a phone:
|
||
|
||
- **Headings are signposts**: a size up, with air above them, so a long
|
||
answer can be scanned and found again.
|
||
- **Options are cards**: a numbered list whose items open with a bold name
|
||
gets a tile badge, the name a size up, a hairline between cards, and a pill
|
||
for a short tag written right after the name — `1. **Federated.**
|
||
[Recommended] …`. The instruction asks the model to mark the one it
|
||
recommends exactly that way.
|
||
- **Sources are chips**: a `[F2, F1]` handle is drawn after the sentence as
|
||
"Fleet AGENTS.md +1", linked when the record has a link, and moved after
|
||
the full stop when the model wrote it before. `renderCitation` still
|
||
replaces it.
|
||
- **Links that leave the site say so**: a dotted underline and a small arrow.
|
||
- **A layered figure** — `{"type":"stack", …}` — for an architecture, a
|
||
pipeline or layers of responsibility: full-width boxes top to bottom, a row
|
||
of tiles where a layer has parts (with an icon from a closed list), the
|
||
words that cross each arrow, an accent tone for the layer that matters, and
|
||
a caption that says what the figure claims. `diagram` stays for an
|
||
arbitrary graph.
|
||
- **"Thought for 3m 38s ›"** above an answer, from `message.thinking`
|
||
(`{ durationMs?, steps?: [{ label, detail? }], summary? }`), closed by
|
||
default; while a turn runs, `live.steps` shows the same row open with the
|
||
newest step marked. `ThinkingRow` is exported for an app's own thread.
|
||
|
||
`demo/screen.html` shows all of it.
|
||
|
||
### Look
|
||
|
||
Every colour, radius and face is a `--ck-*` variable. They default to
|
||
[`@bitbaum/design-tokens`](https://github.com/bitbaum/design-tokens), so
|
||
OrangeCat, Loki, Solon and bitbaum match with no work. Any other app sets
|
||
`--ck-*` on the chat's container and keeps its own look. What you cannot
|
||
change is the behaviour — that is the point.
|
||
|
||
### Language
|
||
|
||
Every visible word is a label: `labels={{ send: "Senden", dictation: {...} }}`
|
||
on `Composer`, `labels` on `ChatThread`.
|
||
|
||
## The standard (what this package guarantees)
|
||
|
||
1. A microphone in the composer, with the server fallback above — and the
|
||
same server leg for a recording picked as a file.
|
||
2. 16px text in the input and the messages (below that iOS zooms the page).
|
||
3. A composer that belongs to the conversation: auto-growing textarea, Enter
|
||
sends, Shift+Enter breaks the line, IME composition respected, 44px targets,
|
||
usable above the phone keyboard (`useViewportHeight`).
|
||
4. Stop in the send slot while a turn is in flight.
|
||
5. A failed turn shows as a failure with Retry — never silence.
|
||
6. Scroll follows new tokens only while the reader is at the bottom, with a
|
||
jump-down button otherwise.
|
||
7. Markdown rendered, never as HTML; `javascript:` links stay text; Copy on
|
||
every answer.
|
||
8. Starters in the empty state; suggested replies under the latest answer;
|
||
the speaker's name on every answer once more than one agent speaks.
|
||
9. Nothing overflows at 320–390px.
|
||
10. In `ChatScreen`, the conversation fills the display and opens at the
|
||
latest message, with its end above the composer, not behind it.
|
||
11. In `ChatApp`, the same app everywhere: one chat list with one row
|
||
anatomy, New chat, Temporary chat that writes nothing, the open chat
|
||
back after a reload, attachments on, a queue behind a running answer.
|
||
|
||
12. Any other text box is `DictationField`: the same microphone, 16px text and
|
||
44px targets as the composer, the same paperclip when asked (`attach`),
|
||
and an optional Improve with Undo. In a form
|
||
it takes a name, an error said in words, the same submit keys in every app
|
||
and a blur that belongs to the whole field.
|
||
13. A conversation under an item is `CommentThread`: oldest first, the same box
|
||
with the microphone, remove your own, a way to sign in for a reader who
|
||
cannot yet write.
|
||
14. People talking to people is `Messenger`: the box at the bottom of the
|
||
screen with nothing empty under it, an agent told from a person by shape,
|
||
mark and bubble, one bubble per message however many times it arrives, a
|
||
failed message kept with Try again, files checked before they upload.
|
||
|
||
`pnpm run verify` proves all of it: unit and render tests, then
|
||
`test/browser.mjs` drives Chromium through the demo at desktop and 390px, light
|
||
and dark, and speaks into a fake microphone past a silent recogniser, and
|
||
`test/browser-messenger.mjs` does the same for the Messenger.
|
||
|
||
## Improving it — here, never in your app
|
||
|
||
When a chat in any product has a bug or is missing something, **fix it in this
|
||
repo**, add the check that would have caught it, bump the version, and let the
|
||
products pick the release up. A local patch in one app is how the fleet got 13
|
||
different chats. If your app needs something truly its own, it goes in a slot
|
||
(`tools`, `header`, `footer`, `renderFooter`, `renderLink`) — ask for a new slot
|
||
here rather than forking the component.
|
||
|
||
Release: bump `version` in `package.json` and merge. The merge publishes it
|
||
(`publish.yml` runs on main, skips a version already on npm, and tags the
|
||
commit `v<version>`). No manual tag.
|
||
|
||
## Develop
|
||
|
||
```sh
|
||
pnpm install
|
||
pnpm run demo # builds demo/dist; open demo/index.html
|
||
pnpm run verify # everything CI runs
|
||
```
|
||
|
||
MIT © Cato
|
||
|
||
### Visual answers (0.11)
|
||
|
||
Append `RICH_ANSWERS_INSTRUCTION` from `@bitbaum/chatkit` to a conversational
|
||
system prompt, alongside `REPLIES_INSTRUCTION`. The model can place fenced
|
||
`chat_ui` JSON blocks inline in its answer: galleries with captions and a
|
||
full-size image sheet, dependency diagrams, recommendation callouts, and
|
||
single-choice follow-ups. Markdown tables and step lists remain available.
|
||
`Markdown` renders these automatically; pass `onReply={send}` for choice forms.
|
||
`ChatThread` wires that callback only on the latest answer and disables it
|
||
while another turn is running. Historical forms remain readable.
|
||
|
||
Products keep their own model routing, tools, evidence rules, auth and `--ck-*`
|
||
tokens. For a JSON-output assistant such as Heidi, ask for rich blocks only
|
||
inside its free-text explanation string, never outside the answer envelope.
|
||
Images must come from supplied context or tool results. No HTML or executable
|
||
SVG is accepted. Images suppress referrers and broken thumbnails retain their
|
||
text labels. Blocks are bounded and validated; incomplete/invalid blocks are
|
||
hidden, so always include the takeaway in ordinary prose too. Diagram edges
|
||
retain their direction and labels, including branches and cycles.
|
||
|
||
Release this package before updating consumer lockfiles to `^0.11.0`.
|
||
Run `pnpm run verify`; `demo/index.html` is the visual reference in light/dark
|
||
and at phone width. The diagram and gallery artwork in the demo is a fixture.
|
||
|
||
### Audio in answers
|
||
|
||
A validated `chat_ui` block can attach a real audio asset:
|
||
|
||
```json
|
||
{"type":"audio","title":"Morning sketch","src":"/provided.wav","creator":"Studio","caption":"An original instrumental draft"}
|
||
```
|
||
|
||
The native player waits for explicit playback and does not preload the file.
|
||
Only attach URLs supplied by a person or a completed tool. Generation and
|
||
catalogue access belong to the app's media tools: this renderer does not
|
||
create a song or grant rights to redistribute it. Copy and speech preserve the
|
||
track's title, creator and caption. The demo WAV is an original synthesized
|
||
fixture; it is not a commercial track or a model-generated recording.
|
||
|
||
The browser word-layout audit uses Unicode word boundaries. Chinese, Japanese and Korean may wrap between characters; those legal breaks are accepted while squeezed Latin words, including words embedded in CJK text, are still reported. Whole-page and chart overflow checks remain separate.
|
||
|
||
### Scrolling in a page or panel
|
||
|
||
`ChatThread` detects whether its own panel, an ancestor, or the page scrolls.
|
||
Upward touch, wheel and keyboard gestures pause automatic following immediately,
|
||
including close to the bottom. Status updates and incoming assistant turns keep
|
||
the reading position. Sending a new user turn or choosing return-to-latest
|
||
resumes following. Full-screen `ChatScreen` keeps its bounded scroll containment;
|
||
embedded threads allow gestures to reach their surrounding page.
|
||
|
||
When the page itself scrolls (a short thread in a card mid-page), following
|
||
only ever moves the page down, to bring a new turn into view; it never pulls
|
||
the page up and takes the composer under the thread off the screen. The jump
|
||
button may go either way. Set `--ck-follow-gap` (a length, default 0) on the
|
||
thread or any ancestor to keep room under the latest turn for what you put
|
||
below it, e.g. `--ck-follow-gap: 10rem` for a composer and a receipt. While
|
||
the reader has sent nothing, the page does not move at all.
|