# Activity trace

Show what an agent is doing while keeping the answer easy to find.

## Preview

activity-preview-1.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { Progress } from "@/components/ui/progress";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Migrate the dialog components to Base UI."
      answer={"Migrated Dialog and AlertDialog. The type checker passes."}
      workDuration={3200}
    >
      {(progress) => <MigrationActivity progress={progress} />}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer: answer2,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer2.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer2
    : answer2.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

var stepLabels = [
  "Install @base-ui/react",
  "Replace the Radix imports",
  "Rename asChild to render",
  "Run the type checker",
];

function MigrationActivity({ progress }) {
  const completed = Math.min(
    stepLabels.length,
    Math.floor(progress * stepLabels.length),
  );
  const state = completed === stepLabels.length ? "complete" : "active";
  const events = stepLabels.map((label, index) => ({
    id: label,
    kind: "task",
    label,
    state:
      index < completed
        ? "complete"
        : index === completed
          ? "active"
          : "pending",
  }));
  return (
    <Activity2 status={state} defaultOpen>
      <ActivitySummary
        state={state}
        statusText={`${completed} of ${stepLabels.length} done`}
        icon={
          <Progress.Clock
            value={completed}
            max={stepLabels.length}
            label="Migration steps complete"
            showCount={false}
            tabIndex={-1}
            aria-hidden="true"
          />
        }
      >
        Migrate to Base UI
      </ActivitySummary>
      <ActivityContent>
        <ActivityList events={events} aria-label="Migration steps" />
      </ActivityContent>
    </Activity2>
  );
}

```

## Design guidance

Use Activity to show steps such as searching for a source or running a check. Start with one row. Let readers expand details and nest any child steps. Put the final answer outside the steps.

Add an icon when it helps identify a step, such as search or reading a document. A shimmering title can be enough for a thinking state. Your app supplies status, event IDs, and order. See [Streaming and runtime](#streaming-runtime) to connect live updates.

**Also known as**

Trace, Agent trace.

Ghost calls this building block Activity. “Trace” describes the observable steps it presents; it is not a separate public component.

## Installation

```sh
npx shadcn@latest add https://ghost-ui.com/r/activity.json
```

## Basic usage

```tsx
import {
  Activity,
  ActivityLine,
  ActivityIcon,
  ActivityTitle,
  ActivityDescription,
} from "@/components/ui/activity";
import { FileText } from "lucide-react";

