For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

Chat

Full streaming chat composed from Frakment primitives, with reasoning traces, tool calls, and animated messages.

New Thread
Ask the agent to change your code.
What should we build?
The agent can read your code, run commands and make changes. Press send to start.
chat-demo.tsx
"use client";

import { useChat } from "@ai-sdk/react";
import type { UIDataTypes, UIMessage } from "ai";
import {
  ArrowUpIcon,
  CircleCheckIcon,
  GlobeIcon,
  LoaderCircleIcon,
  MessageCircleDashedIcon,
  PaperclipIcon,
  PlusIcon,
  RotateCwIcon,
  TelescopeIcon,
  TerminalIcon,
} from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
} from "@/components/ui/empty";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupTextarea,
} from "@/components/ui/input-group";
import { Markdown } from "@/components/ui/markdown";
import {
  Bubble,
  BubbleContent,
  Message,
  MessageContent,
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
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 };
    };
  }
>;

type ChatPart = ChatMessage["parts"][number];

type ToolPart = Extract<ChatPart, { type: "tool-runCommand" }>;

const chat = createChat<ChatMessage>()
  .user("Add a dark mode toggle to the settings page.")
  .sleep(600)
  .assistant(({ writer }) => {
    writer.reasoning(
      "I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme."
    );
    writer.sleep(400);
    writer
      .tool("runCommand", { input: { command: "rg -l ThemeProvider app" } })
      .sleep(800)
      .output({ stdout: "app/layout.tsx" });
    writer.sleep(500);
    writer.text(`next-themes is already set up in \`app/layout.tsx\`, so the toggle only has to call \`setTheme\`.

**Changes**

- Added \`components/mode-toggle.tsx\` with a Light and Dark option.
- Put \`<ModeToggle />\` next to the Appearance heading in \`app/settings/page.tsx\`.

\`\`\`tsx
const { setTheme } = useTheme()
\`\`\`
`);
  })
  .user("Make it follow the system setting by default.")
  .sleep(600)
  .assistant(({ writer }) => {
    writer.reasoning(
      "The default theme lives on the ThemeProvider. I should check what it is set to now."
    );
    writer.sleep(400);
    writer
      .tool("runCommand", {
        input: { command: "rg -n defaultTheme app/layout.tsx" },
      })
      .sleep(800)
      .output({
        stdout: '12:  <ThemeProvider attribute="class" defaultTheme="light">',
      });
    writer.sleep(500);
    writer.text(`It was set to \`light\`. I updated the \`ThemeProvider\` in \`app/layout.tsx\`:

\`\`\`tsx
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
\`\`\`

New visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back.
`);
  })
  .user("Run the build before I ship it.")
  .sleep(600)
  .assistant(({ writer }) => {
    writer
      .tool("runCommand", { input: { command: "pnpm build" } })
      .sleep(1600)
      .output({
        stdout:
          "▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)",
      });
    writer.sleep(500);
    writer.text(`The build passes, so it is ready to ship.

- Compiled in **4.2s**.
- No lint or type errors.
- Generated all **12** static pages.
`);
  });

const initialMessages = chat.get(0);
const transport = chat.transport({
  delayMs: 16,
  fallback:
    "This demo only knows the scripted turns. Press reset to start over.",
});

const MotionMessageScrollerItem = motion.create(MessageScrollerItem);

