Composer for React
The message box for an agent app: mentions, skills, files, a model picker, the Captain swarm control, a queue for follow-ups while a turn runs, and stop. It has a typed headless core, composable styled parts, and an adapter for the Vercel AI SDK. It is safe for SSR and the App Router, and works with React 18.2 and 19.
npx shadcn@latest add https://jawadjalal.com/composer/r/composer.jsonInstall
With shadcn (any project with a components.json):
npx shadcn@latest add https://jawadjalal.com/composer/r/composer.json
That copies seven files into your components folder: captain-composer.tsx and its six captain-composer-* helpers. They are yours to edit, and they have no dependencies beyond React.
Without shadcn, copy src/ into your project. The files import each other by relative path, so they work in any folder.
The styles ship inside the component. Composer.Root renders them as a React 19 <style href precedence> tag, which React hoists into <head> once and streams correctly with SSR. On React 18, or to own the CSS, pass unstyled and import captain-composer.css together with tokens/captain-tokens.css.
Quick start
'use client';
import { CaptainComposer } from '@/components/captain-composer';
export function Box() {
return (
<CaptainComposer
onSubmit={(m) => console.log(m.text, m.mentions, m.attachments, m.model, m.captain)}
models={[{ id: 'opus', label: 'Opus 5.5' }, { id: 'sonnet', label: 'Sonnet 5.5' }]}
triggers={[
{ char: '@', items: [{ id: 'agent-1', label: 'agent-1', kind: 'agent', type: 'build' }] },
{ char: '/', items: [{ id: 'plan', label: 'plan', kind: 'skill' }], startOnly: true },
]}
/>
);
}
CaptainComposer is the default layout. For a different one, build it from the parts.
With the Vercel AI SDK
fromChat turns a useChat() result into the composer's status, onSubmit and onStop. Files go out as file parts, and the request body carries { model, captain, mentions }.
'use client';
import { useChat } from '@ai-sdk/react';
import { CaptainComposer } from '@/components/captain-composer';
import { fromChat } from '@/components/captain-composer-ai-sdk';
export function Chat() {
const chat = useChat();
return (
<>
<div role="log" aria-label="Conversation">
{chat.messages.map((m) => (
<p key={m.id}>{m.parts.map((p) => (p.type === 'text' ? p.text : '')).join('')}</p>
))}
</div>
<CaptainComposer {...fromChat(chat)} agentLabel="Captain" />
</>
);
}
// app/api/chat/route.ts
import { convertToModelMessages, createUIMessageStreamResponse, streamText, toUIMessageStream, type UIMessage } from 'ai';
export async function POST(req: Request) {
const { messages, model, captain } = (await req.json()) as { messages: UIMessage[]; model?: string; captain?: { enabled: boolean; size: number } };
const result = streamText({ model: model ?? 'anthropic/claude-sonnet-5-5', messages: await convertToModelMessages(messages) });
return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) });
}
The adapter is typed against the shape of useChat(), not the package, so it adds no dependency and keeps working across AI SDK minor versions.
examples/t3 is the whole Captain family on create-t3-app: this composer, the transcript drawing the Captain's plan, swarm and tests as blocks, and the thinking loader while a turn waits, each installed from its own registry. With MORPH_API_KEY it streams DeepSeek V4.1 Flash on Morph (first token about 0.4 s); without, it replays a recorded Morph run with its real timings.
<CaptainComposer {...fromChat(chat)} brands={[deepseek]} thinking={<Thinking size={18} />} />
Parts
Every part reads the state from Composer.Root, so put them inside it in any order. Event handlers you pass to a part (onKeyDown, onPaste, onClick, onDrop...) run first; the composer's own handler runs after, unless yours calls preventDefault().
import { Composer } from '@/components/captain-composer';
<Composer.Root onSubmit={send} status={status} onStop={stop} models={models}>
<Composer.Attachments />
<Composer.Queue />
<Composer.Input placeholder="Ask anything" />
<Composer.Menu />
<Composer.Toolbar>
<Composer.AttachButton />
<Composer.ModelPicker />
<Composer.Spacer />
<Composer.Status />
<Composer.Send />
</Composer.Toolbar>
</Composer.Root>
Composer.Root
Holds the state and renders a role="group" with a live region. It takes every option below plus any div attribute.
| Prop | Type | Default | |
|---|---|---|---|
value |
string |
Controlled text. Pair with onValueChange. |
|
defaultValue |
string |
'' |
Uncontrolled starting text. |
onValueChange |
(value: string) => void |
||
status |
'ready' | 'submitted' | 'streaming' | 'error' |
'ready' |
The same four states as useChat().status. |
onSubmit |
(m: ComposerMessage) => void | Promise<void> |
Not called for an empty message. Return a promise and later sends wait until it settles; if it rejects, the message goes back in the field. | |
onStop |
() => void |
The stop button, or Escape while a turn runs. | |
disabled |
boolean |
false |
|
disabledReason |
string |
Shown as the placeholder and read out. | |
queue |
boolean |
true |
Messages sent while a turn runs wait and go out in order. After Stop or an error they keep waiting. With false, Enter during a turn keeps the draft. |
triggers |
TriggerConfig[] |
[] |
@ mentions, / skills, any character. |
models |
ModelOption[] |
[] |
|
model / defaultModel / onModelChange |
string / string / (id) => void |
first model | Controlled or uncontrolled. |
captain / defaultCaptain / onCaptainChange |
CaptainSettings |
on, 12 agents, ask on risk, $2 | Controlled or uncontrolled. |
accept |
string |
As in <input accept>. |
|
maxFileSize |
number |
25 MB | Larger files stay, marked as errors. |
maxAttachments |
number |
||
upload |
(file: File) => Promise<{ url: string }> |
Without it files stay local. Image previews use object URLs, revoked on remove, after upload, and once a send settles. | |
agentLabel |
string |
'Agent' |
Used in announcements: "Agent is responding". |
label |
string |
'Message composer' |
The group's accessible name. |
unstyled |
boolean |
false |
Skip the built-in stylesheet. |
brands |
Brand[] |
none | The logos the model picker can show. Import only the ones you use: import { claude, openai } from '@/components/captain-composer-brands'. Each is a few hundred bytes. |
ComposerMessage is { text, mentions, attachments, model?, captain?, queued? }.
TriggerConfig is { char, items, startOnly?, limit? }. items is a list, or a function of the query that returns one, sync or async.
The other parts
| Part | Props | What it is |
|---|---|---|
Composer.Input |
maxHeight (240), placeholder, any textarea attribute |
The field. A real textarea that grows with the text; picked mentions are drawn as tokens on a layer under it, so the caret and selection stay native. |
Composer.Menu |
The @ and / list (role="listbox"), tied to the field with aria-activedescendant. |
|
Composer.Toolbar |
any div attribute |
role="toolbar". |
Composer.Spacer |
Pushes what follows to the end. | |
Composer.Footer |
any div attribute |
The band under the box, such as the repo and branch. |
Composer.Send |
any button attribute |
Send, Queue message, or Stop, by state. |
Composer.AttachButton |
any button attribute |
Opens the file picker. Files can also be pasted or dropped. |
Composer.Attachments |
className |
The files, with progress, errors and remove buttons. |
Composer.ModelPicker |
className |
A button and a listbox of models, with real brand marks. |
Composer.Captain |
sizes ([6, 12, 24, 200, 1000]), budgets ([1, 2, 5]), types |
The Captain: one agent or a swarm, size, autonomy, budget, agent types. A non-modal dialog. |
Composer.Meter |
usage: { tokens?, usd? } |
Tokens and spend. |
Composer.Status |
label, thinking |
How long the turn has run, as plain type. thinking (a loader, say) shows until the first token. |
Composer.Queue |
className |
Waiting messages, which can be edited or removed. |
CaptainComposer takes the Root props plus placeholder, usage, footer, noCaptain and thinking. It shows all 20 logos unless you pass brands.
Headless
useComposer(options) is the whole behaviour with no markup: state, keyboard, the trigger menu, files, the queue, and announcements. It returns prop getters to spread on your own elements.
import { useComposer } from '@/components/captain-composer-core';
function Bare({ onSubmit }) {
const c = useComposer({ onSubmit, triggers });
return (
<div {...c.getDropProps()}>
<textarea {...c.getInputProps({ 'aria-label': 'Message' })} />
{c.menu && (
<ul {...c.getMenuProps()}>
{c.menu.items.map((item, i) => <li key={item.id} {...c.getOptionProps(item, i)}>{item.label}</li>)}
</ul>
)}
<button {...c.getSendProps()} />
<div role="status" aria-live="polite">{c.announcement}</div>
</div>
);
}
It also returns mentions (the picked mentions in the text), sent (a count, to key a send animation), value, setValue, status, busy, model, setModel, captain, setCaptain, attachments, addFiles, removeAttachment, queue, removeQueued, editQueued, menu, pick, closeMenu, canSend, sendMode, submit, stop, say and focus. The pure helpers findTrigger, filterItems and mentionsIn are exported for tests and servers.
Theming
Every value is a --captain-* CSS variable from TOKENS.md: colour, type, space, radius, glass and motion. Light is the default. Dark applies under .dark or [data-theme="dark"], and [data-theme="system"] follows the OS. The tokens sit in :where(), so any rule of yours wins.
:root {
--captain-accent: #0a7cff;
--captain-radius: 10px;
--captain-glass: 0; /* 0 to 1: solid to frosted */
--captain-depth: .3; /* 0 to 1: flat to raised */
--captain-font: var(--font-sans);
}
With Tailwind v4, add the @theme inline block from TOKENS.md and the tokens become utilities such as bg-captain-surface and text-captain-ink-2. To follow an existing shadcn theme, point the tokens at its variables (--captain-surface: var(--background) and so on; TOKENS.md has the full set). Without Tailwind, the CSS variables are all you need.
Every ink passes WCAG AA on every surface it sits on, in both themes; TOKENS.md has the measured ratios.
Accessibility
- The field is a textarea with
aria-autocomplete="list",aria-controlsandaria-activedescendantwhile the menu is open, so focus never leaves it. - The model list is a
listbox; the Captain is adialogof radio groups (roving tabindex, arrow keys follow the reading direction in RTL) and switches. - A polite live region says "Sent. Captain is thinking.", "Captain is responding.", "Captain finished.", "Queued. 2 waiting." and "Stopped".
- Escape closes the open menu or dialog and returns focus to its button; with nothing open, it stops the running turn.
- Touch targets grow to 44px on coarse pointers. Under
prefers-reduced-motionevery duration is 0. - CI runs axe on the unit render and in Chromium, with colour contrast, in light, dark, RTL and a running turn, with each menu and the dialog open.
| Key | |
|---|---|
| Enter | Send, or queue while a turn runs |
| Shift+Enter | New line |
| Escape | Close the menu; otherwise stop the turn |
| ↑ in an empty field | Bring back the last message, with its mentions |
| Backspace after a mention | Remove the whole mention |
| ↑ ↓, Enter or Tab | Move through the menu and pick |
Size
CI measures each import with size-limit (minified and gzipped, React excluded) and fails if one grows past its budget.
| Import | gzip | Budget |
|---|---|---|
{ Composer, fromChat }: every part and the styles, with only the logos you pass |
15.0 kB | 15 kB |
CaptainComposer with all 20 logos |
22.8 kB | 24 kB |
useComposer from /core, headless |
4.1 kB | 4.5 kB |
fromChat from /ai-sdk |
0.4 kB | 1 kB |
Logos are separate exports (import { claude, openai } from '@captain/composer/brands'), so a bundle carries only the marks it names. dist ships unminified so the /* @__PURE__ */ marks survive and your bundler drops the parts you don't use.
Recipes
Controlled text (drafts saved per thread):
const [draft, setDraft] = useState(saved);
<CaptainComposer value={draft} onValueChange={setDraft} onSubmit={send} />
Async mentions (search files on the server):
triggers={[{ char: '@', items: async (q) => (await fetch(`/api/files?q=${encodeURIComponent(q)}`)).json() }]}
Uploads (to Vercel Blob or S3 before send):
upload={async (file) => {
const res = await fetch('/api/upload', { method: 'POST', body: file });
return { url: (await res.json()).url };
}}
No Captain (one model, no swarm): <CaptainComposer noCaptain />.
Disabled with a reason: <CaptainComposer disabled disabledReason="Out of credits" />.
Develop
npm ci
npm run styles # regenerate src/captain-composer-styles.ts from the CSS
npm test # vitest, with axe
npm run e2e # Playwright on the demo, with axe and contrast
npm run size # bundle budget
CI runs all of it on every pull request, builds the shadcn registry, and runs the T3 example from a clean clone.