export function ActivityExample() {
  return (
    <Activity>
      <ActivityLine>
        <ActivityIcon>
          <FileText />
        </ActivityIcon>
        <ActivityTitle>Compared package changes</ActivityTitle>
        <ActivityDescription>+48 −12</ActivityDescription>
      </ActivityLine>
    </Activity>
  );
}
```

## Streaming and runtime

MessageParts renders the current text and activity parts; Markdown streaming handles incomplete text. Feed it the updated message snapshot from your runtime. Do not add a client typewriter over native SDK output: it delays real chunks and can confuse cancellation with completion. Activity preserves caller IDs, ordering, nested events and disclosure state as snapshots change.

The visual examples simulate data timing for inspection. The two SDK examples instead render normalized native SDK chunks immediately through the same MessageParts owner. Their transports are local protocol fixtures, not live provider requests. They verify the installed Vercel AI SDK and TanStack AI contracts; they do not establish compatibility with every runtime or SDK version.

For another runtime, pass canonical ChatMessage records directly or connect its snapshot/subscription through createChatRuntimeStore and useChatRuntimeStore. The host owns transport, authentication, persistence, cancellation, late-response filtering and execution. A stopped or errored stream retains partial text; an unknown status or capability must not be treated as success or authorization. See [runtime architecture](/libraries/ai-runtime) and [runtime selection](/libraries/ai-runtimes).

## Structures

- Activity
  - ActivityLine
    - ActivityIcon (optional)
    - ActivityActor (avatar glyph, optional)
    - ActivityTitle
    - ActivityDescription (adverbial detail, optional)
    - ActivityAffordance (trailing cue, optional)
  - ActivitySummary (alternative to manual trigger)
  - ActivityTrigger (optional)
    - ActivityLine
  - ActivityContent (optional)
    - ActivityGroup (manual rows)
      - ActivityLine
    - ActivityList (data-driven tree)
      - ActivityItem (one node)
        - ActivityEventRow (shared row)
        - ActivityList (child nodes, optional)
    - ActivityExplanation (optional)

Start with a plain ActivityLine. Add ActivityTrigger and ActivityContent only when recorded detail should be disclosed; ActivitySummary is a convenience run summary. A line is an inline span with no button, link or focus stop. ActivityTrigger owns a native disclosure button and one chevron. ActivityContent keeps spacing inside its animated panel; keepMounted can preserve nested content. ActivityList renders an ordered tree of ActivityItem nodes from caller events; each node row is an ActivityEventRow, and event.children becomes one deeper rail. ActivityGroup as="ol" requires caller-owned list items.

## Examples

Start with line and disclosure composition, then compare state and progress, optional destinations, SDK wiring, and full-turn recipes.

### Rows and nesting

Compose one row from an optional icon, a title and optional detail. Pass a React node to ActivityLine.icon, ActivitySummary.icon or an event’s icon to choose a glyph, Progress clock or Avatar. Omit it for the state glyph; pass null to hide the leading slot. ActivityIcon.children overrides the line icon. Explicit event icons take precedence over automatic progress glyphs; progress text remains visible. Active first-level rows use Shimmer’s shared purple gradient; nested rows use the normal sweep. This applies to direct lines and the first ActivityGroup or ActivityList level outside disclosed detail. Rows inside ActivityContent keep the normal sweep. Use ActivityContent and ActivityGroup or ActivityList to nest multiple rows. These examples show those separate choices.

#### Configurable leading icons

Choose a task glyph, state glyph, Progress clock, Avatar or no leading slot within the same response.

activity-configurable-leading-icons-2.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText, ListChecks, Search } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityGroup,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import { Avatar as Avatar2 } from "@/components/ui/avatar";
import { Progress } from "@/components/ui/progress";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Check the release notes."
      answer="I found the release notes."
    >
      <Activity2 defaultOpen>
        <ActivitySummary state="complete" icon={<ListChecks />}>
          Review release notes
        </ActivitySummary>
        <ActivityContent>
          <ActivityGroup>
            <Row icon={<FileText />}>Read release notes</Row>
            <Row icon={<Search />}>Find affected packages</Row>
            <Row state="complete">Check compatibility</Row>
            <Row
              icon={
                <Progress.Clock
                  value={3}
                  max={3}
                  showCount={false}
                  label="Review complete"
                  tabIndex={-1}
                />
              }
            >
              Review changes
            </Row>
            <Row icon={<Avatar2 name="Review agent" kind="agent" size="xs" />}>
              Ask the review agent
            </Row>
            <Row icon={null}>Prepare the summary</Row>
          </ActivityGroup>
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Rows without icons

Omit ActivityIcon from the row and its child rows. The title begins at the row start; nesting and disclosure still work. State remains available through shimmer and assistive text. The event-list convenience renders state glyphs; use these lower-level parts for text-only work.

activity-rows-without-icons-3.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityTitle as ActivityTitle2,
  ActivityGroup,
  ActivityTrigger,
  ActivityContent,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Check the receipt date and total."
      answer="Both the date and total match the order."
    >
      {(progress) => (
        <Activity2 status={progress === 1 ? "complete" : "active"} defaultOpen>
          <ActivityTrigger>
            <ActivityLine2>
              <ActivityTitle2>
                {progress === 1
                  ? "Checked the receipt"
                  : "Checking the receipt"}
              </ActivityTitle2>
            </ActivityLine2>
          </ActivityTrigger>
          <ActivityContent>
            <ActivityGroup as="ol">
              <li>
                <ActivityLine2 state="complete">
                  <ActivityTitle2>Matched the order date</ActivityTitle2>
                </ActivityLine2>
              </li>
              <li>
                <ActivityLine2 state={progress === 1 ? "complete" : "active"}>
                  <ActivityTitle2>
                    {progress === 1
                      ? "Matched the total"
                      : "Checking the total"}
                  </ActivityTitle2>
                </ActivityLine2>
              </li>
            </ActivityGroup>
          </ActivityContent>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Speaker identity

In a known one-to-one human/agent conversation, the roster hides redundant speaker identity. In a shared conversation, compose the actual MessageHeader as the Activity title: speaker, action, metadata and disclosure stay in one row. The header inherits the row's type size, line height and color. Replay belongs to that assistant message's footer.

activity-speaker-identity-4.jsx

```jsx
import { useEffect, useId, useState } from "react";
import { ActivityTitle } from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <ActivityPlayback
      prompt="Review the receipt with Marta."
      answer="The receipt date and total match the order."
      participants={[
        {
          id: "user",
          name: "You",
          kind: "human",
        },
        activityAgent,
        {
          id: "marta",
          name: "Marta",
          kind: "human",
        },
      ]}
      parts={[
        {
          type: "activity",
          id: "receipt-review",
          event: {
            id: "review",
            kind: "review",
            state: "complete",
            label: "checked the receipt",
            meta: "2 checks",
            children: [
              {
                id: "date",
                kind: "check",
                state: "complete",
                label: "Matched the order date",
              },
              {
                id: "amount",
                kind: "check",
                state: "complete",
                label: "Matched the receipt total",
              },
            ],
          },
        },
      ]}
    >
      {null}
    </ActivityPlayback>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: "Review the receipt with Marta.",
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={undefined}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {undefined}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(30);
  const end =
    answerAt +
    Math.ceil("The receipt date and total match the order.".length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? "The receipt date and total match the order."
    : "The receipt date and total match the order.".slice(
        0,
        Math.max(0, (tick - answerAt) * 2),
      );
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, 30)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={"Review the receipt with Marta."}
        response={response}
        composer={undefined}
        footer={done ? undefined : null}
        renderers={undefined}
        participants={participants2}
        onReplay={() => {
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? undefined : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

```

#### Expandable detail

Open the recorded output from the row.

activity-expandable-detail-5.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { Terminal } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityDescription,
  ActivityTrigger,
  ActivityContent,
} from "@/components/ui/activity";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Run the release checks."
      answer="Expand the release checks to inspect each recorded step."
    >
      <Activity2>
        <ActivityTrigger>
          <Row
            icon={<Terminal />}
            detail={<ActivityDescription>14s</ActivityDescription>}
          >
            Ran compatibility checks
          </Row>
        </ActivityTrigger>
        <ActivityContent>
          <Snippet
            value="24 checks passed"
            title="Compatibility output"
            variant="block"
            contentType="text"
          />
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Controlled disclosure

The caller owns open state; data changes do not reset it.

activity-controlled-disclosure-6.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { useState as useState2 } from "react";
import { FileText, ListChecks } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityGroup,
  ActivityTrigger,
  ActivityContent,
} from "@/components/ui/activity";

export default function Example() {
  const [open, setOpen] = useState2(false);
  return (
    <ActivityDemoTurn
      onReplay={() => setOpen(false)}
      prompt="Show the release steps."
      answer="The completed release steps are ready to inspect."
    >
      {(progress) => (
        <Activity2 open={open} onOpenChange={setOpen}>
          <ActivityTrigger>
            <Row icon={<ListChecks />}>Review release steps</Row>
          </ActivityTrigger>
          <ActivityContent>
            <ActivityGroup as="ol">
              <li>
                <Row icon={<FileText />}>Read release notes</Row>
              </li>
              <li>
                <Row state={progress === 1 ? "complete" : "active"}>
                  {progress === 1
                    ? "Ran compatibility checks"
                    : "Run compatibility checks"}
                </Row>
              </li>
            </ActivityGroup>
          </ActivityContent>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Emergent task steps

Append newly observed steps while keeping caller IDs and order stable. A work history does not invent the pending steps or fixed denominator of a plan.

activity-emergent-task-steps-7.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  const events = [
    {
      id: "review",
      kind: "review",
      state: "active",
      label: "Reviewing the receipt",
      children: [
        {
          id: "gather",
          kind: "gather",
          state: "complete",
          label: "Gathering context",
        },
        {
          id: "search",
          kind: "search",
          state: "active",
          label: "Searching the web",
        },
      ],
    },
    {
      id: "synthesize",
      kind: "synthesize",
      state: "pending",
      label: "Preparing the answer",
    },
  ];
  return (
    <ActivityDemoTurn
      prompt="Find my receipt."
      answer="I found the receipt and matched it to the order."
    >
      {(progress) => (
        <Activity2 status={progress === 1 ? "complete" : "active"} defaultOpen>
          <ActivitySummary state={progress === 1 ? "complete" : "active"}>
            Receipt lookup
          </ActivitySummary>
          <ActivityContent>
            <ActivityList
              events={events.map((event) => ({
                ...event,
                state: progress === 1 ? "complete" : event.state,
                label:
                  progress === 1
                    ? event.id === "review"
                      ? "Reviewed the receipt"
                      : "Prepared the answer"
                    : event.label,
                children: event.children?.map((child) => ({
                  ...child,
                  state: progress === 1 ? "complete" : child.state,
                  label:
                    progress === 1
                      ? child.id === "gather"
                        ? "Gathered context"
                        : "Searched the web"
                      : child.label,
                })),
              }))}
            />
          </ActivityContent>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Nested row composition

Compose a group from individual row parts.

activity-nested-row-composition-8.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityGroup,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Gather the release context."
      answer="I reviewed the launch review and staging notes."
    >
      {(progress) => (
        <Activity2>
          <Row state={progress === 1 ? "complete" : "active"}>
            {progress === 1 ? "Gathered context" : "Gathering context"}
          </Row>
          <ActivityGroup as="ol">
            <li>
              <Row icon={<FileText />}>Read launch-review.pdf</Row>
            </li>
            <li>
              <Row state={progress === 1 ? "complete" : "active"}>
                {progress === 1
                  ? "Read staging-notes.csv"
                  : "Reading staging-notes.csv"}
              </Row>
            </li>
          </ActivityGroup>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Description and tags

ActivityDescription carries a count, duration, result or diff beside the title. It shares the title's type size and uses a lower color hierarchy. Choose the detail that helps interpret that operation.

Use short units for time (14s), counts (2 files), change (+48 −12) and impact (2.1 GB). For results, show an outcome (2 passed), progress (60%) or finality (retained output).

Keep details short and lowercase, without a trailing period or a middle dot. Compose the ordinary Badge as another child of ActivityLine for a classification such as severity; there is no Activity-specific badge part.

activity-description-and-tags-9.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityDescription,
} from "@/components/ui/activity";
import { Badge } from "@/components/ui/badge";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Compare the package changes."
      answer="The compatibility check found changes that need review."
    >
      <Activity2>
        <Row
          icon={<FileText />}
          detail={
            <ActivityDescription>
              <Badge size="sm" tone="success">
                +48
              </Badge>{" "}
              <Badge size="sm" tone="error">
                −12
              </Badge>
            </ActivityDescription>
          }
        >
          Compared package changes
        </Row>
        <ActivityLine2 icon={<FileText />}>
          <ActivityIcon />
          <ActivityTitle2>ReDoS in path-to-regexp 0.1.7</ActivityTitle2>
          <Badge size="md" tone="error">
            high
          </Badge>
        </ActivityLine2>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

### State and progress

#### Thinking

Before the first observable operation, show a shimmering title without a leading icon. Once work is observable, replace it with the operation; settle that work before streaming the final answer. Adding ActivityIcon explicitly opts into the dots Loader for active rows. Shimmer respects reduced motion.

activity-thinking-10.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityTitle as ActivityTitle2,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Find the release notes."
      answer="I found the release notes and the migration guide."
    >
      {(progress) => (
        <Activity2>
          <ActivityLine2 state={progress === 1 ? "complete" : "active"}>
            <ActivityTitle2>
              {progress === 1
                ? "Found release notes"
                : "Searching release notes"}
            </ActivityTitle2>
          </ActivityLine2>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Activity statuses

Pending, active, failed, cancelled and completed work share the same row structure. With ActivityIcon, active work uses the dots Loader and pending work uses a dotted circle. State words remain in assistive text; do not repeat them as visible metadata.

activity-activity-statuses-11.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Check the last release job."
      answer="The job includes pending, active, failed, stopped and completed work."
    >
      <Activity2>
        <Row state="pending">Review compatibility results</Row>
        <Row state="active">Checking package compatibility</Row>
        <Row state="error">Compatibility check failed</Row>
        <Row state="cancelled">Previous check stopped</Row>
        <Row state="complete">Read release notes</Row>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Determinate progress

Render progress only with known finite work and a positive maximum. The Progress.Clock circle becomes the row glyph and the percentage counts in the adverbial detail; no extra progress track is needed.

activity-determinate-progress-12.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Find my receipt."
      answer="I found the receipt and checked its details."
      workDuration={3200}
    >
      {(progress) => <ReceiptProgress progress={progress} />}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

var active = [
  {
    id: "lookup",
    kind: "lookup",
    state: "complete",
    label: "Find matching order",
  },
  {
    id: "read",
    kind: "read",
    state: "active",
    label: "Read receipt details",
    progress: {
      value: 3,
      max: 5,
    },
  },
];

function ReceiptProgress({ progress }) {
  const value = Math.round(progress * 5);
  const state = value === 5 ? "complete" : "active";
  return (
    <Activity2 status={state} defaultOpen>
      <ActivitySummary state={state}>Receipt lookup</ActivitySummary>
      <ActivityContent>
        <ActivityList
          events={[
            active[0],
            {
              ...active[1],
              state,
              progress: {
                value,
                max: 5,
              },
            },
          ]}
        />
      </ActivityContent>
    </Activity2>
  );
}

```

#### Error recovery

The caller acknowledges retry through updated event data.

Retry is a compact outline Button in the failed branch, aligned to the branch start. This demo changes local state; Activity does not retry a tool or a network request by itself.

activity-error-recovery-13.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { useState as useState2 } from "react";
import { Button as Button2 } from "@/components/ui/button";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  const [retried, setRetried] = useState2(false);
  const events = retried
    ? [
        {
          id: "retry",
          kind: "retry",
          state: "complete",
          label: "Receipt found",
          meta: "2nd attempt",
          description: "The second attempt succeeded.",
        },
      ]
    : [
        {
          id: "request",
          kind: "request",
          state: "error",
          label: "Receipt lookup failed",
          meta: "8s",
          description: "The service did not respond.",
        },
      ];
  return (
    <ActivityDemoTurn
      prompt="Find my receipt."
      answer={
        retried
          ? "I found the receipt on the second attempt."
          : "The receipt service did not respond. You can try again."
      }
      onReplay={() => setRetried(false)}
    >
      <Activity2 status={retried ? "complete" : "error"} defaultOpen>
        <ActivitySummary state={retried ? "complete" : "error"}>
          Receipt lookup
        </ActivitySummary>
        <ActivityContent>
          <ActivityList events={events} />
          {!retried ? (
            <Button2
              type="button"
              variant="outline"
              size="xs"
              onClick={() => setRetried(true)}
            >
              Try again
            </Button2>
          ) : null}
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Cancelled

Retain partial history after the operation stops.

activity-cancelled-14.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  const events = [
    {
      id: "cancelled",
      kind: "lookup",
      state: "cancelled",
      label: "Search stopped",
      meta: "0 results",
      description: "No changes were made.",
    },
  ];
  const tree = (
    <Activity2 status={"cancelled"} defaultOpen={true}>
      <ActivitySummary state={"cancelled"} statusText={null} icon={undefined}>
        {"Receipt lookup stopped"}
      </ActivitySummary>
      <ActivityContent>
        <ActivityList events={events} />
      </ActivityContent>
    </Activity2>
  );
  return (
    <ActivityDemoTurn
      prompt={"Find my receipt."}
      answer={"The lookup stopped. No changes were made."}
    >
      {tree}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

### Destinations and supporting detail

#### Link

A native anchor makes the row a navigable reference inside the trace. The trailing affordance keeps the destination visible without adding a second control.

activity-link-15.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { ArrowUpRight, FileText } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityAffordance,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import { Link } from "@/components/ui/link";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Review the staging SLA."
      answer="The staging SLA is available in the linked document."
    >
      <Activity2 defaultOpen>
        <ActivitySummary state="complete" statusText="1 link">
          Reviewed the staging SLA
        </ActivitySummary>
        <ActivityContent>
          <Link
            href="/examples/staging-support-sla.html"
            kind="external"
            variant="plain"
            underline="hover"
            target="_blank"
            rel="noopener noreferrer"
            icon={false}
            className="ui-activity-destination"
          >
            <ActivityLine2>
              <ActivityIcon>
                <FileText />
              </ActivityIcon>
              <ActivityTitle2>
                Read the staging support SLA
                <span className="ui-sr-only">{" (opens in a new tab)"}</span>
              </ActivityTitle2>
              <ActivityAffordance>
                <ArrowUpRight />
              </ActivityAffordance>
            </ActivityLine2>
          </Link>
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Dialog

The canonical Dialog trigger uses the Activity row styling and stays inside the branch.

activity-dialog-16.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { ChevronRight, FileText, X } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityDescription,
  ActivityAffordance,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import { Dialog } from "@/components/ui/dialog";
import { Button as Button2, IconButton } from "@/components/ui/button";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Show the changed files."
      answer="Open the file review to inspect the package changes."
    >
      <Activity2 defaultOpen>
        <ActivitySummary state="complete">Found changed files</ActivitySummary>
        <ActivityContent>
          <Dialog.Root>
            <Dialog.Trigger
              render={
                <Button2 variant="ghost" className="ui-activity-trigger" />
              }
            >
              <Row
                icon={<FileText />}
                detail={<ActivityDescription>1 file</ActivityDescription>}
                affordance={
                  <ActivityAffordance>
                    <ChevronRight />
                  </ActivityAffordance>
                }
              >
                Review changed files
              </Row>
            </Dialog.Trigger>
            <Dialog.Portal>
              <Dialog.Backdrop />
              <Dialog.Popup>
                <Dialog.Header>
                  <Dialog.Title>Changed files</Dialog.Title>
                  <Dialog.Close
                    render={
                      <IconButton
                        variant="ghost"
                        size="icon-sm"
                        aria-label="Close changed files"
                        icon={<X />}
                      />
                    }
                  />
                </Dialog.Header>
                <Dialog.Core>
                  <ActivityDescription>
                    One package file changed in this release.
                  </ActivityDescription>
                  <Snippet
                    value="package.json | 4 +++−"
                    title="Changed files"
                    contentType="text"
                    variant="block"
                  />
                </Dialog.Core>
              </Dialog.Popup>
            </Dialog.Portal>
          </Dialog.Root>
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Drawer

Inspect longer output in the canonical Drawer without leaving the trace.

activity-drawer-17.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { ChevronRight, Terminal, X } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityDescription,
  ActivityAffordance,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import { Drawer } from "@/components/ui/drawer";
import { Button as Button2, IconButton } from "@/components/ui/button";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Inspect the test output."
      answer="Open the output panel to inspect the recorded checks."
    >
      <Activity2 defaultOpen>
        <ActivitySummary state="complete">
          Ran compatibility checks
        </ActivitySummary>
        <ActivityContent>
          <Drawer.Root swipeDirection="right">
            <Drawer.Trigger
              render={
                <Button2 variant="ghost" className="ui-activity-trigger" />
              }
            >
              <Row
                icon={<Terminal />}
                detail={<ActivityDescription>24 checks</ActivityDescription>}
                affordance={
                  <ActivityAffordance>
                    <ChevronRight />
                  </ActivityAffordance>
                }
              >
                Inspect test output
              </Row>
            </Drawer.Trigger>
            <Drawer.Portal>
              <Drawer.Viewport className="ui-drawer-viewport--right">
                <Drawer.Backdrop />
                <Drawer.Popup>
                  <Drawer.Content>
                    <Drawer.Header>
                      <Drawer.Title>Compatibility checks</Drawer.Title>
                      <Drawer.Close
                        render={
                          <IconButton
                            variant="ghost"
                            size="icon-sm"
                            aria-label="Close test output"
                            icon={<X />}
                          />
                        }
                      />
                    </Drawer.Header>
                    <Drawer.Core>
                      <ActivityDescription>
                        Results from the current release review.
                      </ActivityDescription>
                      <Snippet
                        value="24 checks passed"
                        title="Test output"
                        contentType="text"
                        variant="block"
                      />
                    </Drawer.Core>
                  </Drawer.Content>
                </Drawer.Popup>
              </Drawer.Viewport>
            </Drawer.Portal>
          </Drawer.Root>
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Sources

Use a search glyph for web discovery and a document glyph for an attachment. Glyphs describe the operation; they do not determine its runtime behavior. The same source IDs link discovered evidence to inline answer citations and the source summary in MessageActions.

Compose Citation in the same row. appearance="inline" renders the reference number in the title text, so the marker reads as an ID and not as a count chip; the source title and preview stay in the Citation popover.

activity-sources-18.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText, Search } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityGroup,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import {
  Citation,
  CitationList,
  CitationProvider,
} from "@/components/ui/citation";
import { MessageActions } from "@/components/ui/message-actions";

export default function Example() {
  const sources = [
    {
      id: "notes",
      type: "url",
      title: "TanStack release notes",
      url: "https://tanstack.com/blog",
      domain: "tanstack.com",
      snippet: "Updates from the TanStack maintainers.",
    },
    {
      id: "migration",
      type: "url",
      title: "Migration guide",
      url: "https://tanstack.com/router/latest/docs/how-to/migrate-from-react-router",
      domain: "tanstack.com",
      snippet:
        "Review route configuration and navigation when migrating an existing app.",
    },
    {
      id: "review",
      type: "document",
      title: "launch-review.pdf",
      document: {
        name: "launch-review.pdf",
        page: 4,
      },
      snippet:
        "The release checklist requires a migration review before rollout.",
    },
  ];
  return (
    <CitationProvider
      sources={sources}
      citationOrder={["notes", "migration", "review"]}
    >
      <ActivityDemoTurn
        prompt="Review the release notes and attached launch review."
        answer={
          "The release notes and migration guide describe the upgrade. The attached launch review requires a migration check before rollout."
        }
        footer={
          <MessageActions
            text={
              "The release notes and migration guide describe the upgrade. The attached launch review requires a migration check before rollout."
            }
            sources={<CitationList />}
          />
        }
        renderers={{
          text: (part) =>
            part.type === "text" ? (
              <p>
                {part.text}
                {part.state === "complete" ? (
                  <>
                    {" "}
                    <Citation
                      sourceIds={["notes", "migration", "review"]}
                      appearance="inline"
                      placement="inline"
                    />
                  </>
                ) : null}
              </p>
            ) : null,
        }}
      >
        {(progress) => (
          <Activity2 defaultOpen>
            <ActivitySummary
              state={progress === 1 ? "complete" : "active"}
              statusText="3 sources"
            >
              {progress === 1
                ? "Reviewed release evidence"
                : "Reviewing release evidence"}
            </ActivitySummary>
            <ActivityContent>
              <ActivityGroup as="ol">
                <li>
                  <Row icon={<Search />}>
                    {progress === 1
                      ? "Searched release notes"
                      : "Searching release notes"}{" "}
                    <Citation
                      sourceIds={["notes", "migration"]}
                      appearance="inline"
                      placement="inline"
                    />
                  </Row>
                </li>
                <li>
                  <Row icon={<FileText />}>
                    {progress === 1
                      ? "Read launch-review.pdf"
                      : "Reading launch-review.pdf"}{" "}
                    <Citation
                      sourceIds={["review"]}
                      appearance="inline"
                      placement="inline"
                    />
                  </Row>
                </li>
              </ActivityGroup>
            </ActivityContent>
          </Activity2>
        )}
      </ActivityDemoTurn>
    </CitationProvider>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### File changes

Keep code and diff rendering with Snippet.

activity-file-changes-19.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityDescription,
  ActivityTrigger,
  ActivityContent,
} from "@/components/ui/activity";
import { Badge } from "@/components/ui/badge";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Update the release notes."
      answer="The recorded changes are shown above."
    >
      <Activity2 defaultOpen>
        <ActivityTrigger>
          <Row
            icon={<FileText />}
            detail={
              <ActivityDescription>
                <Badge size="sm" tone="success">
                  +4
                </Badge>{" "}
                <Badge size="sm" tone="error">
                  −1
                </Badge>
              </ActivityDescription>
            }
          >
            Updated release notes
          </Row>
        </ActivityTrigger>
        <ActivityContent>
          <Snippet
            value={
              "+ Document the migration steps\n\u2212 Remove the outdated installation command"
            }
            title="release-notes.md"
            language="diff"
            variant="block"
          />
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

### Plans, tools and results

#### Reasoning summary

Only an explicitly classified application summary appears.

activity-reasoning-summary-20.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { ListChecks } from "lucide-react";
import {
  Activity as Activity2,
  ActivityLine as ActivityLine2,
  ActivityIcon,
  ActivityTitle as ActivityTitle2,
  ActivityTrigger,
  ActivityContent,
  ActivityExplanation,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="How did you check compatibility?"
      answer="The summary describes the compatibility review."
    >
      <Activity2 defaultOpen>
        <ActivityTrigger>
          <Row icon={<ListChecks />}>Reviewed compatibility constraints</Row>
        </ActivityTrigger>
        <ActivityContent>
          <ActivityExplanation
            kind="reasoning-summary"
            source="application-summary"
          >
            The exported API stays compatible. The change only adds optional
            fields.
          </ActivityExplanation>
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

function Row({ state, children, icon, detail, affordance }) {
  return (
    <ActivityLine2 state={state} icon={icon}>
      <ActivityIcon />
      <ActivityTitle2>{children}</ActivityTitle2>
      {detail}
      {affordance}
    </ActivityLine2>
  );
}

```

#### Tool input and result

Reuse Tool for one operation and Snippet for its output.

activity-tool-input-and-result-21.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { Snippet } from "@/components/ui/snippet";
import { Tool } from "@/components/ui/tool";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Check package compatibility."
      answer="The compatibility output is available for inspection."
    >
      <Tool name="Check package compatibility" state="output-ready" defaultOpen>
        <Snippet
          value="npm run check:compatibility"
          title="Input"
          language="bash"
          variant="block"
        />
        <Snippet
          value="24 checks passed"
          title="Result"
          contentType="text"
          variant="block"
        />
      </Tool>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Activity execution and explanation

Observable work and classified explanatory content remain distinct. The explanation is a nested row in the same branch, so it reads as part of the trace rather than a detached block.

activity-activity-execution-and-explanation-22.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Find my receipt."
      answer="The receipt matches the order date and account."
    >
      {(progress) => (
        <Activity2 status={progress === 1 ? "complete" : "active"} defaultOpen>
          <ActivitySummary state={progress === 1 ? "complete" : "active"}>
            Receipt lookup
          </ActivitySummary>
          <ActivityContent>
            <ActivityList
              events={[
                active[0],
                {
                  ...active[1],
                  state: progress === 1 ? "complete" : "active",
                  progress: {
                    value: Math.round(progress * 5),
                    max: 5,
                  },
                },
                {
                  id: "account-note",
                  kind: "note",
                  state: "complete",
                  label: "Matched the account",
                  description:
                    "The receipt is from the same account as the order.",
                },
              ]}
            />
          </ActivityContent>
        </Activity2>
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

var active = [
  {
    id: "lookup",
    kind: "lookup",
    state: "complete",
    label: "Find matching order",
  },
  {
    id: "read",
    kind: "read",
    state: "active",
    label: "Read receipt details",
    progress: {
      value: 3,
      max: 5,
    },
  },
];

```

#### Work forecast

TodoList is the plan node: the summary row is the parent activity and every task is a child row. AgentTodoList is an alias of the same owner. The application owns revisions, ordering and any plan approval. This is not a scheduler and it owns no card.

activity-work-forecast-23.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { TodoList } from "@/components/ui/todo-list";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Review the release."
      answer="The release notes and compatibility checks are complete."
    >
      {(progress) => (
        <TodoList
          title="Release review"
          defaultOpen
          items={[
            {
              id: "notes",
              label: "Read release notes",
              status: "complete",
            },
            {
              id: "checks",
              label: "Run compatibility checks",
              status: progress === 1 ? "complete" : "active",
            },
          ]}
        />
      )}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Work queue

Partition the caller's snapshot without changing task IDs or treating failed work as completed. The queue is one Activity node; each status group is a child node and each task is a grandchild on its own rail. There is no second progress meter or automatic dispatch.

activity-work-queue-24.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { TodoList } from "@/components/ui/todo-list";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Work through the release."
      answer="The migration guide is updated. Peer compatibility still needs attention."
    >
      {(progress) => {
        const items = [
          {
            id: "notes",
            label: "Read release notes",
            status: "complete",
          },
          {
            id: "peers",
            label: "Check peer compatibility",
            status: "error",
            description: "The React peer range needs review.",
          },
          {
            id: "guide",
            label: "Update migration guide",
            status: progress === 1 ? "complete" : "active",
          },
        ];
        const groups = [
          {
            id: "remaining",
            title: "To do",
            items: items.filter((item) => item.status !== "complete"),
          },
          {
            id: "completed",
            title: "Completed",
            items: items.filter((item) => item.status === "complete"),
          },
        ];
        return (
          <TodoList title="Release work queue" groups={groups} defaultOpen />
        );
      }}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Subagent history

The host supplies one identified parent run and its ordered, identified child records, including actor IDs, public Activity events, state and optional result finality. Parent state never aggregates from children; only a completed run with resultFinal === true may show a final result. Other output stays a preview, partial or explicitly unknown in finality. Unknown states stay neutral, and mismatched parent IDs are reported. This view does not schedule agents or resolve native cancellation scope.

activity-subagent-history-25.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  Activity as Activity2,
  ActivityActor,
  ActivityContent,
  ActivityDescription,
  ActivityIcon,
  ActivityLine as ActivityLine2,
  ActivityList,
  ActivitySummary,
  ActivityTitle as ActivityTitle2,
  ActivityTrigger,
} from "@/components/ui/activity";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <>
      <SubagentsDemo />
    </>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

var defaultSubagentSnapshot = {
  parent: {
    id: "release-review",
    actorId: "release",
    name: "Release assistant",
    state: "complete",
    events: [
      {
        id: "draft",
        kind: "work",
        label: "Drafted the recommendation",
        state: "complete",
      },
    ],
  },
  children: [
    {
      id: "research",
      parentRunId: "release-review",
      actorId: "research",
      name: "Research agent",
      state: "cancelled",
      events: [
        {
          id: "region",
          kind: "tool",
          label: "Review regional notes",
          state: "cancelled",
        },
      ],
      result: "Two regions checked. The third region was not reached.",
      resultFinal: false,
    },
    {
      id: "checks",
      parentRunId: "release-review",
      actorId: "checks",
      name: "Compatibility agent",
      state: "complete",
      events: [
        {
          id: "exports",
          kind: "tool",
          label: "Check exported names",
          state: "complete",
        },
      ],
      result: "The existing public exports remain available.",
      resultFinal: true,
    },
  ],
};

function SubagentsDemo({ snapshot = defaultSubagentSnapshot } = {}) {
  return <SubagentsView key={snapshot.parent.id} snapshot={snapshot} />;
}

function stateMeta(state) {
  return state === "unknown"
    ? "status unavailable"
    : state === "pending"
      ? "queued"
      : state === "error"
        ? "failed"
        : state === "cancelled"
          ? "stopped"
          : null;
}

function resultMeta(run) {
  if (run.result === undefined) return null;
  const final = run.state === "complete" && run.resultFinal === true;
  return final
    ? "final result"
    : run.state === "active" || run.state === "pending"
      ? "preview only"
      : run.state === "complete"
        ? "partial result"
        : "retained partial output";
}

function SubagentsView({ snapshot }) {
  const issues = validateSubagentSnapshot(snapshot);
  const parentState =
    snapshot.parent.state === "unknown" ? undefined : snapshot.parent.state;
  return (
    <ActivityDemoTurn
      prompt="Review the release with the team."
      answer="Each agent run keeps its own status and retained results."
    >
      <Activity2 defaultOpen>
        {issues.length ? (
          <ActivityTrigger>
            <ActivityLine2>
              <ActivityIcon />
              <ActivityTitle2>Run records unavailable</ActivityTitle2>
            </ActivityLine2>
          </ActivityTrigger>
        ) : snapshot.parent.state === "unknown" ? (
          <ActivityTrigger>
            <ActivityLine2>
              <ActivityIcon>
                <ActivityActor
                  name={snapshot.parent.name}
                  seed={snapshot.parent.actorId}
                />
              </ActivityIcon>
              <ActivityTitle2>
                {snapshot.parent.name}
                {" is reviewing the release"}
              </ActivityTitle2>
              <ActivityDescription>status unavailable</ActivityDescription>
              {snapshot.parent.result !== undefined ? (
                <ActivityDescription>partial result</ActivityDescription>
              ) : null}
            </ActivityLine2>
          </ActivityTrigger>
        ) : (
          <ActivitySummary
            state={parentState}
            statusText={stateMeta(snapshot.parent.state)}
            icon={
              <ActivityActor
                name={snapshot.parent.name}
                seed={snapshot.parent.actorId}
                state={snapshot.parent.state}
              />
            }
          >
            {snapshot.parent.name}{" "}
            {snapshot.parent.state === "complete"
              ? "reviewed the release"
              : "is reviewing the release"}
          </ActivitySummary>
        )}
        <ActivityContent keepMounted>
          {issues.length ? <p role="alert">{issues.join("; ")}</p> : null}
          {issues.length ? null : (
            <ActivityList events={snapshot.parent.events} />
          )}
          {!issues.length ? <RunResult run={snapshot.parent} /> : null}
          {issues.length
            ? null
            : snapshot.children.map((run) => {
                const state = run.state === "unknown" ? undefined : run.state;
                return (
                  <Activity2 key={run.id} data-run-id={run.id} defaultOpen>
                    <ActivityTrigger>
                      <ActivityLine2 state={state}>
                        <ActivityIcon>
                          <ActivityActor
                            name={run.name}
                            seed={run.actorId}
                            state={run.state}
                          />
                        </ActivityIcon>
                        <ActivityTitle2>{run.name}</ActivityTitle2>
                        {stateMeta(run.state) ? (
                          <ActivityDescription>
                            {stateMeta(run.state)}
                          </ActivityDescription>
                        ) : null}
                        {resultMeta(run) ? (
                          <ActivityDescription>
                            {resultMeta(run)}
                          </ActivityDescription>
                        ) : null}
                      </ActivityLine2>
                    </ActivityTrigger>
                    <ActivityContent keepMounted>
                      <ActivityList events={run.events} />
                      <RunResult run={run} />
                    </ActivityContent>
                  </Activity2>
                );
              })}
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

function RunResult({ run }) {
  if (run.result === undefined) return null;
  const final = run.state === "complete" && run.resultFinal === true;
  const stopped = run.state === "error" || run.state === "cancelled";
  const title = stopped
    ? "Retained partial output"
    : run.state === "active" || run.state === "pending"
      ? "Preview only"
      : run.state === "complete" && run.resultFinal === false
        ? "Partial result"
        : "Finality unavailable";
  return (
    <Snippet
      value={run.result}
      title={final ? "Result" : title}
      contentType="text"
      variant="block"
    />
  );
}

function validateSubagentSnapshot(snapshot) {
  const issues = [];
  const ids = /* @__PURE__ */ new Set();
  for (const run of [snapshot.parent, ...snapshot.children]) {
    if (typeof run.id !== "string" || !run.id.trim())
      issues.push("A run is missing its ID");
    else if (ids.has(run.id)) issues.push(`Duplicate run ID: ${run.id}`);
    if (typeof run.id === "string") ids.add(run.id);
    if (
      typeof run.actorId !== "string" ||
      !run.actorId.trim() ||
      typeof run.name !== "string" ||
      !run.name.trim() ||
      ![
        "pending",
        "active",
        "complete",
        "error",
        "cancelled",
        "unknown",
      ].includes(run.state)
    )
      issues.push(`Run ${run.id || "(empty)"} has malformed identity or state`);
    if (
      (run.result !== undefined && typeof run.result !== "string") ||
      (run.resultFinal !== undefined && typeof run.resultFinal !== "boolean")
    )
      issues.push(`Run ${run.id || "(empty)"} has malformed result facts`);
    const eventIds = /* @__PURE__ */ new Set();
    for (const event of run.events) {
      if (
        typeof event.id !== "string" ||
        !event.id.trim() ||
        eventIds.has(event.id) ||
        typeof event.label !== "string" ||
        !event.label.trim() ||
        typeof event.kind !== "string" ||
        !event.kind.trim()
      )
        issues.push(
          `Run ${run.id || "(empty)"} has malformed or duplicate event identity`,
        );
      if (
        !Object.prototype.hasOwnProperty.call(
          {
            pending: true,
            active: true,
            complete: true,
            error: true,
            cancelled: true,
          },
          event.state,
        )
      )
        issues.push(
          `Run ${run.id || "(empty)"} has an event with an invalid status`,
        );
      if (typeof event.id === "string") eventIds.add(event.id);
    }
  }
  for (const child of snapshot.children)
    if (
      typeof child.parentRunId !== "string" ||
      child.parentRunId !== snapshot.parent.id
    )
      issues.push(`Run ${child.id} belongs to a different parent`);
  return issues;
}

```

#### Process output

The stopped process has retained output and no reported exit code. Snippet inspects text; it does not provide a shell, ANSI emulator or executable command input.

activity-process-output-26.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { Snippet } from "@/components/ui/snippet";
import { Tool, ToolInput, ToolOutput } from "@/components/ui/tool";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Check package compatibility."
      answer="The compatibility output is available for inspection."
    >
      <Tool name="Package compatibility process" state="cancelled" defaultOpen>
        <ToolInput>
          <Snippet
            value="npm run check:compatibility"
            title="Command"
            language="bash"
            variant="block"
          />
        </ToolInput>
        <ToolOutput>
          <Snippet
            value={
              "Checking public exports\u2026\nChecking React peers\u2026\nProcess stopped before an exit code was reported."
            }
            title="Retained process output"
            contentType="text"
            variant="block"
          />
        </ToolOutput>
      </Tool>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Test results

The host supplies an immutable run snapshot with explicit lifecycle/outcome, identified suites and tests, and an optional expected total. Counts are derived from recorded tests; run and suite states remain independent. Contradictory passes and inconsistent IDs/totals are reported, while finished unknown outcomes and skipped/unknown tests stay neutral. Raw payload validation remains the caller's responsibility; this composition does not execute or rerun tests.

activity-test-results-27.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { Circle, Terminal } from "lucide-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityDescription,
  ActivityGroup,
  ActivityIcon,
  ActivityLine as ActivityLine2,
  ActivityTitle as ActivityTitle2,
  ActivityTrigger,
} from "@/components/ui/activity";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <>
      <TestResultsDemo />
    </>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

var defaultTestSnapshot = {
  runId: "compatibility-1",
  state: "finished",
  outcome: "failed",
  expectedTotal: 4,
  suites: [
    {
      id: "exports",
      name: "Package compatibility",
      state: "finished",
      outcome: "failed",
      tests: [
        {
          id: "public-exports",
          name: "Public exports",
          state: "passed",
        },
        {
          id: "peer",
          name: "React peer range",
          state: "failed",
          detail:
            "Expected the peer range to include React 19.\nReceived: ^18.0.0",
        },
        {
          id: "optional",
          name: "Optional integration",
          state: "skipped",
        },
        {
          id: "remote",
          name: "Remote transport",
          state: "unknown",
        },
      ],
    },
  ],
};

var testStates = {
  pending: "pending",
  running: "active",
  passed: "complete",
  failed: "error",
  skipped: undefined,
  cancelled: "cancelled",
  unknown: undefined,
};

function validateTestSnapshot(run) {
  const issues = [];
  const ids = /* @__PURE__ */ new Set();
  let count = 0;
  for (const suite of run.suites) {
    if (typeof suite.id !== "string" || !suite.id.trim() || ids.has(suite.id))
      issues.push(`Missing or duplicate suite ID: ${suite.id || "(empty)"}`);
    if (typeof suite.id === "string") ids.add(suite.id);
    if (
      typeof suite.name !== "string" ||
      !suite.name.trim() ||
      (suite.state !== undefined &&
        ![
          "pending",
          "running",
          "finished",
          "error",
          "cancelled",
          "unknown",
        ].includes(suite.state)) ||
      (suite.outcome !== undefined &&
        !["passed", "failed", "unknown"].includes(suite.outcome))
    )
      issues.push(`Suite ${suite.id || "(empty)"} has malformed facts`);
    const testIds = /* @__PURE__ */ new Set();
    for (const test of suite.tests) {
      count++;
      if (
        typeof test.id !== "string" ||
        !test.id.trim() ||
        testIds.has(test.id)
      )
        issues.push(
          `Missing or duplicate test ID in ${suite.id}: ${test.id || "(empty)"}`,
        );
      if (typeof test.id === "string") testIds.add(test.id);
      if (
        typeof test.name !== "string" ||
        !test.name.trim() ||
        !Object.prototype.hasOwnProperty.call(testStates, test.state) ||
        (test.detail !== undefined && typeof test.detail !== "string")
      )
        issues.push(`Test ${test.id || "(empty)"} has malformed facts`);
    }
  }
  if (typeof run.runId !== "string" || !run.runId.trim())
    issues.push("Run is missing its ID");
  if (
    ![
      "pending",
      "running",
      "finished",
      "error",
      "cancelled",
      "unknown",
    ].includes(run.state) ||
    (run.outcome !== undefined &&
      !["passed", "failed", "unknown"].includes(run.outcome))
  )
    issues.push("Run has malformed lifecycle or outcome");
  if (
    run.expectedTotal !== undefined &&
    (!Number.isInteger(run.expectedTotal) ||
      run.expectedTotal < count ||
      (run.state === "finished" && run.expectedTotal !== count))
  )
    issues.push("Expected total does not match the recorded tests");
  return issues;
}

function testCounts(tests) {
  const counts = {
    pending: 0,
    running: 0,
    passed: 0,
    failed: 0,
    skipped: 0,
    cancelled: 0,
    unknown: 0,
  };
  for (const test of tests)
    if (Object.prototype.hasOwnProperty.call(counts, test.state))
      counts[test.state]++;
  return counts;
}

function testOutcome(snapshot, counts, children = []) {
  if (snapshot.state === "error")
    return {
      state: "error",
      label: "operational error",
    };
  if (snapshot.state === "cancelled")
    return {
      state: "cancelled",
      label: "cancelled",
    };
  if (snapshot.state === "pending")
    return {
      state: "pending",
      label: "pending",
    };
  if (snapshot.state === "running")
    return {
      state: "active",
      label: "running",
    };
  if (snapshot.state !== "finished")
    return {
      label: "status unavailable",
    };
  if (snapshot.outcome === "failed")
    return {
      state: "error",
      label: "failed",
    };
  if (snapshot.outcome !== "passed")
    return {
      label: "finished; outcome unavailable",
    };
  if (
    counts.failed > 0 ||
    children.some(
      (child) => child.state === "error" || child.state === "cancelled",
    )
  )
    return {
      state: "error",
      label: "claimed pass conflicts with observed results",
    };
  const unresolved =
    counts.pending + counts.running + counts.unknown + counts.cancelled > 0 ||
    children.some((child) => child.state !== "complete");
  return unresolved
    ? {
        label: "finished; outcome unavailable",
      }
    : {
        state: "complete",
        label: "passed",
      };
}

function TestResultsDemo({ snapshot = defaultTestSnapshot } = {}) {
  return <TestResultsView key={snapshot.runId} snapshot={snapshot} />;
}

function TestResultsView({ snapshot }) {
  const issues = validateTestSnapshot(snapshot);
  const counts = testCounts(snapshot.suites.flatMap((suite) => suite.tests));
  const suites = snapshot.suites.map((suite) => ({
    suite,
    outcome: testOutcome(suite, testCounts(suite.tests)),
  }));
  const outcome = testOutcome(
    snapshot,
    counts,
    suites.map((entry) => entry.outcome),
  );
  const stats = `${counts.passed} passed, ${counts.failed} failed, ${counts.skipped} skipped${counts.cancelled ? `, ${counts.cancelled} cancelled` : ""}, ${counts.unknown} unknown`;
  const showOutcome = outcome.label !== "passed" && outcome.label !== "failed";
  return (
    <ActivityDemoTurn
      prompt="Run the compatibility tests."
      answer="The recorded steps are shown above for review."
    >
      <Activity2 data-test-run-id={snapshot.runId} defaultOpen>
        <ActivityTrigger>
          <ActivityLine2 state={issues.length ? undefined : outcome.state}>
            <ActivityIcon>
              <Terminal />
            </ActivityIcon>
            <ActivityTitle2>Compatibility test results</ActivityTitle2>
            {issues.length ? (
              <ActivityDescription>Invalid test snapshot</ActivityDescription>
            ) : (
              <>
                {showOutcome ? (
                  <ActivityDescription>{outcome.label}</ActivityDescription>
                ) : null}
                <ActivityDescription>{stats}</ActivityDescription>
              </>
            )}
          </ActivityLine2>
        </ActivityTrigger>
        <ActivityContent keepMounted>
          {issues.length ? (
            <p role="alert">
              {"Test snapshot rejected: "}
              {issues.join("; ")}
            </p>
          ) : null}
          {!issues.length
            ? suites.map(({ suite, outcome: suiteOutcome }) => (
                <Activity2 key={suite.id} data-suite-id={suite.id} defaultOpen>
                  <ActivityTrigger>
                    <ActivityLine2 state={suiteOutcome.state}>
                      <ActivityIcon />
                      <ActivityTitle2>{suite.name}</ActivityTitle2>
                      <ActivityDescription>
                        {suiteOutcome.label}
                      </ActivityDescription>
                    </ActivityLine2>
                  </ActivityTrigger>
                  <ActivityContent>
                    <ActivityGroup as="ol">
                      {suite.tests.map((test) => (
                        <li key={test.id}>
                          <ActivityLine2 state={testStates[test.state]}>
                            <ActivityIcon>
                              {test.state === "skipped" ||
                              test.state === "unknown" ? (
                                <Circle />
                              ) : undefined}
                            </ActivityIcon>
                            <ActivityTitle2>{test.name}</ActivityTitle2>
                            <ActivityDescription>
                              {test.state === "unknown"
                                ? "status unavailable"
                                : test.state}
                            </ActivityDescription>
                          </ActivityLine2>
                          {test.detail ? (
                            <Snippet
                              value={test.detail}
                              title="Failure detail"
                              contentType="text"
                              variant="block"
                            />
                          ) : null}
                        </li>
                      ))}
                    </ActivityGroup>
                  </ActivityContent>
                </Activity2>
              ))
            : null}
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

```

#### Stack trace

Inspect recorded frames with the original error. The host validates/redacts details and supplies any permitted navigation; Activity does not parse or execute arbitrary file paths.

activity-stack-trace-28.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileText } from "lucide-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityDescription,
  ActivityIcon,
  ActivityLine as ActivityLine2,
  ActivitySummary,
  ActivityTitle as ActivityTitle2,
} from "@/components/ui/activity";
import { Snippet } from "@/components/ui/snippet";

export default function Example() {
  return (
    <ActivityDemoTurn
      prompt="Why did the peer check fail?"
      answer="The stack trace identifies the failed peer check."
    >
      <Activity2 defaultOpen>
        <ActivitySummary state="error" statusText="package check failed">
          Unsupported peer range
        </ActivitySummary>
        <ActivityContent>
          <ActivityLine2>
            <ActivityIcon>
              <FileText />
            </ActivityIcon>
            <ActivityTitle2>release/check.ts</ActivityTitle2>
            <ActivityDescription>line 17</ActivityDescription>
          </ActivityLine2>
          <Snippet
            value={
              "CompatibilityError: React 19 is outside the declared peer range\n  at checkPeerRange (release/check.ts:17:9)\n  at reviewRelease (release/review.ts:42:3)"
            }
            title="Recorded stack trace"
            contentType="text"
            variant="block"
          />
        </ActivityContent>
      </Activity2>
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

#### Complete turn

The decision and final answer stay reachable outside the collapsed work history. Allow records permission; the separate button genuinely runs three local JavaScript checks. This example uses no server, tool executor or model request.

activity-complete-turn-29.jsx

```jsx
import { useEffect, useId, useState } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { useState as useState2 } from "react";
import { FileText, ListChecks } from "lucide-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";
import { Button as Button2 } from "@/components/ui/button";
import { Snippet } from "@/components/ui/snippet";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [review, setReview] = useState2(1);
  const [decision, setDecision] = useState2("pending");
  const [results, setResults] = useState2(null);
  const release = {
    version: "1.2.0",
    entry: "./dist/index.js",
    private: false,
  };
  function runLocalChecks() {
    setResults([
      {
        id: "version",
        label: "Version is specified",
        passed: /^\d+\.\d+\.\d+$/.test(release.version),
      },
      {
        id: "entry",
        label: "Entry points to dist",
        passed: release.entry.startsWith("./dist/"),
      },
      {
        id: "publish",
        label: "Package permits publication",
        passed: !release.private,
      },
    ]);
  }
  const passed = results?.every((result) => result.passed);
  return (
    <ActivityDemoTurn
      prompt="Check the release settings before I ship."
      answer={
        results
          ? passed
            ? "All three release settings are valid."
            : "A release setting needs attention."
          : decision === "denied"
            ? "The checks have not run."
            : "Review the settings, then choose whether to allow the local checks."
      }
      onReplay={() => {
        setReview((value) => value + 1);
        setDecision("pending");
        setResults(null);
      }}
    >
      <Activity2>
        <ActivitySummary
          state={results ? (passed ? "complete" : "error") : "pending"}
          statusText={
            results ? `${results.length} local checks` : "settings loaded"
          }
          icon={<ListChecks />}
        >
          Release review
        </ActivitySummary>
        <ActivityContent>
          <ActivityList
            events={
              results
                ? results.map((result) => ({
                    id: result.id,
                    kind: "test",
                    label: result.label,
                    state: result.passed ? "complete" : "error",
                  }))
                : [
                    {
                      id: "settings",
                      kind: "read",
                      label: "Loaded release settings",
                      state: "complete",
                      icon: <FileText />,
                    },
                  ]
            }
          />
        </ActivityContent>
      </Activity2>
      <ToolApproval
        approvalId={`local-review-${review}`}
        state={decision}
        prompt="Allow three local configuration checks?"
        onApprove={() => setDecision("approved")}
        onDeny={() => setDecision("denied")}
      >
        <Snippet
          value={JSON.stringify(release, null, 2)}
          title="Release settings"
          language="json"
          variant="block"
        />
      </ToolApproval>
      {decision === "approved" && !results ? (
        <Button2 type="button" size="sm" onClick={runLocalChecks}>
          Run local checks
        </Button2>
      ) : null}
    </ActivityDemoTurn>
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: prompt,
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? undefined : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={renderers}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {composer}
    </div>
  );
}

function ActivityPlayback({
  prompt,
  answer,
  children,
  composer,
  footer,
  renderers,
  workDuration = 1200,
  onReplay,
  participants: participants2,
  parts = [],
  pendingIndicator,
}) {
  const [run, setRun] = useState(0);
  const [tick, setTick] = useState(0);
  const [reduced, setReduced] = useState(false);
  const answerAt = 15 + Math.ceil(workDuration / 40);
  const end = answerAt + Math.ceil(answer.length / 2);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reduced || tick >= end) return;
    const timer = window.setTimeout(() => setTick((value) => value + 1), 40);
    return () => window.clearTimeout(timer);
  }, [tick, end, reduced]);
  const thinking = !reduced && tick < 15;
  const text = reduced
    ? answer
    : answer.slice(0, Math.max(0, (tick - answerAt) * 2));
  const done = reduced || tick >= end;
  const progress = reduced
    ? 1
    : Math.min(1, Math.max(0, (tick - 15) / Math.max(1, answerAt - 15)));
  const inlineActivity = parts.some((part) => part.type === "activity");
  const visibleParts = thinking
    ? parts
        .filter((part) => part.type === "activity")
        .map((part) => ({
          ...part,
          event: {
            ...part.event,
            state: "active",
            label: "is thinking",
            meta: undefined,
            description: undefined,
            children: undefined,
          },
        }))
    : parts;
  const response = {
    id: "activity-response",
    actor: "assistant",
    author: activityAgent,
    status: done ? "complete" : "streaming",
    parts: [
      ...visibleParts,
      {
        type: "text",
        id: "answer",
        text,
        state: done ? "complete" : "streaming",
      },
    ],
  };
  return (
    <div
      data-activity-playback={
        thinking ? "thinking" : done ? "complete" : "streaming"
      }
    >
      <ActivityConversationTurn
        prompt={prompt}
        response={response}
        composer={composer}
        footer={done ? footer : null}
        renderers={renderers}
        participants={participants2}
        onReplay={() => {
          onReplay?.();
          setRun((value) => value + 1);
          setTick(0);
        }}
      >
        {thinking && !inlineActivity ? pendingIndicator : null}
        <div key={run} hidden={thinking}>
          {typeof children === "function" ? children(progress) : children}
        </div>
      </ActivityConversationTurn>
    </div>
  );
}

function ActivityDemoTurn(props) {
  return (
    <ActivityPlayback {...props} pendingIndicator={<ThinkingActivity />} />
  );
}

```

## SDK integration

### Vercel AI SDK

The installed SDK hook receives a native approval response and then native output from a deterministic local transport. The same Ghost views consume the adapter's plain data. Replace the transport with your server for live model output.

activity-vercel-ai-sdk-30.jsx

```jsx
import { Button as Button2 } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { FileText, FolderCheck, ListChecks } from "lucide-react";
import { useId as useId2, useRef, useState as useState2 } from "react";
import { useId } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { simulateReadableStream } from "ai";
import {
  INTERRUPT_BINDING_VERSION,
  hashSchemaInput,
  normalizeApprovalSchema,
  toolDefinition,
  withInterruptBinding,
} from "@tanstack/ai";
import { z } from "zod";
import { useChat as useAiSdkChat } from "@ai-sdk/react";
import "@tanstack/ai-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";
import { AgentTodoList } from "@/components/ui/agent-todo-list";
import { Tool, ToolOutput } from "@/components/ui/tool";
import { ToolApproval } from "@/components/ui/tool-approval";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const sessionId = useId2();
  const [run, setRun] = useState2(0);
  return (
    <AiSdkAgentRun
      key={run}
      sessionId={`${sessionId}-${run}`}
      onReplay={() => setRun((value) => value + 1)}
    />
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: "Review the weekly update and save it.",
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? pendingIndicator : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={undefined}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {undefined}
    </div>
  );
}

var output = {
  path: "docs/weekly-update.md",
  saved: true,
};

var activityEvents = [
  {
    id: "read-update",
    kind: "read",
    state: "complete",
    label: "Read the weekly update",
    icon: <FileText />,
  },
  {
    id: "check-destination",
    kind: "check",
    state: "complete",
    label: "Check the destination",
    icon: <FolderCheck />,
  },
];

var todoItems = [
  {
    id: "review-draft",
    label: "Review the update",
    status: "complete",
  },
  {
    id: "save-draft",
    label: "Save the approved update",
    status: "active",
  },
];

var aiInitialMessages = [
  {
    id: "weekly-update-request",
    role: "user",
    parts: [
      {
        type: "text",
        text: "Save the reviewed weekly update.",
      },
    ],
  },
  {
    id: "weekly-update-agent",
    role: "assistant",
    parts: [
      {
        type: "tool-saveWeeklyUpdate",
        toolCallId: "save-weekly-update-call",
        state: "approval-requested",
        input: {
          path: "docs/weekly-update.md",
        },
        approval: {
          id: "save-weekly-update-approval",
          requestReason: "Save the reviewed weekly update?",
        },
      },
    ],
  },
];

var saveTool = toolDefinition({
  name: "saveWeeklyUpdate",
  description: "Save the reviewed weekly update.",
  needsApproval: true,
  inputSchema: z.object({
    path: z.string(),
  }),
  outputSchema: z.object({
    path: z.string(),
    saved: z.boolean(),
  }),
}).client();

var approvalSchema = normalizeApprovalSchema(undefined, saveTool.inputSchema);

var tanStackResumeSnapshot = {
  resumeState: {
    threadId: "weekly-update",
    runId: "weekly-update-paused",
  },
  pendingInterrupts: [
    withInterruptBinding(
      {
        id: "save-weekly-update-approval",
        reason: "tool_call",
        toolCallId: "save-weekly-update-call",
        message: "Save weekly update?",
        responseSchema: approvalSchema.responseSchema,
      },
      {
        v: INTERRUPT_BINDING_VERSION,
        kind: "tool-approval",
        interruptId: "save-weekly-update-approval",
        interruptedRunId: "weekly-update-paused",
        generation: 0,
        toolName: saveTool.name,
        toolCallId: "save-weekly-update-call",
        originalArgs: {
          path: "docs/weekly-update.md",
        },
        inputSchemaHash: hashSchemaInput(saveTool.inputSchema),
        approvalSchemaHash: approvalSchema.approvalSchemaHash,
        responseSchemaHash: approvalSchema.responseSchemaHash,
      },
    ),
  ],
};

var aiSdkTransport = {
  async sendMessages({ messages }) {
    await new Promise((resolve) => setTimeout(resolve, 35));
    const tool = messages
      .flatMap((message) => ("parts" in message ? message.parts : []))
      .find((part) => part.type === "tool-saveWeeklyUpdate");
    if (!tool || tool.type !== "tool-saveWeeklyUpdate")
      throw new Error("The weekly update request is unavailable.");
    const chunks =
      tool.state === "approval-responded" && tool.approval?.approved
        ? [
            {
              type: "tool-output-available",
              toolCallId: "save-weekly-update-call",
              output,
            },
            {
              type: "start",
              messageId: "weekly-update-result",
            },
            {
              type: "text-start",
              id: "weekly-update-answer",
            },
            ..."The update is saved in docs/weekly-update.md."
              .match(/\S+\s*/g)
              .map((delta) => ({
                type: "text-delta",
                id: "weekly-update-answer",
                delta,
              })),
            {
              type: "text-end",
              id: "weekly-update-answer",
            },
            {
              type: "finish",
              finishReason: "stop",
            },
          ]
        : tool.state === "approval-responded" &&
            tool.approval?.approved === false
          ? [
              {
                type: "tool-output-denied",
                toolCallId: "save-weekly-update-call",
              },
              {
                type: "finish",
                finishReason: "stop",
              },
            ]
          : [];
    return simulateReadableStream({
      chunks,
      chunkDelayInMs: 80,
    });
  },
  async reconnectToStream() {
    return null;
  },
};

var aiSdkAdapter = createAiSdkAdapter();

var tanStackAdapter = createTanStackAdapter();

function AgentWork({ messages, onApprove, onDeny, onReplay, status, onStop }) {
  const currentTool = messages
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const approvalGranted =
    currentTool?.approval?.state === "approved" ||
    currentTool?.state === "output-ready";
  const completed = currentTool?.state === "output-ready";
  const denied =
    currentTool?.approval?.state === "denied" ||
    currentTool?.state === "cancelled";
  const decisionState = approvalGranted
    ? "approved"
    : denied
      ? "denied"
      : "pending";
  const currentTodos = todoItems.map((item) =>
    item.id === "save-draft"
      ? {
          ...item,
          status: completed ? "complete" : denied ? "cancelled" : "active",
        }
      : item,
  );
  const parts = messages
    .filter((message) => message.actor === "assistant")
    .flatMap((message) => message.parts)
    .filter((part) => part.type === "text")
    .map((part) => ({
      ...part,
      state: status === "streaming" ? "streaming" : "complete",
    }));
  const response = {
    id: "weekly-update-response",
    actor: "assistant",
    author: activityAgent,
    status,
    parts: parts.length
      ? parts
      : denied
        ? [
            {
              type: "text",
              id: "denied",
              text: "The save was declined. No update was saved.",
            },
          ]
        : [],
  };
  return (
    <ActivityConversationTurn
      prompt="Review the weekly update and save it."
      response={response}
      onReplay={onReplay}
      pendingIndicator={<ThinkingActivity />}
      footer={
        status === "streaming" ? (
          <Button2 type="button" variant="outline" size="sm" onClick={onStop}>
            Stop
          </Button2>
        ) : status === "stopped" ? (
          <span role="status">Response stopped.</span>
        ) : null
      }
    >
      <div
        style={{
          display: "grid",
          gap: "var(--space-1)",
        }}
      >
        <Activity2 status="complete" defaultOpen>
          <ActivitySummary icon={<ListChecks />} state="complete">
            Reviewed the weekly update
          </ActivitySummary>
          <ActivityContent>
            <ActivityList events={activityEvents} />
          </ActivityContent>
        </Activity2>
        <AgentTodoList title="Weekly update" items={currentTodos} />
        {!completed && !denied ? (
          <ToolApproval
            approvalId={"save-weekly-update-approval"}
            state={decisionState}
            prompt="Save weekly update?"
            onApprove={onApprove}
            onDeny={onDeny}
          >
            <Card.Root density="compact">
              <code>docs/weekly-update.md</code>
            </Card.Root>
          </ToolApproval>
        ) : denied ? null : (
          <Tool name="Save weekly update" state="output-ready" defaultOpen>
            <ToolOutput>
              <code>
                {typeof currentTool?.output === "string"
                  ? currentTool.output
                  : JSON.stringify(currentTool?.output)}
              </code>
            </ToolOutput>
          </Tool>
        )}
      </div>
    </ActivityConversationTurn>
  );
}

function AiSdkAgentRun({ onReplay, sessionId }) {
  const [stopped, setStopped] = useState2(false);
  const { messages, addToolApprovalResponse, error, status, stop } =
    useAiSdkChat({
      id: sessionId,
      messages: aiInitialMessages,
      transport: aiSdkTransport,
      sendAutomaticallyWhen: ({ messages: current2 }) =>
        current2.some((message) =>
          message.parts.some(
            (part) =>
              part.type === "tool-saveWeeklyUpdate" &&
              part.state === "approval-responded" &&
              part.approval?.approved !== undefined,
          ),
        ),
    });
  const normalized = aiSdkAdapter.normalizeMessages(messages);
  const latestTool = normalized
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const current = useRef(latestTool);
  current.current = latestTool;
  const bind = (id) =>
    aiSdkAdapter.bindApproval({
      approvalId: id,
      addToolApprovalResponse: async (response) => {
        await addToolApprovalResponse(response);
      },
      getCurrent: () => current.current,
    });
  return (
    <div
      data-preview-wide
      style={{
        width: 560,
        maxWidth: "100%",
      }}
    >
      {error ? <p role="alert">{error.message}</p> : null}
      <AgentWork
        messages={normalized}
        status={
          stopped
            ? "stopped"
            : status === "streaming" || status === "submitted"
              ? "streaming"
              : status === "error"
                ? "error"
                : "complete"
        }
        onReplay={onReplay}
        onStop={() => {
          setStopped(true);
          void stop();
        }}
        onApprove={async () => {
          await bind("save-weekly-update-approval")(true);
        }}
        onDeny={async () => {
          await bind("save-weekly-update-approval")(false);
        }}
      />
    </div>
  );
}

```

### TanStack AI

The TanStack v1 hook restores a recorded native pause and resolves its bound tool-approval interrupt. Its deterministic connection consumes the native continuation before returning output. Approval acknowledgement remains distinct from execution; no model, server or filesystem is called. See [v1 lifecycle and migration](/libraries/ai-runtime-tanstack#approval).

activity-tanstack-ai-31.jsx

```jsx
import { Button as Button2 } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { FileText, FolderCheck, ListChecks } from "lucide-react";
import { useId as useId2, useRef, useState as useState2 } from "react";
import { useId } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  EventType,
  INTERRUPT_BINDING_VERSION,
  hashSchemaInput,
  normalizeApprovalSchema,
  toolDefinition,
  withInterruptBinding,
} from "@tanstack/ai";
import { z } from "zod";
import { useChat as useTanStackChat } from "@tanstack/ai-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";
import { AgentTodoList } from "@/components/ui/agent-todo-list";
import { Tool, ToolOutput } from "@/components/ui/tool";
import { ToolApproval } from "@/components/ui/tool-approval";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const sessionId = useId2();
  const [run, setRun] = useState2(0);
  return (
    <TanStackAgentRun
      key={run}
      sessionId={`${sessionId}-${run}`}
      onReplay={() => setRun((value) => value + 1)}
    />
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: "Review the weekly update and save it.",
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? pendingIndicator : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={undefined}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {undefined}
    </div>
  );
}

var output = {
  path: "docs/weekly-update.md",
  saved: true,
};

var activityEvents = [
  {
    id: "read-update",
    kind: "read",
    state: "complete",
    label: "Read the weekly update",
    icon: <FileText />,
  },
  {
    id: "check-destination",
    kind: "check",
    state: "complete",
    label: "Check the destination",
    icon: <FolderCheck />,
  },
];

var todoItems = [
  {
    id: "review-draft",
    label: "Review the update",
    status: "complete",
  },
  {
    id: "save-draft",
    label: "Save the approved update",
    status: "active",
  },
];

var tanStackInitialMessages = [
  {
    id: "weekly-update-request",
    role: "user",
    parts: [
      {
        type: "text",
        content: "Save the reviewed weekly update.",
      },
    ],
  },
  {
    id: "weekly-update-agent",
    role: "assistant",
    parts: [
      {
        type: "tool-call",
        id: "save-weekly-update-call",
        name: "saveWeeklyUpdate",
        arguments: '{"path":"docs/weekly-update.md"}',
        state: "approval-requested",
        input: {
          path: "docs/weekly-update.md",
        },
        approval: {
          id: "save-weekly-update-approval",
          needsApproval: true,
        },
      },
    ],
  },
];

var saveTool = toolDefinition({
  name: "saveWeeklyUpdate",
  description: "Save the reviewed weekly update.",
  needsApproval: true,
  inputSchema: z.object({
    path: z.string(),
  }),
  outputSchema: z.object({
    path: z.string(),
    saved: z.boolean(),
  }),
}).client();

var approvalSchema = normalizeApprovalSchema(undefined, saveTool.inputSchema);

var tanStackResumeSnapshot = {
  resumeState: {
    threadId: "weekly-update",
    runId: "weekly-update-paused",
  },
  pendingInterrupts: [
    withInterruptBinding(
      {
        id: "save-weekly-update-approval",
        reason: "tool_call",
        toolCallId: "save-weekly-update-call",
        message: "Save weekly update?",
        responseSchema: approvalSchema.responseSchema,
      },
      {
        v: INTERRUPT_BINDING_VERSION,
        kind: "tool-approval",
        interruptId: "save-weekly-update-approval",
        interruptedRunId: "weekly-update-paused",
        generation: 0,
        toolName: saveTool.name,
        toolCallId: "save-weekly-update-call",
        originalArgs: {
          path: "docs/weekly-update.md",
        },
        inputSchemaHash: hashSchemaInput(saveTool.inputSchema),
        approvalSchemaHash: approvalSchema.approvalSchemaHash,
        responseSchemaHash: approvalSchema.responseSchemaHash,
      },
    ),
  ],
};

var tanStackConnection = {
  async *connect(_messages, _data, signal, context) {
    await new Promise((resolve) => setTimeout(resolve, 35));
    const resolution = context?.resume?.find(
      (item) => item.interruptId === "save-weekly-update-approval",
    );
    const payload =
      resolution?.status === "resolved" ? resolution.payload : undefined;
    if (
      context?.parentRunId !== tanStackResumeSnapshot.resumeState.runId ||
      context.resume?.length !== 1 ||
      !payload ||
      typeof payload !== "object" ||
      !("approved" in payload) ||
      typeof payload.approved !== "boolean"
    ) {
      throw new Error("The native approval continuation is unavailable.");
    }
    const approved = payload.approved;
    const threadId = context?.threadId ?? "weekly-update";
    const runId = context?.runId ?? "weekly-update-run";
    yield {
      type: EventType.RUN_STARTED,
      threadId,
      runId,
    };
    if (!approved) {
      yield {
        type: EventType.RUN_FINISHED,
        threadId,
        runId,
      };
      return;
    }
    if (signal?.aborted) return;
    yield {
      type: EventType.TOOL_CALL_RESULT,
      messageId: "weekly-update-result",
      toolCallId: "save-weekly-update-call",
      content: JSON.stringify(output),
      role: "tool",
    };
    yield {
      type: EventType.TEXT_MESSAGE_START,
      messageId: "weekly-update-answer",
      role: "assistant",
    };
    for (const delta of "The update is saved in docs/weekly-update.md.".match(
      /\S+\s*/g,
    )) {
      await new Promise((resolve) => setTimeout(resolve, 80));
      if (signal?.aborted) return;
      yield {
        type: EventType.TEXT_MESSAGE_CONTENT,
        messageId: "weekly-update-answer",
        delta,
      };
    }
    yield {
      type: EventType.TEXT_MESSAGE_END,
      messageId: "weekly-update-answer",
    };
    yield {
      type: EventType.RUN_FINISHED,
      threadId,
      runId,
    };
  },
};

var aiSdkAdapter = createAiSdkAdapter();

var tanStackAdapter = createTanStackAdapter();

function AgentWork({ messages, onApprove, onDeny, onReplay, status, onStop }) {
  const currentTool = messages
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const approvalGranted =
    currentTool?.approval?.state === "approved" ||
    currentTool?.state === "output-ready";
  const completed = currentTool?.state === "output-ready";
  const denied =
    currentTool?.approval?.state === "denied" ||
    currentTool?.state === "cancelled";
  const decisionState = approvalGranted
    ? "approved"
    : denied
      ? "denied"
      : "pending";
  const currentTodos = todoItems.map((item) =>
    item.id === "save-draft"
      ? {
          ...item,
          status: completed ? "complete" : denied ? "cancelled" : "active",
        }
      : item,
  );
  const parts = messages
    .filter((message) => message.actor === "assistant")
    .flatMap((message) => message.parts)
    .filter((part) => part.type === "text")
    .map((part) => ({
      ...part,
      state: status === "streaming" ? "streaming" : "complete",
    }));
  const response = {
    id: "weekly-update-response",
    actor: "assistant",
    author: activityAgent,
    status,
    parts: parts.length
      ? parts
      : denied
        ? [
            {
              type: "text",
              id: "denied",
              text: "The save was declined. No update was saved.",
            },
          ]
        : [],
  };
  return (
    <ActivityConversationTurn
      prompt="Review the weekly update and save it."
      response={response}
      onReplay={onReplay}
      pendingIndicator={<ThinkingActivity />}
      footer={
        status === "streaming" ? (
          <Button2 type="button" variant="outline" size="sm" onClick={onStop}>
            Stop
          </Button2>
        ) : status === "stopped" ? (
          <span role="status">Response stopped.</span>
        ) : null
      }
    >
      <div
        style={{
          display: "grid",
          gap: "var(--space-1)",
        }}
      >
        <Activity2 status="complete" defaultOpen>
          <ActivitySummary icon={<ListChecks />} state="complete">
            Reviewed the weekly update
          </ActivitySummary>
          <ActivityContent>
            <ActivityList events={activityEvents} />
          </ActivityContent>
        </Activity2>
        <AgentTodoList title="Weekly update" items={currentTodos} />
        {!completed && !denied ? (
          <ToolApproval
            approvalId={"save-weekly-update-approval"}
            state={decisionState}
            prompt="Save weekly update?"
            onApprove={onApprove}
            onDeny={onDeny}
          >
            <Card.Root density="compact">
              <code>docs/weekly-update.md</code>
            </Card.Root>
          </ToolApproval>
        ) : denied ? null : (
          <Tool name="Save weekly update" state="output-ready" defaultOpen>
            <ToolOutput>
              <code>
                {typeof currentTool?.output === "string"
                  ? currentTool.output
                  : JSON.stringify(currentTool?.output)}
              </code>
            </ToolOutput>
          </Tool>
        )}
      </div>
    </ActivityConversationTurn>
  );
}

function TanStackAgentRun({ onReplay, sessionId }) {
  const [stopped, setStopped] = useState2(false);
  const [resumeSnapshot] = useState2(() => ({
    ...tanStackResumeSnapshot,
    resumeState: {
      ...tanStackResumeSnapshot.resumeState,
      threadId: sessionId,
    },
  }));
  const chat = useTanStackChat({
    threadId: sessionId,
    initialMessages: tanStackInitialMessages,
    initialResumeSnapshot: resumeSnapshot,
    tools: [saveTool],
    connection: tanStackConnection,
  });
  const { messages, error, interruptErrors, status, stop } = chat;
  const normalized = tanStackAdapter.normalizeMessages(messages);
  const current = useRef(chat);
  current.current = chat;
  const decide = async (approved) => {
    const interrupt = current.current.interrupts.find(
      (item) => item.id === "save-weekly-update-approval",
    );
    if (interrupt?.kind !== "tool-approval")
      throw new Error("This approval is no longer available.");
    await tanStackAdapter.bindApproval({
      interrupt,
      getCurrent: () => current.current,
    })(approved);
  };
  return (
    <div
      data-preview-wide
      style={{
        width: 560,
        maxWidth: "100%",
      }}
    >
      {error ? <p role="alert">{error.message}</p> : null}
      {interruptErrors.map((issue, index) => (
        <p key={index} role="alert">
          {issue.message}
        </p>
      ))}
      <AgentWork
        messages={normalized}
        status={
          stopped
            ? "stopped"
            : status === "streaming" || status === "submitted"
              ? "streaming"
              : status === "error"
                ? "error"
                : "complete"
        }
        onReplay={onReplay}
        onStop={() => {
          setStopped(true);
          void stop();
        }}
        onApprove={async () => {
          await decide(true);
        }}
        onDeny={async () => {
          await decide(false);
        }}
      />
    </div>
  );
}

```

Use [plain data or optional native runtime bindings](/libraries/ai-runtime). For an existing component library, start with [Migrating to Ghost AI views](/libraries/ai-migration); runtime compatibility and source/prop migration are separate decisions.

## API reference

Activity trace properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| Activity.status | ActivityState \| undefined | — | Optional aggregate polite announcement and default state for child lines. Does not change disclosure. |
| open / defaultOpen | boolean | false | Controlled or initial disclosure state. |
| onOpenChange | (open, details) => void | — | Receives user disclosure changes. |
| ActivityLine.state | pending \| active \| complete \| error \| cancelled \| unknown | — | Explicit row state overrides Activity.status. Active first-level lines use Shimmer's gradient variant; deeper ActivityGroup/ActivityList rows use the default sweep. Use unknown to keep an unreported row neutral even inside active work. Omit to inherit; without a root status the row stays neutral. |
| ActivityLine.icon / ActivityIcon.children | ReactNode | — | Caller glyph; undefined follows row state, null hides the slot. Explicit children override the line icon. Active uses the dots Loader. |
| ActivityActor | name, seed/src, kind, state | — | Compact avatar glyph for a sender or subagent. State moves to the avatar status dot: active is green, failed red, attention yellow, done gray. Pulse is added for active, failed and cancelled runs. |
| ActivityTitle | span props + ref | — | Wrapping title inside the row-level Shimmer; does not add an independent animation. Carries the stronger title color. |
| ActivityDescription | span props + ref | — | Muted adverbial detail beside the title: duration, count, result, impact, outcome or progress. Same type size as the title; no middle-dot separators. |
| ActivityAffordance | span props + ref | — | Decorative trailing glyph for a row that opens a link, dialog, drawer or popover. Never carries status; the wrapping control owns the accessible name. |
| ActivityGroup.as | div \| ol | div | Nested logical rail; ol requires li children. |
| ActivityTrigger | Collapsible.Trigger props + ref | — | Native trigger with one disclosure chevron. Compose a line inside it. |
| ActivityContent.keepMounted | boolean | false | Retains nested content while closed. Inherits Collapsible.Panel props. |
| ActivitySummary | state, statusText, icon, Trigger props | — | Convenience run summary. state defaults to pending and shows through glyph, color and shimmer only. statusText is caller detail such as 3 of 5 or 14s; it never defaults to a state word. |
| ActivityList.events | readonly ActivityEventNode[] | — | Ordered tree nodes with IDs, kind, state, label, optional meta/description/progress/duration/icon/children. Children render as one deeper rail. Progress renders the circle clock glyph and percent detail. |
| ActivityEventRow | event, title, span props | — | One canonical event row for ActivityList and MessageParts. Optional title supplies the sender; its verb phrase follows with one word space and a lowercase initial word. Acronyms and internal names keep their case; standalone event labels keep their supplied case. |
| ActivityEvent.label | string | — | The accessible, past-tense title. Put the actor first when known and write the action as a sentence. |
| ActivityEvent.meta | string | — | Adverbial detail beside the title. Use a numeral plus unit, a diff, a percentage, or an outcome count; do not repeat the state as Error when the title already says failed. |
| ActivityEvent.description | string | — | Longer explanation below the row. Keep it out of the adverbial slot. |
| ActivityEvent.duration | string | — | Compatibility metadata rendered beside the title. Prefer meta for new data. |
| ActivityEvent.kind | string | — | Caller metadata written as data-event-kind. Does not dispatch a renderer or choose behavior. |
| ActivityEvent.children | readonly ActivityEvent[] | — | Optional ordered child operations in the SDK-free runtime record. Each child becomes one deeper Activity row; the host supplies stable IDs, order and states. |
| ActivityExplanation | kind: note \| reasoning-summary; source | — | Nested explanation row. Reasoning summary requires provider-summary or application-summary. Unclassified content stays hidden. |