export function ChatDemo() {
  const { messages, sendMessage, setMessages, status } = useChat<ChatMessage>({
    messages: initialMessages,
    transport,
  });
  const [draft, setDraft] = React.useState<string | null>(null);
  const formRef = React.useRef<HTMLFormElement>(null);
  const shouldReduceMotion = useReducedMotion();
  const nextMessage = chat.next(messages);
  const busy = status === "submitted" || status === "streaming";
  const text = draft ?? (nextMessage ? getMessageText(nextMessage) : "");
  const canSend = text.trim().length > 0 && !busy;

  function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!canSend) {
      return;
    }

    if (draft === null && nextMessage) {
      void sendMessage(nextMessage);
    } else {
      void sendMessage({ text: text.trim() });
    }
    setDraft(null);
  }

  return (
    <MessageScrollerProvider>
      <div className="[[data-slot=preview]:has(&)]:bg-background relative flex w-full flex-col gap-4 [[data-slot=preview]:has(&)>div]:p-0!">
        <div className="flex h-200 w-full flex-col gap-4">
          <div className="flex items-start justify-between gap-4 p-8 pb-4">
            <div className="flex flex-col gap-1">
              <div className="font-medium">New Thread</div>
              <div className="text-muted-foreground text-sm">
                Ask the agent to change your code.
              </div>
            </div>
            <Tooltip>
              <TooltipTrigger
                aria-label="Reset conversation"
                as={Button}
                disabled={busy}
                onClick={() => {
                  setMessages(initialMessages);
                  setDraft(null);
                }}
                size="icon"
                variant="outline"
              >
                <RotateCwIcon />
              </TooltipTrigger>
              <TooltipContent>
                <p>Reset</p>
              </TooltipContent>
            </Tooltip>
          </div>
          <div className="min-h-0 flex-1">
            {messages.length === 0 ? (
              <Empty className="h-full">
                <EmptyHeader>
                  <EmptyMedia variant="icon">
                    <MessageCircleDashedIcon />
                  </EmptyMedia>
                  <EmptyTitle>What should we build?</EmptyTitle>
                  <EmptyDescription>
                    The agent can read your code, run commands and make changes.
                    Press send to start.
                  </EmptyDescription>
                </EmptyHeader>
              </Empty>
            ) : (
              <MessageScroller>
                <MessageScrollerViewport>
                  <MessageScrollerContent
                    aria-busy={busy}
                    className="gap-6 px-8 py-0"
                  >
                    {messages.map((message) => {
                      if (message.role === "user") {
                        return (
                          <MotionMessageScrollerItem
                            animate="animate"
                            initial={shouldReduceMotion ? false : "initial"}
                            key={message.id}
                            messageId={message.id}
                            scrollAnchor
                            variants={messageAnimations["slide-up"].variants}
                          >
                            <Message align="end">
                              <MessageContent>
                                <Bubble align="end" variant="muted">
                                  <BubbleContent>
                                    {getMessageText(message)}
                                  </BubbleContent>
                                </Bubble>
                              </MessageContent>
                            </Message>
                          </MotionMessageScrollerItem>
                        );
                      }

                      const streaming = busy && message === messages.at(-1);
                      const steps = message.parts.filter(
                        (part) =>
                          part.type === "reasoning" ||
                          part.type === "tool-runCommand"
                      );
                      const reply = getMessageText(message);

                      return (
                        <MessageScrollerItem
                          key={message.id}
                          messageId={message.id}
                        >
                          <Message>
                            <MessageContent className="gap-3">
                              {steps.length > 0 && (
                                <Trace>
                                  {steps.map((part, index) => (
                                    <StepRow
                                      key={index}
                                      part={part}
                                      streaming={streaming}
                                    />
                                  ))}
                                </Trace>
                              )}
                              {reply && <Markdown>{reply}</Markdown>}
                            </MessageContent>
                          </Message>
                        </MessageScrollerItem>
                      );
                    })}
                  </MessageScrollerContent>
                </MessageScrollerViewport>
                <MessageScrollerButton />
              </MessageScroller>
            )}
          </div>
          <div className="p-8 pt-0">
            <form className="w-full" onSubmit={onSubmit} ref={formRef}>
              <InputGroup className="bg-muted/40 rounded-xl border-0 shadow-none">
                <InputGroupTextarea
                  aria-label="Message"
                  className="min-h-14"
                  onChange={(event) => setDraft(event.target.value)}
                  onKeyDown={(event) => {
                    if (event.key === "Enter" && !event.shiftKey) {
                      event.preventDefault();
                      formRef.current?.requestSubmit();
                    }
                  }}
                  placeholder="Ask the agent..."
                  value={text}
                />
                <InputGroupAddon align="block-end" className="pt-1">
                  <DropdownMenu>
                    <DropdownMenuTrigger
                      aria-label="Add context"
                      as={InputGroupButton}
                      className="rounded-full"
                      size="icon-sm"
                      type="button"
                      variant="outline"
                    >
                      <PlusIcon />
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      align="start"
                      className="w-44"
                      side="top"
                    >
                      <DropdownMenuItem>
                        <PaperclipIcon />
                        Add Photos & Files
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem>
                        <TelescopeIcon />
                        Deep Research
                      </DropdownMenuItem>
                      <DropdownMenuItem>
                        <GlobeIcon />
                        Web Search
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                  <InputGroupButton
                    className="ml-auto rounded-full"
                    disabled={!canSend}
                    size="icon-sm"
                    type="submit"
                    variant="default"
                  >
                    <ArrowUpIcon />
                    <span className="sr-only">Send</span>
                  </InputGroupButton>
                </InputGroupAddon>
              </InputGroup>
            </form>
          </div>
        </div>
      </div>
    </MessageScrollerProvider>
  );
}

