Composer
The input box for agent apps. One Captain switch turns one agent into a swarm: the agents deal out of the switch into a tray, with the count and the model they run on. Mentions, skills, files and a model picker, and Send becomes Stop while it works.
npx shadcn@latest add https://uimaxxer.com/r/composer.jsonPasskeysFix the duplicate Stripe charge
Checkout charges twice when Stripe retries. Find out why.
Captain
The webhook handler keys on the request, not the Stripe event, so a retry looks new. I can move it onto the job queue and dedupe on event.id.
- stripe-webhook-504s.log13 KB
"use client";
// uimaxxer · Composer, MIT. Idea: one Captain switch, inside the input box, turns one agent into a swarm of N. Delight: flip it and the agents deal out of the switch's thumb into a tray above it, the count and the cost climbing as each one lands.
import { animate, AnimatePresence, motion, useMotionValue, usePresence, useReducedMotion, useTransform } from "motion/react";
import {
createContext, forwardRef, useCallback, useContext, useEffect, useId, useRef, useState,
type ButtonHTMLAttributes, type HTMLAttributes, type KeyboardEvent as RKeyboardEvent, type MutableRefObject, type ReactNode, type TextareaHTMLAttributes,
} from "react";
import { EASE, cx, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
import { Switch as CaptainSwitch } from "@/registry/captain/ui/switch";
import { DEFAULT_CAPTAIN, planSwarm, useComposer, type ComposerApi } from "./composer-core";
import type { Autonomy, CaptainSettings, ComposerOptions, Mention, MentionItem, Usage } from "./composer-types";
import { BRANDS, findBrand, type Brand } from "./composer-brands";
import { MARKS, TYPE_COLOR, TYPE_MARK, type MarkName } from "./composer-marks";
export * from "./composer-core";
export type * from "./composer-types";
export { fromChat, toFileParts, type ChatLike, type FilePart, type FromChatOptions } from "./composer-ai-sdk";
export { BRANDS, findBrand, type Brand } from "./composer-brands";
/** Your handler runs first; the composer's runs unless yours called preventDefault. */
function chain<E extends { defaultPrevented: boolean }>(yours: ((e: E) => void) | undefined, ours: ((e: E) => void) | undefined) {
return (e: E) => {
yours?.(e);
if (!e.defaultPrevented) ours?.(e);
};
}
/** Both always run: for bookkeeping (the drag depth) that must not be skipped when your handler calls preventDefault. */
function both<E>(yours: ((e: E) => void) | undefined, ours: (e: E) => void) {
return (e: E) => {
yours?.(e);
ours(e);
};
}
/* ---------- context ---------- */
const Ctx = createContext<ComposerApi | null>(null);
const NO_BRANDS: readonly Brand[] = [];
const BrandsCtx = createContext<readonly Brand[]>(NO_BRANDS);
type SwarmShared = { origin: MutableRefObject<HTMLDivElement | null>; opts: MutableRefObject<CaptainProps> };
const SwarmCtx = createContext<SwarmShared | null>(null);
/** The composer's state and actions, inside `Composer.Root`. */
export function useComposerContext(): ComposerApi {
const c = useContext(Ctx);
if (!c) throw new Error("Composer parts must be inside <Composer.Root>.");
return c;
}
/* ---------- marks ---------- */
/** A 16x16 pixel mark for an agent type. `working` makes the lit pixels shimmer, offset by `phase` seconds. */
export function Mark({ type, name, size = 14, working, label, phase = 0 }: { type?: string; name?: MarkName; size?: number; working?: boolean; label?: string; phase?: number }) {
const m = MARKS[name ?? TYPE_MARK[type ?? ""] ?? "cube"];
const reduce = useReducedMotion();
const color = type ? TYPE_COLOR[type] ?? `var(--captain-type-${type}, var(--captain-ink-2))` : undefined;
return (
<svg viewBox="0 0 16 16" width={size} height={size} shapeRendering="crispEdges" fill="currentColor" style={{ color }} className="shrink-0"
role={label ? "img" : undefined} aria-label={label} aria-hidden={label ? undefined : true}>
<path d={m.solid} />
<motion.path d={m.lit} initial={false}
animate={working && !reduce ? { opacity: [0.3, 1, 0.3] } : { opacity: 0.55 }}
transition={working && !reduce ? { duration: 1.1, repeat: Infinity, ease: "easeInOut", delay: phase } : { duration: 0.2 }} />
</svg>
);
}
/** The real brand mark for a model or connector name, or nothing. */
export function BrandMark({ name, size = 14 }: { name?: string; size?: number }) {
const b = findBrand(name, useContext(BrandsCtx));
if (!b) return null;
return (
<svg className={cx("shrink-0", b.dark && "[.dark_&]:invert [[data-theme=dark]_&]:invert")} viewBox={b.viewBox || "0 0 24 24"} width={size} height={size}
aria-hidden="true" dangerouslySetInnerHTML={{ __html: b.svg }} />
);
}
/** Close a popover on outside press and Escape; hand focus back to its button. */
function usePopover() {
const [open, setOpen] = useState(false);
const btn = useRef<HTMLButtonElement>(null);
const panel = useRef<HTMLDivElement>(null);
const close = useCallback((refocus = true) => {
setOpen(false);
if (refocus) btn.current?.focus();
}, []);
useEffect(() => {
if (!open) return;
const down = (e: PointerEvent) => {
const t = e.target as Node;
if (!panel.current?.contains(t) && !btn.current?.contains(t)) close(false);
};
document.addEventListener("pointerdown", down);
return () => document.removeEventListener("pointerdown", down);
}, [open, close]);
return { open, setOpen, close, btn, panel };
}
const isRtl = (el: Element | null) => !!el && getComputedStyle(el).direction === "rtl";
// A popover grows from its trigger: from scale .96 and a few pixels, never from nothing.
const POP = {
initial: { opacity: 0, y: 6, scale: 0.97 },
animate: { opacity: 1, y: 0, scale: 1 },
exit: { opacity: 0, y: 4, scale: 0.98, transition: { duration: 0.12, ease: EASE } },
transition: { duration: 0.18, ease: EASE },
} as const;
// glass, but dense enough that the composer's own text never reads through it
const FLOAT = { background: "color-mix(in srgb, var(--captain-surface) 94%, transparent)" } as const;
const quiet = "pressable inline-flex items-center rounded-inner text-ink-2 transition-colors duration-150 hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:text-ink outline-none disabled:opacity-40";
/* ---------- Root ---------- */
export interface RootProps extends ComposerOptions, Omit<HTMLAttributes<HTMLDivElement>, "onSubmit" | "defaultValue"> {
children?: ReactNode;
/** Give the composer an accessible name (default "Message composer"). */
label?: string;
/** Drop the root's own surface (the lifted shell), for when you place the parts on a surface of your own. */
unstyled?: boolean;
/** The brand marks the model picker can show, matched by `ModelOption.brand` or the label. Import only the ones
* you use (`import { claude, openai } from './composer-brands'`); `CaptainComposer` defaults to all 20. */
brands?: readonly Brand[];
}
/** Holds the state and provides it to every part. Renders a labelled group with a live region for announcements. */
export const Root = forwardRef<HTMLDivElement, RootProps>(function Root(props, ref) {
const {
value, defaultValue, onValueChange, status, onSubmit, onStop, disabled, disabledReason, queue, triggers, models, model, defaultModel,
onModelChange, captain, defaultCaptain, onCaptainChange, accept, maxFileSize, maxAttachments, upload, agentLabel, defaultAttachments,
children, className, label = "Message composer", unstyled, brands = NO_BRANDS, onDragEnter, onDragLeave, onDragOver, onDrop, ...rest
} = props;
const api = useComposer({
value, defaultValue, onValueChange, status, onSubmit, onStop, disabled, disabledReason, queue, triggers, models, model, defaultModel,
onModelChange, captain, defaultCaptain, onCaptainChange, accept, maxFileSize, maxAttachments, upload, agentLabel, defaultAttachments,
});
const drop = api.getDropProps();
const origin = useRef<HTMLDivElement | null>(null);
const opts = useRef<CaptainProps>({});
const [swarm] = useState<SwarmShared>(() => ({ origin, opts }));
return (
<Ctx.Provider value={api}>
<BrandsCtx.Provider value={brands}>
<SwarmCtx.Provider value={swarm}>
<div ref={ref} role="group" aria-label={label}
className={cx(!unstyled && "lifted relative flex flex-col rounded-shell text-ink", disabled && "opacity-60", className)}
data-status={api.status} data-disabled={disabled || undefined} {...rest} data-dragging={drop["data-dragging"]}
onDragEnter={both(onDragEnter, drop.onDragEnter)} onDragLeave={both(onDragLeave, drop.onDragLeave)}
onDragOver={chain(onDragOver, drop.onDragOver)} onDrop={both(onDrop, drop.onDrop)}>
{children}
{drop["data-dragging"] && (
<div className="pointer-events-none absolute inset-1 z-40 grid place-items-center rounded-inner bg-accent-tint text-[14px] font-medium text-accent-ink" aria-hidden="true">
Drop to attach
</div>
)}
<div id={api.ids.live} className="sr-only" role="status" aria-live="polite" aria-atomic="true">{api.announcement}</div>
</div>
</SwarmCtx.Provider>
</BrandsCtx.Provider>
</Ctx.Provider>
);
});
/* ---------- Input ---------- */
export interface InputProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "value" | "defaultValue" | "onChange"> {
/** Grows with the text up to this many pixels, then scrolls. Default 240. */
maxHeight?: number;
}
// what a className or style on Input usually changes; the mirror copies them so the marks sit on the typed text
const MIRROR = ["top", "right", "bottom", "left"].map((s) => "padding-" + s).concat("font-family font-size font-weight line-height letter-spacing text-align direction overflow-y".split(" "));
/** The text field. A textarea, so IME, spellcheck, autofill and screen readers behave natively. Mentions read as ink-blue tokens. */
export const Input = forwardRef<HTMLTextAreaElement, InputProps>(function Input({ className, maxHeight = 240, placeholder, onKeyDown, onPaste, onBlur, onSelect, onScroll, ...rest }, ref) {
const c = useComposerContext();
const p = c.getInputProps();
const el = c.inputRef;
useIsoLayoutEffect(() => {
const t = el.current;
if (!t) return;
t.style.height = "auto";
t.style.height = Math.min(maxHeight, t.scrollHeight) + "px";
t.style.overflowY = t.scrollHeight > maxHeight ? "auto" : "hidden";
}, [c.value, maxHeight]);
const setRefs = (node: HTMLTextAreaElement | null) => {
el.current = node;
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
};
// while it works, anything typed joins the running task; otherwise the field says who will answer
const model = c.models.find((m) => m.id === c.model);
const ask = c.captain?.enabled ? "Ask the Captain" : model ? `Ask ${model.label}` : "Ask";
const hl = useRef<HTMLDivElement>(null);
const spans = mentionRanges(c.value, c.mentions);
const marked = spans.length > 0;
const sync = () => {
if (hl.current && el.current) hl.current.scrollTop = el.current.scrollTop;
};
useIsoLayoutEffect(() => {
const h = hl.current, t = el.current;
if (!h || !t) return;
const cs = getComputedStyle(t);
for (const k of MIRROR) h.style.setProperty(k, cs.getPropertyValue(k));
sync();
}, [c.value, marked]);
return (
<div className="relative">
{marked && (
<div ref={hl} className="pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words text-ink" aria-hidden="true">
{spans.map((r, i) =>
r.m ? (
<mark key={i} className="rounded-[3px] bg-accent-tint text-accent-ink [box-decoration-break:clone]">{c.value.slice(r.a, r.b)}</mark>
) : (
<span key={i}>{c.value.slice(r.a, r.b)}</span>
),
)}
{""}
</div>
)}
<textarea
{...p}
ref={setRefs}
className={cx(
"relative block min-h-[56px] w-full resize-none bg-transparent px-4 pt-3.5 pb-2 text-[15px] leading-[1.55] outline-none placeholder:text-ink-3 selection:bg-accent-tint",
marked ? "text-transparent caret-ink" : "text-ink",
className,
)}
placeholder={c.disabled && c.disabledReason ? c.disabledReason : c.busy ? "Add to the task" : placeholder ?? ask}
aria-label={rest["aria-label"] ?? "Message"}
{...rest}
onKeyDown={chain(onKeyDown, p.onKeyDown)}
onPaste={chain(onPaste, p.onPaste)}
onBlur={chain(onBlur, p.onBlur)}
onSelect={chain(onSelect, p.onSelect)}
onScroll={both(onScroll, sync)}
/>
<Menu />
</div>
);
});
/** Where each picked mention sits in the text: whole tokens only, so a half-deleted one stops being marked. */
function mentionRanges(value: string, mentions: readonly Mention[]) {
const hits: { a: number; b: number }[] = [];
for (const m of mentions) {
const t = m.trigger + m.label;
for (let i = value.indexOf(t); i >= 0; i = value.indexOf(t, i + 1)) {
const before = value[i - 1] ?? " ", after = value[i + t.length] ?? " ";
if (/\s/.test(before) && /[\s.,;:!?]/.test(after)) hits.push({ a: i, b: i + t.length });
}
}
if (!hits.length) return [];
// at the same start, the longer mention wins (@Claude Code over @Claude)
hits.sort((x, y) => x.a - y.a || y.b - x.b);
const out: { a: number; b: number; m: boolean }[] = [];
let at = 0;
for (const h of hits) {
if (h.a < at) continue;
if (h.a > at) out.push({ a: at, b: h.a, m: false });
out.push({ ...h, m: true });
at = h.b;
}
if (at < value.length) out.push({ a: at, b: value.length, m: false });
return out;
}
/* ---------- the @ and / menu ---------- */
function ItemMark({ item }: { item: MentionItem }) {
if (item.kind === "file") return <Icon name="file" size={16} className="text-ink-3" />;
if (item.kind === "skill") return <span className="w-4 text-center text-[14px] font-medium text-ink-3" aria-hidden="true">/</span>;
return <Mark type={item.type ?? "captain"} size={14} />;
}
/** The suggestion list for `@` and `/`. Rendered by `Composer.Input`; you rarely place it yourself. */
export function Menu() {
const c = useComposerContext();
const reduce = useReducedMotion();
const m = c.menu;
return (
<AnimatePresence>
{m && (
<motion.div key="menu" {...c.getMenuProps()} {...(reduce ? {} : POP)}
style={FLOAT} className="glass absolute bottom-full left-2 z-30 mb-2 w-[min(380px,calc(100%-16px))] origin-bottom-left rounded-shell p-1">
{m.items.length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3" role="presentation">{m.trigger.char === "/" ? "No skill matches" : "No match"}</div>}
{m.items.map((it, i) => (
<div key={it.id} {...c.getOptionProps(i)}
className={cx("flex h-9 cursor-default items-center gap-2.5 rounded-inner px-2.5 text-[13.5px]", m.active === i && "bg-hover")}>
<span className="grid w-4 place-items-center"><ItemMark item={it} /></span>
<span className="shrink-0 font-medium text-ink">{m.trigger.char === "/" ? "/" : ""}{it.label}</span>
{it.description && <span className="min-w-0 truncate text-ink-3">{it.description}</span>}
{it.shortcut && <kbd className="ml-auto font-sans text-[12px] text-ink-3 tnum">{it.shortcut}</kbd>}
</div>
))}
</motion.div>
)}
</AnimatePresence>
);
}
/* ---------- Toolbar and helpers ---------- */
export const Toolbar = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function Toolbar({ className, ...rest }, ref) {
return <div ref={ref} role="toolbar" aria-label="Message options" aria-orientation="horizontal" className={cx("flex items-center gap-0.5 px-2 pt-1 pb-2", className)} {...rest} />;
});
export function Spacer() {
return <span className="flex-1" aria-hidden="true" />;
}
export const Footer = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function Footer({ className, ...rest }, ref) {
return <div ref={ref} className={cx("px-4 pb-2.5 text-[12px] text-ink-3", className)} {...rest} />;
});
/* ---------- Send ---------- */
/** Send; becomes Stop (a square) while a turn runs and the field is empty, and Queue when it isn't. */
export const Send = forwardRef<HTMLButtonElement, ButtonHTMLAttributes<HTMLButtonElement>>(function Send({ className, onClick, ...rest }, ref) {
const c = useComposerContext();
const p = c.getSendProps();
const reduce = useReducedMotion();
const live = c.sendMode === "stop" || c.canSend;
return (
<button ref={ref} {...p} data-mode={c.sendMode} title={p["aria-label"]} {...rest}
className={cx(
"pressable relative grid size-9 shrink-0 place-items-center rounded-inner outline-none transition-colors duration-150 before:absolute before:-inset-1 before:content-['']",
live ? "bg-primary text-primary-ink shadow-raise focus-visible:bg-accent" : "bg-press text-ink-3",
className,
)}
onClick={chain(onClick, () => { p.onClick(); c.focus(); })}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span key={c.sendMode === "stop" ? "stop" : "send"} className="grid place-items-center"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, rotate: c.sendMode === "stop" ? -90 : 0, y: c.sendMode === "stop" ? 0 : 6 }}
animate={{ opacity: 1, scale: 1, rotate: 0, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, y: c.sendMode === "stop" ? 0 : -8 }}
transition={{ duration: 0.18, ease: EASE }}>
{c.sendMode === "stop" ? <span className="block size-[11px] rounded-[2.5px] bg-current" /> : <Icon name="arrowUp" size={18} />}
</motion.span>
</AnimatePresence>
</button>
);
});
/* ---------- Attachments ---------- */
/** The + button: opens the file picker. */
export const AttachButton = forwardRef<HTMLButtonElement, ButtonHTMLAttributes<HTMLButtonElement>>(function AttachButton({ className, onClick, ...rest }, ref) {
const c = useComposerContext();
const file = useRef<HTMLInputElement>(null);
return (
<>
<button ref={ref} type="button" aria-label="Attach files" title="Attach files" disabled={c.disabled} {...rest}
className={cx(quiet, "relative size-8 justify-center before:absolute before:-inset-1.5 before:content-['']", className)}
onClick={chain(onClick, () => file.current?.click())}>
<Icon name="plus" size={18} />
</button>
<input ref={file} type="file" multiple hidden tabIndex={-1} aria-hidden="true" accept={c.accept}
onChange={(e) => {
if (e.target.files) c.addFiles(e.target.files);
e.target.value = "";
c.focus();
}} />
</>
);
});
const fmt = (b?: number) => (b == null ? "" : b >= 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(b / 1e3))} KB`);
/** The attached files, each with a remove button. Renders nothing when empty. */
export function Attachments({ className }: { className?: string }) {
const c = useComposerContext();
if (!c.attachments.length) return null;
return (
<ul className={cx("flex flex-wrap gap-2 px-3 pt-3", className)} aria-label="Attachments">
{c.attachments.map((a) => (
<li key={a.id} className="raised flex h-11 max-w-full items-center gap-2.5 rounded-inner pr-1 pl-1.5" data-status={a.status}>
{a.url && a.type?.startsWith("image/") ? (
// eslint-disable-next-line @next/next/no-img-element
<img className="size-8 rounded-[6px] object-cover" src={a.url} alt="" />
) : (
<span className="well grid size-8 shrink-0 place-items-center rounded-[6px] text-ink-2"><Icon name="file" size={16} /></span>
)}
<span className="flex min-w-0 flex-col leading-tight">
<span className="max-w-[180px] truncate text-[13px] font-medium text-ink">{a.name}</span>
<span className={cx("text-[11.5px] tnum", a.status === "error" ? "text-danger" : "text-ink-3")}>
{a.status === "error" ? a.error : a.status === "uploading" ? "Uploading" : fmt(a.size)}
</span>
</span>
<button type="button" aria-label={`Remove ${a.name}`} className={cx(quiet, "relative size-7 justify-center text-ink-3 before:absolute before:-inset-2 before:content-['']")}
onClick={() => { c.removeAttachment(a.id); c.focus(); }}>
<Icon name="x" size={14} />
</button>
</li>
))}
</ul>
);
}
/* ---------- Model picker ---------- */
/** A button that opens a listbox of models, with real provider marks and, when given, what one task costs on each. */
export function ModelPicker({ className }: { className?: string }) {
const c = useComposerContext();
const models = c.models;
const pop = usePopover();
const [active, setActive] = useState(0);
const id = useId();
const reduce = useReducedMotion();
const cur = models.find((m) => m.id === c.model) ?? models[0];
useEffect(() => {
if (pop.open) {
setActive(Math.max(0, models.findIndex((m) => m.id === c.model)));
pop.panel.current?.focus();
}
}, [pop.open]); // eslint-disable-line react-hooks/exhaustive-deps
if (!models.length) return null;
const choose = (i: number) => {
const m = models[i];
if (!m) return;
c.setModel(m.id);
c.say(`Model: ${m.label}`);
pop.close();
};
const key = (e: RKeyboardEvent) => {
const n = models.length;
if (e.key === "ArrowDown") { e.preventDefault(); setActive((active + 1) % n); }
else if (e.key === "ArrowUp") { e.preventDefault(); setActive((active - 1 + n) % n); }
else if (e.key === "Home") { e.preventDefault(); setActive(0); }
else if (e.key === "End") { e.preventDefault(); setActive(n - 1); }
else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); choose(active); }
else if (e.key === "Escape") { e.preventDefault(); pop.close(); }
else if (e.key === "Tab") pop.close(false);
};
return (
<div className={cx("relative", className)}>
<button ref={pop.btn} type="button" aria-haspopup="listbox" aria-expanded={pop.open} aria-controls={pop.open ? `${id}-lb` : undefined}
aria-label={`Model: ${cur?.label}`} onClick={() => pop.setOpen(!pop.open)}
onKeyDown={(e) => { if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); pop.setOpen(true); } }}
className={cx(quiet, "h-8 gap-1.5 pr-1.5 pl-2 text-[13px] font-medium", pop.open && "bg-hover text-ink")}>
<BrandMark name={cur?.brand ?? cur?.label} />
<span className="whitespace-nowrap">{cur?.label}</span>
<Icon name="chevron" size={14} className="text-ink-3" />
</button>
<AnimatePresence>
{pop.open && (
<motion.div key="lb" ref={pop.panel} id={`${id}-lb`} role="listbox" aria-label="Model" tabIndex={-1} aria-activedescendant={`${id}-o${active}`} onKeyDown={key}
{...(reduce ? {} : POP)} style={FLOAT} className="glass absolute bottom-full left-0 z-30 mb-2 w-[260px] origin-bottom-left rounded-shell p-1 outline-none">
{models.map((m, i) => (
<div key={m.id} id={`${id}-o${i}`} role="option" aria-selected={m.id === c.model}
className={cx("flex h-10 cursor-default items-center gap-2.5 rounded-inner px-2.5 text-[13.5px]", i === active && "bg-hover")}
onMouseMove={() => setActive(i)} onClick={() => choose(i)}>
<span className="grid w-4 place-items-center"><BrandMark name={m.brand ?? m.label} /></span>
<span className="font-medium text-ink">{m.label}</span>
{m.description && <span className="truncate text-ink-3">{m.description}</span>}
<span className="ml-auto flex items-center gap-2">
<span className="grid w-3.5 place-items-center text-ink">{m.id === c.model && <Icon name="check" size={14} />}</span>
</span>
</div>
))}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
/* ---------- segmented radio group (roving tabindex) ---------- */
function Radios<T extends string | number>({ label, options, value, onChange, describe }: {
label: string; options: { v: T; label: string }[]; value: T; onChange: (v: T) => void; describe?: string;
}) {
const refs = useRef<(HTMLButtonElement | null)[]>([]);
const idx = Math.max(0, options.findIndex((o) => o.v === value));
const key = (e: RKeyboardEvent<HTMLButtonElement>) => {
const rtl = isRtl(e.currentTarget), n = options.length;
const nextKeys = ["ArrowDown", rtl ? "ArrowLeft" : "ArrowRight"], prevKeys = ["ArrowUp", rtl ? "ArrowRight" : "ArrowLeft"];
let j = -1;
if (nextKeys.includes(e.key)) j = (idx + 1) % n;
else if (prevKeys.includes(e.key)) j = (idx - 1 + n) % n;
else if (e.key === "Home") j = 0;
else if (e.key === "End") j = n - 1;
if (j < 0) return;
const o = options[j];
if (!o) return;
e.preventDefault();
onChange(o.v);
refs.current[j]?.focus();
};
const gid = useId();
return (
<div className="grid grid-cols-[76px_1fr] items-center gap-x-3 gap-y-1">
<span className="text-[12.5px] text-ink-2" id={`${gid}-l`}>{label}</span>
<div className="well flex rounded-[7px] p-0.5" role="radiogroup" aria-labelledby={`${gid}-l`} aria-describedby={describe ? `${gid}-d` : undefined}>
{options.map((o, i) => (
<button key={String(o.v)} ref={(el) => { refs.current[i] = el; }} type="button" role="radio" aria-checked={o.v === value} tabIndex={i === idx ? 0 : -1}
onClick={() => onChange(o.v)} onKeyDown={key}
className={cx(
"h-7 flex-1 rounded-[5px] px-2 text-[12.5px] whitespace-nowrap outline-none transition-colors duration-150 tnum",
o.v === value ? "raised font-medium text-ink" : "text-ink-2 hover:text-ink focus-visible:bg-hover",
)}>
{o.label}
</button>
))}
</div>
{describe && <span className="sr-only" id={`${gid}-d`}>{describe}</span>}
</div>
);
}
/* ---------- Captain ---------- */
const AUTONOMY: { v: Autonomy; label: string; d: string }[] = [
{ v: "ask", label: "Ask me", d: "Asks before every write" },
{ v: "risk", label: "On risk", d: "Asks only before deletes, deploys and spend" },
{ v: "full", label: "Full send", d: "Never asks; stops at the budget" },
];
const TYPES = ["review", "tests", "build", "research", "security", "docs", "design", "ship"];
const cap1 = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
const nlab = (n: number) => (n >= 1000 ? `${n / 1000}k` : String(n));
export interface CaptainProps {
className?: string;
/** Swarm sizes offered in the settings. */
sizes?: number[];
budgets?: number[];
/** Agent types offered as switches. */
types?: string[];
}
/** The Captain switch: off, the message goes to one agent; on, a Captain leads a swarm. Lives in the toolbar. */
export function Captain({ className, ...opts }: CaptainProps) {
const c = useComposerContext();
const sw = useContext(SwarmCtx);
const s = c.captain ?? DEFAULT_CAPTAIN;
if (sw) sw.opts.current = opts;
// in a custom layout with no captain passed, the settings shown are the ones that get sent
useEffect(() => { if (!c.captain) c.setCaptain(DEFAULT_CAPTAIN); }, []); // eslint-disable-line react-hooks/exhaustive-deps
const set = (on: boolean) => {
c.setCaptain({ ...s, enabled: on });
c.say(on ? `Captain on, a swarm of ${s.size}` : "One agent");
};
return (
<div ref={sw?.origin} className={cx("flex h-8 items-center gap-2 rounded-inner pr-1.5 pl-2", className)}>
<span className={cx("flex cursor-default items-center gap-1.5 text-[13px] font-medium transition-colors duration-150 select-none", s.enabled ? "text-ink" : "text-ink-2")}
onClick={() => set(!s.enabled)} aria-hidden="true">
<Mark type="captain" size={14} />
Captain
</span>
<CaptainSwitch size="sm" aria-label="Captain" checked={s.enabled} onCheckedChange={set} disabled={c.disabled} />
</div>
);
}
/* ---------- the swarm tray ---------- */
// the agents sit as a dealt hand: each tile overlaps the last, with a small gap where the type changes
const TILE = 22, STEP = 15, SLACK = 40;
const piecesOf = (root: HTMLElement | null) => Array.from(root?.querySelectorAll<HTMLElement>("[data-piece]") ?? []);
export interface SwarmProps extends CaptainProps {}
/** The swarm the Captain will run: the lead, every agent by type, the model they run on and the cost against the budget.
* Opens above the toolbar when the Captain switch is on; its count opens the settings. */
export function Swarm(props: SwarmProps) {
const c = useComposerContext();
const on = !!c.captain?.enabled;
// a tray that is open on the first frame is just there; one opened later is dealt
const mounted = useRef(false);
useEffect(() => { mounted.current = true; }, []);
return <AnimatePresence initial={false}>{on && <SwarmTray key="swarm" deal={mounted.current} {...props} />}</AnimatePresence>;
}
function SwarmTray({ deal, className, ...own }: SwarmProps & { deal: boolean }) {
const c = useComposerContext();
const sw = useContext(SwarmCtx);
const s = c.captain ?? DEFAULT_CAPTAIN;
const opts = { ...sw?.opts.current, ...Object.fromEntries(Object.entries(own).filter(([, v]) => v !== undefined)) } as CaptainProps;
const plan = planSwarm(s, c.models, c.model);
const reduce = useReducedMotion();
const [isPresent, safeToRemove] = usePresence();
const outer = useRef<HTMLDivElement>(null);
const row = useRef<HTMLDivElement>(null);
const [fit, setFit] = useState<number | null>(null);
const n = plan.agents.length;
const count = useMotionValue(n);
const countText = useTransform(count, (v) => nlab(Math.round(v)));
const pop = usePopover();
const id = useId();
// how many tiles fit; past that, the last slot says how many more
useIsoLayoutEffect(() => {
const el = row.current;
if (!el) return;
const calc = (w: number) => Math.max(4, Math.floor((w - TILE - SLACK) / STEP) + 1);
setFit(calc(el.clientWidth));
const ro = new ResizeObserver(([e]) => e && setFit(calc(e.contentRect.width)));
ro.observe(el);
return () => ro.disconnect();
}, []);
const types = s.types.length ? s.types : ["build"];
const tiles: string[] = fit == null ? [] : n <= fit ? plan.agents.map((a) => a.type)
: Array.from({ length: fit - 1 }, (_, i) => types[i % types.length] ?? "build").sort((a, b) => types.indexOf(a) - types.indexOf(b));
const more = n - tiles.length;
// where the switch's thumb rests when on: every piece comes out of it, and goes back into it
const fromThumb = (el: HTMLElement) => {
const sw0 = sw?.origin.current?.querySelector('[role="switch"]')?.getBoundingClientRect();
const r = el.getBoundingClientRect();
if (!sw0) return { x: 0, y: 24 };
return { x: sw0.right - sw0.height / 2 - (r.left + r.width / 2), y: sw0.top + sw0.height / 2 - (r.top + r.height / 2) };
};
const key = `${s.size}:${types.join()}`;
const lastKey = useRef<string | null>(null);
useIsoLayoutEffect(() => {
if (fit == null) return;
const first = lastKey.current === null;
const changed = lastKey.current !== key;
lastKey.current = key;
if (!changed || (first && !deal)) {
count.set(n);
return;
}
const els = piecesOf(outer.current);
// measure every piece where it will rest before the tray is folded shut for the opening
const from = els.map(fromThumb);
// the tray opens over 160ms while the pieces are dealt into it; the last one lands by 280ms
if (first && outer.current) {
const o = outer.current;
const h = o.scrollHeight;
o.style.clipPath = "inset(0 -40px -160px -40px)";
o.style.height = "0px";
animate(o, { height: [0, h] }, { duration: reduce ? 0 : 0.16, ease: EASE }).then(() => {
o.style.height = "auto";
o.style.clipPath = "none";
});
}
const stagger = els.length > 1 ? Math.min(0.011, 0.1 / (els.length - 1)) : 0;
const dur = 0.16;
els.forEach((el, i) => {
if (reduce) {
animate(el, { opacity: [0, 1] }, { duration: 0.12 });
return;
}
const d = from[i] ?? { x: 0, y: 24 };
el.style.opacity = "0";
animate(el, { x: [d.x, 0], y: [d.y, 0], scale: [0.4, 1], opacity: [0, 1] }, {
delay: 0.02 + i * stagger,
x: { duration: dur, ease: EASE },
y: { duration: dur, ease: [0.3, 0, 0.2, 1] },
scale: { duration: dur, ease: EASE },
opacity: { duration: 0.05 },
});
});
// the count rolls up as the agents land
const span = reduce ? 0 : 0.02 + stagger * Math.max(0, els.length - 1) + dur;
animate(count, [1, n], { duration: span, ease: "linear" });
}, [fit, key]); // eslint-disable-line react-hooks/exhaustive-deps
// switching off sends every piece back into the thumb, then the tray closes
useEffect(() => {
if (isPresent) return;
const o = outer.current;
const els = piecesOf(o).reverse();
if (!o || reduce) { safeToRemove?.(); return; }
o.style.clipPath = "inset(0 -40px -160px -40px)";
const stagger = els.length > 1 ? Math.min(0.006, 0.07 / (els.length - 1)) : 0;
els.forEach((el, i) => {
const d = fromThumb(el);
animate(el, { x: d.x, y: d.y, scale: 0.4, opacity: 0 }, { delay: i * stagger, duration: 0.14, ease: [0.5, 0, 0.75, 0], opacity: { duration: 0.14, ease: [0.8, 0, 1, 1] } });
});
animate(count, 1, { duration: 0.14 });
animate(o, { height: 0 }, { duration: 0.16, delay: 0.06, ease: EASE }).then(() => safeToRemove?.());
}, [isPresent]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (pop.open) (pop.panel.current?.querySelector('[tabindex="0"],button') as HTMLElement | null)?.focus();
}, [pop.open]); // eslint-disable-line react-hooks/exhaustive-deps
const set = (patch: Partial<CaptainSettings>) => c.setCaptain({ ...s, ...patch });
const sizes = opts.sizes ?? [6, 12, 24, 200, 1000];
const budgets = opts.budgets ?? [1, 2, 5];
const allTypes = opts.types ?? TYPES;
const lead = plan.lead;
const crew = plan.crew;
return (
<div ref={outer} className={cx("flex flex-col justify-end", className)}>
<div className="relative mx-2 mb-1 flex shrink-0 items-center gap-3 rounded-inner well py-2 pr-3 pl-2" role="group" aria-label="Swarm">
<span data-piece className="lifted grid size-10 shrink-0 place-items-center rounded-[8px]">
<Mark type="captain" size={18} working={c.busy} />
</span>
<div className="min-w-0 flex-1">
<div ref={row} className="flex h-[22px] items-center" aria-hidden="true">
{tiles.map((t, i) => (
<span key={`${key}-${i}`} data-piece style={{ zIndex: i + 1, marginLeft: i === 0 ? 0 : t === tiles[i - 1] ? -(TILE - STEP) : 3 }}
className="raised relative flex size-[22px] shrink-0 items-center rounded-[6px] pl-[3px]">
<Mark type={t} size={12} working={c.busy} phase={(i % 6) * 0.12} />
</span>
))}
{more > 0 && (
<span data-piece className="grid h-[22px] shrink-0 place-items-center pl-2 text-[12px] font-medium text-ink-2 tnum">+{nlab(more)}</span>
)}
</div>
<p className="mt-1.5 text-[12.5px] leading-[18px] text-ink-2">
{lead && <><span className="font-medium text-ink">{lead.label}</span> leads </>}
<span className="relative inline-block">
<button ref={pop.btn} type="button" aria-haspopup="dialog" aria-expanded={pop.open} aria-controls={pop.open ? `${id}-dlg` : undefined}
onClick={() => pop.setOpen(!pop.open)}
className={cx("pressable -mx-1 inline-flex items-center gap-0.5 rounded-[5px] px-1 font-medium text-ink outline-none transition-colors duration-150 hover:bg-hover focus-visible:bg-hover", pop.open && "bg-hover")}>
<motion.span className="tnum">{countText}</motion.span> agents
<Icon name="chevron" size={13} className="text-ink-3" />
</button>
</span>
{crew && <> on <span className="font-medium text-ink">{crew.label}</span></>}
</p>
</div>
<span className="sr-only">
{`${lead ? `${lead.label} leads ` : ""}${n} agents${crew ? ` on ${crew.label}` : ""}`}
</span>
<AnimatePresence>
{pop.open && (
<motion.div key="dlg" ref={pop.panel} id={`${id}-dlg`} role="dialog" aria-label="Captain settings" {...(reduce ? {} : POP)}
onKeyDown={(e) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); pop.close(); } }}
style={FLOAT} className="glass absolute bottom-full left-1/2 z-30 mb-2 flex w-[min(372px,calc(100vw-24px))] -translate-x-1/2 origin-bottom flex-col gap-2.5 rounded-shell p-3">
<Radios label="Swarm" options={sizes.map((v) => ({ v, label: nlab(v) }))} value={s.size} onChange={(v) => set({ size: v })} />
<Radios label="Autonomy" options={AUTONOMY.map((a) => ({ v: a.v, label: a.label }))} value={s.autonomy} onChange={(v) => set({ autonomy: v })}
describe={AUTONOMY.find((a) => a.v === s.autonomy)?.d} />
<Radios label="Budget" options={budgets.map((v) => ({ v, label: `$${v}` }))} value={s.budget} onChange={(v) => set({ budget: v })} />
{c.models.length > 1 && (
<Radios label="Agents on" options={c.models.map((m) => ({ v: m.id, label: m.label }))} value={crew?.id ?? ""} onChange={(v) => set({ crew: v })} />
)}
<div className="grid grid-cols-[76px_1fr] gap-x-3" role="group" aria-labelledby={`${id}-types`}>
<span id={`${id}-types`} className="pt-1.5 text-[12.5px] text-ink-2">May use</span>
<div className="grid grid-cols-4 gap-1">
{allTypes.map((t) => {
const on = s.types.includes(t);
return (
<button key={t} type="button" aria-pressed={on}
onClick={() => set({ types: on ? s.types.filter((x) => x !== t) : s.types.concat(t) })}
className={cx(
"pressable flex h-10 flex-col items-center justify-center gap-1 rounded-[6px] text-[11.5px] outline-none transition-colors duration-150",
on ? "raised text-ink" : "text-ink-3 hover:bg-hover focus-visible:bg-hover [&_svg]:opacity-40",
)}>
<Mark type={t} size={12} />
{cap1(t)}
</button>
);
})}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
);
}
/* ---------- Meter ---------- */
/** Tokens and spend so far; turns amber at 80% of the Captain's budget. */
export function Meter({ usage, className }: { usage?: Usage; className?: string }) {
const c = useComposerContext();
if (!usage || (usage.tokens == null && usage.usd == null)) return null;
const budget = c.captain?.enabled ? c.captain.budget : undefined, usd = usage.usd ?? 0;
const state = budget ? (usd >= budget ? "over" : usd >= budget * 0.8 ? "warn" : undefined) : undefined;
const tok = usage.tokens == null ? "" : usage.tokens >= 1000 ? `${(usage.tokens / 1000).toFixed(usage.tokens >= 1e5 ? 0 : 1)}k` : String(usage.tokens);
return (
<span className={cx("flex items-center gap-2 px-1.5 text-[12px] tnum", state === "over" ? "text-danger" : state === "warn" ? "text-warning" : "text-ink-3", className)}
data-state={state} role="status" aria-label={`${usage.tokens ?? 0} tokens, $${usd.toFixed(2)}${budget ? ` of $${budget}` : ""}`}>
{tok && <span>{tok}</span>}
{usage.usd != null && <span>${usd.toFixed(2)}{budget ? <span className="text-ink-3">/${budget}</span> : null}</span>}
</span>
);
}
/* ---------- Status ---------- */
export interface StatusProps {
className?: string;
/** What the timer says. Default "Working". */
label?: string;
/** Shown while the turn waits for its first token (status `submitted`), such as a loader. */
thinking?: ReactNode;
}
/** How long the turn has run, as plain type. While it waits for the first token, `thinking` shows instead. */
export function Status({ className, label, thinking }: StatusProps) {
const c = useComposerContext();
const [t0, setT0] = useState<number | null>(null);
const [now, setNow] = useState(0);
useEffect(() => {
if (!c.busy) { setT0(null); return; }
const s = Date.now();
setT0(s);
setNow(s);
const h = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(h);
}, [c.busy]);
if (!c.busy || t0 == null) return null;
if (thinking && c.status === "submitted") return <span className={cx("px-1.5 text-[12.5px] text-ink-2", className)} aria-hidden="true">{thinking}</span>;
const sec = Math.floor((now - t0) / 1000);
return (
<span className={cx("px-1.5 text-[12.5px] text-ink-2", className)} aria-hidden="true">
{label ?? "Working"} <span className="text-ink tnum">{Math.floor(sec / 60)}:{String(sec % 60).padStart(2, "0")}</span>
</span>
);
}
/* ---------- Queue ---------- */
/** Messages waiting for the turn to end. Each can be edited back into the field or removed. */
export function Queue({ className }: { className?: string }) {
const c = useComposerContext();
if (!c.queue.length) return null;
return (
<ol className={cx("well mx-2 mt-2 flex flex-col rounded-inner p-1", className)} aria-label={`Queued, ${c.queue.length} waiting`}>
{c.queue.map((m, i) => (
<li key={m.id} className="flex h-8 items-center gap-2 rounded-[6px] pr-0.5 pl-2 text-[13px]">
<span className="w-3 text-[12px] text-ink-3 tnum" aria-hidden="true">{i + 1}</span>
<span className="min-w-0 flex-1 truncate text-ink">{m.text || `${m.attachments.length} file${m.attachments.length === 1 ? "" : "s"}`}</span>
<button type="button" className={cx(quiet, "size-7 justify-center text-ink-3")} aria-label={`Edit queued message ${i + 1}`} onClick={() => c.editQueued(m.id)}><Icon name="pen" size={14} /></button>
<button type="button" className={cx(quiet, "size-7 justify-center text-ink-3")} aria-label={`Remove queued message ${i + 1}`} onClick={() => c.removeQueued(m.id)}><Icon name="x" size={14} /></button>
</li>
))}
</ol>
);
}
/* ---------- the default layout ---------- */
export interface CaptainComposerProps extends RootProps {
/** Default: "Ask the Captain" with the switch on, "Ask <model>" with it off; "Add to the task" while it works. */
placeholder?: string;
/** Kept for compatibility. Spend belongs in the thread, so the default layout does not show it; place `Composer.Meter` yourself to show it. */
usage?: Usage;
/** Shown in the footer band, such as the repo and branch. */
footer?: ReactNode;
/** Hide the Captain switch and its swarm. */
noCaptain?: boolean;
/** Kept for compatibility. Status belongs in the thread; place `Composer.Status` yourself to show it. */
thinking?: ReactNode;
}
/** Every part in the default layout. Use the parts directly when you want a different one. */
export const CaptainComposer = forwardRef<HTMLDivElement, CaptainComposerProps>(function CaptainComposer(
{ placeholder, usage: _usage, footer, noCaptain, thinking: _thinking, brands = BRANDS, ...root }, ref,
) {
// the Captain switch shows DEFAULT_CAPTAIN when nothing is passed, so the state starts there too
const defaultCaptain = root.defaultCaptain ?? (noCaptain || root.captain ? undefined : DEFAULT_CAPTAIN);
return (
<Root ref={ref} {...root} brands={brands} defaultCaptain={defaultCaptain}>
<Attachments />
<Queue />
<Input placeholder={placeholder} />
{!noCaptain && <Swarm />}
<Toolbar>
<AttachButton />
<ModelPicker />
{!noCaptain && <Captain />}
<Spacer />
<Send />
</Toolbar>
{footer && <Footer>{footer}</Footer>}
</Root>
);
});
/** The parts, as one namespace: `<Composer.Root>`, `<Composer.Input>`... */
export const Composer = { Root, Input, Menu, Toolbar, Spacer, Footer, Send, AttachButton, Attachments, ModelPicker, Captain, Swarm, Meter, Status, Queue };// uimaxxer · Composer core, MIT. The headless composer: state, keyboard, menus, attachments, the queue, announcements and the swarm plan.
import { useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent, type ClipboardEvent, type DragEvent, type KeyboardEvent, type MouseEvent, type SyntheticEvent } from 'react';
import type {
Attachment, CaptainSettings, ComposerMessage, ComposerOptions, ComposerStatus, MenuState, Mention, MentionItem,
ModelOption, QueuedMessage, TriggerConfig,
} from './composer-types';
/** A value that is controlled when `value` is given and uncontrolled otherwise. */
export function useControllable<T>(value: T | undefined, initial: T, onChange?: (v: T) => void): [T, (v: T) => void] {
const [inner, setInner] = useState<T>(initial);
const controlled = value !== undefined;
const current = controlled ? (value as T) : inner;
const set = useCallback((v: T) => { if (!controlled) setInner(v); onChange?.(v); }, [controlled, onChange]);
return [current, set];
}
export const DEFAULT_CAPTAIN: CaptainSettings = { enabled: true, size: 12, autonomy: 'risk', budget: 2, types: ['build', 'design', 'tests', 'review', 'docs'] };
/** One agent in a planned swarm. */
export interface SwarmAgent { type: string; model?: ModelOption }
/** What a Captain run will look like: who leads, the agents by type, the model they run on and the rough cost. */
export interface SwarmPlan {
lead?: ModelOption;
crew?: ModelOption;
agents: SwarmAgent[];
/** Lead plus every agent, when the models carry a `usd`. */
usd?: number;
/** True when `usd` is past the budget: the run will stop and ask there. */
over: boolean;
}
/** Plan a swarm from the settings: agents dealt across the allowed types in turn, grouped by type, with the cost. */
export function planSwarm(s: CaptainSettings, models: ModelOption[], leadId?: string): SwarmPlan {
const lead = models.find(m => m.id === leadId) ?? models[0];
const priced = models.filter(m => m.usd != null).sort((a, b) => (a.usd ?? 0) - (b.usd ?? 0));
const crew = models.find(m => m.id === s.crew) ?? priced[0] ?? lead;
const types = s.types.length ? s.types : ['build'];
const counts = types.map((_, i) => Math.floor(s.size / types.length) + (i < s.size % types.length ? 1 : 0));
const agents: SwarmAgent[] = types.flatMap((type, i) => Array.from({ length: counts[i] ?? 0 }, () => ({ type, model: crew })));
const usd = lead?.usd != null && crew?.usd != null ? lead.usd + crew.usd * s.size : undefined;
return { lead, crew, agents, usd, over: usd != null && usd > s.budget };
}
const busyOf = (s: ComposerStatus) => s === 'submitted' || s === 'streaming';
let seq = 0;
const nextId = (p: string) => `${p}-${(++seq).toString(36)}`;
const raf = (f: () => void) => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(f) : setTimeout(f, 0));
const fmtBytes = (b: number) => (b >= 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(b / 1e3))} KB`);
/** Where a trigger character starts before the caret, if the caret is inside a mention being typed. */
export function findTrigger(value: string, caret: number, triggers: TriggerConfig[]): { trigger: TriggerConfig; start: number; query: string } | null {
const before = value.slice(0, caret);
for (const trigger of triggers) {
const i = before.lastIndexOf(trigger.char);
if (i < 0) continue;
if (trigger.startOnly ? before.slice(0, i).trim() !== '' : i > 0 && !/\s/.test(before[i - 1] ?? '')) continue;
const query = before.slice(i + 1);
if (/\s/.test(query) || query.length > 40) continue;
return { trigger, start: i, query };
}
return null;
}
/** Filter and rank a fixed list: prefix matches first, then anything containing the query. */
export function filterItems(items: MentionItem[], query: string, limit = 8): MentionItem[] {
const q = query.toLowerCase();
if (!q) return items.slice(0, limit);
const starts: MentionItem[] = [], has: MentionItem[] = [];
for (const it of items) {
const l = it.label.toLowerCase(), id = it.id.toLowerCase();
if (l.startsWith(q) || id.startsWith(q)) starts.push(it);
else if (l.includes(q) || id.includes(q) || (it.description || '').toLowerCase().includes(q)) has.push(it);
}
return starts.concat(has).slice(0, limit);
}
/** The mentions whose text is still in the message. */
export function mentionsIn(text: string, picked: Mention[]): Mention[] {
const seen = new Set<string>();
return picked.filter(m => {
const k = m.trigger + m.id;
if (seen.has(k) || !text.includes(m.trigger + m.label)) return false;
seen.add(k); return true;
});
}
/** The mentions already in a starting text, matched against the fixed trigger lists. */
export function seedMentions(text: string, triggers: TriggerConfig[]): Mention[] {
const out: Mention[] = [];
for (const t of triggers) {
if (!Array.isArray(t.items)) continue;
for (const it of t.items) {
const tok = t.char + it.label;
for (let i = text.indexOf(tok); i >= 0; i = text.indexOf(tok, i + 1)) {
if (/\s/.test(text[i - 1] ?? ' ') && /[\s.,;:!?]/.test(text[i + tok.length] ?? ' ')) {
out.push({ id: it.id, label: it.label, kind: it.kind ?? (t.char === '/' ? 'skill' : 'agent'), trigger: t.char });
break;
}
}
}
}
return out;
}
/**
* The headless composer: state, keyboard, menus, attachments, the queue and announcements.
* It renders nothing. `Composer.Root` calls it and shares the result through context; call it yourself to build
* your own markup, and spread the prop getters onto your elements.
*/
export function useComposer(o: ComposerOptions = {}) {
const uid = useId();
const ids = useMemo(() => ({ input: `${uid}-input`, menu: `${uid}-menu`, live: `${uid}-live`, option: (i: number) => `${uid}-opt-${i}` }), [uid]);
const status: ComposerStatus = o.status ?? 'ready';
// a send whose onSubmit promise has not settled (files still encoding, request in flight) counts as busy
const [pending, setPending] = useState(false);
const [sent, setSent] = useState(0);
const [dragging, setDragging] = useState(false);
const dragDepth = useRef(0);
const busy = busyOf(status) || pending;
const triggers = o.triggers ?? [];
const maxFileSize = o.maxFileSize ?? 25e6;
const agent = o.agentLabel ?? 'Agent';
const [value, setValue] = useControllable(o.value, o.defaultValue ?? '', o.onValueChange);
const [modelState, setModel] = useControllable(o.model, o.defaultModel ?? o.models?.[0]?.id ?? '', o.onModelChange);
// models can arrive after mount; then the first one is both shown and sent
const model = modelState || o.models?.[0]?.id || '';
const [captain, setCaptain] = useControllable<CaptainSettings | undefined>(o.captain, o.defaultCaptain, o.onCaptainChange as ((s: CaptainSettings | undefined) => void) | undefined);
const [attachments, setAttachments] = useState<Attachment[]>(() => o.defaultAttachments ?? []);
const [queue, setQueueState] = useState<QueuedMessage[]>([]);
const queueRef = useRef<QueuedMessage[]>([]);
const setQueue = useCallback((q: QueuedMessage[]) => { queueRef.current = q; setQueueState(q); }, []);
const [menu, setMenu] = useState<MenuState | null>(null);
const [announcement, setAnnouncement] = useState('');
const inputRef = useRef<HTMLTextAreaElement | null>(null);
// a restored draft keeps its mentions marked: whole tokens that match a fixed trigger list count as picked
const [seeded] = useState(() => seedMentions(o.value ?? o.defaultValue ?? '', o.triggers ?? []));
const picked = useRef<Mention[]>(seeded);
const lastSent = useRef('');
const lastPicked = useRef<Mention[]>([]);
const pendingRef = useRef(false);
const stoppedRef = useRef(false);
const statusRef = useRef(status); statusRef.current = status;
const dismissed = useRef<number | null>(null);
const objectUrls = useRef(new Set<string>());
const req = useRef(0);
const latest = useRef(o); latest.current = o;
const say = useCallback((t: string) => { setAnnouncement(''); raf(() => setAnnouncement(t)); }, []);
/* ---- the trigger menu ---- */
const syncMenu = useCallback((text: string, caret: number) => {
const hit = findTrigger(text, caret, triggers);
if (!hit || dismissed.current === hit.start) { if (!hit) dismissed.current = null; setMenu(null); return; }
const { trigger, start, query } = hit, limit = trigger.limit ?? 8;
const show = (items: MentionItem[]) => setMenu(m => ({ trigger, query, start, items, active: m && m.start === start ? Math.min(m.active, Math.max(0, items.length - 1)) : 0 }));
if (Array.isArray(trigger.items)) { show(filterItems(trigger.items, query, limit)); return; }
const my = ++req.current, r = trigger.items(query);
if (r instanceof Promise) r.then(items => { if (my === req.current) show(items.slice(0, limit)); }).catch(() => {});
else show(r.slice(0, limit));
}, [triggers]);
const pick = useCallback((item: MentionItem) => {
const el = inputRef.current;
if (!menu) return;
const caret = el ? el.selectionStart ?? value.length : value.length;
const insert = `${menu.trigger.char}${item.label} `;
const next = value.slice(0, menu.start) + insert + value.slice(caret);
picked.current.push({ id: item.id, label: item.label, kind: item.kind ?? (menu.trigger.char === '/' ? 'skill' : 'agent'), trigger: menu.trigger.char });
setValue(next); setMenu(null);
const at = menu.start + insert.length;
raf(() => { const e = inputRef.current; if (e) { e.focus(); e.setSelectionRange(at, at); } });
}, [menu, value, setValue]);
/* ---- attachments ---- */
/** Revoke the object URLs this composer made for these attachments. */
const release = useCallback((atts: Attachment[]) => {
for (const a of atts) if (a.url && objectUrls.current.has(a.url)) { URL.revokeObjectURL(a.url); objectUrls.current.delete(a.url); }
}, []);
const addFiles = useCallback((files: FileList | File[]) => {
if (latest.current.disabled) return;
const list = Array.from(files), max = latest.current.maxAttachments ?? Infinity;
const room = Math.max(0, max - attachments.length);
const take = list.slice(0, room);
if (list.length > room) say(`Only ${max} files fit. ${list.length - room} left out.`);
const made: Attachment[] = take.map(file => {
const tooBig = file.size > maxFileSize;
let url: string | undefined;
if (!tooBig && file.type.startsWith('image/') && typeof URL !== 'undefined' && URL.createObjectURL) { url = URL.createObjectURL(file); objectUrls.current.add(url); }
return { id: nextId('att'), name: file.name, size: file.size, type: file.type, file, url,
status: tooBig ? 'error' : latest.current.upload ? 'uploading' : 'ready',
error: tooBig ? `Too large: ${fmtBytes(file.size)}, the limit is ${fmtBytes(maxFileSize)}` : undefined };
});
if (!made.length) return;
setAttachments(a => a.concat(made));
say(made.length === 1 ? `Attached ${made[0]?.name}` : `Attached ${made.length} files`);
const up = latest.current.upload;
if (up) made.filter(a => a.status === 'uploading').forEach(a => {
up(a.file as File).then(({ url }) => { release([a]); setAttachments(xs => xs.map(x => x.id === a.id ? { ...x, url, status: 'ready' } : x)); },
(err: unknown) => setAttachments(xs => xs.map(x => x.id === a.id ? { ...x, status: 'error', error: err instanceof Error ? err.message : 'Upload failed' } : x)));
});
}, [attachments.length, maxFileSize, say, release]);
const removeAttachment = useCallback((id: string) => {
const a = attachments.find(x => x.id === id);
if (!a) return;
release([a]);
setAttachments(xs => xs.filter(x => x.id !== id));
say(`Removed ${a.name}`);
}, [attachments, say, release]);
useEffect(() => () => { objectUrls.current.forEach(u => URL.revokeObjectURL(u)); objectUrls.current.clear(); }, []);
/* ---- send, queue and stop ---- */
const uploading = attachments.some(a => a.status === 'uploading');
const ready = attachments.filter(a => a.status === 'ready');
const hasText = value.trim().length > 0;
const canSend = !o.disabled && !uploading && (hasText || ready.length > 0);
// send the next queued message once nothing is running, unless the person pressed Stop
const drainRef = useRef<() => void>(() => {});
const deliver = useCallback((message: ComposerMessage, draft: string) => {
let r: void | Promise<void>;
try { r = latest.current.onSubmit?.(message); } catch (err) { r = Promise.reject(err); }
if (!r || typeof (r as Promise<void>).then !== 'function') { release(message.attachments); return; }
pendingRef.current = true; setPending(true);
(r as Promise<void>).then(
() => release(message.attachments),
() => {
// nothing was sent: put the message back if the field is still empty
if (!inputRef.current || inputRef.current.value === '') { setValue(draft); setAttachments(xs => message.attachments.concat(xs)); }
say('Not sent. The message is back in the field.');
},
).finally(() => { pendingRef.current = false; setPending(false); drainRef.current(); });
}, [release, say, setValue]);
drainRef.current = () => {
if (pendingRef.current || busyOf(statusRef.current)) return;
if (stoppedRef.current) {
stoppedRef.current = false;
const n = queueRef.current.length;
if (n) say(`Stopped. ${n} still queued.`);
return;
}
const [head, ...rest] = queueRef.current;
if (!head) return;
const { id: _id, ...msg } = head;
setQueue(rest);
deliver({ ...msg, queued: true }, msg.text);
};
const submit = useCallback(() => {
if (!canSend) { if (uploading) say('Waiting for uploads to finish'); return false; }
if (busy && latest.current.queue === false) { say(`${agent} is still working.`); return false; }
const text = value.trim();
const message: ComposerMessage = { text, mentions: mentionsIn(text, picked.current), attachments: ready, model: model || undefined, captain: captain?.enabled ? captain : undefined };
lastSent.current = value; lastPicked.current = picked.current;
picked.current = []; dismissed.current = null;
setValue(''); setAttachments(xs => xs.filter(a => a.status === 'error')); setMenu(null);
if (busy) {
const n = queueRef.current.concat({ ...message, id: nextId('q') });
setQueue(n); say(`Queued. ${n.length} waiting.`);
return true;
}
stoppedRef.current = false;
setSent(n => n + 1);
deliver(message, value);
return true;
}, [canSend, uploading, value, ready, model, captain, busy, agent, setValue, setQueue, say, deliver]);
const stop = useCallback(() => { if (!busy) return; stoppedRef.current = true; latest.current.onStop?.(); say('Stopped'); }, [busy, say]);
const removeQueued = useCallback((id: string) => {
const m = queueRef.current.find(x => x.id === id);
if (m) release(m.attachments);
setQueue(queueRef.current.filter(x => x.id !== id));
}, [setQueue, release]);
const editQueued = useCallback((id: string) => {
const m = queueRef.current.find(x => x.id === id);
if (!m) return;
setQueue(queueRef.current.filter(x => x.id !== id)); setValue(m.text);
picked.current = m.mentions.slice(); setAttachments(xs => m.attachments.concat(xs));
inputRef.current?.focus();
}, [setQueue, setValue]);
// announce the turn, and send the next queued message when a turn ends
const prev = useRef(status);
useEffect(() => {
const was = prev.current; prev.current = status;
if (was === status) return;
if (status === 'submitted') say(`Sent. ${agent} is thinking.`);
else if (status === 'streaming' && was !== 'streaming') say(`${agent} is responding.`);
else if (status === 'error') {
// the queue waits after an error; it goes out after the next turn ends
const n = queueRef.current.length;
say(`${agent} hit an error.${n ? ` ${n} still queued.` : ''}`);
}
else if (status === 'ready' && busyOf(was)) {
if (!stoppedRef.current && !queueRef.current.length) say(`${agent} finished.`);
drainRef.current();
}
}, [status, agent, say]);
/* ---- keyboard ---- */
const onKeyDown = useCallback((e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
if (menu && menu.items.length) {
const n = menu.items.length;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); const d = e.key === 'ArrowDown' ? 1 : -1; setMenu({ ...menu, active: (menu.active + d + n) % n }); return; }
if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); const it = menu.items[menu.active]; if (it) pick(it); return; }
if (e.key === 'Escape') { e.preventDefault(); dismissed.current = menu.start; setMenu(null); return; }
}
if (e.key === 'Enter' && !e.shiftKey && !e.altKey) { e.preventDefault(); submit(); return; }
// Backspace right after a mention removes the whole mention, as one token
if (e.key === 'Backspace' && !e.altKey && !e.metaKey && !e.ctrlKey) {
const t = e.currentTarget, c = t.selectionStart;
if (c === t.selectionEnd && c > 0) {
const m = picked.current.find(x => {
const tok = x.trigger + x.label, a = c - tok.length;
return a >= 0 && value.slice(a, c) === tok && (a === 0 || /\s/.test(value[a - 1] ?? '')) && (c === value.length || /\s/.test(value[c] ?? ''));
});
if (m) {
e.preventDefault();
const a = c - m.trigger.length - m.label.length;
const next = value.slice(0, a) + value.slice(c);
if (!next.includes(m.trigger + m.label)) picked.current = picked.current.filter(x => x !== m);
// delete through the editor so Cmd+Z brings the mention back; fall back to setting the value
let native = false;
try { t.setSelectionRange(a, c); native = !!t.ownerDocument.execCommand?.('delete'); } catch { native = false; }
if (!native) { setValue(next); raf(() => t.setSelectionRange(a, a)); }
setMenu(null);
say(`Removed ${m.trigger}${m.label}`);
return;
}
}
}
if (e.key === 'Escape' && busy) { e.preventDefault(); stop(); return; }
if (e.key === 'ArrowUp' && value === '' && lastSent.current) { e.preventDefault(); setValue(lastSent.current); picked.current = lastPicked.current.slice(); }
}, [menu, pick, submit, busy, stop, value, setValue, say]);
const onChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
setValue(e.target.value); syncMenu(e.target.value, e.target.selectionStart ?? e.target.value.length);
}, [setValue, syncMenu]);
const onSelect = useCallback((e: SyntheticEvent<HTMLTextAreaElement>) => {
const t = e.currentTarget; syncMenu(t.value, t.selectionStart ?? t.value.length);
}, [syncMenu]);
const onPaste = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {
const files = e.clipboardData?.files;
if (files && files.length && !e.clipboardData.getData('text/plain')) { e.preventDefault(); addFiles(files); }
}, [addFiles]);
const onBlur = useCallback(() => setMenu(null), []);
/* ---- prop getters ---- */
const getInputProps = useCallback(() => ({
ref: inputRef,
id: ids.input,
value,
onChange, onKeyDown, onSelect, onPaste, onBlur,
disabled: o.disabled,
rows: 1,
'aria-autocomplete': 'list' as const,
'aria-controls': menu ? ids.menu : undefined,
'aria-activedescendant': menu && menu.items.length ? ids.option(menu.active) : undefined,
'aria-describedby': ids.live,
}), [ids, value, onChange, onKeyDown, onSelect, onPaste, onBlur, o.disabled, menu]);
const getMenuProps = useCallback(() => ({
id: ids.menu,
role: 'listbox' as const,
'aria-label': menu?.trigger.char === '/' ? 'Commands' : 'Mentions',
}), [ids, menu]);
const getOptionProps = useCallback((i: number) => ({
id: ids.option(i),
role: 'option' as const,
'aria-selected': !!menu && menu.active === i,
onMouseDown: (e: MouseEvent) => e.preventDefault(),
onMouseMove: () => setMenu(m => (m && m.active !== i ? { ...m, active: i } : m)),
onClick: () => { const it = menu?.items[i]; if (it) pick(it); },
}), [ids, menu, pick]);
const sendMode: 'send' | 'queue' | 'stop' = busy ? ((hasText || ready.length) && o.queue !== false ? 'queue' : 'stop') : 'send';
const getSendProps = useCallback(() => ({
type: 'button' as const,
'aria-label': sendMode === 'stop' ? 'Stop' : sendMode === 'queue' ? 'Queue message' : 'Send',
disabled: sendMode === 'stop' ? false : !canSend,
onClick: () => (sendMode === 'stop' ? stop() : submit()),
}), [sendMode, canSend, stop, submit]);
const isFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types || []).includes('Files');
const getDropProps = useCallback(() => ({
'data-dragging': dragging || undefined,
onDragEnter: (e: DragEvent) => { if (!latest.current.disabled && isFiles(e)) { dragDepth.current++; setDragging(true); } },
onDragLeave: (e: DragEvent) => { if (isFiles(e) && --dragDepth.current <= 0) { dragDepth.current = 0; setDragging(false); } },
onDragOver: (e: DragEvent) => { if (!latest.current.disabled && isFiles(e)) e.preventDefault(); },
// the depth always resets; the files are only taken when your onDrop didn't call preventDefault
onDrop: (e: DragEvent) => { dragDepth.current = 0; setDragging(false); if (!e.defaultPrevented && e.dataTransfer?.files?.length) { e.preventDefault(); addFiles(e.dataTransfer.files); } },
}), [addFiles, dragging]);
return {
ids, status, busy, disabled: !!o.disabled, disabledReason: o.disabledReason, value, setValue, models: o.models ?? [], accept: o.accept, model, setModel, captain, setCaptain,
attachments, addFiles, removeAttachment, queue, removeQueued, editQueued,
menu, pick, closeMenu: () => setMenu(null), announcement, say,
/** The mentions picked from the menu that are in the text now. */
mentions: picked.current as readonly Mention[],
canSend, sendMode, submit, stop, inputRef,
/** How many messages this composer has sent; parts key a send animation on it. */
sent,
getInputProps, getMenuProps, getOptionProps, getSendProps, getDropProps,
focus: () => inputRef.current?.focus(),
};
}
export type ComposerApi = ReturnType<typeof useComposer>;// uimaxxer · Composer types, MIT. The shapes the composer takes and sends, shared by the parts, the hook and the AI SDK adapter.
/** Where a turn is. The same four states as the Vercel AI SDK's `useChat().status`. */
export type ComposerStatus = 'ready' | 'submitted' | 'streaming' | 'error';
/** Something the `@` or `/` menu can insert: an agent, a file, a skill, anything with an id. */
export interface MentionItem {
id: string;
label: string;
/** What it is. `agent`, `file` and `skill` have built-in marks; any other string works. */
kind?: 'agent' | 'file' | 'skill' | (string & {});
description?: string;
/** An agent type (`build`, `review`...) colours the mark with `--captain-type-<type>`. */
type?: string;
/** A shortcut shown at the end of the row, such as `⌘⇧S`. */
shortcut?: string;
group?: string;
}
/** A mention as it ended up in the sent text. */
export interface Mention {
id: string;
label: string;
kind: string;
trigger: string;
}
export type AttachmentStatus = 'uploading' | 'ready' | 'error';
export interface Attachment {
id: string;
name: string;
/** Bytes. */
size?: number;
/** MIME type. */
type?: string;
/** A preview or uploaded URL. Object URLs made by the composer are revoked when the attachment goes. */
url?: string;
file?: File;
status: AttachmentStatus;
error?: string;
}
export interface ModelOption {
id: string;
label: string;
/** Shown after the label in the picker, such as `medium` or `fast`. */
description?: string;
/** Matched against the built-in brand marks (`claude`, `openai`, `gemini`...). Defaults to the label. */
brand?: string;
group?: string;
/** Rough US dollars for one agent's task on this model. With it, the swarm shows what a run will cost. */
usd?: number;
}
export type Autonomy = 'ask' | 'risk' | 'full';
/** The Captain: one lead model that plans the work and fans it out to a swarm. */
export interface CaptainSettings {
/** Off: the message goes to one agent. On: the Captain plans and delegates. */
enabled: boolean;
size: number;
autonomy: Autonomy;
/** US dollars the run may spend before it stops and asks. */
budget: number;
/** Agent types the Captain may use. */
types: string[];
/** The model id the swarm's agents run on. Default: the cheapest model with a `usd`, else the picked model. */
crew?: string;
}
/** Everything a send carries. */
export interface ComposerMessage {
text: string;
mentions: Mention[];
attachments: Attachment[];
model?: string;
captain?: CaptainSettings;
/** True when this message waited in the queue while a turn ran. */
queued?: boolean;
}
export interface QueuedMessage extends ComposerMessage {
id: string;
}
/** Token and spend so far, for `Composer.Meter`. */
export interface Usage {
tokens?: number;
usd?: number;
}
export interface TriggerConfig {
/** One character, such as `@` or `/`. */
char: string;
/** A fixed list, or a function of the query (sync or async). */
items: MentionItem[] | ((query: string) => MentionItem[] | Promise<MentionItem[]>);
/** Only open at the very start of the input (slash commands). Default false. */
startOnly?: boolean;
/** How many rows to show. Default 8. */
limit?: number;
}
export interface ComposerOptions {
/** Controlled text. Pair with `onValueChange`. */
value?: string;
/** Uncontrolled starting text. */
defaultValue?: string;
onValueChange?: (value: string) => void;
/** The turn's status. Drive it from your backend, or from `useChat().status`. Default `ready`. */
status?: ComposerStatus;
/** Called with the message on send. Not called for an empty message. */
onSubmit?: (message: ComposerMessage) => void | Promise<void>;
/** Called when the person stops a running turn (the stop button, or Escape). */
onStop?: () => void;
disabled?: boolean;
/** Why it is disabled, read out and shown as the placeholder. */
disabledReason?: string;
/** Messages sent while a turn runs wait here and go out in order when it ends. Default true. */
queue?: boolean;
/** `@` mentions, `/` skills, or any other trigger characters. */
triggers?: TriggerConfig[];
models?: ModelOption[];
model?: string;
defaultModel?: string;
onModelChange?: (id: string) => void;
captain?: CaptainSettings;
defaultCaptain?: CaptainSettings;
onCaptainChange?: (settings: CaptainSettings) => void;
/** File types for the picker and drop, as in `<input accept>`. */
accept?: string;
/** Bytes. Larger files are kept but marked as errors. Default 25 MB. */
maxFileSize?: number;
maxAttachments?: number;
/** Files already attached when the composer mounts, such as a draft restored from storage. */
defaultAttachments?: Attachment[];
/** Upload a file and return its URL. Without it, files stay local (`file` and an object URL). */
upload?: (file: File) => Promise<{ url: string }>;
/** The label for the agent that is working, read out to screen readers. Default `Agent`. */
agentLabel?: string;
}
export interface MenuState {
trigger: TriggerConfig;
query: string;
/** Where the trigger character sits in the value. */
start: number;
items: MentionItem[];
active: number;
}// uimaxxer · Composer agent marks, MIT. 16x16 pixel silhouettes from composer-kit; "lit" is the part that shimmers while an agent works.
export const MARKS = {
eye: { solid: "M6 3h4v1h-4zM3 4h10v1h-10zM2 5h4v1h-4zM10 5h4v1h-4zM1 6h4v1h-4zM7 6h2v1h-2zM11 6h4v1h-4zM0 7h4v1h-4zM6 7h4v1h-4zM12 7h4v1h-4zM0 8h4v1h-4zM6 8h4v1h-4zM12 8h4v1h-4zM1 9h4v1h-4zM7 9h2v1h-2zM11 9h4v1h-4zM2 10h4v1h-4zM10 10h4v1h-4z", lit: "M3 11h10v1h-10zM6 12h4v1h-4z" },
nib: { solid: "M7 1h2v1h-2zM6 2h4v1h-4zM5 3h6v1h-6zM4 4h8v1h-8zM4 5h3v1h-3zM9 5h3v1h-3zM3 6h4v1h-4zM9 6h4v1h-4zM3 7h5v1h-5zM9 7h4v1h-4zM3 8h4v1h-4zM8 8h5v1h-5zM4 9h3v1h-3zM8 9h4v1h-4zM4 10h3v1h-3zM8 10h3v1h-3z", lit: "M5 11h6v1h-6zM5 12h6v1h-6zM5 13h6v1h-6z" },
flask: { solid: "M5 1h6v1h-6zM6 2h4v1h-4zM6 3h4v1h-4zM6 4h4v1h-4zM5 5h6v1h-6zM4 6h3v1h-3zM9 6h3v1h-3zM3 7h3v1h-3zM10 7h3v1h-3zM2 8h3v1h-3zM11 8h3v1h-3zM2 9h2v1h-2zM12 9h2v1h-2zM1 10h3v1h-3zM12 10h3v1h-3zM1 11h2v1h-2zM13 11h2v1h-2zM1 12h14v1h-14z", lit: "M4 9h8v1h-8zM4 10h8v1h-8zM3 11h10v1h-10z" },
bolt: { solid: "M9 1h4v1h-4zM8 2h4v1h-4zM7 3h4v1h-4zM6 4h4v1h-4zM5 5h4v1h-4zM4 6h10v1h-10zM3 7h10v1h-10zM8 8h4v1h-4zM7 9h4v1h-4z", lit: "M6 10h4v1h-4zM5 11h3v1h-3zM4 12h2v1h-2z" },
lens: { solid: "M4 1h6v1h-6zM3 2h8v1h-8zM2 3h3v1h-3zM9 3h3v1h-3zM2 4h2v1h-2zM10 4h2v1h-2zM2 5h2v1h-2zM10 5h2v1h-2zM2 6h2v1h-2zM10 6h2v1h-2zM2 7h3v1h-3zM9 7h3v1h-3zM3 8h8v1h-8zM4 9h7v1h-7zM9 10h3v1h-3zM10 11h3v1h-3zM11 12h3v1h-3zM12 13h2v1h-2z", lit: "M5 3h4v1h-4zM4 4h6v1h-6zM4 5h6v1h-6zM4 6h6v1h-6zM5 7h4v1h-4z" },
shield: { solid: "M2 1h12v1h-12zM2 2h2v1h-2zM10 2h4v1h-4zM2 3h2v1h-2zM10 3h4v1h-4zM2 4h2v1h-2zM10 4h4v1h-4zM2 5h2v1h-2zM10 5h4v1h-4zM2 6h3v1h-3zM10 6h4v1h-4zM3 7h2v1h-2zM10 7h3v1h-3zM3 8h3v1h-3zM10 8h3v1h-3zM4 9h2v1h-2zM10 9h2v1h-2zM5 10h2v1h-2zM9 10h2v1h-2zM6 11h4v1h-4zM7 12h2v1h-2z", lit: "M4 2h6v1h-6zM4 3h6v1h-6zM4 4h6v1h-6zM4 5h6v1h-6zM5 6h5v1h-5zM5 7h5v1h-5zM6 8h4v1h-4zM6 9h4v1h-4zM7 10h2v1h-2z" },
leaf: { solid: "M12 1h2v1h-2zM9 2h5v1h-5zM6 3h8v1h-8zM4 4h10v1h-10zM3 5h3v1h-3zM8 5h6v1h-6zM2 6h3v1h-3zM7 6h7v1h-7zM2 7h2v1h-2zM6 7h7v1h-7zM2 8h2v1h-2zM5 8h7v1h-7zM2 9h1v1h-1zM4 9h6v1h-6zM1 10h1v1h-1zM4 10h4v1h-4zM0 11h1v1h-1z", lit: "M6 5h2v1h-2zM5 6h2v1h-2zM4 7h2v1h-2zM4 8h1v1h-1z" },
cube: { solid: "M2 6h2v1h-2zM12 6h2v1h-2zM2 7h4v1h-4zM10 7h4v1h-4zM2 8h6v1h-6zM9 8h6v1h-6zM2 9h6v1h-6zM9 9h6v1h-6zM2 10h6v1h-6zM9 10h6v1h-6zM2 11h6v1h-6zM9 11h6v1h-6zM3 12h5v1h-5zM9 12h5v1h-5zM5 13h3v1h-3zM9 13h3v1h-3z", lit: "M7 2h2v1h-2zM5 3h6v1h-6zM3 4h10v1h-10zM2 5h12v1h-12zM4 6h8v1h-8zM6 7h4v1h-4z" },
captain: { solid: "M7 0h2v1h-2zM7 1h2v1h-2zM2 2h1v1h-1zM7 2h2v1h-2zM13 2h1v1h-1zM3 3h1v1h-1zM7 3h2v1h-2zM12 3h1v1h-1zM4 4h1v1h-1zM6 4h4v1h-4zM11 4h1v1h-1zM5 5h6v1h-6zM4 6h3v1h-3zM9 6h3v1h-3zM0 7h7v1h-7zM9 7h7v1h-7zM0 8h7v1h-7zM9 8h7v1h-7zM4 9h3v1h-3zM9 9h3v1h-3zM5 10h6v1h-6zM4 11h1v1h-1zM6 11h4v1h-4zM11 11h1v1h-1zM3 12h1v1h-1zM7 12h2v1h-2zM12 12h1v1h-1zM2 13h1v1h-1zM7 13h2v1h-2zM13 13h1v1h-1zM7 14h2v1h-2zM7 15h2v1h-2z", lit: "M7 6h2v1h-2zM7 7h2v1h-2zM7 8h2v1h-2zM7 9h2v1h-2z" },
person: { solid: "M6 1h4v1h-4zM5 2h6v1h-6zM5 3h6v1h-6zM5 4h6v1h-6zM6 5h4v1h-4zM3 7h10v1h-10zM2 8h12v1h-12zM2 9h4v1h-4zM10 9h4v1h-4zM2 10h3v1h-3zM11 10h3v1h-3zM2 11h2v1h-2zM12 11h2v1h-2zM2 12h12v1h-12z", lit: "M6 9h4v1h-4zM5 10h6v1h-6zM4 11h8v1h-8z" },
} as const;
export type MarkName = keyof typeof MARKS;
/** Which mark an agent type uses. */
export const TYPE_MARK: Record<string, MarkName> = { captain: "captain", review: "eye", design: "nib", tests: "flask", ship: "bolt", research: "lens", security: "shield", docs: "leaf", build: "cube" };
/** Each agent type's colour, readable on the surface in both themes. Override with `--captain-type-<type>`. */
export const TYPE_COLOR: Record<string, string> = {
captain: "var(--captain-type-captain, var(--captain-ink))",
build: "var(--captain-type-build, light-dark(#0E7C86, #3CC4CF))",
design: "var(--captain-type-design, light-dark(#C2410C, #FF8A57))",
tests: "var(--captain-type-tests, light-dark(#1E8A4C, #4FCB83))",
review: "var(--captain-type-review, light-dark(#2E5BFF, #7D9BFF))",
docs: "var(--captain-type-docs, light-dark(#8A6A12, #E0B94A))",
research: "var(--captain-type-research, light-dark(#4E5BA6, #9AA6EE))",
security: "var(--captain-type-security, light-dark(#A63A9C, #E77EDC))",
ship: "var(--captain-type-ship, light-dark(#A86F00, #F0B53E))",
};// uimaxxer · Composer brand marks, MIT. Real marks for models and connectors, from composer-kit (see its kit/BRANDS.md for sources and terms).
/** Import only the marks you show, or BRANDS for all of them. Each is a few hundred bytes gzipped. */
export interface Brand { key: string; match: RegExp; viewBox?: string; dark?: boolean; svg: string }
export const claude: Brand = { key: "claude", match: /anthropic|claude|opus|sonnet|haiku/i, svg: "<path fill=\"#D97757\" d=\"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z\"/>" };
export const openai: Brand = { key: "openai", match: /openai|gpt|\bo\d/i, svg: "<path fill=\"currentColor\" d=\"M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z\"/>" };
export const gmail: Brand = { key: "gmail", match: /gmail/i, svg: "<path fill=\"#EA4335\" d=\"M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z\"/>" };
export const googledrive: Brand = { key: "googledrive", match: /google ?drive|gdrive/i, svg: "<path fill=\"#4285F4\" d=\"M12.01 1.485c-2.082 0-3.754.02-3.743.047.01.02 1.708 3.001 3.774 6.62l3.76 6.574h3.76c2.081 0 3.753-.02 3.742-.047-.005-.02-1.708-3.001-3.775-6.62l-3.76-6.574zm-4.76 1.73a789.828 789.861 0 0 0-3.63 6.319L0 15.868l1.89 3.298 1.885 3.297 3.62-6.335 3.618-6.33-1.88-3.287C8.1 4.704 7.255 3.22 7.25 3.214zm2.259 12.653-.203.348c-.114.198-.96 1.672-1.88 3.287a423.93 423.948 0 0 1-1.698 2.97c-.01.026 3.24.042 7.222.042h7.244l1.796-3.157c.992-1.734 1.85-3.23 1.906-3.323l.104-.167h-7.249z\"/>" };
export const gemini: Brand = { key: "gemini", match: /gemini|google/i, svg: "<path d=\"M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z\" fill=\"#3186FF\"/><path d=\"M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z\" fill=\"url(#ck-gm-0)\"/><path d=\"M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z\" fill=\"url(#ck-gm-1)\"/><path d=\"M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z\" fill=\"url(#ck-gm-2)\"/><defs><linearGradient gradientUnits=\"userSpaceOnUse\" id=\"ck-gm-0\" x1=\"7\" x2=\"11\" y1=\"15.5\" y2=\"12\"><stop stop-color=\"#08B962\"/><stop offset=\"1\" stop-color=\"#08B962\" stop-opacity=\"0\"/></linearGradient><linearGradient gradientUnits=\"userSpaceOnUse\" id=\"ck-gm-1\" x1=\"8\" x2=\"11.5\" y1=\"5.5\" y2=\"11\"><stop stop-color=\"#F94543\"/><stop offset=\"1\" stop-color=\"#F94543\" stop-opacity=\"0\"/></linearGradient><linearGradient gradientUnits=\"userSpaceOnUse\" id=\"ck-gm-2\" x1=\"3.5\" x2=\"17.5\" y1=\"13.5\" y2=\"12\"><stop stop-color=\"#FABC12\"/><stop offset=\".46\" stop-color=\"#FABC12\" stop-opacity=\"0\"/></linearGradient></defs>" };
export const xai: Brand = { key: "xai", match: /xai|x\.ai|grok/i, svg: "<path fill=\"currentColor\" d=\"M6.469 8.776L16.512 23h-4.464L2.005 8.776H6.47zm-.004 7.9l2.233 3.164L6.467 23H2l4.465-6.324zM22 2.582V23h-3.659V7.764L22 2.582zM22 1l-9.952 14.095-2.233-3.163L17.533 1H22z\"/>" };
export const mistral: Brand = { key: "mistral", match: /mistral/i, svg: "<path d=\"M3.428 3.4h3.429v3.428H3.428V3.4zm13.714 0h3.43v3.428h-3.43V3.4z\" fill=\"gold\"/><path d=\"M3.428 6.828h6.857v3.429H3.429V6.828zm10.286 0h6.857v3.429h-6.857V6.828z\" fill=\"#FFAF00\"/><path d=\"M3.428 10.258h17.144v3.428H3.428v-3.428z\" fill=\"#FF8205\"/><path d=\"M3.428 13.686h3.429v3.428H3.428v-3.428zm6.858 0h3.429v3.428h-3.429v-3.428zm6.856 0h3.43v3.428h-3.43v-3.428z\" fill=\"#FA500F\"/><path d=\"M0 17.114h10.286v3.429H0v-3.429zm13.714 0H24v3.429H13.714v-3.429z\" fill=\"#E10500\"/>" };
export const deepseek: Brand = { key: "deepseek", match: /deepseek/i, svg: "<path d=\"M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z\" fill=\"#4D6BFE\"/>" };
export const github: Brand = { key: "github", match: /github/i, dark: true, svg: "<path fill=\"#181717\" d=\"M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12\"/>" };
export const gitlab: Brand = { key: "gitlab", match: /gitlab/i, svg: "<path fill=\"#FC6D26\" d=\"m23.6004 9.5927-.0337-.0862L20.3.9814a.851.851 0 0 0-.3362-.405.8748.8748 0 0 0-.9997.0539.8748.8748 0 0 0-.29.4399l-2.2055 6.748H7.5375l-2.2057-6.748a.8573.8573 0 0 0-.29-.4412.8748.8748 0 0 0-.9997-.0537.8585.8585 0 0 0-.3362.4049L.4332 9.5015l-.0325.0862a6.0657 6.0657 0 0 0 2.0119 7.0105l.0113.0087.03.0213 4.976 3.7264 2.462 1.8633 1.4995 1.1321a1.0085 1.0085 0 0 0 1.2197 0l1.4995-1.1321 2.4619-1.8633 5.006-3.7489.0125-.01a6.0682 6.0682 0 0 0 2.0094-7.003z\"/>" };
export const linear: Brand = { key: "linear", match: /linear/i, svg: "<path fill=\"#5E6AD2\" d=\"M2.886 4.18A11.982 11.982 0 0 1 11.99 0C18.624 0 24 5.376 24 12.009c0 3.64-1.62 6.903-4.18 9.105L2.887 4.18ZM1.817 5.626l16.556 16.556c-.524.33-1.075.62-1.65.866L.951 7.277c.247-.575.537-1.126.866-1.65ZM.322 9.163l14.515 14.515c-.71.172-1.443.282-2.195.322L0 11.358a12 12 0 0 1 .322-2.195Zm-.17 4.862 9.823 9.824a12.02 12.02 0 0 1-9.824-9.824Z\"/>" };
export const sentry: Brand = { key: "sentry", match: /sentry/i, dark: true, svg: "<path fill=\"#362D59\" d=\"M13.91 2.505c-.873-1.448-2.972-1.448-3.844 0L6.904 7.92a15.478 15.478 0 0 1 8.53 12.811h-2.221A13.301 13.301 0 0 0 5.784 9.814l-2.926 5.06a7.65 7.65 0 0 1 4.435 5.848H2.194a.365.365 0 0 1-.298-.534l1.413-2.402a5.16 5.16 0 0 0-1.614-.913L.296 19.275a2.182 2.182 0 0 0 .812 2.999 2.24 2.24 0 0 0 1.086.288h6.983a9.322 9.322 0 0 0-3.845-8.318l1.11-1.922a11.47 11.47 0 0 1 4.95 10.24h5.915a17.242 17.242 0 0 0-7.885-15.28l2.244-3.845a.37.37 0 0 1 .504-.13c.255.14 9.75 16.708 9.928 16.9a.365.365 0 0 1-.327.543h-2.287c.029.612.029 1.223 0 1.831h2.297a2.206 2.206 0 0 0 1.922-3.31z\"/>" };
export const figma: Brand = { key: "figma", match: /figma/i, svg: "<path d=\"M4 20a4 4 0 014-4h4v4a4 4 0 01-8 0z\" fill=\"#24CB71\"/><path d=\"M12 0v8h4a4 4 0 000-8h-4z\" fill=\"#FF7237\"/><path d=\"M15.967 16a4 4 0 100-8 4 4 0 000 8z\" fill=\"#00B6FF\"/><path d=\"M4 4a4 4 0 004 4h4V0H8a4 4 0 00-4 4z\" fill=\"#FF3737\"/><path d=\"M4 12a4 4 0 004 4h4V8H8a4 4 0 00-4 4z\" fill=\"#874FFF\"/>" };
export const notion: Brand = { key: "notion", match: /notion/i, dark: true, svg: "<path fill=\"#000000\" d=\"M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z\"/>" };
export const vercel: Brand = { key: "vercel", match: /vercel/i, dark: true, svg: "<path fill=\"#000000\" d=\"m12 1.608 12 20.784H0Z\"/>" };
export const jira: Brand = { key: "jira", match: /jira/i, svg: "<path fill=\"#0052CC\" d=\"M11.571 11.513H0a5.218 5.218 0 0 0 5.232 5.215h2.13v2.057A5.215 5.215 0 0 0 12.575 24V12.518a1.005 1.005 0 0 0-1.005-1.005zm5.723-5.756H5.736a5.215 5.215 0 0 0 5.215 5.214h2.129v2.058a5.218 5.218 0 0 0 5.215 5.214V6.758a1.001 1.001 0 0 0-1.001-1.001zM23.013 0H11.455a5.215 5.215 0 0 0 5.215 5.215h2.129v2.057A5.215 5.215 0 0 0 24 12.483V1.005A1.001 1.001 0 0 0 23.013 0Z\"/>" };
export const discord: Brand = { key: "discord", match: /discord/i, svg: "<path fill=\"#5865F2\" d=\"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z\"/>" };
export const stripe: Brand = { key: "stripe", match: /stripe/i, svg: "<path fill=\"#635BFF\" d=\"M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z\"/>" };
export const supabase: Brand = { key: "supabase", match: /supabase/i, svg: "<path fill=\"#3FCF8E\" d=\"M11.9 1.036c-.015-.986-1.26-1.41-1.874-.637L.764 12.05C-.33 13.427.65 15.455 2.409 15.455h9.579l.113 7.51c.014.985 1.259 1.408 1.873.636l9.262-11.653c1.093-1.375.113-3.403-1.645-3.403h-9.642z\"/>" };
export const slack: Brand = { key: "slack", match: /slack/i, viewBox: "0 0 128 128", svg: "<path d=\"M27.255 80.719c0 7.33-5.978 13.317-13.309 13.317C6.616 94.036.63 88.049.63 80.719s5.987-13.317 13.317-13.317h13.309zm6.709 0c0-7.33 5.987-13.317 13.317-13.317s13.317 5.986 13.317 13.317v33.335c0 7.33-5.986 13.317-13.317 13.317-7.33 0-13.317-5.987-13.317-13.317zm0 0\" fill=\"#E01E5A\"/><path d=\"M47.281 27.255c-7.33 0-13.317-5.978-13.317-13.309C33.964 6.616 39.951.63 47.281.63s13.317 5.987 13.317 13.317v13.309zm0 6.709c7.33 0 13.317 5.987 13.317 13.317s-5.986 13.317-13.317 13.317H13.946C6.616 60.598.63 54.612.63 47.281c0-7.33 5.987-13.317 13.317-13.317zm0 0\" fill=\"#36C5F0\"/><path d=\"M100.745 47.281c0-7.33 5.978-13.317 13.309-13.317 7.33 0 13.317 5.987 13.317 13.317s-5.987 13.317-13.317 13.317h-13.309zm-6.709 0c0 7.33-5.987 13.317-13.317 13.317s-13.317-5.986-13.317-13.317V13.946C67.402 6.616 73.388.63 80.719.63c7.33 0 13.317 5.987 13.317 13.317zm0 0\" fill=\"#2EB67D\"/><path d=\"M80.719 100.745c7.33 0 13.317 5.978 13.317 13.309 0 7.33-5.987 13.317-13.317 13.317s-13.317-5.987-13.317-13.317v-13.309zm0-6.709c-7.33 0-13.317-5.987-13.317-13.317s5.986-13.317 13.317-13.317h33.335c7.33 0 13.317 5.986 13.317 13.317 0 7.33-5.987 13.317-13.317 13.317zm0 0\" fill=\"#ECB22E\"/>" };
export const BRANDS: Brand[] = [claude, openai, gmail, googledrive, gemini, xai, mistral, deepseek, github, gitlab, linear, sentry, figma, notion, vercel, jira, discord, stripe, supabase, slack];
export const findBrand = (name: string | undefined, brands: readonly Brand[]): Brand | undefined => (name ? brands.find(b => b.match.test(name)) : undefined);// uimaxxer · Composer adapter for the Vercel AI SDK, MIT. `fromChat(useChat())` wires status, send and stop.
import type { Attachment, ComposerMessage, ComposerOptions } from './composer-types';
/**
* The part of the Vercel AI SDK's `useChat()` result the composer needs. Typed by shape, so this file has no
* dependency on `ai` or `@ai-sdk/react`, and any chat hook with the same shape works.
*/
export interface ChatLike {
status: 'submitted' | 'streaming' | 'ready' | 'error';
sendMessage: (message: { text: string; files?: FilePart[] }, options?: { body?: object; headers?: Record<string, string> }) => unknown;
stop: () => unknown;
}
/** The AI SDK's `FileUIPart`. */
export interface FilePart {
type: 'file';
mediaType: string;
filename?: string;
url: string;
}
const dataUrl = (f: File) => new Promise<string>((res, rej) => {
const r = new FileReader();
r.onload = () => res(String(r.result)); r.onerror = () => rej(r.error); r.readAsDataURL(f);
});
/** Files become AI SDK file parts. Uploaded files keep their URL; local files go as data URLs. */
export async function toFileParts(attachments: Attachment[]): Promise<FilePart[]> {
return Promise.all(attachments.map(async a => ({
type: 'file' as const,
mediaType: a.type || 'application/octet-stream',
filename: a.name,
url: a.url && !a.url.startsWith('blob:') ? a.url : a.file ? await dataUrl(a.file) : '',
}))).then(parts => parts.filter(p => p.url));
}
export interface FromChatOptions {
/** Extra request body per message. The model, the Captain settings and the mentions are always sent. */
body?: (message: ComposerMessage) => object;
headers?: Record<string, string>;
}
/**
* Wire a composer to `useChat()`:
*
* const chat = useChat();
* <Composer.Root {...fromChat(chat)} />
*
* Status, send and stop come from the chat. Each message goes out as text plus file parts, and the body carries
* `{ model, captain, mentions }` for your route handler.
*/
export function fromChat(chat: ChatLike, o: FromChatOptions = {}): Pick<ComposerOptions, 'status' | 'onSubmit' | 'onStop'> {
return {
status: chat.status,
onStop: () => { chat.stop(); },
onSubmit: async (m: ComposerMessage) => {
const files = m.attachments.length ? await toFileParts(m.attachments) : undefined;
await chat.sendMessage({ text: m.text, files }, {
headers: o.headers,
body: { model: m.model, captain: m.captain, mentions: m.mentions, ...(o.body ? o.body(m) : {}) },
});
},
};
}Usage
import { CaptainComposer, fromChat } from "@/components/ui/composer"
import { useChat } from "@ai-sdk/react"
const chat = useChat()
<CaptainComposer
{...fromChat(chat)}
models={[
{ id: "opus", label: "Opus 5.5" },
{ id: "sonnet", label: "Sonnet 5.5" },
]}
triggers={[
{ char: "@", items: agents },
{ char: "/", items: skills, startOnly: true },
]}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| onSubmit | (message: ComposerMessage) => void | Promise<void> | Text, mentions, attachments, the model and the Captain settings. A rejected promise puts the message back. | |
| status | "ready" | "submitted" | "streaming" | "error" | "ready" | The same four states as useChat().status. Busy turns Send into Stop. |
| onStop | () => void | Stop, or Escape while it works. | |
| models | { id; label; brand?; description?; usd? }[] | The model picker, with real provider marks. usd is kept as data for your thread (planSwarm returns the estimate); the composer shows no money. | |
| captain | { enabled; size; autonomy; budget; types; crew? } | Controlled Captain settings; pair with onCaptainChange. crew is the model id the agents run on. | |
| defaultCaptain | CaptainSettings | on, 12 agents, $2 | Uncontrolled starting settings. |
| triggers | { char; items; startOnly?; limit? }[] | @ mentions and / skills. items is a list or a (query) => items function, sync or async. | |
| value / defaultValue | string | Controlled or starting text. Mentions in a starting text are marked. | |
| defaultAttachments | Attachment[] | Files already attached, such as a restored draft. | |
| upload | (file: File) => Promise<{ url }> | Upload as files are added. Without it, files stay local. | |
| queue | boolean | true | Messages sent while it works wait and go out in order. |
| placeholder | string | Ask the Captain / Ask <model> | While it works the field reads Add to the task. |
| noCaptain | boolean | false | Hide the Captain switch and its swarm. |
Keyboard
- Enter
- Send
- Shift+Enter
- New line
- @ and /
- Open mentions or skills
- ↑ ↓ then Enter or Tab
- Pick a mention
- Backspace after a mention
- Remove it whole
- Escape
- Close the menu, or stop the turn
- ↑ in an empty field
- Bring back the last message
Accessibility
- A labelled textarea with a listbox for mentions (aria-activedescendant), so IME, spellcheck and screen readers behave natively.
- The Captain is a real switch named Captain; the swarm is read once as one sentence: who leads, how many agents and on which model.
- The model picker and the Captain settings are a listbox and a dialog with arrow keys, Escape and focus returned to their buttons.
- Sends, stops, queued messages and errors are announced in a polite live region.
- Reduced motion fades the swarm in place instead of dealing it.