Composer field
FreeThe chat box of an AI agent: files, your words, tools, the model with its effort, dictation and send, with folder, branch and permission below. Messages sent while it works wait in order.
npx shadcn@latest add https://pixilui.com/r/composer-field.jsonPreview
import { ComposerFieldChat } from "@/components/pixilui/composer-field";
import { useComposerSimulation } from "@/components/pixilui/composer-field.examples";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
notices: ["in", "above"],
} as const;
/**
* The composer in a chat, playing the locked page's run: ask why checkout fails, queue two follow-ups while the agent works,
* press Stop and they fly back into the box. Every menu is live: tools, connectors, the model with its effort, permission,
* folder, branch, / commands and @ files.
*/
export default function ComposerFieldDemo({ notices = "in" }: KnobValues<typeof knobs>) {
const sim = useComposerSimulation();
return (
<div className="flex h-[560px] w-full max-w-2xl flex-col">
<ComposerFieldChat {...sim} noticePlace={notices} />
</div>
);
}When to use
Use it when
- The box of a chat with an agent that works in steps: <ComposerFieldChat> for the thread and the queue, or <ComposerField> alone under your own thread.
- Pick the model and its effort, turn tools on, attach files, mention files with @ and run commands with /.
- Say where the agent works (folder, branch) and what it may do (ask, auto-approve edits, read only).
Use something else when
- A plain search or a one-line field: use the search field or the input.
- A box that only sends and stops: use the prompt input.
Installation
npx shadcn@latest add https://pixilui.com/r/composer-field.jsonAdds composer-field.tsx with button.tsx, chip.tsx, dropdown-menu.tsx, text-shimmer.tsx, kbd.tsx, tooltip.tsx, meter.tsx and usage-meter.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
"use client";
/*
The composer (H2, locked 29 Nov 2026; the Think shimmer and the folded trail 30 Nov; the tooltip family 1 Dec): the chat box
of an AI agent. design/explorations/components/locked/composer, its composer.js ported to React. The look is foundation.css
section 8 (.pixilui-composer-*), ported from composer.css and proven on the locked page.
ComposerField the box and the tray: files, your words, the tools that are on, the model with its effort, dictation and
send; under it the folder, the branch, context past 70% and what the agent may do. Every menu is the locked
dropdown (the library's DropdownMenu, opening upward); / and @ open typed menus at the caret.
ComposerFieldChat the chat: the thread (your messages, the agent's turns, the approval card, the long-run line, the answer
and its actions) over the field, and the queue. Keep typing while the agent works: each message waits in
the thread in order, and Stop puts them all back in the box, flying back the way they came.
Plain data in, events out: no model calls inside. status uses the Vercel AI SDK's names (submitted, streaming, ready,
error) in our own type. Every word is in `words`, every icon in `icons`.
Motion is the lock's: your words fly into the thread (380ms, an in-out cubic that follows a target that can move:
the one curve that can't be CSS), the first message glides the box from the middle (560ms), Stop flies waiting messages
back lowest first (80ms apart, 420ms each), the send sweep, the approval card's arrival glow, the effort ramp's sweep and
breathing, rows that open as grid rows, file tiles that arrive, fill their ring and resolve into a check. Every duration
and curve is read from the foundation's tokens. Reduced motion: everything lands at once.
*/
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
type ClipboardEvent,
type CSSProperties,
type KeyboardEvent,
type ReactElement,
type ReactNode,
} from "react";
import { createPortal, flushSync } from "react-dom";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";
import { Button } from "./button";
import { Chip } from "./chip";
import { DropdownMenu, glideMenu, hideMenu, showMenu, type DropdownMenuGroup, type DropdownMenuRow } from "./dropdown-menu";
import { TextShimmer } from "./text-shimmer";
import { Tooltip } from "./tooltip";
import { UsageMeterWindow } from "./usage-meter";
import { safeAnimate } from "./lib/motion/animate";
/* ------------------------------------------------------------------ data */
/** The chat's status, by the Vercel AI SDK's names: submitted and streaming are the agent at work. */
export type ComposerStatus = "submitted" | "streaming" | "ready" | "error";
/** A file tile's kind: a picture shows itself; the rest show their kind's icon. */
export type ComposerFileKind = "img" | "pdf" | "code" | "sheet" | "pr" | "doc" | "paste" | "drive";
export type ComposerFile = {
/** Stable id: what onRemoveFile and onRetryFile report. */
id: string;
/** The file's name ("trace.pdf"). */
name: string;
/** Its size or extent, as words ("1.2 MB", "14 pages"). */
size: string;
/** Its kind; worked out from the name when left out. */
kind?: ComposerFileKind;
/** up while it uploads (the ring fills), done, or failed (it says why, with Retry). */
state?: "up" | "done" | "failed";
/** Upload progress, 0 to 1. */
progress?: number;
/** Why it failed ("Too large to read"). */
reason?: string;
/** A picture's thumbnail, as a CSS image ("url(...)"). */
thumb?: string;
};
/** A row in one of the composer's menus: a source, a tool, a connector, a model, a permission, a folder, a command. */
export type ComposerOption = {
/** Stable id: what the menu reports. */
id: string;
/** The row's words. */
label: string;
/** A second line ("Fast and capable"). */
description?: string;
/** Its icon or the product's mark. */
icon?: ReactNode;
};
/** A tool that turns on from the + menu and shows as a chip in the bar. */
export type ComposerTool = ComposerOption & {
/** The chip's short name ("Search", "Think"). */
chip: string;
/** shimmer: the chip's word wears the locked text shimmer, color style (Think). */
shimmer?: boolean;
};
/** A connector in the + menu's Connectors submenu. */
export type ComposerConnector = ComposerOption & {
/** Its switch, on or off. */
on: boolean;
/** Signed out: it says so in the warning color, and picking it reconnects in place. */
signedOut?: boolean;
/** Reconnecting now: its second line says so. */
reconnecting?: boolean;
};
/** A notice in the box: something went wrong, a limit, or the connection. */
export type ComposerNotice = "fail" | "limit" | "offline" | "online" | "mic" | "busy";
/** What a send carries. */
export type ComposerMessageDraft = {
/** The words, trimmed. */
text: string;
/** Words quoted from a reply. */
quote?: string;
/** The finished files. */
files: ComposerFile[];
};
/** The effort levels, low to high. */
export type ComposerEffort = 0 | 1 | 2 | 3;
/* ------------------------------------------------------------------ words and icons */
/** Every word the composer says. */
export type ComposerWords = {
placeholder: string;
placeholderFollowUp: string;
placeholderWorking: string;
message: string;
messageDescription: string;
add: string;
connectors: string;
connectorsReconnect: string;
connectorSignedOut: string;
connectorReconnecting: string;
connectorsBrowse: string;
connectorsManage: string;
modelMenu: string;
modelLabel: (model: string, effort: string) => string;
effort: string;
efforts: [string, string, string, string];
effortCosts: [string, string, string, string];
permissionMenu: string;
folder: string;
folderRecent: string;
folderOpen: string;
branch: string;
branches: string;
branchFind: string;
branchNone: string;
branchNew: string;
commands: string;
commandsNone: string;
files: string;
filesNone: string;
dictate: string;
dictateStop: string;
send: string;
queue: string;
stop: string;
reasonEmpty: string;
reasonTooLong: string;
reasonUploading: string;
reasonLimit: string;
reasonReturning: string;
removeQuote: string;
removeFile: string;
cancelUpload: string;
removeFileLabel: (name: string) => string;
cancelUploadLabel: (name: string) => string;
retry: string;
turnOff: string;
turnOffLabel: (tool: string) => string;
drop: string;
readOnly: string;
readOnlyContinue: string;
context: string;
compact: string;
count: (n: number, max: number) => string;
noticeOver: string;
noticeFail: string;
noticeLimit: string;
noticeUpgrade: string;
noticeOffline: string;
noticeOnline: string;
noticeMic: string;
noticeBusy: (model: string) => string;
noticeUseModel: (model: string) => string;
noticeTryAgain: string;
kinds: Partial<Record<ComposerFileKind, string>>;
progress: (pct: number, size: string) => string;
};
export const composerWords: ComposerWords = {
placeholder: "Ask anything",
placeholderFollowUp: "Ask a follow-up",
placeholderWorking: "Queue a follow-up",
message: "Message",
messageDescription: "Enter sends. Shift Enter adds a line. Slash opens commands, at mentions a file.",
add: "Add files and tools",
connectors: "Connectors",
connectorsReconnect: "1 needs reconnection",
connectorSignedOut: "Signed out · Reconnect",
connectorReconnecting: "Reconnecting…",
connectorsBrowse: "Browse connectors",
connectorsManage: "Manage connectors",
modelMenu: "Model",
modelLabel: (m, e) => `Model: ${m}, ${e} effort`,
effort: "Effort",
efforts: ["Low", "Medium", "High", "Max"],
effortCosts: ["About 2s", "About 8s", "About 25s", "About 1 min, more usage"],
permissionMenu: "What the agent may do",
folder: "Folder",
folderRecent: "Recent folders",
folderOpen: "Open a folder",
branch: "Branch",
branches: "Branches",
branchFind: "Find a branch",
branchNone: "No branch matches",
branchNew: "New branch",
commands: "Commands",
commandsNone: "No commands match",
files: "Files",
filesNone: "No files match",
dictate: "Dictate",
dictateStop: "Stop dictating",
send: "Send",
queue: "Queue message",
stop: "Stop",
reasonEmpty: "Type a message to send",
reasonTooLong: "Too long to send",
reasonUploading: "Sends when the uploads finish",
reasonLimit: "You've used today's messages",
reasonReturning: "Your messages are coming back",
removeQuote: "Remove quote",
removeFile: "Remove",
cancelUpload: "Cancel upload",
removeFileLabel: (n) => `Remove ${n}`,
cancelUploadLabel: (n) => `Cancel upload of ${n}`,
retry: "Retry",
turnOff: "Turn off",
turnOffLabel: (t) => `Turn off ${t}`,
drop: "Drop files to add them",
readOnly: "You're viewing a shared chat",
readOnlyContinue: "Continue this chat",
context: "Context",
compact: "Compact",
count: (n, max) => `${n.toLocaleString("en-US")} / ${max.toLocaleString("en-US")}`,
noticeOver: "Too long to send. Shorten it, or attach it as a file.",
noticeFail: "Couldn't send. Your message is still here.",
noticeLimit: "Daily limit reached. It resets at 4:00 PM.",
noticeUpgrade: "Upgrade",
noticeOffline: "You’re offline. Messages send when you’re back.",
noticeOnline: "Back online.",
noticeMic: "Your microphone is blocked. Allow it for this site in your browser, then try again.",
noticeBusy: (m) => `${m} is busy right now. Your message is still here.`,
noticeUseModel: (m) => `Use ${m}`,
noticeTryAgain: "Try again",
kinds: { pdf: "PDF", code: "Code", sheet: "Sheet", pr: "GitHub", doc: "Doc", drive: "Drive" },
progress: (pct, size) => `${pct}% of ${size}`,
};
/** The icons the composer draws (the house's animated icons in the demos; any icon works). */
export type ComposerIcons = {
/** The + button (add). */
add: ReactNode;
/** Remove: a cross. */
remove: ReactNode;
/** A menu trigger's chevron (arrow down). */
chevron: ReactNode;
/** Send's arrow; in stop mode it turns into the square (the send-stop icon does both). */
send: ReactNode;
/** The mic. */
mic: ReactNode;
/** A finished upload's check. */
check: ReactNode;
/** A notice that something went wrong. */
alert: ReactNode;
/** A limit or a wait. */
clock: ReactNode;
/** Offline. */
offline: ReactNode;
/** Back online. */
online: ReactNode;
/** Connectors. */
plug: ReactNode;
/** Browse connectors (search). */
search: ReactNode;
/** Manage connectors. */
settings: ReactNode;
/** The folder. */
folder: ReactNode;
/** The branch. */
branch: ReactNode;
/** A new folder or branch. */
newItem: ReactNode;
/** A shared chat, read-only. */
view: ReactNode;
/** A file's kind tile, by kind. */
kinds: Partial<Record<ComposerFileKind, ReactNode>>;
/** A mentioned file in the field. */
file: ReactNode;
};
/** The icon slot's class (.pixilui-i), added to an icon the composer is given, as the locked page draws its icons. */
function slot(node: ReactNode, extra?: string): ReactNode {
if (!node || typeof node !== "object" || !("props" in (node as ReactElement))) return node;
const el = node as ReactElement<{ className?: string }>;
return { ...el, props: { ...el.props, className: cn("pixilui-i", extra, el.props.className) } } as ReactElement;
}
/* ------------------------------------------------------------------ helpers */
const ERR: (ComposerNotice | "over")[] = ["over", "fail", "limit", "offline", "online", "mic", "busy"];
const KIND = (name: string): ComposerFileKind =>
/\.(png|jpe?g|gif|webp)$/i.test(name) ? "img" : /\.pdf$/i.test(name) ? "pdf" : /\.(ts|tsx|js|py|go|rb|css|json)$/i.test(name) ? "code" : /\.(csv|xlsx)$/i.test(name) ? "sheet" : /^#|pull request/i.test(name) ? "pr" : "doc";
/** Reads a token on the element: a duration in ms, or a number. */
const num = (el: Element | null, name: string) => (el ? parseFloat(getComputedStyle(el).getPropertyValue(name)) || 0 : 0);
const tok = (el: Element | null, name: string) => (el ? getComputedStyle(el).getPropertyValue(name).trim() : "");
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function caretToEnd(node: HTMLElement) {
const s = getSelection();
if (!s) return;
const r = document.createRange();
r.selectNodeContents(node);
r.collapse(false);
s.removeAllRanges();
s.addRange(r);
}
const textOf = (input: HTMLElement | null) => (input ? (input.innerText ?? input.textContent ?? "").replace(/\u00a0/g, " ").replace(/\n$/, "") : "");
const innerRect = (n: Element) => {
const r = n.getBoundingClientRect();
const cs = getComputedStyle(n);
return { left: r.left + parseFloat(cs.paddingLeft), top: r.top + parseFloat(cs.paddingTop), width: r.width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight) };
};
/**
* Flies a copy of `text` from a rectangle to a target re-measured every frame (composer.js fly): an in-out cubic on its
* own clock, the one curve here that can't be CSS. Resolves with the ghost when `keep` (the caller removes it), else removes it.
*/
export function composerFly(
text: string,
from: { left: number; top: number; width: number },
fromStyle: { fontSize: string; lineHeight: string },
to: () => { left: number; top: number; width?: number },
ms: number,
o: { toOpacity?: number; fromOpacity?: number; keep?: boolean } = {},
): Promise<HTMLElement | void> {
if (prefersReducedMotion()) return Promise.resolve();
const toOpacity = o.toOpacity ?? 1;
const fromOpacity = o.fromOpacity ?? 1;
const g = document.createElement("div");
g.className = "pixilui-composer-ghost";
g.textContent = text;
g.style.cssText += `left:${from.left}px;top:${from.top}px;width:${from.width}px;font-size:${fromStyle.fontSize};line-height:${fromStyle.lineHeight}`;
document.body.appendChild(g);
const ease = (k: number) => (k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2);
const t0 = performance.now();
return new Promise((res) => {
const frame = (now: number) => {
const k = Math.min(1, (now - t0) / ms);
const e = ease(k);
const d = to();
g.style.transform = `translate(${(d.left - from.left) * e}px,${(d.top - from.top) * e}px)`;
if (d.width) g.style.width = `${from.width + (d.width - from.width) * e}px`;
g.style.opacity = String(fromOpacity + (toOpacity - fromOpacity) * e);
if (k < 1) requestAnimationFrame(frame);
else if (o.keep) res(g);
else {
g.remove();
res();
}
};
requestAnimationFrame(frame);
});
}
/* ------------------------------------------------------------------ effort */
/** The ramp's shape, read from the tokens (--pixilui-composer-ramp-*): each bar's place, height and share of its half. */
function rampBars(el: Element | null) {
const n = num(el, "--pixilui-composer-ramp-bars") || 32;
const min = num(el, "--pixilui-composer-ramp-min") || 7;
const rise = num(el, "--pixilui-composer-ramp-rise") || 16;
const curve = num(el, "--pixilui-composer-ramp-curve") || 1.2;
return Array.from({ length: n }, (_, k) => {
const x = k / (n - 1);
return { k, h: (min + rise * Math.pow(x, curve)).toFixed(1), m: x < 0.5 ? Math.round(x * 200) : Math.round((x - 0.5) * 200), hi: x >= 0.5 };
});
}
const edgeOf = (i: number, bars: number) => Math.round((i * (bars - 1)) / 3);
type EffortProps = { level: ComposerEffort; words: ComposerWords; onChange: (level: ComposerEffort) => void; measure: Element | null };
/** Effort, in the model menu: a header with its cost, a 32-bar ramp (a slider) and the level names under their stops. */
function Effort({ level, words, onChange, measure }: EffortProps) {
const bars = useMemo(() => rampBars(measure), [measure]);
const ramp = useRef<HTMLDivElement>(null);
// the level shown, the one it came from (the light sweeps between them), and the cost line's swap
const [st, setSt] = useState<{ level: ComposerEffort; from: ComposerEffort; now: string; out?: string; key: number }>({ level, from: level, now: words.effortCosts[level], key: 0 });
if (st.level !== level) setSt({ level, from: st.level, now: words.effortCosts[level], out: prefersReducedMotion() ? undefined : st.now, key: st.key + 1 });
const cost = st;
const [preview, setPreview] = useState<number | null>(null);
const drag = useRef(false);
const e = edgeOf(level, bars.length);
const a = edgeOf(st.from, bars.length);
const up = e > a;
const at = (x: number) => {
const r = ramp.current!.getBoundingClientRect();
return Math.max(0, Math.min(3, Math.round(((x - r.left) / r.width) * 3))) as ComposerEffort;
};
// (reduced motion: the foundation turns the ramp's transitions and the swap's animations off)
return (
<div className="pixilui-composer-effort" data-level={level}>
<div className="pixilui-composer-ef-h">
<span>{words.effort}</span>
<span className="pixilui-composer-ef-t">
{cost.out != null ? (
<span key={`o${cost.key}`} data-out="" onAnimationEnd={() => setSt((c) => ({ ...c, out: undefined }))}>
{cost.out}
</span>
) : null}
<span key={`n${cost.key}`} data-in={cost.key && cost.out != null ? "" : undefined}>
{cost.now}
</span>
</span>
</div>
<div
ref={ramp}
className="pixilui-composer-ef-ramp"
role="slider"
tabIndex={0}
aria-label={words.effort}
aria-valuemin={0}
aria-valuemax={3}
aria-valuenow={level}
aria-valuetext={words.efforts[level]}
onPointerDown={(ev) => {
drag.current = true;
ramp.current?.setPointerCapture(ev.pointerId);
setPreview(null);
onChange(at(ev.clientX));
ev.preventDefault();
}}
onPointerMove={(ev) => {
if (drag.current) onChange(at(ev.clientX));
else if (ev.pointerType === "mouse") setPreview(at(ev.clientX));
}}
onPointerUp={() => (drag.current = false)}
onPointerLeave={() => setPreview(null)}
>
{bars.map((b) => {
const on = b.k <= e;
const delay = up ? Math.max(0, b.k - a) : Math.max(0, a - b.k);
const pv = preview != null && b.k <= edgeOf(preview, bars.length) && !on;
return (
<i
key={b.k}
className={cn(on && "pixilui-composer-on", b.k === e && "pixilui-composer-edge", pv && "pixilui-composer-pv") || undefined}
data-hi={b.hi ? "" : undefined}
style={{ "--pixilui-composer-k": b.k, "--btn-h": b.h, "--pixilui-composer-m": b.m, ...(st.key ? { "--pixilui-composer-d": `calc(var(--pixilui-composer-ramp-step) * ${delay})` } : null) } as CSSProperties}
/>
);
})}
</div>
<div className="pixilui-composer-ef-stops">
{words.efforts.map((x, k) => (
<button key={x} type="button" className={cn("pixilui-composer-ef-s", k === level && "pixilui-composer-on")} tabIndex={-1} style={{ "--pixilui-composer-k": k } as CSSProperties} onClick={() => onChange(k as ComposerEffort)}>
{x}
</button>
))}
</div>
</div>
);
}
/** The trigger's four-bar ramp, lit to the chosen level. */
const EffBars = ({ level }: { level: number }) => (
<span className="pixilui-composer-effbars" aria-hidden="true">
{[0, 1, 2, 3].map((k) => (
<i key={k} className={k <= level ? "pixilui-composer-on" : undefined} style={{ "--pixilui-composer-k": k } as CSSProperties} />
))}
</span>
);
/* ------------------------------------------------------------------ the field */
/** A source in the + menu: upload opens the file picker (onFiles); the rest are your pickers (onAddSource). */
export type ComposerSource = ComposerOption & { upload?: boolean };
/** What the dictation shows while it listens: the words heard so far, the newest still grey, the time and the voice's level. */
export type ComposerDictation = {
/** Words that have settled (ink). */
words: string;
/** The newest words, still being confirmed (grey). */
interim?: string;
/** Seconds since it started. */
seconds: number;
/** The 18 bars' levels, 0 to 1 (the voice); at rest without. */
levels?: number[];
};
/** The field's handle, for the chat around it. */
export type ComposerFieldApi = {
/** The writing surface. */
input: HTMLDivElement | null;
/** The text, as typed. */
text: () => string;
/** Replace the text (hidden: drawn transparent, for words flying back into it); the caret goes to the end. */
setText: (text: string, o?: { hidden?: boolean; focus?: boolean }) => void;
/** Show the words again after a flight. */
reveal: () => void;
/** The send sweep, once. */
sweep: () => void;
/** Focus the field, caret at the end. */
focus: () => void;
};
export type ComposerFieldProps = Omit<React.ComponentPropsWithoutRef<"div">, "onSubmit" | "onChange" | "defaultValue"> & {
/** The chat's status: submitted or streaming is the agent at work (send becomes Stop, or Queue once you type). */
status?: ComposerStatus;
/** Words in the field at first. */
defaultValue?: string;
/** Runs as the words change. */
onChange?: (text: string) => void;
/** Runs on Enter or Send with what to send; the field then clears. Return false to keep the words in the box (the model is busy). */
onSubmit?: (draft: ComposerMessageDraft) => void | boolean | Promise<void>;
/** Runs on Stop (or Escape) while the agent works. */
onStop?: () => void;
/** Runs on Up in an empty field: edit your last message. */
onEditLast?: () => void;
/** The placeholder; the words' placeholder by default (the working one while the agent works). */
placeholder?: string;
/** The longest message: from 90% a count shows; over it, send is off. */
maxLength?: number;
/** Words quoted from a reply, over the field. */
quote?: string;
/** Runs when the quote's cross is pressed. */
onQuoteRemove?: () => void;
/** The file tiles. */
files?: ComposerFile[];
/** Runs when a tile's cross is pressed (it leaves first). */
onRemoveFile?: (id: string) => void;
/** Runs on a failed tile's Retry. */
onRetryFile?: (id: string) => void;
/** Files picked, pasted as files or dropped (up to six). */
onFiles?: (files: File[]) => void;
/** A paste over 600 characters or 10 lines: it becomes a "Pasted text" file instead of a wall of words. */
onLongPaste?: (text: string) => void;
/** The + menu's sources. */
sources?: ComposerSource[];
/** Runs when a source (not upload) is picked. */
onAddSource?: (id: string) => void;
/** The + menu's tools; the ones on show as chips. */
tools?: ComposerTool[];
/** The tools that are on. */
toolsOn?: string[];
/** Runs with the tools on after a switch or a chip's cross. */
onToolsChange?: (ids: string[]) => void;
/** The Connectors submenu. */
connectors?: ComposerConnector[];
/** Runs when a connector's switch flips. */
onConnectorChange?: (id: string, on: boolean) => void;
/** Runs when a signed-out connector is picked (it reconnects in place: set reconnecting, then on). */
onReconnect?: (id: string) => void;
/** Browse connectors. */
onBrowseConnectors?: () => void;
/** Manage connectors. */
onManageConnectors?: () => void;
/** The models. */
models?: ComposerOption[];
/** The model in use (an id). */
model?: string;
/** Runs when a model is picked. */
onModelChange?: (id: string) => void;
/** Effort, 0 to 3 (Low, Medium, High, Max). */
effort?: ComposerEffort;
/** Runs when the effort changes (the ramp, its names, or Left and Right in the model menu). */
onEffortChange?: (level: ComposerEffort) => void;
/** What the agent may do. */
permissions?: ComposerOption[];
/** The permission in use (an id). */
permission?: string;
/** The permission whose button shows its lock open (auto-approve). */
unlocked?: string;
/** Runs when a permission is picked. */
onPermissionChange?: (id: string) => void;
/** Recent folders. */
folders?: string[];
/** The folder it works in. */
folder?: string;
/** Runs when a folder is picked. */
onFolderChange?: (folder: string) => void;
/** Open a folder. */
onOpenFolder?: () => void;
/** Branches. */
branches?: string[];
/** The branch it works on. */
branch?: string;
/** Runs when a branch is picked. */
onBranchChange?: (branch: string) => void;
/** Start a new branch. */
onNewBranch?: () => void;
/** How full the context is, 0 to 100: from 70 the tray shows the inline meter and Compact. */
context?: number;
/** Compact the conversation. */
onCompact?: () => void;
/** / commands. */
commands?: ComposerOption[];
/** Files to mention after an at sign: label the name, description its path. */
mentions?: ComposerOption[];
/** A notice in the box. */
notice?: ComposerNotice | null;
/** in: an inset banner at the top of the box (the default); above: a plain line over it. */
noticePlace?: "in" | "above";
/** The busy model and the one to offer instead, for the busy notice. */
busy?: { model: string; instead: string };
/** A notice's button: retry the send, upgrade, or use the other model (retry and the other model then send again). */
onNoticeAction?: (action: "retry" | "upgrade" | "use-model") => void;
/** While dictating: what it has heard. */
dictation?: ComposerDictation | null;
/** The mic: start dictating (your speech recognition), or finish while dictating. */
onDictate?: () => void;
/** Escape while dictating: cancel it (the words before it come back). */
onDictationCancel?: () => void;
/** A shared chat: the box says so, with Continue. */
readOnly?: boolean;
/** Continue a shared chat. */
onContinue?: () => void;
/** Messages are flying back into the box: send waits for them. */
returning?: boolean;
/** The tray under the box (folder, branch, context, permission). */
tray?: boolean;
/** The field's handle, for the chat around it. */
api?: React.Ref<ComposerFieldApi>;
/** The icons it draws. */
icons: ComposerIcons;
/** Every word it says. */
words?: Partial<ComposerWords>;
};
type Typed = { kind: "cmd" | "file"; node: Text; start: number; end: number; q: string };
/** The chat box: your words, files and tools, the model with its effort, dictation and send; the tray under it. */
export const ComposerField = forwardRef<HTMLDivElement, ComposerFieldProps>(function ComposerField(
{
status = "ready",
defaultValue = "",
onChange,
onSubmit,
onStop,
onEditLast,
placeholder,
maxLength = 2000,
quote,
onQuoteRemove,
files = [],
onRemoveFile,
onRetryFile,
onFiles,
onLongPaste,
sources = [],
onAddSource,
tools = [],
toolsOn = [],
onToolsChange,
connectors,
onConnectorChange,
onReconnect,
onBrowseConnectors,
onManageConnectors,
models = [],
model,
onModelChange,
effort = 1,
onEffortChange,
permissions = [],
permission,
unlocked,
onPermissionChange,
folders,
folder,
onFolderChange,
onOpenFolder,
branches,
branch,
onBranchChange,
onNewBranch,
context,
onCompact,
commands = [],
mentions = [],
notice = null,
noticePlace = "in",
busy,
onNoticeAction,
dictation = null,
onDictate,
onDictationCancel,
readOnly,
onContinue,
returning = false,
tray = true,
api,
icons,
words: wordsProp,
className,
...rest
},
ref,
) {
const words = useMemo(() => ({ ...composerWords, ...wordsProp }), [wordsProp]);
const working = status === "submitted" || status === "streaming";
const root = useRef<HTMLDivElement | null>(null);
const [rootEl, setRootEl] = useState<HTMLDivElement | null>(null);
const box = useRef<HTMLDivElement | null>(null);
const input = useRef<HTMLDivElement | null>(null);
const scroller = useRef<HTMLDivElement | null>(null);
const send = useRef<HTMLButtonElement | null>(null);
const fileList = useRef<HTMLDivElement | null>(null);
const picker = useRef<HTMLInputElement | null>(null);
const mentionIcon = useRef<HTMLSpanElement | null>(null);
const [text, setTextState] = useState(defaultValue);
const [hidden, setHidden] = useState(false);
const [drop, setDrop] = useState(false);
const [sent, setSent] = useState(0);
const [nudge, setNudge] = useState(0);
const [reasonOpen, setReasonOpen] = useState(false);
const [leaving, setLeaving] = useState<string[]>([]);
const [entering, setEntering] = useState<string[]>([]);
const [justDone, setJustDone] = useState<string[]>([]);
const [typed, setTyped] = useState<Typed | null>(null);
const [typedX, setTypedX] = useState<Record<string, number>>({});
const [fade, setFade] = useState({ on: false, end: false });
const dragDepth = useRef(0);
const recBefore = useRef<string | null>(null);
const n = text.length;
const over = n > maxLength;
const near = !over && n >= maxLength * 0.9;
const uploading = files.some((f) => f.state === "up");
const reason = returning ? words.reasonReturning : !text.trim() ? words.reasonEmpty : notice === "limit" ? words.reasonLimit : over ? words.reasonTooLong : uploading ? words.reasonUploading : "";
const mode: "send" | "queue" | "stop" = working ? (text.trim() ? "queue" : "stop") : "send";
const off = mode === "send" && !!reason;
// the field grows with its words, gliding, then scrolls inside past six lines (composer.js fit)
const fit = useCallback(() => {
const s = scroller.current;
const i = input.current;
if (!s || !i) return;
const max = num(root.current, "--pixilui-composer-field-max");
const prev = s.style.getPropertyValue("--pixilui-composer-fh");
s.style.setProperty("--pixilui-composer-fh", "auto");
const full = i.offsetHeight;
const h = Math.min(full, max);
s.classList.toggle("pixilui-composer-ovf", full > max);
s.style.setProperty("--pixilui-composer-fh", prev || `${h}px`);
void s.offsetHeight;
requestAnimationFrame(() => s.style.setProperty("--pixilui-composer-fh", `${h}px`));
}, []);
const changed = useCallback(() => {
const t = textOf(input.current);
setTextState(t);
onChange?.(t);
fit();
}, [fit, onChange]);
const setText = useCallback(
(t: string, o: { hidden?: boolean; focus?: boolean } = {}) => {
const i = input.current;
if (!i) return;
i.textContent = t;
setHidden(!!o.hidden);
changed();
if (o.focus !== false) {
i.focus();
caretToEnd(i);
}
},
[changed],
);
useImperativeHandle(
api,
() => ({
input: input.current,
text: () => textOf(input.current),
setText,
reveal: () => setHidden(false),
sweep: () => {
if (!prefersReducedMotion()) setSent((x) => x + 1);
},
focus: () => {
input.current?.focus();
if (input.current) caretToEnd(input.current);
},
}),
[setText],
);
useLayoutEffect(() => {
if (input.current && defaultValue) input.current.textContent = defaultValue;
fit();
// the first words only
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// send nudges when it turns on (motion: the arrow lifts once)
// (the first state is only recorded: words the field starts with don't nudge it)
const wasOff = useRef<boolean | null>(null);
const armed = useRef(false);
useEffect(() => {
const f = requestAnimationFrame(() => (armed.current = true));
return () => cancelAnimationFrame(f);
}, []);
useEffect(() => {
if (armed.current && wasOff.current && !off && mode === "send" && !prefersReducedMotion()) setNudge((x) => x + 1);
wasOff.current = off;
}, [off, mode]);
// the nudge replays on the same button (a new one under a resting pointer would count as a fresh hover)
useLayoutEffect(() => {
const b = send.current;
if (!nudge || !b) return;
b.classList.remove("pixilui-composer-nudge");
void b.offsetWidth;
b.classList.add("pixilui-composer-nudge");
}, [nudge]);
// the send sweep's class comes off just after its run
useEffect(() => {
if (!sent) return;
const t = setTimeout(() => setSent(0), num(root.current, "--pixilui-composer-sweep-hold"));
return () => clearTimeout(t);
}, [sent]);
// files: new tiles come in, finished uploads resolve into a check, and the list fades at its edge while it scrolls
const seen = useRef(new Map<string, string | undefined>());
useLayoutEffect(() => {
const prev = seen.current;
const fresh = files.filter((f) => !prev.has(f.id)).map((f) => f.id);
const done = files.filter((f) => prev.has(f.id) && prev.get(f.id) === "up" && f.state === "done").map((f) => f.id);
seen.current = new Map(files.map((f) => [f.id, f.state]));
if (!prefersReducedMotion() && fresh.length) setEntering((e) => [...e, ...fresh]);
if (done.length) {
setJustDone((d) => [...d, ...done]);
setTimeout(() => setJustDone((d) => d.filter((x) => !done.includes(x))), num(root.current, "--pixilui-composer-file-done-hold"));
}
const fl = fileList.current;
if (fl && fresh.length) fl.scrollLeft = fl.scrollWidth;
// the edge fade is worked out as files arrive (and as the list scrolls), as the locked script does
if (!fresh.length) return;
requestAnimationFrame(() => {
const el = fileList.current;
if (el) setFade({ on: el.scrollWidth > el.clientWidth + 1, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 2 });
});
}, [files]);
// dictation: heard words land grey after what was there, older ones settle to ink; cancel puts the words back
useLayoutEffect(() => {
const i = input.current;
if (!i) return;
if (dictation) {
if (recBefore.current == null) recBefore.current = textOf(i);
const before = recBefore.current;
i.textContent = "";
const lead = before && !/\s$/.test(before) && (dictation.words || dictation.interim) ? `${before} ` : before;
i.append(document.createTextNode(lead + (dictation.words ? `${dictation.words}${dictation.interim ? " " : ""}` : "")));
const span = document.createElement("span");
span.className = "pixilui-composer-interim";
span.textContent = dictation.interim ?? "";
i.append(span);
changed();
} else if (recBefore.current != null) {
recBefore.current = null;
i.normalize();
const span = i.querySelector(".pixilui-composer-interim");
if (span) span.replaceWith(document.createTextNode(span.textContent ?? ""));
i.normalize();
changed();
i.focus();
caretToEnd(i);
}
}, [dictation, changed]);
const cancelDictation = () => {
const before = recBefore.current;
recBefore.current = null;
if (input.current && before != null) input.current.textContent = before;
changed();
onDictationCancel?.();
};
// ---------- the typed menus: / commands and @ files open at the caret and filter as you type ----------
const typedMenu = (k: "cmd" | "file") => root.current?.querySelector<HTMLElement>(`.pixilui-composer-dd-${k} > .pixilui-dropdown-menu`) ?? null;
const typedRows = (k: "cmd" | "file") => [...(typedMenu(k)?.querySelectorAll<HTMLElement>(":scope > .pixilui-dropdown-item:not([hidden])") ?? [])];
const caretX = () => {
const s = getSelection();
const edge = num(root.current, "--pixilui-composer-typed-edge");
if (!s?.rangeCount || !box.current) return edge;
const r = s.getRangeAt(0).cloneRange();
r.collapse(true);
const rect = r.getClientRects()[0];
return rect ? rect.left - box.current.getBoundingClientRect().left - num(root.current, "--pixilui-composer-typed-x") : edge;
};
const closeTyped = useCallback(() => {
setTyped((t) => {
if (t) {
const m = root.current?.querySelector<HTMLElement>(`.pixilui-composer-dd-${t.kind} > .pixilui-dropdown-menu`);
if (m) hideMenu(m);
}
return null;
});
}, []);
const watchTrigger = () => {
const s = getSelection();
if (!s?.rangeCount) return;
const node = s.anchorNode;
const at = s.anchorOffset;
const m = node && node.nodeType === 3 ? (node.textContent ?? "").slice(0, at).match(/(^|\s)([/@])([\w.-]*)$/) : null;
if (!m) {
closeTyped();
return;
}
const kind = m[2] === "/" ? "cmd" : "file";
if (typed && typed.kind !== kind) closeTyped();
const next: Typed = { kind, node: node as Text, start: at - m[3]!.length - 1, end: at, q: m[3]!.toLowerCase() };
const menu = typedMenu(kind);
if (menu && (menu.hidden || menu.hasAttribute("data-out"))) {
const edge = num(root.current, "--pixilui-composer-typed-edge");
const place = () => Math.max(edge, Math.min((box.current?.offsetWidth ?? 0) - menu.offsetWidth - edge, caretX()));
flushSync(() => setTypedX((x) => ({ ...x, [kind]: place() })));
showMenu(menu);
flushSync(() => setTypedX((x) => ({ ...x, [kind]: place() })));
}
flushSync(() => setTyped(next));
if (!menu) return;
const first = typedRows(kind)[0];
if (!first) {
menu.removeAttribute("data-hl");
menu.removeAttribute("aria-activedescendant");
return;
}
const cur = document.getElementById(menu.getAttribute("aria-activedescendant") || "");
glideMenu(menu, cur && !cur.hidden && menu.hasAttribute("data-hl") ? cur : first, true);
};
const typedPick = (it: HTMLElement) => {
const t = typed;
closeTyped();
const i = input.current;
if (!t || !i) return;
i.focus();
const r = document.createRange();
r.setStart(t.node, t.start);
r.setEnd(t.node, t.end);
r.deleteContents();
if (t.kind === "cmd") r.insertNode(document.createTextNode(`${it.dataset.value} `));
else {
const tok = document.createElement("span");
tok.className = "pixilui-cite pixilui-composer-tok";
tok.contentEditable = "false";
const ic = mentionIcon.current?.firstElementChild?.cloneNode(true) as Element | undefined;
if (ic) {
ic.classList.add("pixilui-i", "pixilui-cite-ic", "pixilui-cite-ol");
tok.append(ic);
}
const name = document.createElement("span");
name.className = "pixilui-cite-name";
name.textContent = it.dataset.value ?? "";
tok.append(name);
r.insertNode(tok);
tok.after(document.createTextNode(" "));
}
caretToEnd(i);
changed();
};
// ---------- send ----------
const submit = () => {
if (returning) return;
if (dictation) onDictate?.();
const t = textOf(input.current).trim();
if (!working && off) {
// the reason shows on send, as if you'd pointed at it (composer.js showTip)
if (send.current) setReasonOpen(true);
return;
}
if (!t) return;
const kept = onSubmit?.({ text: t, quote, files: files.filter((f) => f.state === "done") });
if (kept === false) return;
if (input.current) input.current.textContent = "";
changed();
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const native = e.nativeEvent;
if (typed) {
const menu = typedMenu(typed.kind);
const list = typedRows(typed.kind);
const cur = menu ? document.getElementById(menu.getAttribute("aria-activedescendant") || "") : null;
const i = cur ? list.indexOf(cur) : -1;
if (!list.length && (e.key === "Enter" || e.key === "Tab" || e.key === "Escape")) closeTyped();
else {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const d = e.key === "ArrowDown" ? 1 : -1;
if (menu) glideMenu(menu, list[i < 0 ? (d > 0 ? 0 : list.length - 1) : (i + d + list.length) % list.length]);
return;
}
if ((e.key === "Enter" || e.key === "Tab") && !native.isComposing) {
e.preventDefault();
if (cur && !cur.hidden) typedPick(cur);
return;
}
if (e.key === "Escape") {
e.preventDefault();
closeTyped();
return;
}
}
}
if (dictation && e.key === "Enter") {
e.preventDefault();
onDictate?.();
return;
}
if (e.key === "Enter" && !e.shiftKey && !native.isComposing) {
e.preventDefault();
submit();
return;
}
if (e.key === "ArrowUp" && !textOf(input.current) && !working) {
if (onEditLast) {
e.preventDefault();
onEditLast();
}
return;
}
if (e.key === "Escape") {
if (dictation) {
e.preventDefault();
cancelDictation();
return;
}
if (working) {
e.preventDefault();
onStop?.();
}
}
};
// ⌘K focuses the field
useEffect(() => {
const k = (e: globalThis.KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
input.current?.focus();
}
};
document.addEventListener("keydown", k);
return () => document.removeEventListener("keydown", k);
}, []);
// ---------- menus ----------
const dd = (k: string, extra?: string) => cn("pixilui-composer-dd", `pixilui-composer-dd-${k}`, extra);
const signedOut = connectors?.find((c) => c.signedOut);
const plusGroups: DropdownMenuGroup[] = [
{
rows: [
...sources.map<DropdownMenuRow>((s) => ({ id: s.id, label: s.label, icon: s.icon, onSelect: () => setTimeout(() => (s.upload ? picker.current?.click() : onAddSource?.(s.id))) })),
...(connectors
? [
{
id: "connectors",
label: words.connectors,
description: signedOut ? words.connectorsReconnect : undefined,
risk: !!signedOut,
icon: icons.plug,
submenu: {
"aria-label": words.connectors,
groups: [
{
rows: connectors.map<DropdownMenuRow>((c) =>
c.signedOut
? { id: c.id, label: c.label, icon: c.icon, description: c.reconnecting ? words.connectorReconnecting : words.connectorSignedOut, risk: true, keepOpen: true, onSelect: () => !c.reconnecting && onReconnect?.(c.id) }
: { id: c.id, label: c.label, icon: c.icon, kind: "switch", checked: c.on, onCheckedChange: (on) => onConnectorChange?.(c.id, on) },
),
},
{
rows: [
{ id: "browse", label: words.connectorsBrowse, icon: icons.search, onSelect: () => onBrowseConnectors?.() },
{ id: "manage", label: words.connectorsManage, icon: icons.settings, onSelect: () => onManageConnectors?.() },
],
},
],
},
} satisfies DropdownMenuRow,
]
: []),
],
},
...(tools.length
? [
{
rows: tools.map<DropdownMenuRow>((t) => ({
id: t.id,
label: t.label,
icon: t.icon,
kind: "switch",
checked: toolsOn.includes(t.id),
onCheckedChange: (on) => onToolsChange?.(on ? [...toolsOn.filter((x) => x !== t.id), t.id] : toolsOn.filter((x) => x !== t.id)),
})),
},
]
: []),
];
const cur = models.find((m) => m.id === model) ?? models[0];
const perm = permissions.find((p) => p.id === permission) ?? permissions[0];
const menuWidth = (k: string) => `var(--pixilui-composer-menu-${k}-w)`;
const modelKeys = (e: KeyboardEvent<HTMLDivElement>) => {
// Left and Right change effort in the model menu (Home and End on the ramp)
const target = e.target as HTMLElement;
if (!target.closest(".pixilui-dropdown-menu")) return;
const onRamp = target.classList.contains("pixilui-composer-ef-ramp");
const to = e.key === "ArrowRight" ? effort + 1 : e.key === "ArrowLeft" ? effort - 1 : e.key === "Home" && onRamp ? 0 : e.key === "End" && onRamp ? 3 : null;
if (to == null) return;
e.preventDefault();
e.stopPropagation();
onEffortChange?.(Math.max(0, Math.min(3, to)) as ComposerEffort);
};
const noticeBody = (k: ComposerNotice | "over" | null) => {
// Retry and the other model clear the notice and send again (composer.js retry-send, use-sonnet)
const link = (label: string, action: "retry" | "upgrade" | "use-model") => (
<Button
variant="link"
size="xs"
onClick={() => {
onNoticeAction?.(action);
if (action !== "upgrade") setTimeout(submit);
}}
>
<span>{label}</span>
</Button>
);
if (k === "over")
return (
<div className="pixilui-composer-nt pixilui-composer-err">
{slot(icons.alert)}
<span>{words.noticeOver}</span>
</div>
);
if (k === "fail")
return (
<div className="pixilui-composer-nt pixilui-composer-err">
{slot(icons.alert)}
<span>{words.noticeFail}</span>
{link(words.retry, "retry")}
</div>
);
if (k === "limit")
return (
<div className="pixilui-composer-nt pixilui-composer-wait">
{slot(icons.clock)}
<span>{words.noticeLimit}</span>
{link(words.noticeUpgrade, "upgrade")}
</div>
);
if (k === "offline")
return (
<div className="pixilui-composer-nt">
{slot(icons.offline)}
<span>{words.noticeOffline}</span>
</div>
);
if (k === "online")
return (
<div className="pixilui-composer-nt pixilui-composer-ok">
{slot(icons.online)}
<span>{words.noticeOnline}</span>
</div>
);
if (k === "mic")
return (
<div className="pixilui-composer-nt pixilui-composer-err">
{slot(icons.alert)}
<span>{words.noticeMic}</span>
</div>
);
if (k === "busy" && busy)
return (
<div className="pixilui-composer-nt pixilui-composer-wait">
{slot(icons.clock)}
<span>{words.noticeBusy(busy.model)}</span>
{link(words.noticeUseModel(busy.instead), "use-model")}
{link(words.noticeTryAgain, "retry")}
</div>
);
return <div className="pixilui-composer-nt" />;
};
// over the limit, the box says so (above any other notice); the notice row keeps its last words while it folds shut
const shown: ComposerNotice | "over" | null = over ? "over" : notice;
const [shownNotice, setShownNotice] = useState(shown);
if (shown && shown !== shownNotice) setShownNotice(shown);
const noticeOn = !!shown && ERR.includes(shown);
const noticeRow = (
<div className={cn("pixilui-composer-row pixilui-composer-notice", noticeOn && "pixilui-composer-on")} data-place={noticePlace}>
<div className="pixilui-composer-rin">{noticeBody(shown ?? shownNotice)}</div>
</div>
);
const countOn = over || near;
if (readOnly)
return (
<div ref={ref} className={cn("pixilui-composer font-body", className)} {...rest}>
<div className="pixilui-composer-box">
<div className="pixilui-composer-ro">
{slot(icons.view)}
<span>{words.readOnly}</span>
<Button size="sm" onClick={onContinue}>
{words.readOnlyContinue}
</Button>
</div>
</div>
</div>
);
const kindLabel = (f: ComposerFile, kind: ComposerFileKind) => (words.kinds[kind] ? `${words.kinds[kind]} · ${f.size}` : f.size);
const ph = placeholder ?? (working ? words.placeholderWorking : words.placeholder);
const sendLabel = mode === "stop" ? words.stop : mode === "queue" ? words.queue : words.send;
const typedList = (k: "cmd" | "file") => {
const list = k === "cmd" ? commands : mentions;
const q = typed?.kind === k ? typed.q : "";
const shown = list.filter((o) => o.label.toLowerCase().replace("/", "").includes(q));
const empty = k === "cmd" ? words.commandsNone : words.filesNone;
return (
<div className={cn("pixilui-dropdown font-body", dd(k, "pixilui-composer-typed"))} style={typedX[k] != null ? { left: `${typedX[k]}px` } : undefined}>
<button className="pixilui-dropdown-trigger" type="button" hidden tabIndex={-1} aria-hidden="true" />
<div
className="pixilui-dropdown-menu"
role="listbox"
aria-label={k === "cmd" ? words.commands : words.files}
hidden
onPointerDown={(e) => e.preventDefault()}
onClick={(e) => {
const it = (e.target as HTMLElement).closest<HTMLElement>(".pixilui-dropdown-item");
if (it) typedPick(it);
}}
onMouseMove={(e) => {
const it = (e.target as HTMLElement).closest<HTMLElement>(".pixilui-dropdown-item");
const m = e.currentTarget;
if (it && m.getAttribute("aria-activedescendant") !== it.id) glideMenu(m, it);
}}
>
<span className="pixilui-dropdown-highlight" aria-hidden="true" />
<div className="pixilui-dropdown-label">{k === "cmd" ? words.commands : words.files}</div>
{list.map((o) => (
<div key={o.id} id={`${o.id}-${k}`} className="pixilui-dropdown-item" role="option" data-value={o.label} hidden={!shown.includes(o)}>
{slot(o.icon)}
<span className="pixilui-dropdown-text">
{o.description ? (
<>
<b>{o.label}</b>
<small className={k === "file" ? "pixilui-composer-mono-meta" : undefined}>{o.description}</small>
</>
) : (
o.label
)}
</span>
</div>
))}
<div className="pixilui-dropdown-empty" data-text={empty} hidden={shown.length > 0}>
{shown.length ? null : `${empty} “${q}”`}
</div>
</div>
</div>
);
};
return (
<div
ref={(el) => {
root.current = el;
if (el !== rootEl) setRootEl(el);
if (typeof ref === "function") ref(el);
else if (ref) ref.current = el;
}}
className={cn("pixilui-composer font-body", className)}
{...rest}
>
{noticePlace === "above" ? noticeRow : null}
<div
ref={box}
className={cn("pixilui-composer-box", dictation && "pixilui-composer-rec")}
data-working={working ? "" : undefined}
data-drop={drop ? "" : undefined}
onPointerDown={(e) => {
const t = e.target as HTMLElement;
if (t === e.currentTarget || t.closest(".pixilui-composer-bar") === t || t.classList.contains("pixilui-composer-left")) {
e.preventDefault();
input.current?.focus();
if (input.current) caretToEnd(input.current);
}
}}
onDragEnter={(e) => {
e.preventDefault();
dragDepth.current++;
setDrop(true);
}}
onDragOver={(e) => e.preventDefault()}
onDragLeave={() => {
if (--dragDepth.current <= 0) {
dragDepth.current = 0;
setDrop(false);
}
}}
onDrop={(e) => {
e.preventDefault();
dragDepth.current = 0;
setDrop(false);
const list = [...(e.dataTransfer?.files ?? [])].slice(0, 6);
if (list.length) onFiles?.(list);
}}
>
{noticePlace === "in" ? noticeRow : null}
<div className={cn("pixilui-composer-row pixilui-composer-qrow", quote && "pixilui-composer-on")}>
<div className="pixilui-composer-rin">
<div className="pixilui-composer-quote">
<p>{quote ?? ""}</p>
<Tooltip label={words.removeQuote}>
<Button variant="secondary-2" size="xs" aria-label={words.removeQuote} icon={slot(icons.remove)} onClick={() => onQuoteRemove?.()} />
</Tooltip>
</div>
</div>
</div>
<div className={cn("pixilui-composer-row pixilui-composer-files", files.length > 0 && "pixilui-composer-on")}>
<div className="pixilui-composer-rin">
<div
ref={fileList}
className={cn("pixilui-composer-fl", fade.on && "pixilui-composer-fade", fade.end && "pixilui-composer-end")}
onScroll={(e) => {
const el = e.currentTarget;
setFade({ on: el.scrollWidth > el.clientWidth + 1, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 2 });
}}
>
{files.map((f) => {
const kind = f.kind ?? KIND(f.name);
const img = kind === "img";
const state = f.state ?? "done";
const pct = Math.round((f.progress ?? 0) * 100);
return (
<div
key={f.id}
className={cn("pixilui-composer-file", entering.includes(f.id) && "pixilui-composer-enter", leaving.includes(f.id) && "pixilui-composer-leave", justDone.includes(f.id) && "pixilui-composer-just-done")}
data-state={state}
data-kind={kind}
style={{ "--pixilui-composer-pr": f.progress ?? 0 } as CSSProperties}
onAnimationEnd={(e) => {
if (e.target === e.currentTarget && entering.includes(f.id)) setEntering((x) => x.filter((id) => id !== f.id));
}}
>
<span className={cn("pixilui-composer-ft", img && "pixilui-composer-img")} style={img && f.thumb ? { backgroundImage: f.thumb } : undefined}>
{slot(icons.kinds[kind])}
<svg className="pixilui-composer-ring" viewBox="0 0 38 38" aria-hidden="true">
<circle cx="19" cy="19" r="17.5" pathLength={100} />
</svg>
<span className="pixilui-composer-okb">{slot(icons.check)}</span>
</span>
<span className="pixilui-composer-fn">
<b>{f.name}</b>
<small>
{state === "failed" ? (
<>
{`${f.reason ?? ""} ·`}
<Button variant="link" size="xs" onClick={() => onRetryFile?.(f.id)}>
<span>{words.retry}</span>
</Button>
</>
) : state === "up" ? (
words.progress(pct, f.size)
) : kind === "paste" ? (
f.size
) : (
kindLabel(f, kind)
)}
</small>
</span>
<Tooltip label={state === "up" ? words.cancelUpload : words.removeFile}>
<Button
variant="secondary-2"
size="xs"
aria-label={state === "up" ? words.cancelUploadLabel(f.name) : words.removeFileLabel(f.name)}
icon={slot(icons.remove)}
onClick={() => {
setLeaving((l) => [...l, f.id]);
setTimeout(() => {
setLeaving((l) => l.filter((x) => x !== f.id));
onRemoveFile?.(f.id);
}, prefersReducedMotion() ? 0 : num(root.current, "--pixilui-composer-file-out"));
input.current?.focus();
}}
/>
</Tooltip>
</div>
);
})}
</div>
</div>
</div>
<div ref={scroller} className="pixilui-composer-scroll">
<div
ref={input}
className="pixilui-composer-input"
contentEditable={"plaintext-only" as unknown as boolean}
suppressContentEditableWarning
role="textbox"
aria-multiline="true"
aria-label={words.message}
aria-description={words.messageDescription}
data-ph={ph}
spellCheck={false}
style={hidden ? { color: "transparent" } : undefined}
onInput={() => {
const i = input.current!;
if (!i.textContent?.trim() && !i.querySelector(".pixilui-composer-tok")) i.innerHTML = "";
changed();
watchTrigger();
}}
onKeyDown={onKey}
onPaste={(e: ClipboardEvent<HTMLDivElement>) => {
e.preventDefault();
const t = e.clipboardData.getData("text/plain");
if (t.length > 600 || t.split("\n").length > 10) {
onLongPaste?.(t);
return;
}
document.execCommand("insertText", false, t);
}}
/>
</div>
<div className={cn("pixilui-composer-row pixilui-composer-note", countOn && "pixilui-composer-on")}>
<div className="pixilui-composer-rin">
{countOn ? (
<div className={cn("pixilui-composer-nt pixilui-composer-count", over && "pixilui-composer-err")}>
<span className="pixilui-composer-n">{words.count(n, maxLength)}</span>
</div>
) : (
<div className="pixilui-composer-nt" />
)}
</div>
</div>
<div className="pixilui-composer-bar">
{sources.length || tools.length || connectors ? (
<DropdownMenu
className={dd("plus")}
aria-label={words.add}
groups={plusGroups}
// the tooltip family reads data-pixilui-tip (a Tooltip around a menu's trigger would lose the trigger's class)
trigger={<Button variant="secondary-2" aria-label={words.add} data-pixilui-tip={words.add} icon={slot(icons.add)} className="pixilui-composer-plus" />}
/>
) : null}
<div className="pixilui-composer-left">
{tools
.filter((t) => toolsOn.includes(t.id))
.map((t) => (
<Chip
key={t.id}
data-tool={t.id}
className={t.shimmer ? "pixilui-composer-chip-think" : undefined}
icon={slot(t.icon)}
removeLabel={words.turnOffLabel(t.label)}
removeIcon={slot(icons.remove)}
onRemove={() => onToolsChange?.(toolsOn.filter((x) => x !== t.id))}
>
{t.shimmer ? <TextShimmer tone="color">{t.chip}</TextShimmer> : t.chip}
</Chip>
))}
</div>
<div className="pixilui-composer-right">
{cur ? (
<DropdownMenu
className={dd("model")}
align="end"
aria-label={words.modelMenu}
select="single"
width={menuWidth("model")}
onKeyDownCapture={modelKeys}
groups={[{ label: words.modelMenu, rows: models.map((m) => ({ id: m.id, label: m.label, description: m.description, icon: slot(m.icon, "pixilui-composer-logo"), checked: m.id === cur.id, onSelect: () => onModelChange?.(m.id) })) }]}
after={<Effort level={effort} words={words} onChange={(l) => l !== effort && onEffortChange?.(l)} measure={rootEl} />}
trigger={
<Button variant="secondary-2" size="sm" className="pixilui-composer-model" aria-label={words.modelLabel(cur.label, words.efforts[effort])} icon={slot(cur.icon, "pixilui-composer-logo")} iconEnd={slot(icons.chevron)}>
<span className="pixilui-btn-label">{cur.label}</span>
<EffBars level={effort} />
<span className="pixilui-composer-eff">{words.efforts[effort]}</span>
</Button>
}
/>
) : null}
<div className="pixilui-composer-wave" aria-hidden="true">
<span className="pixilui-composer-bars">
{Array.from({ length: 18 }, (_, k) => (
<i key={k} style={dictation?.levels?.[k] != null ? ({ "--pixilui-composer-a": dictation.levels[k] } as CSSProperties) : undefined} />
))}
</span>
<span className="pixilui-composer-wt">{`0:${String(Math.floor(dictation?.seconds ?? 0)).padStart(2, "0")}`}</span>
</div>
{onDictate ? (
<Tooltip label={dictation ? words.dictateStop : words.dictate} shortcut={dictation ? "↵" : undefined}>
<Button
variant={dictation ? "tinted" : "secondary-2"}
className="pixilui-composer-mic"
pressed={!!dictation}
aria-label={dictation ? words.dictateStop : words.dictate}
icon={slot(icons.mic)}
onClick={() => onDictate()}
/>
</Tooltip>
) : null}
<Tooltip label={sendLabel} shortcut={mode === "stop" ? "Esc" : "↵"} reason={off ? reason : undefined} open={reasonOpen && off ? true : undefined} onOpenChange={(o) => !o && setReasonOpen(false)}>
<button
ref={send}
type="button"
className="pixilui-btn pixilui-composer-send"
data-variant={mode === "stop" ? "secondary-2" : "primary"}
data-size="md"
data-icon-only=""
data-mode={mode}
data-state={mode === "stop" ? "running" : undefined}
data-sent={sent ? "" : undefined}
aria-label={off ? `${words.send}. ${reason}` : sendLabel}
aria-disabled={off ? "true" : undefined}
data-pixilui-tip-reason={off ? reason : undefined}
onClick={() => {
if (mode === "stop") onStop?.();
else if (!off) submit();
}}
>
<span className="pixilui-composer-ic">
{slot(icons.send)}
<span className="pixilui-composer-sq" />
</span>
<span className="pixilui-composer-sweep" aria-hidden="true" />
</button>
</Tooltip>
</div>
</div>
<div className="pixilui-composer-drop" aria-hidden="true">
{words.drop}
</div>
{commands.length ? typedList("cmd") : null}
{mentions.length ? typedList("file") : null}
</div>
{/* off the box, as the locked script keeps them on the page: the file picker, and the icon a mention copies */}
{rootEl
? createPortal(
<>
<span ref={mentionIcon} hidden>
{icons.file}
</span>
<input
ref={picker}
type="file"
multiple
hidden
onChange={(e) => {
const list = [...(e.target.files ?? [])].slice(0, 6);
e.target.value = "";
if (list.length) onFiles?.(list);
}}
/>
</>,
rootEl.ownerDocument.body,
)
: null}
{tray ? (
<div className="pixilui-composer-tray">
{folders || branches ? (
<span className="pixilui-composer-ws">
{folders && folder ? (
<DropdownMenu
className={dd("folder")}
menuClassName="pixilui-composer-mono"
aria-label={words.folder}
select="single"
groups={[
{ label: words.folderRecent, rows: folders.map((f) => ({ id: f, label: f, icon: slot(icons.folder), checked: f === folder, onSelect: () => onFolderChange?.(f) })) },
{ rows: [{ id: "open", label: words.folderOpen, icon: slot(icons.newItem), kind: "action", onSelect: () => onOpenFolder?.() }] },
]}
trigger={
<Button variant="secondary-2" size="xs" className="pixilui-composer-folder" aria-label={words.folder} icon={slot(icons.folder)} iconEnd={slot(icons.chevron)}>
<code>{folder}</code>
</Button>
}
/>
) : null}
{branches && branch ? (
<DropdownMenu
className={dd("branch")}
menuClassName="pixilui-composer-mono"
aria-label={words.branch}
select="single"
width={menuWidth("branch")}
search={{ placeholder: words.branchFind, "aria-label": words.branchFind, empty: words.branchNone, icon: icons.search }}
groups={[
{ label: words.branches, rows: branches.map((b) => ({ id: b, label: b, icon: slot(icons.branch), checked: b === branch, onSelect: () => onBranchChange?.(b) })) },
{ rows: [{ id: "new", label: words.branchNew, icon: slot(icons.newItem), kind: "action", onSelect: () => onNewBranch?.() }] },
]}
trigger={
<Button variant="secondary-2" size="xs" className="pixilui-composer-branch" aria-label={words.branch} icon={slot(icons.branch)} iconEnd={slot(icons.chevron)}>
<code>{branch}</code>
</Button>
}
/>
) : null}
</span>
) : null}
<span className="pixilui-composer-grow" />
{context != null ? (
<span className="pixilui-composer-ctxn" hidden={context < 70}>
<UsageMeterWindow label={words.context} used={context} pace={context >= 85 ? 100 : context} variant="inline" />
<Button variant="link" size="xs" onClick={() => onCompact?.()}>
<span>{words.compact}</span>
</Button>
<span className="pixilui-composer-sep" aria-hidden="true" />
</span>
) : null}
{perm ? (
<span className="pixilui-composer-pg">
<DropdownMenu
className={dd("perm")}
align="end"
aria-label={words.permissionMenu}
select="single"
width={menuWidth("perm")}
groups={[{ label: words.permissionMenu, rows: permissions.map((p) => ({ id: p.id, label: p.label, description: p.description, icon: slot(p.icon), checked: p.id === perm.id, onSelect: () => onPermissionChange?.(p.id) })) }]}
trigger={
<Button variant="secondary-2" size="xs" className="pixilui-composer-perm" data-v={perm.id} data-state={perm.id === unlocked ? "unlocked" : undefined} icon={slot(perm.icon)} iconEnd={slot(icons.chevron)}>
<span className="pixilui-btn-label">{perm.label}</span>
</Button>
}
/>
</span>
) : null}
</div>
) : null}
</div>
);
});
/* ------------------------------------------------------------------ the chat */
/** The agent asking before it runs a command, and, once answered, what you chose. */
export type ComposerApproval = {
/** The question ("Run this command?"). */
question: ReactNode;
/** The command, in mono. */
command: string;
/** What running it does. */
why: ReactNode;
/** Your answer: the card folds to one line that says it. stopped: Stop came first. */
answer?: "once" | "chat" | "deny" | "stopped";
};
/** One entry in the thread. */
export type ComposerChatMessage =
| {
id: string;
role: "user";
/** Your words. */
text: string;
/** Words you quoted from a reply. */
quote?: string;
/** The files it carried, as words ("trace.pdf", "3 files"). */
files?: string;
/** Every version of it after edits; text is the one shown. */
versions?: string[];
/** Which version shows (0 based). */
version?: number;
}
| {
id: string;
role: "agent";
/** The agent's work: the working line or the reasoning trail. */
trail?: ReactNode;
/** It is waiting for your approval, or was. */
approval?: ComposerApproval;
/** It has run past a minute: the long-run line. notify: you asked to be told. */
long?: boolean | "notify";
/** The answer, streaming or done. */
answer?: ReactNode;
/** The reply is finished: its actions come in. */
done?: boolean;
}
| {
id: string;
role: "note";
/** A quiet line ("Earlier messages summarized · 34k tokens freed"). */
text: ReactNode;
};
/** Every word the thread and the queue say, and what they announce. */
export type ComposerThreadWords = {
waitingConnection: string;
sendNow: string;
edit: string;
removeQueued: string;
remove: string;
copy: string;
copyMessage: string;
editMessage: string;
previousVersion: string;
nextVersion: string;
version: (i: number, n: number) => string;
goodReply: string;
badReply: string;
tryAgain: string;
waitForReply: string;
allowOnce: string;
allowChat: string;
deny: string;
approvalGroup: string;
said: Record<NonNullable<ComposerApproval["answer"]>, string>;
longRun: string;
notify: string;
notified: string;
cancel: string;
save: string;
editLabel: string;
quote: string;
sayQueued: (n: number) => string;
saySending: string;
sayStopped: string;
sayGivenBack: (n: number) => string;
sayOffline: string;
sayOnline: string;
sayRemoved: string;
sayBackInBox: string;
sayCopied: string;
sayEditing: string;
sayApproval: string;
sayQuoted: string;
};
export const composerThreadWords: ComposerThreadWords = {
waitingConnection: "Waiting for connection",
sendNow: "Send now",
edit: "Edit",
removeQueued: "Remove this message",
remove: "Remove",
copy: "Copy",
copyMessage: "Copy message",
editMessage: "Edit message",
previousVersion: "Previous version",
nextVersion: "Next version",
version: (i, n) => `${i} / ${n}`,
goodReply: "Good reply",
badReply: "Bad reply",
tryAgain: "Try again",
waitForReply: "Wait for the reply, or stop it",
allowOnce: "Allow once",
allowChat: "Allow for this chat",
deny: "Deny",
approvalGroup: "The agent is waiting for your approval",
said: { once: "Allowed once", chat: "Allowed for this chat", deny: "Denied", stopped: "Stopped before it ran" },
longRun: "This is taking longer than usual.",
notify: "Notify me when it’s done",
notified: "I’ll let you know when it’s done.",
cancel: "Cancel",
save: "Save",
editLabel: "Edit your message",
quote: "Quote",
sayQueued: (n) => (n > 1 ? `Queued. ${n} messages are waiting` : "Queued. It sends after this reply"),
saySending: "Sending your queued message",
sayStopped: "Stopped",
sayGivenBack: (n) => (n > 1 ? `Stopped. ${n} waiting messages are back in the box` : "Stopped. Your waiting message is back in the box"),
sayOffline: "You’re offline. It sends when you’re back",
sayOnline: "Back online",
sayRemoved: "Removed from the queue",
sayBackInBox: "Back in the box to edit",
sayCopied: "Copied",
sayEditing: "Editing your message. Enter saves, Escape cancels",
sayApproval: "The agent is waiting for your approval",
sayQuoted: "Quote added to your message",
};
/** The thread's icons. */
export type ComposerThreadIcons = {
copy: ReactNode;
edit: ReactNode;
previous: ReactNode;
next: ReactNode;
good: ReactNode;
bad: ReactNode;
retry: ReactNode;
remove: ReactNode;
attachment: ReactNode;
allowed: ReactNode;
denied: ReactNode;
clock: ReactNode;
notify: ReactNode;
quote: ReactNode;
note: ReactNode;
};
/** A small icon button in the thread with its tooltip (copy, edit, versions, remove). */
function ThreadButton({ label, tip, icon, onClick, shortcut, disabled, copied }: { label: string; tip?: string; icon: ReactNode; onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void; shortcut?: string; disabled?: boolean; copied?: boolean }) {
return (
<Tooltip label={tip ?? label} shortcut={shortcut}>
<Button variant="secondary-2" size="xs" aria-label={label} icon={slot(icon)} onClick={onClick} disabled={disabled} copied={copied} />
</Tooltip>
);
}
/** A waiting message's caption: "Waiting for connection" (offline only), Send now, Edit and remove. */
function QueueCaption({ words: w, icon, onSendNow, onEdit, onRemove }: { words: ComposerThreadWords; icon: ReactNode; onSendNow?: () => void; onEdit?: () => void; onRemove?: () => void }) {
return (
<div className="pixilui-composer-qcap">
<span className="pixilui-composer-qnote">{w.waitingConnection}</span>
<Button variant="secondary-2" size="xs" onClick={onSendNow}>
{w.sendNow}
</Button>
<Button variant="secondary-2" size="xs" onClick={onEdit}>
{w.edit}
</Button>
<ThreadButton label={w.removeQueued} tip={w.remove} icon={icon} onClick={onRemove} />
</div>
);
}
type Queued = { id: string; draft: ComposerMessageDraft };
export type ComposerFieldChatProps = Omit<ComposerFieldProps, "onSubmit" | "onStop" | "returning" | "api" | "onEditLast" | "placeholder"> & {
/** The conversation so far: your messages, the agent's turns, notes. */
messages: ComposerChatMessage[];
/** The chat's status: submitted or streaming is the agent at work; messages you send then wait in the thread. */
status?: ComposerStatus;
/** Offline: messages wait in the thread and go, in order, when it comes back. */
offline?: boolean;
/** A message goes to the agent: now, or when its turn in the queue comes. Add it to messages and start the reply. Return false to keep it in the box (the model is busy). */
onSend: (draft: ComposerMessageDraft) => void | boolean;
/** Stop the reply. Waiting messages fly back into the box. */
onStop?: () => void;
/** Your answer to an approval. */
onApprove?: (turnId: string, answer: "once" | "chat" | "deny") => void;
/** A sent message, edited: add a version and run the reply again. */
onEdit?: (messageId: string, text: string) => void;
/** Show another version of an edited message. */
onVersion?: (messageId: string, index: number) => void;
/** Try the reply again. */
onRetry?: (turnId: string) => void;
/** Rate a reply. */
onRate?: (turnId: string, rating: "good" | "bad" | null) => void;
/** Ask to be told when a long run is done. */
onNotify?: (turnId: string) => void;
/** Words selected in a reply, carried into the box (set quote). */
onQuote?: (text: string) => void;
/** Every word the thread says. */
threadWords?: Partial<ComposerThreadWords>;
/** The thread's icons. */
threadIcons: ComposerThreadIcons;
/** Before the first message: what shows over the box (a greeting, starters). */
greeting?: ReactNode;
/** The field's placeholder once the chat has started. */
placeholder?: string;
};
/**
* The chat: the thread over the composer field, and the queue. Messages you send while the agent works wait in the thread in
* order; the next goes when the reply ends, Send now jumps the line, Stop flies them all back into the box.
*/
export const ComposerFieldChat = forwardRef<HTMLDivElement, ComposerFieldChatProps>(function ComposerFieldChat(
{ messages, status = "ready", offline = false, onSend, onStop, onApprove, onEdit, onVersion, onRetry, onRate, onNotify, onQuote, threadWords, threadIcons: ti, greeting, notice, placeholder, className, words, ...field },
ref,
) {
const w = useMemo(() => ({ ...composerThreadWords, ...threadWords }), [threadWords]);
const fw = useMemo(() => ({ ...composerWords, ...words }), [words]);
const working = status === "submitted" || status === "streaming";
const chat = useRef<HTMLDivElement | null>(null);
const thread = useRef<HTMLDivElement | null>(null);
const dock = useRef<HTMLDivElement | null>(null);
const api = useRef<ComposerFieldApi | null>(null);
const [queue, setQueue] = useState<Queued[]>([]);
const [returning, setReturning] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [refused, setRefused] = useState<string | null>(null);
const [said, setSaid] = useState("");
const [rated, setRated] = useState<Record<string, "good" | "bad" | null>>({});
const [copied, setCopied] = useState<string | null>(null);
const [online, setOnline] = useState(false);
const [qtb, setQtb] = useState<{ x: number; y: number } | null>(null);
const [actsOn, setActsOn] = useState<string[]>([]);
const flight = useRef<{ text: string; rect: ReturnType<typeof innerRect>; style: { fontSize: string; lineHeight: string }; queued?: boolean; id?: string } | null>(null);
const ids = useRef(0);
const fresh = messages.length === 0 && queue.length === 0;
const ms = (name: string) => num(chat.current, name);
// the live region: cleared, then said a frame later, so the same words are announced again
const say = (t: string) =>
requestAnimationFrame(() => {
setSaid("");
requestAnimationFrame(() => setSaid(t));
});
const scrollEnd = () => {
if (thread.current) thread.current.scrollTop = thread.current.scrollHeight;
};
// the first message: the box glides from where it sat to the bottom
const wasFresh = useRef(fresh);
const dockTop = useRef(0);
useLayoutEffect(() => {
const d = dock.current;
if (!d) return;
if (wasFresh.current && !fresh) {
const dy = dockTop.current - d.getBoundingClientRect().top;
if (!prefersReducedMotion() && Math.abs(dy) > 1) safeAnimate(d, [{ transform: `translateY(${dy}px)` }, { transform: "none" }], { duration: ms("--pixilui-composer-glide"), easing: tok(chat.current, "--pixilui-composer-ease") });
}
// while the chat is empty, where the box sits (it glides from here when the first message goes)
if (fresh) dockTop.current = d.getBoundingClientRect().top;
wasFresh.current = fresh;
});
// the hand-off: your words fly from the box into their bubble, which fills in under them
const takeOff = (text: string, queued?: boolean, id?: string) => {
const input = api.current?.input;
if (!input) return;
const cs = getComputedStyle(input);
flight.current = { text, rect: innerRect(input), style: { fontSize: cs.fontSize, lineHeight: cs.lineHeight }, queued, id };
};
useLayoutEffect(() => {
const f = flight.current;
if (!f || !thread.current) return;
const rows = [...thread.current.querySelectorAll<HTMLElement>(".pixilui-composer-urow")];
const row = f.id ? thread.current.querySelector<HTMLElement>(`[data-queue-id="${f.id}"]`) : rows.filter((r) => !r.hasAttribute("data-queue-id")).pop();
if (!row) return;
flight.current = null;
scrollEnd();
if (prefersReducedMotion()) return;
const bubble = row.querySelector<HTMLElement>(".pixilui-composer-user")!;
const ut = row.querySelector<HTMLElement>(".pixilui-composer-ut")!;
bubble.classList.add("pixilui-composer-arriving");
ut.style.color = "transparent";
setTimeout(() => {
bubble.classList.add("pixilui-composer-land");
bubble.classList.remove("pixilui-composer-arriving");
}, ms("--pixilui-composer-land"));
void composerFly(
f.text,
f.rect,
f.style,
() => {
const r = ut.getBoundingClientRect();
return { left: r.left, top: r.top, width: r.width + 1 };
},
ms("--pixilui-composer-fly"),
{ toOpacity: f.queued ? num(chat.current, "--pixilui-composer-queued-o") : 1 },
).then(() => (ut.style.color = ""));
});
const submit = (draft: ComposerMessageDraft): boolean => {
if (returning) return false;
if (working || offline) {
const id = `q${++ids.current}`;
api.current?.sweep();
takeOff(draft.text, true, id);
setQueue((q) => [...q, { id, draft }]);
say(offline && !working ? w.sayOffline : w.sayQueued(queue.length + 1));
return true;
}
takeOff(draft.text);
if (onSend(draft) === false) {
flight.current = null;
return false;
}
api.current?.sweep();
return true;
};
// the next waiting message goes when the reply ends, or when the connection comes back
const activate = (q: Queued) => {
setQueue((list) => list.filter((x) => x.id !== q.id));
say(w.saySending);
onSend(q.draft);
};
const wasWorking = useRef(working);
// a reply stopped (Stop, Send now) is not a reply ended: the queue doesn't move on by itself then
const stopped = useRef(false);
useEffect(() => {
const ended = wasWorking.current && !working;
wasWorking.current = working;
if (ended && stopped.current) {
stopped.current = false;
return;
}
if (!ended || offline || !queue[0]) return;
const first = queue[0];
const t = setTimeout(() => activate(first), ms("--pixilui-composer-next-after"));
return () => clearTimeout(t);
// the reply ending is the trigger
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [working]);
const wasOffline = useRef(offline);
useEffect(() => {
const back = wasOffline.current && !offline;
wasOffline.current = offline;
if (offline) say(w.sayOffline);
if (!back) return;
say(w.sayOnline);
const t0 = setTimeout(() => setOnline(true));
const t1 = setTimeout(() => setOnline(false), ms("--pixilui-composer-online-note"));
const first = queue[0];
const t2 = !working && first ? setTimeout(() => activate(first), ms("--pixilui-composer-online-send")) : undefined;
return () => {
clearTimeout(t0);
clearTimeout(t1);
clearTimeout(t2);
};
// the connection changing is the trigger
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [offline]);
// Stop: the waiting messages travel back into the box, lowest first, onto the lines you'd type them on; send waits for them
const giveBack = async () => {
const rows = [...(thread.current?.querySelectorAll<HTMLElement>(".pixilui-composer-urow[data-queue-id]") ?? [])];
const input = api.current?.input;
if (!rows.length || !input) return;
const list = queue;
const before = api.current!.text();
const lines0 = before ? before.split("\n").length : 0;
const lh = parseFloat(getComputedStyle(input).lineHeight) || 20;
const starts = rows.map((r) => {
const ut = r.querySelector<HTMLElement>(".pixilui-composer-ut")!;
return { ut, rect: ut.getBoundingClientRect(), cs: getComputedStyle(ut) };
});
setReturning(true);
api.current!.setText((before ? `${before}\n` : "") + list.map((q) => q.draft.text).join("\n"), { hidden: true, focus: false });
const reduce = prefersReducedMotion();
const ghosts = await Promise.all(
rows.map((r, i) =>
sleep(reduce ? 0 : (rows.length - 1 - i) * ms("--pixilui-composer-back-stagger")).then(() => {
const { ut, rect, cs } = starts[i]!;
ut.style.color = "transparent";
if (!reduce && typeof r.animate === "function") safeAnimate(r, [{ opacity: 1, height: `${r.offsetHeight}px` }, { opacity: 0, height: "0px" }], { duration: ms("--pixilui-dur-travel"), easing: tok(chat.current, "--pixilui-ease-move"), fill: "forwards" });
return composerFly(
list[i]!.draft.text,
{ left: rect.left, top: rect.top, width: rect.width },
cs,
() => {
const x = innerRect(input);
return { left: x.left, top: x.top + (lines0 + i) * lh, width: x.width };
},
ms("--pixilui-dur-travel"),
{ fromOpacity: num(chat.current, "--pixilui-composer-queued-o"), keep: true },
);
}),
),
);
flushSync(() => setQueue([]));
api.current!.reveal();
ghosts.forEach((g) => g && g.remove());
setReturning(false);
api.current!.focus();
say(w.sayGivenBack(list.length));
};
const stop = () => {
if (!working) return;
stopped.current = true;
onStop?.();
if (queue.length) void giveBack();
else say(w.sayStopped);
};
const sendNow = (q: Queued) => {
if (offline) return;
if (working) {
stopped.current = true;
onStop?.();
}
setQueue((list) => [q, ...list.filter((x) => x.id !== q.id)]);
activate(q);
};
// edit in place; the old version and its reply stay a click away
const lastUser = [...messages].reverse().find((m) => m.role === "user");
// a one-off reason on a control that can't act right now
const refuse = (id: string) => {
setRefused(id);
setTimeout(() => setRefused(null), ms("--pixilui-composer-reason-hold"));
};
const startEdit = (id: string) => {
if (working) return refuse(id);
setEditing(id);
say(w.sayEditing);
};
const editor = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const ed = editor.current;
if (!editing || !ed) return;
const m = messages.find((x) => x.id === editing);
if (m?.role === "user") ed.textContent = m.text;
ed.focus();
caretToEnd(ed);
ed.closest(".pixilui-composer-urow")?.scrollIntoView({ block: "nearest", behavior: prefersReducedMotion() ? "auto" : "smooth" });
// a new editor only
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editing]);
const swapped = useRef<string | null>(null);
const saveEdit = () => {
const id = editing;
const t = (editor.current?.innerText ?? editor.current?.textContent ?? "").trim();
const m = messages.find((x) => x.id === id);
setEditing(null);
api.current?.focus();
if (!id || !t || (m?.role === "user" && t === m.text)) return;
swapped.current = id;
onEdit?.(id, t);
};
useLayoutEffect(() => {
const id = swapped.current;
if (!id) return;
swapped.current = null;
const ut = thread.current?.querySelector<HTMLElement>(`[data-message-id="${id}"] .pixilui-composer-ut`);
if (ut && !prefersReducedMotion()) safeAnimate(ut, [{ opacity: 0, filter: `blur(${tok(chat.current, "--pixilui-blur-swap")})` }, { opacity: 1, filter: "none" }], { duration: ms("--pixilui-composer-edit-swap"), easing: tok(chat.current, "--pixilui-ease-out") });
});
// a reply's actions come in a beat after its last words
const doneIds = messages.filter((m) => m.role === "agent" && m.done).map((m) => m.id);
useEffect(() => {
const fresh2 = doneIds.filter((id) => !actsOn.includes(id));
if (!fresh2.length) return;
const t = setTimeout(() => requestAnimationFrame(() => requestAnimationFrame(() => setActsOn((a) => [...a, ...fresh2]))), ms("--pixilui-composer-acts-after"));
return () => clearTimeout(t);
});
useLayoutEffect(scrollEnd, [messages.length, queue.length]);
// quote: words selected in a reply carry into the box
useEffect(() => {
if (!onQuote) return;
const sel = () => {
const s = getSelection();
const node = s?.anchorNode && (s.anchorNode.nodeType === 3 ? s.anchorNode.parentElement : (s.anchorNode as Element));
if (!s || !s.rangeCount || s.isCollapsed || !node || !thread.current?.contains(node) || !node.closest(".pixilui-composer-ans") || s.toString().trim().length < 3) {
setQtb(null);
return;
}
const r = s.getRangeAt(0).getBoundingClientRect();
setQtb({ x: r.left + r.width / 2 - num(chat.current, "--pixilui-composer-quote-x"), y: r.top - num(chat.current, "--pixilui-composer-quote-y") });
};
document.addEventListener("selectionchange", sel);
return () => document.removeEventListener("selectionchange", sel);
}, [onQuote]);
const latest = [...messages].reverse().find((m) => m.role === "agent" && m.done)?.id;
const bubble = (m: { text: string; quote?: string; files?: string }) => (
<div className="pixilui-composer-user">
{m.quote ? <span className="pixilui-composer-qb">{m.quote}</span> : null}
{m.files ? (
<span className="pixilui-composer-fa">
{slot(ti.attachment)}
{m.files}
</span>
) : null}
<span className="pixilui-composer-ut">{m.text}</span>
</div>
);
const copy = (id: string, text: string) => {
void navigator.clipboard?.writeText(text).catch(() => {});
setCopied(id);
setTimeout(() => setCopied(null), ms("--pixilui-composer-copy-state"));
say(w.sayCopied);
};
const editQueued = (q: Queued) => {
setQueue((l) => l.filter((x) => x.id !== q.id));
const t = api.current?.text() ?? "";
api.current?.setText((t ? `${t}\n` : "") + q.draft.text);
say(w.sayBackInBox);
};
const dropQueued = (q: Queued) => {
const row = thread.current?.querySelector<HTMLElement>(`[data-queue-id="${q.id}"]`);
const done = () => setQueue((l) => l.filter((x) => x.id !== q.id));
if (!row || prefersReducedMotion()) done();
else safeAnimate(row, [{ opacity: 1 }, { opacity: 0 }], { duration: ms("--pixilui-composer-row-out"), easing: tok(chat.current, "--pixilui-ease-in") }).finished.then(done, done);
api.current?.focus();
say(w.sayRemoved);
};
return (
<div
ref={(el) => {
chat.current = el;
if (typeof ref === "function") ref(el);
else if (ref) ref.current = el;
}}
className={cn("flex h-full min-h-0 w-full flex-col font-body", fresh && "justify-center", className)}
data-fresh={fresh ? "" : undefined}
>
<div ref={thread} className="pixilui-composer-thread" hidden={fresh}>
{messages.map((m) => {
if (m.role === "note")
return (
<div key={m.id} className="pixilui-composer-tnote">
{slot(ti.note)}
{m.text}
</div>
);
if (m.role === "user") {
const n = m.versions?.length ?? 1;
const v = m.version ?? n - 1;
const isEditing = editing === m.id;
return (
<div key={m.id} className={cn("pixilui-composer-urow", isEditing && "pixilui-composer-editing")} data-message-id={m.id}>
{bubble(m)}
<div className={cn("pixilui-composer-uacts", n > 1 && "pixilui-composer-pin")}>
<span className="pixilui-composer-ver" hidden={n < 2}>
<ThreadButton label={w.previousVersion} icon={ti.previous} onClick={() => !working && onVersion?.(m.id, v - 1)} disabled={v === 0} />
<span className="pixilui-composer-vn">{n > 1 ? w.version(v + 1, n) : ""}</span>
<ThreadButton label={w.nextVersion} icon={ti.next} onClick={() => !working && onVersion?.(m.id, v + 1)} disabled={v === n - 1} />
</span>
<ThreadButton label={w.copyMessage} tip={w.copy} icon={ti.copy} copied={copied === m.id} onClick={() => copy(m.id, m.text)} />
<Tooltip label={w.edit} shortcut="↑" reason={refused === m.id ? w.waitForReply : undefined} open={refused === m.id ? true : undefined}>
<Button variant="secondary-2" size="xs" aria-label={w.editMessage} icon={slot(ti.edit)} onClick={() => startEdit(m.id)} />
</Tooltip>
</div>
<QueueCaption words={w} icon={ti.remove} />
{isEditing ? (
<div className="pixilui-composer-uedit">
<div
ref={editor}
contentEditable={"plaintext-only" as unknown as boolean}
suppressContentEditableWarning
role="textbox"
aria-multiline="true"
aria-label={w.editLabel}
spellCheck={false}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
saveEdit();
}
if (e.key === "Escape") {
e.preventDefault();
setEditing(null);
api.current?.focus();
}
}}
/>
<div className="pixilui-composer-edit-row">
<Button size="sm" variant="secondary-2" onClick={() => { setEditing(null); api.current?.focus(); }}>
{w.cancel}
</Button>
<Button size="sm" variant="primary" onClick={saveEdit}>
{w.save}
</Button>
</div>
</div>
) : null}
</div>
);
}
const a = m.approval;
return (
<div key={m.id} className={cn("pixilui-composer-turn", latest === m.id && "pixilui-composer-latest")}>
<div className="pixilui-composer-trail">{m.trail}</div>
{a && !a.answer ? (
<div className="pixilui-composer-approve" role="group" aria-label={w.approvalGroup} data-arriving={prefersReducedMotion() ? undefined : ""} onAnimationEnd={(e) => e.currentTarget.removeAttribute("data-arriving")}>
<p className="pixilui-composer-ap-q">{a.question}</p>
<code className="pixilui-composer-ap-cmd">{a.command}</code>
<p className="pixilui-composer-ap-why">{a.why}</p>
<div className="pixilui-composer-ap-acts">
<Button size="sm" variant="primary" onClick={() => onApprove?.(m.id, "once")}>
{w.allowOnce}
</Button>
<Button size="sm" variant="secondary-2" onClick={() => onApprove?.(m.id, "chat")}>
{w.allowChat}
</Button>
<span className="pixilui-composer-grow" />
<Button size="sm" variant="secondary-2" onClick={() => onApprove?.(m.id, "deny")}>
{w.deny}
</Button>
</div>
</div>
) : a?.answer ? (
<div className="pixilui-composer-ap-done">
{slot(a.answer === "once" || a.answer === "chat" ? ti.allowed : ti.denied)}
<span>{w.said[a.answer]}</span>
<code>{a.command}</code>
</div>
) : null}
{m.long && !m.done ? (
<div className="pixilui-composer-long">
{m.long === "notify" ? (
<>
{slot(ti.notify)}
<span>{w.notified}</span>
</>
) : (
<>
{slot(ti.clock)}
<span>{w.longRun}</span>
<Button variant="link" size="xs" onClick={() => onNotify?.(m.id)}>
<span>{w.notify}</span>
</Button>
</>
)}
</div>
) : null}
{m.answer != null ? <div className="pixilui-composer-ans pixilui-answer">{m.answer}</div> : null}
{m.done ? (
<div className={cn("pixilui-composer-acts", actsOn.includes(m.id) && "pixilui-composer-on")}>
<ThreadButton label={w.copy} icon={ti.copy} copied={copied === m.id} onClick={(e) => copy(m.id, e.currentTarget.closest(".pixilui-composer-turn")?.querySelector<HTMLElement>(".pixilui-composer-ans")?.innerText ?? "")} />
{(["good", "bad"] as const).map((r) => (
<Tooltip key={r} label={r === "good" ? w.goodReply : w.badReply}>
<Button
variant="secondary-2"
size="xs"
aria-label={r === "good" ? w.goodReply : w.badReply}
icon={slot(r === "good" ? ti.good : ti.bad)}
pressed={rated[m.id] === r}
pressedLook="glyph"
onClick={() => {
const next = rated[m.id] === r ? null : r;
setRated((x) => ({ ...x, [m.id]: next }));
onRate?.(m.id, next);
}}
/>
</Tooltip>
))}
<Tooltip label={w.tryAgain} reason={refused === m.id ? w.waitForReply : undefined} open={refused === m.id ? true : undefined}>
<Button
variant="secondary-2"
size="xs"
aria-label={w.tryAgain}
icon={slot(ti.retry)}
onClick={() => (working ? refuse(m.id) : onRetry?.(m.id))}
/>
</Tooltip>
</div>
) : null}
</div>
);
})}
{queue.map((q) => (
<div key={q.id} className={cn("pixilui-composer-urow pixilui-composer-queued", offline && "pixilui-composer-net")} data-queue-id={q.id}>
{bubble({ text: q.draft.text, quote: q.draft.quote })}
<div className="pixilui-composer-uacts">
<span className="pixilui-composer-ver" hidden />
<ThreadButton label={w.copyMessage} tip={w.copy} icon={ti.copy} />
<ThreadButton label={w.editMessage} tip={w.edit} icon={ti.edit} shortcut="↑" />
</div>
<QueueCaption words={w} icon={ti.remove} onSendNow={() => sendNow(q)} onEdit={() => editQueued(q)} onRemove={() => dropQueued(q)} />
</div>
))}
</div>
{fresh ? greeting : null}
<div ref={dock}>
<ComposerField
{...field}
words={words}
status={status}
notice={offline ? "offline" : online ? "online" : notice}
placeholder={placeholder ?? (working ? fw.placeholderWorking : messages.length ? fw.placeholderFollowUp : fw.placeholder)}
returning={returning}
api={api}
onSubmit={submit}
onStop={stop}
onEditLast={() => lastUser && startEdit(lastUser.id)}
/>
</div>
{qtb && onQuote ? (
<div className="pixilui-composer-qtb pixilui-composer-on" style={{ left: `${qtb.x}px`, top: `${qtb.y}px` }}>
<Button
variant="inverse"
size="xs"
icon={slot(ti.quote)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
const t = getSelection()?.toString().trim().replace(/\s+/g, " ") ?? "";
getSelection()?.removeAllRanges();
setQtb(null);
onQuote(t);
api.current?.focus();
say(w.sayQuoted);
}}
>
{w.quote}
</Button>
</div>
) : null}
<div className="pixilui-composer-sr" aria-live="polite">
{said}
</div>
</div>
);
});
It uses Button, Chip, Dropdown menu, Text shimmer, Kbd, Tooltip, Meter and Usage meter: add them the same way. Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
import { ComposerField } from "@/components/pixilui/composer-field";
<ComposerField
icons={icons}
onChange={onChange}
onSubmit={onSubmit}
/>Fills its container and follows its own width (container queries): the effort word, then the branch, then the folder step aside as it narrows.
API reference
iconsRequiredComposerIcons–The icons it draws.status"submitted" | "streaming" | "ready" | "error""ready"The chat's status: submitted or streaming is the agent at work (send becomes Stop, or Queue once you type).defaultValuestring""Words in the field at first.onChange(text: string) => void–Runs as the words change.onSubmit(draft: ComposerMessageDraft) => void | boolean | Promise<void>–Runs on Enter or Send with what to send; the field then clears. Return false to keep the words in the box (the model is busy).onStop() => void–Runs on Stop (or Escape) while the agent works.onEditLast() => void–Runs on Up in an empty field: edit your last message.placeholderstring–The placeholder; the words' placeholder by default (the working one while the agent works).maxLengthnumber2000The longest message: from 90% a count shows; over it, send is off.quotestring–Words quoted from a reply, over the field.onQuoteRemove() => void–Runs when the quote's cross is pressed.filesComposerFile[][]The file tiles.onRemoveFile(id: string) => void–Runs when a tile's cross is pressed (it leaves first).onRetryFile(id: string) => void–Runs on a failed tile's Retry.onFiles(files: File[]) => void–Files picked, pasted as files or dropped (up to six).onLongPaste(text: string) => void–A paste over 600 characters or 10 lines: it becomes a "Pasted text" file instead of a wall of words.sourcesComposerSource[][]The + menu's sources.onAddSource(id: string) => void–Runs when a source (not upload) is picked.toolsComposerTool[][]The + menu's tools; the ones on show as chips.toolsOnstring[][]The tools that are on.onToolsChange(ids: string[]) => void–Runs with the tools on after a switch or a chip's cross.connectorsComposerConnector[]–The Connectors submenu.onConnectorChange(id: string, on: boolean) => void–Runs when a connector's switch flips.onReconnect(id: string) => void–Runs when a signed-out connector is picked (it reconnects in place: set reconnecting, then on).onBrowseConnectors() => void–Browse connectors.onManageConnectors() => void–Manage connectors.modelsComposerOption[][]The models.modelstring–The model in use (an id).onModelChange(id: string) => void–Runs when a model is picked.effort0 | 1 | 2 | 31Effort, 0 to 3 (Low, Medium, High, Max).onEffortChange(level: ComposerEffort) => void–Runs when the effort changes (the ramp, its names, or Left and Right in the model menu).permissionsComposerOption[][]What the agent may do.permissionstring–The permission in use (an id).unlockedstring–The permission whose button shows its lock open (auto-approve).onPermissionChange(id: string) => void–Runs when a permission is picked.foldersstring[]–Recent folders.folderstring–The folder it works in.onFolderChange(folder: string) => void–Runs when a folder is picked.onOpenFolder() => void–Open a folder.branchesstring[]–Branches.branchstring–The branch it works on.onBranchChange(branch: string) => void–Runs when a branch is picked.onNewBranch() => void–Start a new branch.contextnumber–How full the context is, 0 to 100: from 70 the tray shows the inline meter and Compact.onCompact() => void–Compact the conversation.commandsComposerOption[][]/ commands.mentionsComposerOption[][]Files to mention after an at sign: label the name, description its path.noticeComposerNotice | nullnullA notice in the box.noticePlace"in" | "above""in"in: an inset banner at the top of the box (the default); above: a plain line over it.busy{ model: string; instead: string }–The busy model and the one to offer instead, for the busy notice.onNoticeAction(action: "retry" | "upgrade" | "use-model") => void–A notice's button: retry the send, upgrade, or use the other model (retry and the other model then send again).dictationComposerDictation | nullnullWhile dictating: what it has heard.onDictate() => void–The mic: start dictating (your speech recognition), or finish while dictating.onDictationCancel() => void–Escape while dictating: cancel it (the words before it come back).readOnlyboolean–A shared chat: the box says so, with Continue.onContinue() => void–Continue a shared chat.returningbooleanfalseMessages are flying back into the box: send waits for them.traybooleantrueThe tray under the box (folder, branch, context, permission).apiReact.Ref<ComposerFieldApi>–The field's handle, for the chat around it.wordsPartial<ComposerWords>–Every word it says.Also takes every native <div> attribute, and a ref.
Keyboard
Accessibility
- The field is a textbox (aria-multiline) described as "Enter sends. Shift Enter adds a line. Slash opens commands, at mentions a file."
- Send stays focusable when it can't send: aria-disabled with its reason as the tooltip (Type a message to send, Too long to send, Sends when the uploads finish).
- Every icon button has a name and its tooltip shows its key; menus are the locked dropdown's (roles, aria-activedescendant, switch rows).
- The effort ramp is a slider with aria-valuetext; the approval card is a group named "The agent is waiting for your approval".
- A polite live region says what happened: Queued, Stopped and the messages back in the box, Copied, Back online.
Motion
- Send: your words fly from the field into their bubble (380ms, an ease-in-out cubic that follows a target that can move) while it fills in.
- The first message glides the box from the middle to the bottom (560ms).
- Stop with waiting messages: they fly back into the box, lowest first, 80ms apart, each 420ms, their rows folding; send stays off until they land.
- A white sheen sweeps across send once as a message leaves; the arrow lifts when send turns on.
- Effort: the light sweeps bar by bar to the new stop (12ms a bar), the lit bars breathe faster the harder it thinks, Max adds a glint; the cost line swaps with a blur.
- Notices, quote, files and the count open as grid rows (260ms); file tiles arrive, fill their ring and resolve into a check.
- The approval card arrives with a soft glow in the waiting color (1500ms).
- Reduced motion: everything lands at once.