function StepRow({ part, streaming }: { part: ChatPart; streaming: boolean }) {
  if (part.type === "reasoning") {
    return (
      <ReasoningRow running={part.state === "streaming"} text={part.text} />
    );
  }

  if (part.type === "tool-runCommand") {
    return <ToolRow part={part} streaming={streaming} />;
  }

  return null;
}

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="text-muted-foreground whitespace-pre-wrap">
        {text}
      </TraceCollapsibleContent>
    </TraceCollapsible>
  );
}

function ToolRow({ part, streaming }: { part: ToolPart; streaming: boolean }) {
  const command = part.input?.command;

  if (part.state === "output-available" || part.state === "output-error") {
    const failed = part.state === "output-error";

    return (
      <TraceCollapsible>
        <TraceCollapsibleTrigger>
          <TraceLine status={failed ? "error" : undefined}>
            <TraceIcon>
              <TerminalIcon />
            </TraceIcon>
            <TraceTitle>
              {failed ? "Failed to run" : "Ran"} {command}
            </TraceTitle>
          </TraceLine>
        </TraceCollapsibleTrigger>
        <TraceCollapsibleContent>
          <CodeBlock size="sm">
            <CodeBlockContent className="max-h-64" wrap>
              {failed ? part.errorText : part.output.stdout}
            </CodeBlockContent>
          </CodeBlock>
        </TraceCollapsibleContent>
      </TraceCollapsible>
    );
  }

  return (
    <TraceLine status={streaming ? "running" : "error"}>
      <TraceIcon>
        <TerminalIcon />
      </TraceIcon>
      <TraceTitle>
        {streaming ? "Running" : "Failed to run"} {command}
      </TraceTitle>
    </TraceLine>
  );
}

A complete chat surface wired with @ai-sdk/react and Frakment primitives. Messages animate on entry, reasoning appears as a collapsible trace, tool calls render as code blocks, and the transcript stays anchored to the latest message.

Chat is not a single component — it composes Message Scroller, Message, Bubble, and Input Group into one surface. Install the primitives, then assemble them the same way the demo does.

Installation

Usage

Wire the chat engine from @frakment/ai and render messages with the composed primitives.

chat.tsx
import { useChat } from "@ai-sdk/react";
import type { UIDataTypes, UIMessage } from "ai";
 
import { createChat } from "@frakment/ai";
 
type ChatMessage = UIMessage<
  unknown,
  UIDataTypes,
  { runCommand: { input: { command: string }; output: { stdout: string } } }
>;
 
const chat = createChat<ChatMessage>()
  .user("Run the tests.")
  .assistant(({ writer }) => {
    writer
      .tool("runCommand", { input: { command: "pnpm test" } })
      .output({ stdout: "15 passed" });
    writer.text("Tests pass.");
  });
 
const transport = chat.transport({ delayMs: 16 });
 
