# Agent thread (智能体对话流)

Agent conversation with collapsible reasoning, expandable tool calls, copyable code results and a docked composer. Loading, empty and error states included.

- Ref: `component/agent-thread` (component · ai-chat)
- Page: https://uifino.com/en/components/ai-chat/agent-thread
- Markdown: https://uifino.com/md/components/agent-thread.md
- Preview image: https://uifino.com/blocks/covers/agent-thread-dark.webp

## Install

- shadcn: `npx shadcn@latest add "https://uifino.com/r/blocks/agent-thread.json"`
- UIFino CLI: `npx uifino@latest add component/agent-thread`

## Dependencies

`lucide-react`

## shadcn/ui components it builds on

- `accordion`, `badge`, `button`, `empty`, `input-group`, `skeleton`. The shadcn CLI installs them together with the block.

## Theme

The block reads the project's shadcn theme variables, so it follows whatever DESIGN.md the project uses and needs no options of its own.
To give the project the look of a UIFino brand or style, install its theme: `npx shadcn@latest add "https://uifino.com/r/themes/<brand-or-style-id>.json"`.

## Usage

The files under `examples/` show the block wired with content, including its loading, empty and error states where it has them.

## Files

| Path | Role | Size |
| :--- | :--- | ---: |
| components/blocks/agent-thread/agent-thread.tsx | source | 12.9 KB |
| components/blocks/agent-thread/examples/content.ts | demo | 7.6 KB |
| components/blocks/agent-thread/examples/default.tsx | demo | 483 B |
| components/blocks/agent-thread/examples/empty.tsx | demo | 452 B |
| components/blocks/agent-thread/examples/error.tsx | demo | 524 B |
| components/blocks/agent-thread/examples/loading.tsx | demo | 500 B |
| components/blocks/agent-thread/examples/working.tsx | demo | 480 B |

### components/blocks/agent-thread/agent-thread.tsx

