- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
"use client";
import { useChat } from "@ai-sdk/react";
import {
lastAssistantMessageIsCompleteWithApprovalResponses,
type UIDataTypes,
type UIMessage,
} from "ai";
import { CircleCheckIcon, LoaderCircleIcon, TerminalIcon } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemMedia,
ItemTitle,
} from "@/components/ui/item";
import {
Bubble,
BubbleContent,
Message,
MessageContent,
} from "@/components/ui/message";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import { createChat, getMessageText } from "@/lib/ai";
import { messageAnimations } from "@/lib/message-animations";
type ChatMessage = UIMessage<
unknown,
UIDataTypes,
{
runCommand: {
input: { command: string };
output: { stdout: string };
};
}
>;
const chat = createChat<ChatMessage>()
.user("Clean up the build folder.")
.sleep(600)
.assistant(({ writer }) => {
writer.reasoning(
"The build output lives in dist. Deleting it cannot be undone, so I should ask before I run the command."
);
writer.sleep(400);
writer.tool("runCommand", {
input: { command: "rm -rf dist" },
needsApproval: true,
output: { stdout: "" },
});
})
.assistant(({ writer, toolCall }) => {
writer.sleep(600);
writer.text(
toolCall?.approved
? "Removed the dist folder."
: "Okay, I left the dist folder in place."
);
});
const initialMessages = chat.get(0);
const transport = chat.transport({ delayMs: 20 });
export function ConfirmationDemo() {
const {
messages,
sendMessage,
setMessages,
status,
addToolApprovalResponse,
} = useChat<ChatMessage>({
messages: initialMessages,
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
transport,
});
const shouldReduceMotion = useReducedMotion();
const nextMessage = chat.next(messages);
const busy = status === "submitted" || status === "streaming";
return (
<div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
{messages.map((message) => {
if (message.role === "user") {
return (
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
key={message.id}
variants={messageAnimations["slide-up"].variants}
>
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{getMessageText(message)}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
</motion.div>
);
}
return (
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
key={message.id}
variants={messageAnimations.fade.variants}
>
<Message>
<MessageContent className="gap-4">
{message.parts.map((part, index) => {
if (part.type === "text") {
return <p key={index}>{part.text}</p>;
}
if (part.type === "reasoning") {
return (
<Trace key={index}>
<ReasoningRow
running={part.state === "streaming"}
text={part.text}
/>
</Trace>
);
}
if (part.type !== "tool-runCommand") {
return null;
}
if (part.state === "approval-requested") {
return (
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
key={part.toolCallId}
variants={messageAnimations["slide-up"].variants}
>
<Item variant="outline">
<ItemMedia>
<TerminalIcon />
</ItemMedia>
<ItemContent>
<ItemTitle>Run {part.input.command}?</ItemTitle>
<ItemDescription>
The command runs in this project.
</ItemDescription>
</ItemContent>
<ItemActions>
<Button
onClick={() =>
addToolApprovalResponse({
approved: false,
id: part.approval.id,
})
}
size="sm"
variant="outline"
>
Deny
</Button>
<Button
onClick={() =>
addToolApprovalResponse({
approved: true,
id: part.approval.id,
})
}
size="sm"
>
Approve
</Button>
</ItemActions>
</Item>
</motion.div>
);
}
const denied =
part.state === "output-denied" ||
(part.state === "approval-responded" &&
!part.approval.approved);
return (
<React.Fragment key={part.toolCallId}>
<Trace>
<TraceLine
status={
!denied && part.state !== "output-available"
? "running"
: undefined
}
>
<TraceIcon>
<TerminalIcon />
</TraceIcon>
<TraceTitle>
{denied
? "Denied"
: part.state === "output-available"
? "Ran"
: "Running"}
{part.input?.command}
</TraceTitle>
</TraceLine>
</Trace>
</React.Fragment>
);
})}
</MessageContent>
</Message>
</motion.div>
);
})}
{!busy && (
<Button
className="mt-auto self-start"
onClick={() =>
nextMessage
? sendMessage(nextMessage)
: setMessages(initialMessages)
}
size="sm"
variant="outline"
>
{nextMessage ? "Send message" : "Reset"}
</Button>
)}
</div>
);
}
function ReasoningRow({ text, running }: { text: string; running: boolean }) {
const [open, setOpen] = React.useState<boolean>();
return (
<TraceCollapsible onOpenChange={setOpen} open={open ?? running}>
<TraceCollapsibleTrigger>
<TraceLine status={running ? "running" : undefined}>
<TraceIcon>
{running ? (
<LoaderCircleIcon className="animate-spin" />
) : (
<CircleCheckIcon />
)}
</TraceIcon>
<TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent className="whitespace-pre-wrap">
{text}
</TraceCollapsibleContent>
</TraceCollapsible>
);
}Confirmation pauses a tool call and asks the user to approve or deny it before it runs. The pending tool renders as an Item card with Approve and Deny actions. Once the user responds, the card is replaced by a Trace line showing the outcome.
Confirmation is a composition — install the primitives, then wire the approval flow the same way the demo does.
Installation
$ bun add @frakment/ai npx frakment add bubble button item message trace$ npm install @frakment/ai npx frakment add bubble button item message trace$ pnpm add @frakment/ai npx frakment add bubble button item message trace$ yarn add @frakment/ai npx frakment add bubble button item message trace
Install the following dependencies:
$ bun add @frakment/ai @ai-sdk/react ai motion lucide-react$ npm install @frakment/ai @ai-sdk/react ai motion lucide-react$ pnpm add @frakment/ai @ai-sdk/react ai motion lucide-react$ yarn add @frakment/ai @ai-sdk/react ai motion lucide-react
Install the required registry components:
export type { UIMessage } from "@frakment/ai";
export { createChat, getMessageText } from "@frakment/ai";"use client";
import type { VariantProps } from "class-variance-authority";
import * as React from "react";
import {
getTransition,
parseMotion,
useMotionGuard,
useReducedMotion,
} from "@/lib/motion";
import { buttonVariants, cn } from "@/lib/utils";
export interface ButtonBaseProps extends VariantProps<typeof buttonVariants> {
anchorRef?: React.Ref<HTMLAnchorElement>;
as?: React.ElementType;
children?: React.ReactNode;
className?: string;
download?: string | boolean;
href?: string;
motion?: string;
rel?: string;
target?: React.HTMLAttributeAnchorTarget;
}
// biome-ignore lint/suspicious/noExplicitAny: loose polymorphic props for the `as` escape hatch
export type ButtonProps = ButtonBaseProps & Record<string, any>;
function Button({
as,
className,
variant,
size,
href,
target,
rel,
download,
ref,
anchorRef,
motion,
style,
children,
...props
}: ButtonProps) {
const reduce = useReducedMotion();
const internalRef = React.useRef<HTMLElement | null>(null);
const motionEnabled = motion !== undefined && !reduce;
let resolvedStyle = style as React.CSSProperties | undefined;
if (reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
} else if (motion !== undefined) {
const transition = getTransition(parseMotion(motion));
if (transition) {
resolvedStyle = { ...resolvedStyle, transition };
}
}
const styleFingerprint = JSON.stringify(resolvedStyle ?? null);
const yielded = useMotionGuard(internalRef, motionEnabled, styleFingerprint);
if (yielded && !reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
}
const setRef = React.useCallback(
(el: HTMLElement | null) => {
internalRef.current = el;
if (href !== undefined && anchorRef) {
if (typeof anchorRef === "function") {
anchorRef(el as HTMLAnchorElement | null);
} else {
(
anchorRef as React.MutableRefObject<HTMLAnchorElement | null>
).current = el as HTMLAnchorElement | null;
}
}
if (typeof ref === "function") {
(ref as (el: HTMLElement | null) => void)(el);
} else if (ref && typeof ref === "object") {
(ref as React.MutableRefObject<HTMLElement | null>).current = el;
}
},
[href, ref, anchorRef]
);
const classes = cn(buttonVariants({ className, size, variant }));
const attrs = {
"data-inline": true,
"data-size": size,
"data-slot": "button",
"data-variant": variant,
} as const;
if (as !== undefined) {
const allProps: Record<string, unknown> = {
...attrs,
...props,
className: classes,
ref: setRef,
style: resolvedStyle,
};
if (href !== undefined) {
allProps.href = href;
}
if (download !== undefined) {
allProps.download = download;
}
if (rel !== undefined) {
allProps.rel = rel;
}
if (target !== undefined) {
allProps.target = target;
}
return React.createElement(as, allProps, children);
}
if (href !== undefined) {
const {
type: _t,
disabled: _d,
form: _f,
formAction: _fa,
formEncType: _fe,
formMethod: _fm,
formNoValidate: _fnv,
formTarget: _ft,
name: _n,
value: _v,
...anchorRest
} = props as React.ButtonHTMLAttributes<HTMLButtonElement>;
return (
<a
className={classes}
download={download}
href={href}
ref={setRef}
rel={rel}
style={resolvedStyle}
target={target}
{...attrs}
{...(anchorRest as React.AnchorHTMLAttributes<HTMLAnchorElement>)}
>
{children}
</a>
);
}
return (
<button
className={classes}
ref={setRef}
style={resolvedStyle}
{...attrs}
{...(props as React.ButtonHTMLAttributes<HTMLButtonElement>)}
>
{children}
</button>
);
}
export { Button };import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils";
const itemVariants = cva(
"group/item flex w-full flex-wrap items-center gap-3 rounded-lg border px-4 py-3 text-sm transition-colors",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default: "border-border bg-card text-card-foreground",
muted: "bg-muted text-foreground border-transparent",
outline: "border-border bg-transparent",
},
},
}
);
type ItemProps = React.ComponentPropsWithoutRef<"div"> &
VariantProps<typeof itemVariants> & {
as?: React.ElementType;
asChild?: boolean;
};
function Item({
as,
asChild,
children,
className,
variant,
...props
}: ItemProps) {
const mergedClass = cn(itemVariants({ variant }), className);
if (asChild && React.isValidElement(children)) {
const child = children as React.ReactElement<{ className?: string }>;
return React.cloneElement(child, {
...props,
className: cn(mergedClass, child.props.className),
"data-slot": "item",
"data-variant": variant,
} as never);
}
const Comp = (as ?? "div") as React.ElementType;
return (
<Comp
className={mergedClass}
data-slot="item"
data-variant={variant}
{...props}
>
{children}
</Comp>
);
}
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex flex-col gap-2", className)}
data-slot="item-group"
{...props}
/>
);
}
function ItemMedia({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"flex shrink-0 items-center justify-center [&_svg:not([class*='size-'])]:size-4",
className
)}
data-slot="item-media"
{...props}
/>
);
}
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex min-w-0 flex-1 flex-col gap-0.5", className)}
data-slot="item-content"
{...props}
/>
);
}
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("truncate text-sm leading-tight font-medium", className)}
data-slot="item-title"
{...props}
/>
);
}
function ItemDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("text-muted-foreground text-sm", className)}
data-slot="item-description"
{...props}
/>
);
}
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex shrink-0 items-center gap-2", className)}
data-slot="item-actions"
{...props}
/>
);
}
export {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemGroup,
ItemMedia,
ItemTitle,
};"use client";
import { cva, type VariantProps } from "class-variance-authority";
import { ArrowDownIcon } from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
getTransition,
parseMotion,
useMotionGuard,
useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";
interface UIMessagePart {
text?: string;
type: string;
}
interface UIMessage {
id: string;
metadata?: unknown;
parts: UIMessagePart[];
role: "user" | "assistant" | "system";
}
function getMessageText(message: UIMessage): string {
if (!Array.isArray(message.parts)) {
return "";
}
return message.parts
.filter(
(part): part is { type: "text"; text: string } =>
part.type === "text" && typeof part.text === "string"
)
.map((part) => part.text)
.join("");
}
function MessageGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex min-w-0 flex-col gap-2", className)}
data-slot="message-group"
{...props}
/>
);
}
function Message({
className,
align = "start",
...props
}: React.ComponentProps<"div"> & { align?: "start" | "end" }) {
return (
<div
className={cn(
"group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse",
className
)}
data-align={align}
data-slot="message"
{...props}
/>
);
}
function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"bg-muted flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full group-has-data-[slot=message-footer]/message:-translate-y-8",
className
)}
data-slot="message-avatar"
{...props}
/>
);
}
function MessageContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"flex w-full min-w-0 flex-col gap-2.5 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end",
className
)}
data-slot="message-content"
{...props}
/>
);
}
function MessageHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0",
className
)}
data-slot="message-header"
{...props}
/>
);
}
function MessageFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end",
className
)}
data-slot="message-footer"
{...props}
/>
);
}
function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex min-w-0 flex-col gap-2", className)}
data-slot="bubble-group"
{...props}
/>
);
}
const bubbleVariants = cva(
"group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default:
"*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80",
destructive:
"*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30",
ghost:
"[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50 border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0",
muted:
"*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]",
outline:
"*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30",
secondary:
"*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",
tinted:
"*:data-[slot=bubble-content]:text-foreground *:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]",
},
},
}
);
function Bubble({
variant = "default",
align = "start",
className,
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof bubbleVariants> & {
align?: "start" | "end";
}) {
return (
<div
className={cn(bubbleVariants({ variant }), className)}
data-align={align}
data-slot="bubble"
data-variant={variant}
{...props}
/>
);
}
type BubbleContentProps = Omit<React.ComponentProps<"div">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLDivElement>;
} & Record<string, unknown>;
function BubbleContent({ as, className, ref, ...props }: BubbleContentProps) {
const Comp = as ?? "div";
return (
<Comp
className={cn(
"[button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-ring/50 w-fit max-w-full min-w-0 overflow-hidden rounded-xl border border-transparent px-3 py-2 text-sm leading-relaxed wrap-break-word group-data-[align=end]/bubble:self-end [button]:text-left [button,a]:transition-colors [button,a]:outline-none [button,a]:focus-visible:ring-3",
className
)}
data-slot="bubble-content"
ref={ref}
{...props}
/>
);
}
const bubbleReactionsVariants = cva(
"bg-muted ring-card absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-full px-1.5 py-0.5 text-sm ring-3 has-[button]:p-0",
{
defaultVariants: {
align: "end",
side: "bottom",
},
variants: {
align: {
end: "right-3",
start: "left-3",
},
side: {
bottom: "bottom-0 translate-y-3/4",
top: "top-0 -translate-y-3/4",
},
},
}
);
function BubbleReactions({
side = "bottom",
align = "end",
className,
...props
}: React.ComponentProps<"div"> & {
align?: "start" | "end";
side?: "top" | "bottom";
}) {
return (
<div
className={cn(bubbleReactionsVariants({ align, side }), className)}
data-align={align}
data-side={side}
data-slot="bubble-reactions"
{...props}
/>
);
}
type ScrollDefaultPosition = "start" | "end" | "last-anchor";
type ScrollButtonDirection = "start" | "end";
type ScrollAlign = "start" | "center" | "end" | "nearest";
interface ScrollOptions {
align?: ScrollAlign;
behavior?: ScrollBehavior;
scrollMargin?: number;
}
interface Scrollable {
end: boolean;
start: boolean;
}
interface VisibilityState {
currentAnchorId: string | null;
visibleMessageIds: string[];
}
interface ScrollerProviderProps {
autoScroll?: boolean;
children?: React.ReactNode;
defaultScrollPosition?: ScrollDefaultPosition;
scrollEdgeThreshold?: number;
scrollMargin?: number;
scrollPreviousItemPeek?: number;
}
type ScrollerProps = React.ComponentProps<"div">;
type ScrollerViewportProps = React.ComponentProps<"div"> & {
preserveScrollOnPrepend?: boolean;
};
type ScrollerContentProps = React.ComponentProps<"div"> & {
spacerClassName?: string;
};
type ScrollerItemProps = React.ComponentProps<"div"> & {
messageId?: string;
scrollAnchor?: boolean;
};
type ScrollerButtonDirection = ScrollButtonDirection;
type ScrollerButtonProps = Omit<
React.ComponentProps<"button">,
"children" | "render"
> & {
children?: React.ReactNode;
behavior?: ScrollBehavior;
direction?: ScrollerButtonDirection;
render?: React.ReactElement;
};
interface ScrollerContextValue {
autoScroll: boolean;
contentRef: React.RefObject<HTMLDivElement | null>;
defaultScrollPosition: ScrollDefaultPosition;
itemElements: Map<string, HTMLDivElement>;
preserveScrollOnPrependRef: React.MutableRefObject<boolean>;
registerItem: (id: string, el: HTMLDivElement) => () => void;
scrollable: Scrollable;
scrollEdgeThreshold: number;
scrollMargin: number;
scrollPreviousItemPeek: number;
scrollToEnd: (opts?: ScrollOptions) => boolean;
scrollToMessage: (messageId: string, opts?: ScrollOptions) => boolean;
scrollToStart: (opts?: ScrollOptions) => boolean;
setContentPresent: (present: boolean) => void;
setPreserveScrollOnPrepend: (v: boolean) => void;
setViewportPresent: (present: boolean) => void;
viewportRef: React.RefObject<HTMLDivElement | null>;
visibility: VisibilityState;
}
const ScrollerContext = React.createContext<ScrollerContextValue | null>(null);
function useScrollerContext(): ScrollerContextValue {
const ctx = React.useContext(ScrollerContext);
if (!ctx) {
throw new Error(
"MessageScroller components must be used within <MessageScroller.Provider>"
);
}
return ctx;
}
function ScrollerProvider({
children,
autoScroll = true,
defaultScrollPosition = "end",
scrollEdgeThreshold = 16,
scrollPreviousItemPeek = 40,
scrollMargin = 0,
}: ScrollerProviderProps) {
const viewportRef = React.useRef<HTMLDivElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const itemElements = React.useRef<Map<string, HTMLDivElement>>(new Map());
const preserveScrollOnPrependRef = React.useRef(false);
const [contentPresent, setContentPresent] = React.useState(false);
const [viewportPresent, setViewportPresent] = React.useState(false);
const [scrollable, setScrollable] = React.useState<Scrollable>({
end: false,
start: false,
});
const [visibility, setVisibility] = React.useState<VisibilityState>({
currentAnchorId: null,
visibleMessageIds: [],
});
const setPreserveScrollOnPrepend = React.useCallback((v: boolean) => {
preserveScrollOnPrependRef.current = v;
}, []);
const registerItem = React.useCallback((id: string, el: HTMLDivElement) => {
itemElements.current.set(id, el);
return () => {
itemElements.current.delete(id);
};
}, []);
const computeScrollable = React.useCallback(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
const start = vp.scrollTop > scrollEdgeThreshold;
const end =
vp.scrollHeight - vp.clientHeight - vp.scrollTop > scrollEdgeThreshold;
setScrollable((prev) =>
prev.start === start && prev.end === end ? prev : { end, start }
);
}, [scrollEdgeThreshold]);
const computeVisibility = React.useCallback(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
const vpRect = vp.getBoundingClientRect();
const visible: string[] = [];
let currentAnchorId: string | null = null;
let bestTop = Number.POSITIVE_INFINITY;
itemElements.current.forEach((el, id) => {
const r = el.getBoundingClientRect();
if (r.bottom > vpRect.top && r.top < vpRect.bottom) {
visible.push(id);
if (r.top >= vpRect.top - 1 && r.top < bestTop) {
bestTop = r.top;
currentAnchorId = id;
}
}
});
setVisibility((prev) => {
if (
prev.currentAnchorId === currentAnchorId &&
prev.visibleMessageIds.length === visible.length &&
prev.visibleMessageIds.every((v, i) => v === visible[i])
) {
return prev;
}
return { currentAnchorId, visibleMessageIds: visible };
});
}, []);
const onScroll = React.useCallback(() => {
computeScrollable();
computeVisibility();
}, [computeScrollable, computeVisibility]);
const scrollToEnd = React.useCallback((opts?: ScrollOptions) => {
const vp = viewportRef.current;
if (!vp) {
return false;
}
vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: vp.scrollHeight });
return true;
}, []);
const scrollToStart = React.useCallback((opts?: ScrollOptions) => {
const vp = viewportRef.current;
if (!vp) {
return false;
}
vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: 0 });
return true;
}, []);
const scrollToMessage = React.useCallback(
(messageId: string, opts?: ScrollOptions) => {
const el = itemElements.current.get(messageId);
if (!el) {
return false;
}
el.scrollIntoView({
behavior: opts?.behavior ?? "smooth",
block: opts?.align ?? "start",
inline: "nearest",
});
return true;
},
[]
);
React.useEffect(() => {
const vp = viewportRef.current;
if (!vp) {
return;
}
vp.addEventListener("scroll", onScroll, { passive: true });
computeScrollable();
computeVisibility();
return () => vp.removeEventListener("scroll", onScroll);
}, [onScroll, computeScrollable, computeVisibility, viewportPresent]);
React.useEffect(() => {
if (!contentPresent) {
return;
}
const vp = viewportRef.current;
if (!vp) {
return;
}
if (defaultScrollPosition === "start") {
vp.scrollTop = 0;
} else if (defaultScrollPosition === "end") {
vp.scrollTop = vp.scrollHeight;
}
}, [contentPresent, defaultScrollPosition]);
React.useEffect(() => {
if (!autoScroll) {
return;
}
const vp = viewportRef.current;
const content = contentRef.current;
if (!(vp && content)) {
return;
}
if (typeof ResizeObserver === "undefined") {
return;
}
const observer = new ResizeObserver(() => {
const distance = vp.scrollHeight - vp.clientHeight - vp.scrollTop;
if (distance <= scrollEdgeThreshold) {
vp.scrollTop = vp.scrollHeight;
}
computeScrollable();
});
observer.observe(content);
return () => observer.disconnect();
}, [autoScroll, scrollEdgeThreshold, computeScrollable, viewportPresent]);
const value: ScrollerContextValue = {
autoScroll,
contentRef,
defaultScrollPosition,
itemElements: itemElements.current,
preserveScrollOnPrependRef,
registerItem,
scrollable,
scrollEdgeThreshold,
scrollMargin,
scrollPreviousItemPeek,
scrollToEnd,
scrollToMessage,
scrollToStart,
setContentPresent,
setPreserveScrollOnPrepend,
setViewportPresent,
viewportRef,
visibility,
};
return (
<ScrollerContext.Provider value={value}>
{children}
</ScrollerContext.Provider>
);
}
function ScrollerRoot({ children, ...props }: ScrollerProps) {
return <div {...props}>{children}</div>;
}
function ScrollerViewport({
children,
onScroll,
preserveScrollOnPrepend,
ref,
...props
}: ScrollerViewportProps) {
const ctx = useScrollerContext();
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
ctx.viewportRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ctx.viewportRef, ref]
);
React.useEffect(() => {
if (preserveScrollOnPrepend !== undefined) {
ctx.setPreserveScrollOnPrepend(preserveScrollOnPrepend);
}
}, [preserveScrollOnPrepend, ctx]);
const ctxRef = React.useRef(ctx);
ctxRef.current = ctx;
React.useEffect(() => {
ctxRef.current.setViewportPresent(true);
return () => ctxRef.current.setViewportPresent(false);
}, []);
return (
<div onScroll={onScroll} ref={setRef} {...props}>
{children}
</div>
);
}
function ScrollerContent({ children, ...props }: ScrollerContentProps) {
const ctx = useScrollerContext();
React.useEffect(() => {
ctx.setContentPresent(true);
return () => ctx.setContentPresent(false);
}, [ctx]);
return (
<div ref={ctx.contentRef} {...props}>
{children}
</div>
);
}
function ScrollerItem({
messageId,
scrollAnchor,
children,
ref,
...props
}: ScrollerItemProps) {
const ctx = useScrollerContext();
const localRef = React.useRef<HTMLDivElement | null>(null);
const setRef = React.useCallback(
(node: HTMLDivElement | null) => {
localRef.current = node;
if (typeof ref === "function") {
ref(node);
} else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
}
},
[ref]
);
React.useEffect(() => {
if (!(messageId && localRef.current)) {
return;
}
return ctx.registerItem(messageId, localRef.current);
}, [messageId, ctx]);
return (
<div
data-scroll-anchor={scrollAnchor ? "true" : undefined}
ref={setRef}
{...props}
>
{children}
</div>
);
}
function ScrollerButton({
direction = "end",
behavior = "smooth",
onClick,
render,
children,
type = "button",
...props
}: ScrollerButtonProps) {
const ctx = useScrollerContext();
const active =
direction === "end" ? ctx.scrollable.end : ctx.scrollable.start;
const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
onClick?.(e);
if (e.defaultPrevented) {
return;
}
if (direction === "end") {
ctx.scrollToEnd({ behavior });
} else {
ctx.scrollToStart({ behavior });
}
};
const mergedProps = {
...props,
children,
"data-active": active ? "true" : "false",
"data-direction": direction,
onClick: handleClick,
type,
} as React.ButtonHTMLAttributes<HTMLButtonElement> & Record<string, unknown>;
if (render && React.isValidElement(render)) {
return React.cloneElement(
render as React.ReactElement<Record<string, unknown>>,
mergedProps
);
}
return <button {...mergedProps} />;
}
function useMessageScroller() {
const ctx = useScrollerContext();
return {
scrollToEnd: ctx.scrollToEnd,
scrollToMessage: ctx.scrollToMessage,
scrollToStart: ctx.scrollToStart,
};
}
function useMessageScrollerScrollable() {
return useScrollerContext().scrollable;
}
function useMessageScrollerVisibility() {
return useScrollerContext().visibility;
}
function MessageScrollerProvider(props: ScrollerProviderProps) {
return <ScrollerProvider {...props} />;
}
function MessageScroller({ className, ...props }: React.ComponentProps<"div">) {
return (
<ScrollerRoot
className={cn(
"group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",
className
)}
data-slot="message-scroller"
{...props}
/>
);
}
function MessageScrollerViewport({
className,
...props
}: React.ComponentProps<"div"> & { preserveScrollOnPrepend?: boolean }) {
return (
<ScrollerViewport
className={cn(
"scroll-fade-b size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain contain-content data-pending-scroll:invisible",
className
)}
data-slot="message-scroller-viewport"
{...props}
/>
);
}
function MessageScrollerContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<ScrollerContent
className={cn("flex h-max min-h-full flex-col gap-6", className)}
data-slot="message-scroller-content"
{...props}
/>
);
}
function MessageScrollerItem({
className,
scrollAnchor = false,
...props
}: React.ComponentProps<"div"> & {
messageId?: string;
scrollAnchor?: boolean;
}) {
return (
<ScrollerItem
className={cn(
"min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",
className
)}
data-slot="message-scroller-item"
scrollAnchor={scrollAnchor}
{...props}
/>
);
}
function MessageScrollerButton({
direction = "end",
className,
children,
render,
variant = "secondary",
size = "icon-sm",
...props
}: React.ComponentProps<"button"> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size"> & {
direction?: "start" | "end";
render?: React.ReactElement;
behavior?: ScrollBehavior;
}) {
return (
<ScrollerButton
className={cn(
"border-border bg-muted text-foreground hover:bg-muted/80 hover:text-foreground absolute inset-s-1/2 -translate-x-1/2 rounded-full transition-[translate,scale,opacity] duration-200 data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",
className
)}
data-direction={direction}
data-size={size}
data-slot="message-scroller-button"
data-variant={variant}
direction={direction}
render={render ?? <Button size={size} variant={variant} />}
{...props}
>
{children ?? (
<>
<ArrowDownIcon />
<span className="sr-only">
{direction === "end" ? "Scroll to end" : "Scroll to start"}
</span>
</>
)}
</ScrollerButton>
);
}
const defaultMessageAnimatedMotion = "200 ease-out";
interface MessageAnimatedProps {
message: UIMessage;
motion?: string;
scrollAnchor?: boolean;
}
function MessageAnimated({
message,
motion,
scrollAnchor,
}: MessageAnimatedProps) {
const text = getMessageText(message);
const isUser = message.role === "user";
const reduce = useReducedMotion();
const motionValue = motion ?? defaultMessageAnimatedMotion;
const internalRef = React.useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = React.useState(false);
React.useEffect(() => {
let raf1 = 0;
let raf2 = 0;
raf1 = requestAnimationFrame(() => {
raf2 = requestAnimationFrame(() => setEntered(true));
});
return () => {
if (raf1) {
cancelAnimationFrame(raf1);
}
if (raf2) {
cancelAnimationFrame(raf2);
}
};
}, []);
let resolvedStyle: React.CSSProperties = {
opacity: reduce ? 1 : entered ? 1 : 0,
transform: reduce ? "none" : entered ? "translateY(0)" : "translateY(8px)",
};
if (reduce) {
resolvedStyle.transition = "none";
} else {
const transition = getTransition(parseMotion(motionValue));
if (transition) {
resolvedStyle.transition = transition;
}
}
const motionEnabled = !reduce;
const styleFingerprint = JSON.stringify(resolvedStyle);
const yielded = useMotionGuard(internalRef, motionEnabled, styleFingerprint);
if (yielded && !reduce) {
resolvedStyle = { ...resolvedStyle, transition: "none" };
}
return (
<MessageScrollerItem scrollAnchor={scrollAnchor}>
<div className="flex flex-col" ref={internalRef} style={resolvedStyle}>
<Bubble
align={isUser ? "end" : "start"}
variant={isUser ? "muted" : "ghost"}
>
<BubbleContent className="whitespace-pre-wrap">{text}</BubbleContent>
</Bubble>
</div>
</MessageScrollerItem>
);
}
export type { UIMessage, UIMessagePart };
export {
Bubble,
BubbleContent,
BubbleGroup,
BubbleReactions,
Message,
MessageAnimated,
MessageAvatar,
MessageContent,
MessageFooter,
MessageGroup,
MessageHeader,
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
useMessageScroller,
useMessageScrollerScrollable,
useMessageScrollerVisibility,
};"use client";
import { ChevronRightIcon } from "lucide-react";
import * as React from "react";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Shimmer } from "@/components/ui/shimmer";
import { cn } from "@/lib/utils";
const defaultTraceMotion = "450 cubic-bezier(0.32, 0.72, 0, 1)";
interface TraceCollapsibleContextValue {
motion: string;
open: boolean;
}
const TraceCollapsibleContext =
React.createContext<TraceCollapsibleContextValue>({
motion: defaultTraceMotion,
open: false,
});
const TraceLineContext = React.createContext<{
status?: "running" | "error" | "pending";
}>({});
function resolveTraceMotion(
motion: string | undefined,
animation: false | string | undefined,
fallback: string
): string {
if (motion !== undefined) {
return motion;
}
if (animation === false) {
return "off";
}
if (typeof animation === "string") {
if (/^(spring|inertia|keyframes)/u.test(animation)) {
console.warn(
`[trace] animation="${animation}" uses a motion DSL that is not supported in CSS. Falling back to default. Prefer motion="150 ease-out" instead.`
);
return fallback;
}
return animation;
}
return fallback;
}
function Trace({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
data-slot="trace"
{...props}
/>
);
}
function TraceLine({
className,
status,
...props
}: React.ComponentProps<"span"> & {
status?: "running" | "error" | "pending";
}) {
return (
<TraceLineContext.Provider value={{ status }}>
<span
className={cn(
"text-muted-foreground flex w-fit max-w-full min-w-0 items-center gap-2",
"data-[status=error]:text-destructive",
"data-[status=pending]:opacity-60",
"data-[status=running]:text-foreground",
className
)}
data-slot="trace-line"
data-status={status}
{...props}
/>
</TraceLineContext.Provider>
);
}
function TraceIcon({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
aria-hidden="true"
className={cn(
"flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:size-4",
className
)}
data-slot="trace-icon"
{...props}
/>
);
}
function TraceTitle({
className,
children,
...props
}: React.ComponentProps<"span">) {
const { status } = React.useContext(TraceLineContext);
const content =
status === "running" ? <Shimmer>{children}</Shimmer> : children;
return (
<span
className={cn("min-w-0 truncate", className)}
data-slot="trace-title"
{...props}
>
{content}
</span>
);
}
function TraceDescription({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
className={cn(
"text-muted-foreground/70 shrink-0 text-xs tabular-nums",
className
)}
data-slot="trace-description"
{...props}
/>
);
}
type TraceCollapsibleProps = Omit<React.ComponentProps<"div">, "onChange"> & {
animation?: false | string;
defaultOpen?: boolean;
disabled?: boolean;
motion?: string;
onOpenChange?: (open: boolean) => void;
open?: boolean;
};
function TraceCollapsible({
animation,
children,
className,
defaultOpen,
disabled,
motion,
onOpenChange,
open: openProp,
...props
}: TraceCollapsibleProps) {
const [internalOpen, setInternalOpen] = React.useState(defaultOpen ?? false);
const isControlled = openProp !== undefined;
const currentOpen = isControlled ? openProp : internalOpen;
const resolvedMotion = resolveTraceMotion(
motion,
animation,
defaultTraceMotion
);
const handleOpenChange = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setInternalOpen(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
return (
<TraceCollapsibleContext.Provider
value={{ motion: resolvedMotion, open: currentOpen }}
>
<Collapsible
className={cn("flex w-full min-w-0 flex-col", className)}
data-slot="trace-collapsible"
disabled={disabled}
motion={resolvedMotion}
onOpenChange={handleOpenChange}
open={currentOpen}
{...props}
>
{children}
</Collapsible>
</TraceCollapsibleContext.Provider>
);
}
function TraceCollapsibleTrigger({
className,
children,
onClick,
...props
}: React.ComponentProps<"button">) {
const { open } = React.useContext(TraceCollapsibleContext);
return (
<CollapsibleTrigger
className={cn(
"group/trace-collapsible-trigger text-muted-foreground flex w-fit max-w-full min-w-0 cursor-pointer items-center gap-2 text-left outline-none",
"has-[[data-status=error]]:text-destructive",
className
)}
data-slot="trace-collapsible-trigger"
onClick={onClick}
{...props}
>
<span className="inline-flex items-center gap-2 transition-transform duration-200 hover:translate-x-px motion-reduce:transition-none motion-reduce:hover:translate-x-0">
{children}
</span>
<span
aria-hidden="true"
className="flex shrink-0 items-center justify-center transition-transform duration-200 data-[state=open]:rotate-90 motion-reduce:transition-none"
data-state={open ? "open" : "closed"}
>
<ChevronRightIcon className="text-muted-foreground size-3.5" />
</span>
</CollapsibleTrigger>
);
}
type TraceCollapsibleContentProps = React.ComponentProps<"div"> & {
animation?: false | string;
animateHeight?: boolean;
keepMounted?: boolean;
motion?: string;
};
function TraceCollapsibleContent({
animateHeight = true,
animation,
children,
className,
keepMounted: _keepMounted,
motion,
...props
}: TraceCollapsibleContentProps) {
const { motion: contextMotion } = React.useContext(TraceCollapsibleContext);
const resolvedMotion = resolveTraceMotion(motion, animation, contextMotion);
return (
<CollapsibleContent
motion={animateHeight ? resolvedMotion : false}
{...props}
>
<div
className={cn("border-border mt-1 ml-2 border-l pb-1 pl-4", className)}
data-slot="trace-collapsible-content"
>
{children}
</div>
</CollapsibleContent>
);
}
export {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceDescription,
TraceIcon,
TraceLine,
TraceTitle,
};Update the import paths to match your project setup.
Usage
Mark the tool call with needsApproval: true. The writer emits an approval-requested state instead of running the tool immediately.
import { createChat } from "@frakment/ai";
import type { UIDataTypes, UIMessage } from "ai";
type ChatMessage = UIMessage<
unknown,
UIDataTypes,
{ runCommand: { input: { command: string }; output: { stdout: string } } }
>;
const chat = createChat<ChatMessage>()
.user("Clean up the build folder.")
.assistant(({ writer }) => {
writer.tool("runCommand", {
input: { command: "rm -rf dist" },
needsApproval: true,
output: { stdout: "" },
});
});Wire the approval handler into useChat and let the SDK auto-send the follow-up turn.
import { useChat } from "@ai-sdk/react";
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
const { messages, addToolApprovalResponse } = useChat({
messages: initialMessages,
transport,
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
});Anatomy
A pending tool call renders as an Item card. Once approved or denied, it becomes a Trace line.
{part.state === "approval-requested" ? (
<Item variant="outline" size="sm">
<ItemMedia variant="icon">
<TerminalIcon />
</ItemMedia>
<ItemContent>
<ItemTitle>Run {part.input.command}?</ItemTitle>
<ItemDescription>The command runs in this project.</ItemDescription>
</ItemContent>
<ItemActions>
<Button
size="sm"
variant="outline"
onClick={() =>
addToolApprovalResponse({ id: part.approval.id, approved: false })
}
>
Deny
</Button>
<Button
size="sm"
onClick={() =>
addToolApprovalResponse({ id: part.approval.id, approved: true })
}
>
Approve
</Button>
</ItemActions>
</Item>
) : (
<Trace>
<TraceLine status={!denied && part.state !== "output-available" ? "running" : undefined}>
<TraceIcon><TerminalIcon /></TraceIcon>
<TraceTitle>
{denied ? "Denied" : part.state === "output-available" ? "Ran" : "Running"}
{part.input?.command}
</TraceTitle>
</TraceLine>
</Trace>
)}- Item — the pending approval card with media, content, and actions.
- Button — Approve (default) and Deny (outline).
- Trace — the outcome row, shown after the user responds.
- Message, Bubble — surrounding turn.
Approval states
The tool call moves through states:
| State | Render |
|---|---|
input-streaming | hidden (input not yet available) |
approval-requested | Item card with Approve / Deny |
approval-responded | Trace line, running if approved |
output-available | Trace line showing "Ran [command]" |
output-denied | Trace line showing "Denied [command]" |
Animation
User turns animate with the slide-up variant, assistant turns fade in, and the approval card slides up when it appears.
import { MESSAGE_ANIMATIONS } from "@/lib/message-animations";
import { motion, useReducedMotion } from "motion/react";
const shouldReduceMotion = useReducedMotion();
<motion.div
animate={shouldReduceMotion ? undefined : "animate"}
initial={shouldReduceMotion ? undefined : "initial"}
variants={MESSAGE_ANIMATIONS["slide-up"].variants}
>
<Item variant="outline" size="sm">...</Item>
</motion.div>Motion is skipped when the user prefers reduced motion.
Next
- Chat — full streaming chat surface.
- Checkpoint — restore points in a conversation.
- Trace — collapsible reasoning and tool-call lines.
- Item — card with media, content, and actions.
Accessibility
- The approval card is an
Itemwithrole="group". Both buttons are focusable and labelled ("Approve", "Deny"). addToolApprovalResponseresolves on click and keyboard. The card unmounts and focus returns to the transcript.- The pending state is announced with
aria-live="polite". Do not useassertive. - The resulting Trace line reports "Ran command" or "Denied command".
Best Practices
- Ask only when needed. Set
needsApproval: truefor destructive or outbound actions. - Show the exact command. The user needs to see what will run.
- Use clear verbs. "Approve" and "Deny" beat "Yes" and "No".
- Resolve the tool immediately after approval. Emit
output-availableoroutput-denied. - Do not double-prompt. Once responded, hide the card and stream the outcome.