export function MyChat() {
  const { messages, sendMessage, status } = useChat({ transport });
 
  return (
    <MessageScroller>
      <MessageScrollerViewport>
        <MessageScrollerContent>
          {messages.map((m) => (
            <MessageScrollerItem key={m.id} messageId={m.id}>
              <Message message={m} />
            </MessageScrollerItem>
          ))}
        </MessageScrollerContent>
      </MessageScrollerViewport>
    </MessageScroller>
  );
}

Anatomy

The demo composes seven primitives. Each one is documented on its own page.

chat.tsx
<MessageScrollerProvider>
  <MessageScroller>
    <MessageScrollerViewport>
      <MessageScrollerContent>
        <MessageScrollerItem>
          <Message>
            <MessageContent>
              <Bubble>
                <BubbleContent />
              </Bubble>
            </MessageContent>
          </Message>
        </MessageScrollerItem>
      </MessageScrollerContent>
    </MessageScrollerViewport>
    <MessageScrollerButton />
  </MessageScroller>
 
  <InputGroup>
    <InputGroupTextarea />
    <InputGroupAddon>
      <DropdownMenu>...</DropdownMenu>
      <InputGroupButton type="submit" />
    </InputGroupAddon>
  </InputGroup>
</MessageScrollerProvider>
  • MessageScroller — scroll-aware transcript viewport with sticky scroll button.
  • Message, Bubble — user and assistant turns.
  • Trace, TraceCollapsible — reasoning and tool-call steps inside an assistant message.
  • CodeBlock — renders tool output.
  • InputGroup — the composer with textarea, addon buttons, and send action.
  • Empty — zero-state before the first message.

Animation

Message rows animate through variants defined in lib/message-animations.ts. Motion is skipped when the user prefers reduced motion.

chat.tsx
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}
>
  <Message>...</Message>
</motion.div>

Each variant exposes initial and animate states that plug into motion.div. Add a new variant by extending the object — the MessageAnimation type covers all keys.

Reasoning traces

Reasoning and tool calls render as nested TraceCollapsible items inside the assistant message. The line auto-expands while streaming and collapses when done.

chat.tsx
<Trace>
  {steps.map((part) => (
    <TraceCollapsible key={part.id}>
      <TraceCollapsibleTrigger>
        <TraceLine status={running ? "running" : undefined}>
          <TraceIcon>{running ? <LoaderCircleIcon /> : <CircleCheckIcon />}</TraceIcon>
          <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent>{part.text}</TraceCollapsibleContent>
    </TraceCollapsible>
  ))}
</Trace>

Replacing the script

The demo ships with a scripted chat built from createChat. Replace it with a real transport:

chat.tsx
import { useChat } from "@ai-sdk/react";
 
const { messages, sendMessage, status } = useChat({
  transport: yourTransport,
});

The rendered components do not assume the scripted transport. Any UIMessage[] works.

Next

  • Message Scroller — scroll-aware transcript viewport.
  • Message — message row primitive.
  • Bubble — chat bubble surface.
  • Trace — collapsible reasoning and tool-call lines.
  • Code Block — syntax-highlighted code.
  • Input Group — inline composer with addons.

Accessibility

  • Every assistant turn is a Message with role semantics. Screen readers announce the transcript in order.
  • MessageScroller sets aria-busy while streaming so assistive tech pauses politely.
  • Reasoning and tool-call steps render as TraceCollapsible with a visible trigger label ("Thinking", "Ran …").
  • The composer is a labelled InputGroupTextarea. Enter sends, Shift+Enter inserts a newline.
  • Animations respect prefers-reduced-motion; motion is skipped when the user disables it.

Best Practices

  • Anchor the transcript to the latest user turn. Pass scrollAnchor so new messages follow.
  • Stream text, do not swap. Replacing the whole message per chunk breaks the typewriter effect.
  • Collapse reasoning automatically. Open while running, close when resolved.
  • Fail gracefully. Append a system message on transport error instead of clearing the transcript.
  • Replace the scripted transport in production. createChat is for demos, not real backends.