```tsx
"use client";

import { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";
import {
  ArrowUp,
  Check,
  CircleAlert,
  Copy,
  FileCode2,
  Loader2,
  MessageSquare,
  Paperclip,
  RotateCw,
  Wrench
} from "lucide-react";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextarea } from "@/components/ui/input-group";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";

export interface AgentToolCall {
  readonly id: string;
  readonly name: string;
  readonly summary: string;
  readonly status: "done" | "running" | "error";
  readonly durationMs?: number;
  readonly output?: string;
}

export interface AgentArtifact {
  readonly filename: string;
  readonly code: string;
}

export interface AgentMessage {
  readonly id: string;
  readonly role: "user" | "assistant";
  readonly time?: string;
  readonly content: string;
  readonly reasoning?: {
    readonly duration: string;
    readonly open?: boolean;
    readonly steps: readonly string[];
  };
  readonly toolCalls?: readonly AgentToolCall[];
  readonly artifact?: AgentArtifact;
}

export interface AgentStarter {
  readonly id: string;
  readonly label: string;
  readonly prompt: string;
}

export interface AgentThreadLabels {
  readonly reasoning: string;
  readonly placeholder: string;
  readonly send: string;
  readonly attach: string;
  readonly copy: string;
  readonly copied: string;
  readonly retry: string;
  readonly running: string;
  readonly emptyTitle: string;
  readonly emptyDescription: string;
  readonly errorTitle: string;
  readonly errorDescription: string;
}

export interface AgentThreadProps {
  readonly title: string;
  readonly model?: string;
  readonly messages: readonly AgentMessage[];
  readonly labels: AgentThreadLabels;
  readonly status?: "ready" | "loading" | "error";
  readonly starters?: readonly AgentStarter[];
  readonly attachments?: readonly string[];
  readonly onSend?: (prompt: string) => void;
  readonly onRetry?: () => void;
  readonly className?: string;
}

function ToolCalls({ calls }: { readonly calls: readonly AgentToolCall[] }) {
  return (
    <Accordion type="multiple" className="border-y">
      {calls.map((call) => (
        <AccordionItem key={call.id} value={call.id}>
          <AccordionTrigger
            disabled={!call.output}
            className="min-w-0 items-center gap-2 rounded-md px-1 py-2 text-sm hover:no-underline"
          >
            <span className="flex min-w-0 flex-1 items-center gap-2">
              {call.status === "running" ? (
                <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" aria-hidden="true" />
              ) : call.status === "error" ? (
                <CircleAlert className="size-3.5 shrink-0 text-destructive" aria-hidden="true" />
              ) : (
                <Wrench className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
              )}
              <span className="max-w-2/5 shrink-0 truncate font-mono font-medium">{call.name}</span>
              <span className="min-w-0 truncate font-normal text-muted-foreground">{call.summary}</span>
            </span>
            {call.durationMs !== undefined ? (
              <span className="shrink-0 font-normal tabular-nums text-muted-foreground">{call.durationMs} ms</span>
            ) : null}
          </AccordionTrigger>
          {call.output ? (
            <AccordionContent className="pb-0">
              <pre className="overflow-x-auto rounded-md bg-muted/50 px-3 py-2 mb-2 font-mono text-xs leading-relaxed text-muted-foreground">
                <code>{call.output}</code>
              </pre>
            </AccordionContent>
          ) : null}
        </AccordionItem>
      ))}
    </Accordion>
  );
}

function ArtifactCard({
  artifact,
  labels
}: {
  readonly artifact: AgentArtifact;
  readonly labels: AgentThreadLabels;
}) {
  const [copied, setCopied] = useState(false);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(artifact.code);
    } catch {
      return;
    }
    setCopied(true);
    window.setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="overflow-hidden rounded-lg bg-muted/50">
      <div className="flex items-center justify-between gap-2 border-b py-1 pr-1 pl-3">
        <span className="flex min-w-0 items-center gap-2 text-xs">
          <FileCode2 className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
          <span className="truncate font-mono">{artifact.filename}</span>
        </span>
        <Button type="button" variant="ghost" size="sm" onClick={copy} className="text-muted-foreground">
          {copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
          {copied ? labels.copied : labels.copy}
        </Button>
      </div>
      <pre className="px-3 py-3 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap">
        <code>{artifact.code}</code>
      </pre>
    </div>
  );
}

function Reasoning({
  reasoning,
  label,
  id
}: {
  readonly reasoning: NonNullable<AgentMessage["reasoning"]>;
  readonly label: string;
  readonly id: string;
}) {
  return (
    <Accordion type="single" collapsible defaultValue={reasoning.open ? id : undefined}>
      <AccordionItem value={id} className="border-b-0">
        <AccordionTrigger className="items-center justify-start gap-1.5 py-0 text-sm font-normal text-muted-foreground hover:no-underline">
          {label} · <span className="tabular-nums">{reasoning.duration}</span>
        </AccordionTrigger>
        <AccordionContent className="pb-0">
          <ol className="mt-2 flex list-decimal flex-col gap-1.5 border-l pl-6 text-sm leading-relaxed text-foreground/70">
            {reasoning.steps.map((step) => (
              <li key={step}>{step}</li>
            ))}
          </ol>
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  );
}

function AssistantMessage({
  message,
  labels
}: {
  readonly message: AgentMessage;
  readonly labels: AgentThreadLabels;
}) {
  return (
    <div className="flex min-w-0 flex-col gap-3">
      {message.reasoning ? (
        <Reasoning reasoning={message.reasoning} label={labels.reasoning} id={message.id} />
      ) : null}
      {message.toolCalls && message.toolCalls.length > 0 ? <ToolCalls calls={message.toolCalls} /> : null}
      <p className="max-w-prose text-sm leading-relaxed text-pretty break-words">{message.content}</p>
      {message.artifact ? <ArtifactCard artifact={message.artifact} labels={labels} /> : null}
    </div>
  );
}

function LoadingThread({ labels }: { readonly labels: AgentThreadLabels }) {
  return (
    <div className="flex flex-col gap-3" aria-busy="true">
      <span className="flex items-center gap-2 text-sm text-muted-foreground">
        <Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
        {labels.running}
      </span>
      <Skeleton className="h-9 w-full bg-muted-foreground/15" />
      <Skeleton className="h-4 w-5/6 bg-muted-foreground/15" />
      <Skeleton className="h-4 w-3/5 bg-muted-foreground/15" />
    </div>
  );
}

export function AgentThread({
  title,
  model,
  messages,
  labels,
  status = "ready",
  starters = [],
  attachments = [],
  onSend,
  onRetry,
  className
}: AgentThreadProps) {
  const [draft, setDraft] = useState("");
  const busy = status === "loading";
  const canSend = !busy && draft.trim().length > 0;

  const submit = (event?: FormEvent) => {
    event?.preventDefault();
    if (!canSend) return;
    onSend?.(draft.trim());
    setDraft("");
  };

  const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
      event.preventDefault();
      submit();
    }
  };

  const isEmpty = status === "ready" && messages.length === 0;
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages.length, status]);

  return (
    <section
      className={cn(
        "@container mx-auto flex w-full max-w-3xl min-w-0 flex-col overflow-hidden rounded-xl border",
        className
      )}
    >
      <header className="flex items-center justify-between gap-3 border-b px-4 py-3">
        <h3 className="truncate text-sm font-medium">{title}</h3>
        {model ? (
          <Badge variant="outline" className="shrink-0 font-mono font-normal">
            {model}
          </Badge>
        ) : null}
      </header>

      <div ref={scrollRef} className="max-h-144 overflow-y-auto">
        <div className="flex flex-col gap-6 p-4 @md:p-6">
          {isEmpty ? (
            <Empty className="border-0 p-0 py-8">
              <EmptyHeader>
                <EmptyMedia variant="icon">
                  <MessageSquare aria-hidden="true" />
                </EmptyMedia>
                <EmptyTitle>{labels.emptyTitle}</EmptyTitle>
                <EmptyDescription>{labels.emptyDescription}</EmptyDescription>
              </EmptyHeader>
              {starters.length > 0 ? (
                <EmptyContent className="flex-row flex-wrap justify-center">
                  {starters.map((starter) => (
                    <Button
                      key={starter.id}
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => onSend?.(starter.prompt)}
                    >
                      {starter.label}
                    </Button>
                  ))}
                </EmptyContent>
              ) : null}
            </Empty>
          ) : (
            <>
              {messages.map((message) =>
                message.role === "user" ? (
                  <div key={message.id} className="flex justify-end">
                    <div className="max-w-[85%] min-w-0 rounded-lg bg-muted px-3 py-2">
                      <p className="max-w-prose text-sm leading-relaxed break-words">{message.content}</p>
                      {message.time ? (
                        <p className="mt-1 text-right text-xs tabular-nums text-muted-foreground">{message.time}</p>
                      ) : null}
                    </div>
                  </div>
                ) : (
                  <AssistantMessage key={message.id} message={message} labels={labels} />
                )
              )}
              {busy ? <LoadingThread labels={labels} /> : null}
              {status === "error" ? (
                <div role="alert" className="flex items-start gap-3">
                  <CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" aria-hidden="true" />
                  <div className="flex min-w-0 flex-col items-start gap-1">
                    <p className="text-sm font-medium">{labels.errorTitle}</p>
                    <p className="text-sm text-muted-foreground">{labels.errorDescription}</p>
                    {onRetry ? (
                      <Button type="button" variant="outline" size="sm" onClick={onRetry} className="mt-2">
                        <RotateCw aria-hidden="true" />
                        {labels.retry}
                      </Button>
                    ) : null}
                  </div>
                </div>
              ) : null}
            </>
          )}
        </div>
      </div>

      <form onSubmit={submit} className="border-t p-3">
        <InputGroup>
          <InputGroupTextarea
            value={draft}
            disabled={busy}
            onChange={(event) => setDraft(event.target.value)}
            onKeyDown={onKeyDown}
            placeholder={labels.placeholder}
            aria-label={labels.placeholder}
            rows={2}
            className="min-h-0 resize-none"
          />
          <InputGroupAddon align="block-end">
            <InputGroupButton type="button" size="icon-xs" aria-label={labels.attach} disabled={busy}>
              <Paperclip aria-hidden="true" />
            </InputGroupButton>
            <div className="flex min-w-0 flex-1 gap-1.5 overflow-hidden">
              {attachments.map((file) => (
                <Badge key={file} variant="secondary" className="min-w-0 font-mono font-normal">
                  <span className="truncate">{file}</span>
                </Badge>
              ))}
            </div>
            <InputGroupButton
              type="submit"
              variant="default"
              size="icon-xs"
              className="ml-auto rounded-full"
              aria-label={labels.send}
              disabled={!canSend}
            >
              <ArrowUp aria-hidden="true" />
            </InputGroupButton>
          </InputGroupAddon>
        </InputGroup>
      </form>
    </section>
  );
}
```

Not inlined (6 files, 10.0 KB). Full sources: https://uifino.com/r/blocks/agent-thread.json
