AI Composer
Three ways to ask an agent: a chat dock where a light travels round the card while the agent works, a pill that opens in place into a full prompt, and a command palette with a live preview pane.
"use client"
import * as React from "react"
import {
ArrowUp,
CornerDownLeft,
FileCode,
FileText,
Image as ImageIcon,
Mic,
Plus,
Search,
X,
} from "lucide-react"
import {
AiKitStyles,
AiStyle,
cx,
Face,
Mark,
Roll,
type AiMood,
type AiShape,
type AiTone,
} from "@/lib/ai-kit"
const CSS = `
.aik-cp-dock{--aik-r-shell:28px;--aik-rim:6px;width:min(100%,560px);container-type:inline-size}
.aik-cp-dock[data-s="disabled"]{opacity:.55}
.aik-cp-banner{display:flex;align-items:center;gap:10px;min-height:40px;padding:4px 10px 8px 12px;font-size:13px;color:var(--aik-text-2);animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-cp-card{display:grid;gap:6px;padding:16px 12px 12px 18px;transition:box-shadow var(--aik-d-state) var(--aik-ease-out)}
.aik-cp-dock:focus-within .aik-cp-card{box-shadow:inset 0 0 0 1px var(--aik-line-3)}
.aik-cp-tray{display:flex;gap:8px;flex-wrap:wrap;padding-bottom:6px}
.aik-cp-file{position:relative;display:flex;align-items:center;gap:9px;height:44px;padding:0 12px 0 4px;border-radius:12px;background:var(--aik-raised);font-size:12.5px;animation:aik-pop var(--aik-d-enter) var(--aik-ease-out) both}
.aik-cp-thumb{position:relative;display:grid;place-items:center;width:36px;height:36px;border-radius:9px;background:var(--aik-card);color:var(--aik-text-2);overflow:hidden;box-shadow:inset 0 0 0 1px var(--aik-line)}
.aik-cp-thumb::after{content:"";position:absolute;inset:0;border-radius:inherit;background:conic-gradient(var(--aik-blue) calc(var(--p,1)*360deg),transparent 0);-webkit-mask:radial-gradient(circle,transparent 15px,#000 15.5px);mask:radial-gradient(circle,transparent 15px,#000 15.5px);opacity:0;transition:opacity var(--aik-d-state)}
.aik-cp-file[data-up] .aik-cp-thumb::after{opacity:1}
.aik-cp-file b{display:block;font-weight:500;line-height:16px;max-width:132px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-cp-file span span{display:block;color:var(--aik-text-3);font-size:11.5px;line-height:15px;font-variant-numeric:tabular-nums}
.aik-cp-file button{position:absolute;top:-5px;right:-5px;display:grid;place-items:center;width:18px;height:18px;border-radius:50%;background:var(--aik-pri);color:var(--aik-pri-ink);opacity:0;transform:scale(.6);transition:opacity var(--aik-d-state),transform var(--aik-d-state) var(--aik-ease-out)}
.aik-cp-file:hover button,.aik-cp-file button:focus-visible{opacity:1;transform:none}
.aik-cp-field{position:relative}
.aik-cp-text{display:block;width:100%;min-height:44px;max-height:192px;padding:0 6px 0 0;resize:none;border:0;outline:0;background:none;font-size:15px;line-height:22px}
.aik-cp-text::placeholder,.aik-cp-pin::placeholder,.aik-cp-q::placeholder{color:var(--aik-text-3);opacity:1}
.aik-cp-dock[data-s="running"] .aik-cp-text::placeholder{color:transparent}
.aik .aik-cp-text:focus-visible,.aik .aik-cp-pin:focus-visible,.aik .aik-cp-q:focus-visible{outline:none}
.aik-cp-ghost{position:absolute;inset:0 auto auto 0;pointer-events:none;font-size:15px;line-height:22px}
.aik-cp-bar{display:flex;align-items:center;gap:4px;margin-left:-8px}
.aik-cp-ib{display:grid;place-items:center;width:34px;height:34px;flex:none;border-radius:10px;color:var(--aik-text-2);transition:background var(--aik-d-state),color var(--aik-d-state),transform var(--aik-d-press) var(--aik-ease-out)}
.aik-cp-ib:hover{background:var(--aik-hover);color:var(--aik-text)}
.aik-cp-ib:active{transform:scale(.94)}
.aik-cp-modes{position:relative;display:grid;grid-auto-flow:column;grid-auto-columns:64px;height:30px;padding:2px;border-radius:10px;background:var(--aik-raised)}
.aik-cp-modes::before{content:"";position:absolute;top:2px;left:2px;width:64px;height:26px;border-radius:8px;background:var(--aik-card);box-shadow:var(--aik-sh-card);transform:translateX(calc(var(--i,0)*100%));transition:transform var(--aik-d-panel) var(--aik-ease-move)}
.aik-cp-modes button{position:relative;font-size:12.5px;font-weight:500;color:var(--aik-text-3);transition:color var(--aik-d-state)}
.aik-cp-modes button[aria-checked="true"]{color:var(--aik-text)}
.aik-cp-grow{flex:1}
.aik-cp-agent{display:inline-flex;align-items:center;gap:7px;height:34px;padding:0 8px 0 6px;border-radius:10px;font-size:13px;font-weight:500;white-space:nowrap;transition:background var(--aik-d-state)}
.aik-cp-agent:hover{background:var(--aik-hover)}
.aik-cp-agent > span:not(.aik-face){color:var(--aik-text-3);font-weight:400}
.aik-cp-pie{width:14px;height:14px;border-radius:50%;background:conic-gradient(var(--c,var(--aik-text-2)) calc(var(--p)*3.6deg),var(--aik-line-2) 0);-webkit-mask:radial-gradient(circle,transparent 3.6px,#000 4.2px);mask:radial-gradient(circle,transparent 3.6px,#000 4.2px)}
.aik-cp-pie[data-near]{--c:var(--aik-amber)}
.aik-cp-send{position:relative;display:grid;place-items:center;width:36px;height:36px;flex:none;border-radius:11px;background:color-mix(in oklab,var(--aik-raised) 78%,var(--aik-text) 22%);color:var(--aik-pri-ink);transition:background var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-press) var(--aik-ease-out)}
.aik-cp-send:active{transform:scale(.94)}
.aik-cp-send > *{grid-area:1/1;transition:opacity var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-state) var(--aik-ease-out)}
.aik-cp-send i{width:11px;height:11px;border-radius:3px;background:currentColor;opacity:0;transform:scale(.4)}
[data-s="ready"] .aik-cp-send,[data-s="running"] .aik-cp-send,.aik-cp-send[data-ready]{background:var(--aik-pri)}
[data-s="running"] .aik-cp-send svg{opacity:0;transform:scale(.4)}
[data-s="running"] .aik-cp-send i{opacity:1;transform:none}
.aik-cp-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;height:36px;padding:0 12px 0 14px;color:var(--aik-text-3);font-size:12px}
.aik-cp-foot .aik-roll{line-height:18px}
.aik-cp-foot > span:last-child{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;font-variant-numeric:tabular-nums}
@container (max-width:430px){.aik-cp-modes{display:none}.aik-cp-agent > span:not(.aik-face){display:none}.aik-cp-foot > span:last-child{display:none}}
.aik-cp-pill{position:relative;width:min(100%,540px);filter:drop-shadow(0 10px 22px rgb(12 12 24 / 14%)) drop-shadow(0 0 1px rgb(12 12 24 / 30%))}
.aik-cp-pbox{position:relative;border-radius:26px;background:var(--aik-card);clip-path:inset(0 calc(50% - 132px) calc(100% - 52px) calc(50% - 132px) round 26px);transition:clip-path 520ms var(--aik-ease-move)}
.aik-cp-pill[data-open] .aik-cp-pbox{clip-path:inset(0 0 0 0 round 26px)}
.aik-cp-ptop{position:relative;height:52px}
.aik-cp-prest{position:absolute;inset:0;margin:auto;width:264px;display:flex;align-items:center;gap:10px;padding:0 14px 0 12px;font-size:14px;font-weight:500;text-align:left;transition:opacity var(--aik-d-state) var(--aik-ease-out)}
.aik-cp-prest .aik-roll{flex:1;min-width:0;color:var(--aik-text-2)}
.aik-cp-pill[data-s="running"] .aik-cp-prest .aik-roll{color:var(--aik-blue)}
.aik-cp-pill[data-s="done"] .aik-cp-prest .aik-roll{color:var(--aik-green)}
.aik-cp-pring{position:absolute;inset:0;margin:auto;width:264px;height:52px;border-radius:26px;pointer-events:none}
.aik-cp-prow{position:absolute;inset:0;display:flex;align-items:center;gap:10px;padding:0 8px 0 12px;opacity:0;pointer-events:none;transition:opacity var(--aik-d-state) var(--aik-ease-out)}
.aik-cp-pill[data-open] .aik-cp-prest{opacity:0;pointer-events:none}
.aik-cp-pill[data-open] .aik-cp-prow{opacity:1;pointer-events:auto;transition-delay:160ms}
.aik-cp-pin{flex:1;min-width:0;height:100%;border:0;outline:0;background:none;font-size:15px}
.aik-cp-pbody{display:grid;gap:12px;padding:6px 12px 12px;opacity:0;transform:translateY(-6px);transition:opacity var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-panel) var(--aik-ease-out)}
.aik-cp-pill[data-open] .aik-cp-pbody{opacity:1;transform:none;transition-delay:200ms}
.aik-cp-sugg{display:grid;gap:2px}
.aik-cp-sugg button{display:flex;align-items:center;gap:10px;height:36px;padding:0 10px;border-radius:10px;font-size:13.5px;color:var(--aik-text-2);text-align:left;transition:background var(--aik-d-state),color var(--aik-d-state)}
.aik-cp-sugg button:hover,.aik-cp-sugg button:focus-visible{background:var(--aik-raised);color:var(--aik-text)}
.aik-cp-sugg svg{color:var(--aik-text-3)}
.aik-cp-tools{display:flex;gap:6px;flex-wrap:wrap;padding-top:10px;border-top:1px solid var(--aik-line)}
.aik-cp-tool{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 10px;border-radius:9px;font-size:12.5px;font-weight:500;color:var(--aik-text-2);box-shadow:inset 0 0 0 1px var(--aik-line-2);transition:background var(--aik-d-state),color var(--aik-d-state),box-shadow var(--aik-d-state),transform var(--aik-d-press)}
.aik-cp-tool:active{transform:scale(.96)}
.aik-cp-tool[aria-pressed="true"]{color:var(--aik-blue);background:color-mix(in oklab,var(--aik-blue) 11%,transparent);box-shadow:inset 0 0 0 1px color-mix(in oklab,var(--aik-blue) 40%,transparent)}
@media (prefers-reduced-motion: reduce){.aik-cp-pbox{transition:none}}
.aik-cp-pal{--aik-r-shell:24px;--aik-rim:5px;width:min(100%,580px);container-type:inline-size}
.aik-cp-pcard{overflow:hidden}
.aik-cp-search{display:flex;align-items:center;gap:10px;height:52px;padding:0 12px 0 16px;border-bottom:1px solid var(--aik-line);color:var(--aik-text-3)}
.aik-cp-q{flex:1;min-width:0;height:100%;border:0;outline:0;background:none;font-size:15px;color:var(--aik-text)}
.aik-cp-pal[data-s="running"] .aik-cp-q,.aik-cp-pal[data-s="done"] .aik-cp-q{display:none}
.aik-cp-pstat{flex:1;min-width:0;display:none;align-items:center;gap:8px;font-size:15px;font-weight:500;color:var(--aik-text)}
.aik-cp-pal[data-s="running"] .aik-cp-pstat,.aik-cp-pal[data-s="done"] .aik-cp-pstat{display:flex;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-cp-pgrid{display:grid;grid-template-columns:minmax(0,1fr) 216px;height:288px}
.aik-cp-list{position:relative;overflow-y:auto;padding:6px;scrollbar-width:none}
.aik-cp-hl{position:absolute;left:6px;right:6px;top:0;height:36px;border-radius:10px;background:var(--aik-raised);transform:translateY(var(--y,6px));transition:transform var(--aik-d-state) var(--aik-ease-move)}
.aik-cp-glabel{position:relative;display:flex;align-items:center;height:28px;padding:0 10px}
.aik-cp-row{position:relative;display:flex;align-items:center;gap:10px;width:100%;height:36px;padding:0 10px;border-radius:10px;font-size:13.5px;text-align:left;color:var(--aik-text-2);transition:color var(--aik-d-state)}
.aik-cp-row[aria-selected="true"]{color:var(--aik-text)}
.aik-cp-row b{flex:1;min-width:0;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-cp-row em{font:11.5px var(--aik-mono);font-style:normal;color:var(--aik-text-3);white-space:nowrap}
.aik-cp-empty{display:grid;place-items:center;height:100%;color:var(--aik-text-3);font-size:13.5px}
.aik-cp-prev{display:grid;align-content:start;gap:10px;padding:16px;border-left:1px solid var(--aik-line);background:var(--aik-panel);min-width:0}
.aik-cp-prev > div{display:grid;gap:10px;animation:aik-in var(--aik-d-panel) var(--aik-ease-out) both}
.aik-cp-tile{display:grid;place-items:center;width:44px;height:44px;border-radius:12px;background:var(--aik-raised);color:var(--aik-text)}
.aik-cp-prev h4{font-size:14.5px;line-height:20px;font-weight:600;letter-spacing:-.01em}
.aik-cp-prev p{font-size:13px;line-height:19px;color:var(--aik-text-2)}
.aik-cp-kv{display:grid;gap:6px;padding-top:10px;border-top:1px solid var(--aik-line);font-size:12px}
.aik-cp-kv div{display:flex;justify-content:space-between;gap:8px;color:var(--aik-text-3)}
.aik-cp-kv b{font:12px var(--aik-mono);font-weight:400;color:var(--aik-text-2)}
.aik-cp-pfoot{display:flex;align-items:center;gap:14px;height:36px;padding:0 12px;color:var(--aik-text-3);font-size:12px}
.aik-cp-pfoot span{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.aik-cp-pfoot span:last-child{margin-left:auto}
@container (max-width:470px){.aik-cp-pgrid{grid-template-columns:minmax(0,1fr)}.aik-cp-prev{display:none}}
`
export interface AiAgentLook {
name: string
/** A short qualifier after the name, such as "fast". */
detail?: string
tone?: AiTone | (string & {})
shape?: AiShape
mood?: AiMood
}
export interface AiComposerAttachment {
id: string
name: string
kind?: "file" | "code" | "image"
/** A second line under the name, such as a size. */
meta?: string
/** Upload progress from 0 to 1. Omit once the file is ready. */
progress?: number
/** A custom thumbnail in place of the kind icon. */
preview?: React.ReactNode
}
export interface AiComposerProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSubmit"
> {
value: string
onValueChange: (value: string) => void
/** Called with the trimmed text on Enter or the send button. */
onSubmit?: (value: string) => void
/** Called when send is pressed, or Escape is hit, while `status` is `streaming`. */
onStop?: () => void
status?: "ready" | "streaming"
placeholder?: string
/** Shown, shimmering, in the empty field while the agent works. */
streamingPlaceholder?: string
attachments?: AiComposerAttachment[]
onRemoveAttachment?: (id: string) => void
onAttach?: () => void
onVoice?: () => void
/** Mode names for the segmented switch in the bar, such as Ask, Plan, Build. */
modes?: string[]
mode?: string
onModeChange?: (mode: string) => void
agent?: AiAgentLook
onAgentClick?: () => void
/** How full the context window is, 0 to 100. Shown as a pie on the agent chip. */
context?: number
/** A row docked inside the frame above the card, for an approval or a queued message. */
banner?: React.ReactNode
disabled?: boolean
}
const KIND_ICON = { file: FileText, code: FileCode, image: ImageIcon }
/**
* The chat dock: a rim holding one card. Attachments sit in a tray, the field
* grows with its text, send becomes stop in place, and while the agent works a
* light travels round the card's edge.
*/
export function AiComposer({
value,
onValueChange,
onSubmit,
onStop,
status = "ready",
placeholder = "Ask anything",
streamingPlaceholder = "Working. Esc to stop.",
attachments = [],
onRemoveAttachment,
onAttach,
onVoice,
modes,
mode,
onModeChange,
agent,
onAgentClick,
context,
banner,
disabled = false,
className,
...rest
}: AiComposerProps) {
const field = React.useRef<HTMLTextAreaElement>(null)
const streaming = status === "streaming"
const ready = value.trim().length > 0
React.useLayoutEffect(() => {
const node = field.current
if (!node) return
node.style.height = "auto"
node.style.height = `${node.scrollHeight}px`
}, [value])
const submit = () => {
if (streaming) return onStop?.()
if (ready && !disabled) onSubmit?.(value.trim())
}
const modeIndex = Math.max(0, modes?.indexOf(mode ?? "") ?? 0)
return (
<div
{...rest}
className={cx("aik aik-cp-dock", className)}
data-s={
disabled
? "disabled"
: streaming
? "running"
: ready
? "ready"
: "empty"
}
>
<AiKitStyles />
<AiStyle id="ai-composer" css={CSS} />
<div className="aik-shell">
{banner ? <div className="aik-cp-banner">{banner}</div> : null}
<div className="aik-surface aik-cp-card">
{attachments.length > 0 ? (
<div className="aik-cp-tray">
{attachments.map((file) => {
const Icon = KIND_ICON[file.kind ?? "file"]
const uploading =
file.progress !== undefined && file.progress < 1
return (
<span
key={file.id}
className="aik-cp-file"
data-up={uploading ? "" : undefined}
>
<span
className="aik-cp-thumb"
style={
{ "--p": file.progress ?? 1 } as React.CSSProperties
}
>
{file.preview ?? <Icon size={16} />}
</span>
<span>
<b>{file.name}</b>
<span>
{uploading
? `${Math.round((file.progress ?? 0) * 100)}%`
: (file.meta ?? "Ready")}
</span>
</span>
<button
type="button"
aria-label={`Remove ${file.name}`}
onClick={() => onRemoveAttachment?.(file.id)}
>
<X size={11} strokeWidth={2.5} />
</button>
</span>
)
})}
</div>
) : null}
<div className="aik-cp-field">
<textarea
ref={field}
className="aik-cp-text"
rows={1}
value={value}
disabled={disabled}
placeholder={placeholder}
aria-label={placeholder}
onChange={(event) => onValueChange(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape" && streaming) onStop?.()
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.nativeEvent.isComposing
) {
event.preventDefault()
submit()
}
}}
/>
{streaming && !value ? (
<span className="aik-cp-ghost aik-shimmer">
{streamingPlaceholder}
</span>
) : null}
</div>
<div className="aik-cp-bar">
<button
type="button"
className="aik-cp-ib"
aria-label="Attach"
onClick={onAttach}
>
<Plus size={18} />
</button>
{modes && modes.length > 0 ? (
<div
className="aik-cp-modes"
role="radiogroup"
aria-label="Mode"
style={{ "--i": modeIndex } as React.CSSProperties}
>
{modes.map((item, index) => (
<button
key={item}
type="button"
role="radio"
aria-checked={index === modeIndex}
onClick={() => onModeChange?.(item)}
>
{item}
</button>
))}
</div>
) : null}
<span className="aik-cp-grow" />
{agent ? (
<button
type="button"
className="aik-cp-agent"
onClick={onAgentClick}
>
<Face
size={20}
shape={agent.shape ?? "orb"}
tone={agent.tone ?? "blue"}
mood={
agent.mood ??
(streaming ? "work" : ready ? "listen" : "idle")
}
/>
{agent.name}
{agent.detail ? <span>{agent.detail}</span> : null}
{context === undefined ? null : (
<i
className="aik-cp-pie"
data-near={context >= 80 ? "" : undefined}
title={`${Math.round(context)}% of context used`}
style={{ "--p": context } as React.CSSProperties}
/>
)}
</button>
) : null}
<button
type="button"
className="aik-cp-ib"
aria-label="Voice"
onClick={onVoice}
>
<Mic size={18} />
</button>
<button
type="button"
className="aik-cp-send"
aria-label={streaming ? "Stop" : "Send"}
disabled={disabled || (!streaming && !ready)}
onClick={submit}
>
<ArrowUp size={18} />
<i />
</button>
</div>
<i className="aik-beam" data-on={streaming ? "" : undefined} />
</div>
<div className="aik-cp-foot">
<Roll>
{streaming
? "Esc stops · keep typing to queue a follow-up"
: "Enter sends · Shift Enter for a new line"}
</Roll>
{context === undefined ? null : (
<span>{Math.round(context)}% context</span>
)}
</div>
</div>
</div>
)
}
export interface AiPromptTool {
id: string
label: string
icon?: React.ReactNode
on: boolean
}
export interface AiPromptPillProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSubmit"
> {
/** Whether the pill is opened into the full prompt. */
open: boolean
onOpenChange: (open: boolean) => void
value: string
onValueChange: (value: string) => void
onSubmit?: (value: string) => void
/** `running` and `done` show `statusLabel` in the closed pill. */
status?: "idle" | "running" | "done"
statusLabel?: string
/** The closed pill's resting label. */
label?: string
/** One-tap prompts listed in the open pill. */
suggestions?: string[]
onPick?: (suggestion: string) => void
/** Toggles along the bottom of the open pill, such as Web or Files. */
tools?: AiPromptTool[]
onToggleTool?: (id: string) => void
agent?: Omit<AiAgentLook, "name" | "detail">
}
/**
* A prompt that lives as a small pill and opens in place into a full composer.
* After sending it folds back and the pill itself reports progress.
*/
export function AiPromptPill({
open,
onOpenChange,
value,
onValueChange,
onSubmit,
status = "idle",
statusLabel,
label = "Ask anything",
suggestions = [],
onPick,
tools = [],
onToggleTool,
agent,
className,
onKeyDown,
...rest
}: AiPromptPillProps) {
const input = React.useRef<HTMLInputElement>(null)
React.useEffect(() => {
if (open) input.current?.focus({ preventScroll: true })
}, [open])
const mood: AiMood =
agent?.mood ??
(status === "running"
? "work"
: status === "done"
? "happy"
: open
? "listen"
: "idle")
const send = (text: string) => {
if (text.trim()) onSubmit?.(text.trim())
}
const hasText = value.trim().length > 0
return (
<div
{...rest}
className={cx("aik aik-cp-pill", className)}
data-open={open ? "" : undefined}
data-s={status}
onKeyDown={(event) => {
if (event.key === "Escape" && open) onOpenChange(false)
onKeyDown?.(event)
}}
>
<AiKitStyles />
<AiStyle id="ai-composer" css={CSS} />
<div className="aik-cp-pbox">
<div className="aik-cp-ptop">
<button
type="button"
className="aik-cp-prest"
aria-expanded={open}
tabIndex={open ? -1 : 0}
onClick={() => onOpenChange(true)}
>
<Face
size={28}
shape={agent?.shape ?? "orb"}
tone={agent?.tone ?? "blue"}
mood={mood}
/>
<Roll>{status === "idle" ? label : (statusLabel ?? label)}</Roll>
{status === "idle" ? <kbd className="aik-kbd">⌘K</kbd> : null}
{status === "done" ? <Mark status="done" /> : null}
</button>
<span className="aik-cp-pring">
<i
className="aik-beam"
data-on={status === "running" && !open ? "" : undefined}
/>
</span>
<div className="aik-cp-prow">
<Face
size={28}
shape={agent?.shape ?? "orb"}
tone={agent?.tone ?? "blue"}
mood={mood}
/>
<input
ref={input}
className="aik-cp-pin"
value={value}
placeholder={label}
aria-label={label}
tabIndex={open ? 0 : -1}
onChange={(event) => onValueChange(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault()
send(value)
}
}}
/>
<button
type="button"
className="aik-cp-send"
data-ready={hasText ? "" : undefined}
aria-label="Send"
tabIndex={open ? 0 : -1}
onClick={() => send(value)}
>
<ArrowUp size={18} />
<i />
</button>
</div>
</div>
<div className="aik-cp-pbody" inert={!open}>
{suggestions.length > 0 ? (
<div className="aik-cp-sugg">
{suggestions.map((item) => (
<button
key={item}
type="button"
onClick={() => (onPick ? onPick(item) : send(item))}
>
<CornerDownLeft size={14} />
{item}
</button>
))}
</div>
) : null}
{tools.length > 0 ? (
<div className="aik-cp-tools">
{tools.map((tool) => (
<button
key={tool.id}
type="button"
className="aik-cp-tool"
aria-pressed={tool.on}
onClick={() => onToggleTool?.(tool.id)}
>
{tool.icon}
{tool.label}
</button>
))}
</div>
) : null}
</div>
</div>
</div>
)
}
export interface AiPaletteItem {
id: string
title: string
/** Shown at the right of the row, in mono: a shortcut or a path. */
hint?: string
icon?: React.ReactNode
/** The preview pane's paragraph. */
description?: string
/** Label and value pairs under the description. */
facts?: Array<[string, string]>
}
export interface AiPaletteGroup {
label: string
items: AiPaletteItem[]
}
export interface AiCommandPaletteProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSubmit"
> {
groups: AiPaletteGroup[]
query: string
onQueryChange: (query: string) => void
/** Called on Enter or a click with the highlighted item. */
onRun?: (item: AiPaletteItem) => void
/** The highlighted item's id. Leave undefined to let the arrow keys manage it. */
active?: string
onActiveChange?: (id: string) => void
status?: "idle" | "running" | "done"
/** Replaces the search field while running or done. */
statusLabel?: string
placeholder?: string
}
const ROW = 36
const LABEL = 28
/**
* A command palette for agents: one search over commands, files and agents,
* a highlight that slides between rows, and a preview pane for the current row.
*/
export function AiCommandPalette({
groups,
query,
onQueryChange,
onRun,
active,
onActiveChange,
status = "idle",
statusLabel,
placeholder = "Search commands, files and agents",
className,
...rest
}: AiCommandPaletteProps) {
const uid = React.useId()
const [ownActive, setOwnActive] = React.useState<string | undefined>()
const needle = query.trim().toLowerCase()
const shown = groups
.map((group) => ({
...group,
items: needle
? group.items.filter((item) =>
`${item.title} ${item.hint ?? ""}`.toLowerCase().includes(needle)
)
: group.items,
}))
.filter((group) => group.items.length > 0)
const flat = shown.flatMap((group) => group.items)
const wanted = active ?? ownActive
const current = flat.find((item) => item.id === wanted) ?? flat[0]
// The highlight's offset is arithmetic, not a DOM measurement: rows and labels have fixed heights.
let offset = 6
let found = false
for (const group of shown) {
if (found) break
offset += LABEL
for (const item of group.items) {
if (item.id === current?.id) {
found = true
break
}
offset += ROW
}
}
const select = (id: string) => {
if (active === undefined) setOwnActive(id)
onActiveChange?.(id)
}
const step = (delta: number) => {
if (flat.length === 0) return
const at = Math.max(
0,
flat.findIndex((item) => item.id === current?.id)
)
const next = flat[(at + delta + flat.length) % flat.length]
if (next) select(next.id)
}
return (
<div {...rest} className={cx("aik aik-cp-pal", className)} data-s={status}>
<AiKitStyles />
<AiStyle id="ai-composer" css={CSS} />
<div className="aik-shell">
<div className="aik-surface aik-cp-pcard">
<div className="aik-cp-search">
{status === "idle" ? (
<Search size={18} />
) : (
<Mark status={status === "done" ? "done" : "run"} />
)}
<input
className="aik-cp-q"
value={query}
placeholder={placeholder}
aria-label={placeholder}
role="combobox"
aria-expanded="true"
aria-controls={`${uid}-list`}
aria-activedescendant={
current ? `${uid}-${current.id}` : undefined
}
onChange={(event) => onQueryChange(event.target.value)}
onKeyDown={(event) => {
if (event.key === "ArrowDown") {
event.preventDefault()
step(1)
} else if (event.key === "ArrowUp") {
event.preventDefault()
step(-1)
} else if (event.key === "Enter" && current) {
event.preventDefault()
onRun?.(current)
} else if (event.key === "Escape") {
onQueryChange("")
}
}}
/>
<span className="aik-cp-pstat" role="status">
{status === "running" ? (
<span className="aik-shimmer">{statusLabel}</span>
) : (
<span>{statusLabel}</span>
)}
</span>
<kbd className="aik-kbd">esc</kbd>
</div>
<div className="aik-cp-pgrid">
<div className="aik-cp-list" id={`${uid}-list`} role="listbox">
{flat.length === 0 ? (
<div className="aik-cp-empty">
Nothing matches “{query.trim()}”.
</div>
) : (
<>
<div
className="aik-cp-hl"
style={{ "--y": `${offset}px` } as React.CSSProperties}
/>
{shown.map((group) => (
<React.Fragment key={group.label}>
<div className="aik-cp-glabel aik-label">
{group.label}
</div>
{group.items.map((item) => (
<button
key={item.id}
id={`${uid}-${item.id}`}
type="button"
role="option"
aria-selected={item.id === current?.id}
className="aik-cp-row"
tabIndex={-1}
onMouseEnter={() => select(item.id)}
onClick={() => onRun?.(item)}
>
{item.icon}
<b>{item.title}</b>
{item.hint ? <em>{item.hint}</em> : null}
</button>
))}
</React.Fragment>
))}
</>
)}
</div>
<div className="aik-cp-prev" aria-live="polite">
{current ? (
<div key={current.id}>
<span className="aik-cp-tile">{current.icon}</span>
<h4>{current.title}</h4>
{current.description ? <p>{current.description}</p> : null}
{current.facts && current.facts.length > 0 ? (
<div className="aik-cp-kv">
{current.facts.map(([key, fact]) => (
<div key={key}>
<span>{key}</span>
<b>{fact}</b>
</div>
))}
</div>
) : null}
</div>
) : null}
</div>
</div>
<i
className="aik-beam"
data-on={status === "running" ? "" : undefined}
/>
</div>
<div className="aik-cp-pfoot">
<span>
<kbd className="aik-kbd">↑</kbd>
<kbd className="aik-kbd">↓</kbd>move
</span>
<span>
<kbd className="aik-kbd">⏎</kbd>run
</span>
<span>
{flat.length} {flat.length === 1 ? "result" : "results"}
</span>
</div>
</div>
</div>
)
}
Installation
One command adds ai-composer and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.
$npx shadcn@latest add https://tweenui.dev/r/ai-composer.json
ai-composer-demo
"use client"
import * as React from "react"
import {
BookOpen,
Brain,
FileCode,
FolderOpen,
GitPullRequest,
Globe,
Rocket,
Wrench,
} from "lucide-react"
import { AiDemo } from "@/lib/ai-demo"
import {
AiStyle,
Face,
paceToken,
typeInto,
useAiLoop,
useIdleHands,
type AiMood,
} from "@/lib/ai-kit"
import {
AiCommandPalette,
AiComposer,
AiPromptPill,
type AiComposerAttachment,
type AiPaletteGroup,
type AiPaletteItem,
} from "@/registry/tween/ai-composer"
const CSS = `
.aik-cpd-scene{display:grid;gap:14px;width:min(100%,560px)}
.aik-cpd-thread{display:flex;flex-direction:column;justify-content:flex-end;gap:12px;min-height:176px;padding:0 6px}
.aik-cpd-user{align-self:flex-end;max-width:78%;padding:10px 16px;border-radius:18px;background:var(--aik-raised);font-size:15px;line-height:22px;transform-origin:100% 100%;animation:aik-cpd-launch 520ms var(--aik-ease-move) both}
.aik-cpd-bot{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;align-items:start;font-size:15px;line-height:24px;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-cpd-bot p{padding-top:2px}
.aik-cpd-bot code{font-size:13px;padding:2px 5px;border-radius:6px;background:var(--aik-raised)}
@keyframes aik-cpd-launch{from{opacity:.2;transform:translateY(96px) scale(.9)}}
.aik-cpd-art{position:absolute;inset:0;background:radial-gradient(80% 90% at 20% 20%,var(--aik-f-amber),transparent 60%),radial-gradient(90% 90% at 85% 80%,var(--aik-f-rose),transparent 62%),var(--aik-f-violet)}
.aik-cpd-pill{display:grid;align-content:start;justify-items:center;width:min(100%,540px);min-height:236px}
@media (prefers-reduced-motion: reduce){.aik-cpd-user{animation:none}}
`
const PROMPT = "Make the headline reveal word by word"
const REPLY =
"Done. The headline now uses text-skew-reveal with a 0.05s stagger, so the whole line lands in under a second."
interface Turn {
id: number
role: "user" | "bot"
text: string
}
function Dock() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [value, setValue] = React.useState("")
const [files, setFiles] = React.useState<AiComposerAttachment[]>([])
const [mode, setMode] = React.useState("Ask")
const [status, setStatus] = React.useState<"ready" | "streaming">("ready")
const [context, setContext] = React.useState(12)
const [turns, setTurns] = React.useState<Turn[]>([])
const [mood, setMood] = React.useState<AiMood>("idle")
const run = React.useRef(0)
// Plays the agent's reply. Shared by the script and by a real send.
const respond = React.useCallback(
async (sleep: (ms: number) => Promise<void>, mine: number) => {
const alive = () => run.current === mine
setStatus("streaming")
setMood("think")
await sleep(1100)
if (!alive()) return
const id = Date.now()
setMood("talk")
setTurns((list) => [...list.slice(-1), { id, role: "bot", text: "" }])
let text = ""
for (const word of REPLY.split(" ")) {
if (!alive()) return
text += (text ? " " : "") + word
const next = text
setTurns((list) =>
list.map((turn) => (turn.id === id ? { ...turn, text: next } : turn))
)
await sleep(paceToken(word, 38))
}
if (!alive()) return
setStatus("ready")
setMood("happy")
setContext((value) => Math.min(96, value + 7))
},
[]
)
useAiLoop(
root,
async ({ sleep }) => {
const mine = ++run.current
setTurns([])
setFiles([])
setValue("")
setMode("Ask")
setStatus("ready")
setContext(12)
setMood("idle")
await sleep(700)
for (const progress of [0.15, 0.45, 0.8, 1]) {
setFiles([
{
id: "hero",
name: "hero.tsx",
kind: "code",
meta: "4 KB",
progress,
},
])
await sleep(240)
}
setContext(18)
await typeInto(setValue, PROMPT, sleep)
await sleep(350)
setMode("Build")
await sleep(900)
setTurns([{ id: 1, role: "user", text: PROMPT }])
setValue("")
setFiles([])
await respond(sleep, mine)
await sleep(2200)
},
{ gap: 400, enabled: !hands }
)
// The first touch takes over from the script: whatever it was mid-way through is cancelled.
const takeOver = () => {
if (!hands) {
run.current++
setStatus("ready")
setMood("idle")
}
touch()
}
const send = (text: string) => {
const mine = ++run.current
setTurns([{ id: Date.now(), role: "user", text }])
setValue("")
setFiles([])
void respond(
(ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
mine
)
}
return (
<div
ref={root}
className="aik-cpd-scene"
onPointerDown={takeOver}
onKeyDown={takeOver}
>
<div className="aik-cpd-thread" aria-live="polite">
{turns.map((turn) =>
turn.role === "user" ? (
<div key={turn.id} className="aik-cpd-user">
{turn.text}
</div>
) : (
<div key={turn.id} className="aik-cpd-bot">
<Face size={28} shape="orb" mood={mood} />
<p>
{turn.text}
{status === "streaming" ? <i className="aik-caret" /> : null}
</p>
</div>
)
)}
</div>
<AiComposer
value={value}
onValueChange={setValue}
status={status}
attachments={files}
onRemoveAttachment={(id) =>
setFiles((list) => list.filter((file) => file.id !== id))
}
onAttach={() =>
setFiles((list) =>
list.some((file) => file.id === "ref")
? list
: [
...list,
{
id: "ref",
name: "reference.png",
kind: "image",
meta: "1.8 MB",
preview: <span className="aik-cpd-art" />,
},
]
)
}
modes={["Ask", "Plan", "Build"]}
mode={mode}
onModeChange={setMode}
agent={{ name: "Mira", detail: "fast", mood }}
context={context}
placeholder="Ask Mira to build something"
streamingPlaceholder="Mira is working. Esc to stop."
onSubmit={send}
onStop={() => {
run.current++
setStatus("ready")
setMood("idle")
}}
/>
</div>
)
}
const PILL_STEPS = ["Reading hero.tsx", "Rewriting 3 lines", "Checking types"]
function Pill() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [open, setOpen] = React.useState(false)
const [value, setValue] = React.useState("")
const [status, setStatus] = React.useState<"idle" | "running" | "done">(
"idle"
)
const [label, setLabel] = React.useState("")
const [tools, setTools] = React.useState({
web: false,
files: true,
think: false,
})
const run = React.useRef(0)
const work = React.useCallback(
async (sleep: (ms: number) => Promise<void>, mine: number) => {
setOpen(false)
setValue("")
setStatus("running")
for (const step of PILL_STEPS) {
if (run.current !== mine) return
setLabel(step)
await sleep(1300)
}
if (run.current !== mine) return
setStatus("done")
setLabel("Done · 3 lines changed")
await sleep(2000)
if (run.current !== mine) return
setStatus("idle")
},
[]
)
useAiLoop(
root,
async ({ sleep }) => {
const mine = ++run.current
setOpen(false)
setStatus("idle")
setValue("")
setTools({ web: false, files: true, think: false })
await sleep(1200)
setOpen(true)
await sleep(900)
await typeInto(setValue, "Tighten the hero copy", sleep, 32)
await sleep(400)
setTools({ web: false, files: true, think: true })
await sleep(900)
await work(sleep, mine)
await sleep(600)
},
{ gap: 300, enabled: !hands }
)
return (
<div
ref={root}
className="aik-cpd-pill"
onPointerDown={() => {
if (!hands) {
run.current++
setStatus("idle")
}
touch()
}}
onKeyDown={touch}
>
<AiPromptPill
open={open}
onOpenChange={setOpen}
value={value}
onValueChange={setValue}
status={status}
statusLabel={label}
label="Ask Mira anything"
suggestions={[
"Tighten the hero copy",
"Add a pricing section with a toggle",
"Explain how text-skew-reveal works",
]}
tools={[
{ id: "web", label: "Web", icon: <Globe size={14} />, on: tools.web },
{
id: "files",
label: "Project files",
icon: <FolderOpen size={14} />,
on: tools.files,
},
{
id: "think",
label: "Think longer",
icon: <Brain size={14} />,
on: tools.think,
},
]}
onToggleTool={(id) =>
setTools((state) => ({
...state,
[id]: !state[id as keyof typeof state],
}))
}
onSubmit={() => {
const mine = ++run.current
void work(
(ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
mine
)
}}
/>
</div>
)
}
const GROUPS: AiPaletteGroup[] = [
{
label: "Commands",
items: [
{
id: "build",
title: "Build a section",
hint: "/build",
icon: <Rocket size={16} />,
description:
"Describe a section and Mira writes it with components already in your registry.",
facts: [
["Agent", "Mira"],
["Usually", "40 s"],
],
},
{
id: "fix",
title: "Fix lint and type errors",
hint: "/fix",
icon: <Wrench size={16} />,
description:
"Runs the checks, fixes what it can and lists what needs you.",
facts: [
["Open errors", "14"],
["Files", "6"],
],
},
{
id: "review",
title: "Review open changes",
hint: "/review",
icon: <GitPullRequest size={16} />,
description:
"Odo reads the diff and leaves comments on anything risky.",
facts: [
["Agent", "Odo"],
["Changed", "+126 −8"],
],
},
],
},
{
label: "Files",
items: [
{
id: "pricing",
title: "pricing-section.tsx",
hint: "components",
icon: <FileCode size={16} />,
description: "The pricing section with a monthly and yearly toggle.",
facts: [
["Lines", "148"],
["Edited", "2 min ago"],
],
},
{
id: "docs",
title: "text-skew-reveal.mdx",
hint: "docs",
icon: <BookOpen size={16} />,
description: "Docs page for the skewed word-by-word reveal.",
facts: [
["Lines", "92"],
["Edited", "yesterday"],
],
},
],
},
]
function Palette() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [query, setQuery] = React.useState("")
const [active, setActive] = React.useState<string | undefined>("build")
const [status, setStatus] = React.useState<"idle" | "running" | "done">(
"idle"
)
const [label, setLabel] = React.useState("")
const run = React.useRef(0)
const launch = React.useCallback(
async (
item: AiPaletteItem,
sleep: (ms: number) => Promise<void>,
mine: number
) => {
setStatus("running")
setLabel(`Running: ${item.title}`)
await sleep(2400)
if (run.current !== mine) return
setStatus("done")
setLabel(`Finished: ${item.title}`)
await sleep(1700)
if (run.current !== mine) return
setStatus("idle")
setQuery("")
},
[]
)
useAiLoop(
root,
async ({ sleep }) => {
const mine = ++run.current
setStatus("idle")
setQuery("")
setActive("build")
await sleep(1100)
for (const id of ["fix", "review", "pricing", "docs", "pricing"]) {
setActive(id)
await sleep(780)
}
await typeInto(setQuery, "fix", sleep, 90)
setActive("fix")
await sleep(900)
const item = GROUPS[0]?.items[1]
if (item) await launch(item, sleep, mine)
},
{ gap: 500, enabled: !hands }
)
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 580px)" }}
onPointerDown={() => {
if (!hands) {
run.current++
setStatus("idle")
}
touch()
}}
onKeyDown={touch}
>
<AiCommandPalette
groups={GROUPS}
query={query}
onQueryChange={setQuery}
active={hands ? undefined : active}
status={status}
statusLabel={label}
onRun={(item) => {
const mine = ++run.current
void launch(
item,
(ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
mine
)
}}
/>
</div>
)
}
export function AiComposerDemo({ only }: { only?: string }) {
return (
<>
<AiStyle id="ai-composer-demo" css={CSS} />
<AiDemo
only={only}
tabs={[
{ name: "Dock", node: <Dock /> },
{ name: "Prompt pill", node: <Pill /> },
{ name: "Command palette", node: <Palette /> },
]}
/>
</>
)
}
Installation
Usage
import {
AiCommandPalette,
AiComposer,
AiPromptPill,
} from "@/components/ui/ai-composer"const [value, setValue] = useState("")
const [status, setStatus] = useState<"ready" | "streaming">("ready")
<AiComposer
value={value}
onValueChange={setValue}
status={status}
modes={["Ask", "Plan", "Build"]}
mode={mode}
onModeChange={setMode}
agent={{ name: "Mira", detail: "fast" }}
context={18}
onSubmit={(text) => {
setStatus("streaming")
setValue("")
send(text)
}}
onStop={() => setStatus("ready")}
/>status maps directly onto the AI SDK: pass "streaming" while useChat reports submitted or streaming, and "ready" otherwise.
Versions
AiComposeris the chat dock: a rim holding one card. Attachments sit in a tray with an upload ring, the field grows with its text, and a mode switch slides between Ask, Plan and Build. Enter sends and Shift Enter adds a line. While streaming, send becomes stop in place, a light travels round the card's edge, and Escape stops the run.AiPromptPilllives as a small pill and opens in place into a full prompt with suggestions and tool toggles. After sending it folds back, and the pill itself reports progress withstatusLabel.AiCommandPaletteis one search over commands, files and agents. A highlight slides between rows as you arrow through them, and a preview pane describes the current row. While a command runs, the search row becomes the status line.
Props
AiComposer
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | The field's text. | |
onValueChange | (value: string) => void | Called on every edit. | |
onSubmit | (value: string) => void | Called with the trimmed text on Enter or send. | |
onStop | () => void | Called on send or Escape while streaming. | |
status | "ready" | "streaming" | "ready" | Streaming turns send into stop and starts the edge light. |
attachments | { id, name, kind?, meta?, progress?, preview? }[] | [] | Tray chips. progress from 0 to 1 shows an upload ring. |
onRemoveAttachment | (id: string) => void | Called from a chip's remove button. | |
modes | string[] | Names for the segmented mode switch. | |
mode | string | The selected mode. | |
onModeChange | (mode: string) => void | Called when a mode is picked. | |
agent | { name, detail?, tone?, shape?, mood? } | The agent chip. Its face listens while you type. | |
context | number | Context use from 0 to 100, as a pie on the agent chip. | |
banner | ReactNode | A row docked in the frame above the card. | |
disabled | boolean | false | Dims the dock and blocks input. |
AiPromptPill
| Prop | Type | Default | Description |
|---|---|---|---|
open | boolean | Whether the pill is opened into the full prompt. | |
onOpenChange | (open: boolean) => void | Called on click, and on Escape. | |
value | string | The prompt text. | |
onSubmit | (value: string) => void | Called on Enter, send, or a suggestion. | |
status | "idle" | "running" | "done" | "idle" | Running and done show statusLabel in the pill. |
statusLabel | string | What the pill says while it works. | |
label | string | "Ask anything" | The resting label and placeholder. |
suggestions | string[] | [] | One-tap prompts in the open pill. |
tools | { id, label, icon?, on }[] | [] | Toggles along the bottom. |
onToggleTool | (id: string) => void | Called when a toggle is pressed. |
AiCommandPalette
| Prop | Type | Default | Description |
|---|---|---|---|
groups | { label, items }[] | Items take id, title, hint, icon, description and facts. | |
query | string | The search text. Filtering is built in. | |
onQueryChange | (query: string) => void | Called on every edit. | |
onRun | (item) => void | Called on Enter or a click. | |
active | string | Controls the highlighted item. Omit to use arrow keys. | |
status | "idle" | "running" | "done" | "idle" | Running and done replace the search field. |
statusLabel | string | The status line's text. |