# Chain of Thought

Displays a summary that expands into the steps an agent took.

Source: https://webjs.dev/ui/docs/ai-elements/chain-of-thought

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { badgeClass } from '#components/ui/badge.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  codeBlockClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import {
  traceClass, traceLineClass, traceIconClass, traceTitleClass,
  traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import {
  ArrowUpRightIcon, ChevronRightIcon, CircleCheckIcon, GlobeIcon,
} from '#lib/ui/lucide.ts';

const question = 'Why is the checkout deploy so slow?';
const log = 'install    41s\ncompile    38s\nimages   3m 52s';
const results = [
  { title: 'Image component | nextjs.org', url: 'https://nextjs.org/docs/app/api-reference/components/image' },
  { title: 'Build cache | vercel.com', url: 'https://vercel.com/docs/deployments/troubleshoot-a-build' },
];
const files = ['next.config.ts', 'scripts/optimize-images.ts'];
const answer =
  'Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead.';

// A finished step: a check icon and the title in the past tense.
function line(title: string) {
  return html`<span data-slot="trace-line" class=${traceLineClass()}>
    <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${CircleCheckIcon()}</span>
    <span data-slot="trace-title" class=${traceTitleClass()}>${title}</span>
  </span>`;
}

// A row that opens. The chevron after the line turns while it is open.
function collapsible(head: unknown, content: unknown, open = false) {
  return html`
    <details data-slot="trace-collapsible" ?open=${open} class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
      <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
        ${head}
        <span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform group-open/trace-collapsible:rotate-90')}>${ChevronRightIcon()}</span>
      </summary>
      ${content}
    </details>
  `;
}

// The conversation once the reply has streamed. The summary closed when the
// answer started, and the build log step inside it starts open.
export default function ChainOfThoughtDemo() {
  return html`
    <div class="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
      <div data-slot="message" data-align="end" class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant="muted" data-align="end" class=${bubbleClass({ variant: 'muted' })}>
            <div data-slot="bubble-content" class=${bubbleContentClass()}>${question}</div>
          </div>
        </div>
      </div>
      <div data-slot="message" data-align="start" class=${messageClass()}>
        <div data-slot="message-content" class=${cn(messageContentClass(), 'gap-4')}>
          <div data-slot="trace" class=${traceClass()}>
            ${collapsible(
              line('Researched in 3 steps'),
              html`<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
                <div data-slot="trace" class=${traceClass()}>
                  ${collapsible(
                    line('Read the build log for dpl_8Kx2'),
                    html`<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
                      <div data-slot="code-block" data-variant="default" data-size="sm" class=${codeBlockClass()}>
                        <pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${cn(codeBlockContentClass(), 'max-h-64')}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${log}</code></pre>
                      </div>
                    </div>`,
                    true,
                  )}
                  ${collapsible(
                    line('Searched the web for next.js image cache key'),
                    html`<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
                      <div data-slot="trace" class=${traceClass()}>
                        ${results.map((result) => html`
                          <a href=${result.url} target="_blank" rel="noreferrer">
                            <span data-slot="trace-line" class=${traceLineClass()}>
                              <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${GlobeIcon()}</span>
                              <span data-slot="trace-title" class=${traceTitleClass()}>
                                ${result.title}
                                <span class="sr-only"> (opens in a new tab)</span>
                              </span>
                              <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${ArrowUpRightIcon()}</span>
                            </span>
                          </a>
                        `)}
                      </div>
                    </div>`,
                  )}
                  ${collapsible(
                    line('Searched the code for cacheKey'),
                    html`<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
                      <div class="flex flex-wrap gap-1.5">
                        ${files.map((file) => html`<span data-slot="badge" data-variant="secondary" class=${cn(badgeClass({ variant: 'secondary' }), 'font-mono')}>${file}</span>`)}
                      </div>
                    </div>`,
                  )}
                </div>
              </div>`,
            )}
          </div>
          <p>${answer}</p>
        </div>
      </div>
      <button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${cn(buttonClass({ variant: 'outline', size: 'sm' }), 'mt-auto self-start')}>
        Replay
      </button>
    </div>
  `;
}
```

Chain of Thought is a summary line that expands into the steps an agent took. The summary says what happened, like "Researched in 3 steps". The steps sit inside it, each one a line of its own.

Chain of Thought is built with a trace, with a trace collapsible for the summary.

## Installation

Chain of Thought is built with the [Trace](https://webjs.dev/ui/docs/components/trace), [Code Block](https://webjs.dev/ui/docs/components/code-block) and [Badge](https://webjs.dev/ui/docs/components/badge) components.

```bash
npx @webjsdev/ui add trace code-block badge
```

### Install the following dependencies:

```bash
npx @webjsdev/ui add code-block badge
```

### Copy and paste the following code into your project.

````ts title="components/ui/trace.ts"
/**
 * Trace: a vertical timeline of steps (a tool call, a reasoning step, a
 * deploy stage), each with an icon on a connecting line, a title and an
 * optional collapsible detail. Tier-1 class helper; compose with plain
 * elements and `<details>` for the collapsible part.
 *
 * shadcn parity:
 *   Trace                       → traceClass()
 *   TraceLine / TraceIcon       → traceLineClass() / traceIconClass()
 *   TraceTitle / TraceDescription
 *                               → traceTitleClass() / traceDescriptionClass()
 *   TraceCollapsible / TraceCollapsibleTrigger / TraceCollapsibleContent
 *                               → <details> / <summary> / a div, with the
 *                                 trace collapsible helpers
 *
 * shadcn has no new-york version of this component, so its look in the
 * default style is shadcn's vega style, the classic shadcn look.
 *
 * A11y (required for accessible output): a trace is an ordered list of steps,
 * so render it as `<ol>` with each step an `<li>`. A step's status must be in
 * text, not only in the icon colour ("Failed", "Done"), and a decorative icon
 * takes `aria-hidden="true"`. A collapsible step is a native `<details>` with a
 * `<summary>`, which carries the expanded state by itself.
 *
 * Design tokens used: --border, --muted-foreground, --foreground.
 *
 * @example
 * ```html
 * <ol class=${traceClass()} data-slot="trace">
 *   <li class=${traceLineClass()} data-slot="trace-line">
 *     <span class=${traceTitleClass()} data-slot="trace-title">Fetched the issue</span>
 *   </li>
 * </ol>
 * ```
 */

/** Set `data-slot="trace"` on the element. */
export function traceClass(): string {
  return 'gap-2 *:has-[>[data-slot=trace-line]]:rounded-md *:has-[>[data-slot=trace-line]]:focus-visible:ring-3 *:has-[>[data-slot=trace-line]]:focus-visible:ring-ring/50 flex w-full min-w-0 flex-col *:has-[>[data-slot=trace-line]]:flex *:has-[>[data-slot=trace-line]]:w-fit *:has-[>[data-slot=trace-line]]:max-w-full *:has-[>[data-slot=trace-line]]:min-w-0 *:has-[>[data-slot=trace-line]]:text-start *:has-[>[data-slot=trace-line]]:outline-none';
}

/** Set `data-slot="trace-line"` on the element. */
export function traceLineClass(): string {
  return 'gap-2 text-sm flex w-fit max-w-full min-w-0 items-center text-muted-foreground transition-colors in-[a,button]:cursor-pointer in-[a:hover,button:hover]:text-foreground data-[status=error]:text-destructive data-[status=error]:in-[a:hover,button:hover]:text-destructive data-[status=pending]:opacity-60 data-[status=running]:*:data-[slot=trace-title]:shimmer';
}

/** Set `data-slot="trace-icon"` on the element. */
export function traceIconClass(): string {
  return "size-4 [&_svg:not([class*='size-'])]:size-4 [[data-slot=trace-title]~&]:-ms-1 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none";
}

/** Set `data-slot="trace-title"` on the element. */
export function traceTitleClass(): string {
  return 'min-w-0 truncate motion-reduce:shimmer-none';
}

/** Set `data-slot="trace-description"` on the element. */
export function traceDescriptionClass(): string {
  return 'shrink-0 text-muted-foreground/70 tabular-nums';
}

/** Set `data-slot="trace-collapsible"` on the element. */
export function traceCollapsibleClass(): string {
  return 'flex w-full min-w-0 flex-col';
}

/** Set `data-slot="trace-collapsible-trigger"` on the element. */
export function traceCollapsibleTriggerClass(): string {
  return 'gap-1 rounded-md focus-visible:ring-3 focus-visible:ring-ring/50 group/trace-collapsible-trigger flex w-fit max-w-full min-w-0 cursor-pointer items-center text-start text-muted-foreground transition-colors outline-none hover:text-foreground has-[[data-status=error]]:text-destructive';
}

/** Set `data-slot="trace-collapsible-content"` on the element. */
export function traceCollapsibleContentClass(): string {
  return 'mt-2 mb-1 ms-[calc(--spacing(2)-1px)] border-s pe-1 ps-4 leading-relaxed min-w-0 wrap-break-word text-muted-foreground';
}
````

### Update the import paths to match your project setup.

## Usage

```ts
import {
  traceClass,
  traceCollapsibleClass,
  traceCollapsibleContentClass,
  traceCollapsibleTriggerClass,
  traceIconClass,
  traceLineClass,
  traceTitleClass,
} from '#components/ui/trace.ts';
```

```ts
<div data-slot="trace" class=${traceClass()}>
  <details data-slot="trace-collapsible" open class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
    <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
      <span data-slot="trace-line" class=${traceLineClass()}>
        <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>
          ${CircleCheckIcon()}
        </span>
        <span data-slot="trace-title" class=${traceTitleClass()}>Researched in 3 steps</span>
      </span>
      <span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform group-open/trace-collapsible:rotate-90')}>
        ${ChevronRightIcon()}
      </span>
    </summary>
    <div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
      <div data-slot="trace" class=${traceClass()}>
        <span data-slot="trace-line" class=${traceLineClass()}>
          <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>
            ${CircleCheckIcon()}
          </span>
          <span data-slot="trace-title" class=${traceTitleClass()}>Read the build log for dpl_8Kx2</span>
        </span>
        <span data-slot="trace-line" class=${traceLineClass()}>
          <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>
            ${CircleCheckIcon()}
          </span>
          <span data-slot="trace-title" class=${traceTitleClass()}>Searched the web for next.js image cache key</span>
        </span>
        <span data-slot="trace-line" class=${traceLineClass()}>
          <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>
            ${CircleCheckIcon()}
          </span>
          <span data-slot="trace-title" class=${traceTitleClass()}>Searched the code for cacheKey</span>
        </span>
      </div>
    </div>
  </details>
</div>
```

## Steps

Each step is a trace line. Set its `data-status` and write the title in the matching tense.

| Step | data-status | Title |
| --- | --- | --- |
| Running | `"running"` | Searching for … |
| Done, with detail | none | Searched for … |
| Done, links out | none | Read the Image component docs |
| Failed | `"error"` | Failed to search for … |

## Search Results

When a step runs a web search, show the results as a badge for each hostname in the step's content.

```ts
<div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'flex flex-wrap gap-1.5')}>
  ${results.map((result) => html`
    <span data-slot="badge" data-variant="secondary" class=${badgeClass({ variant: 'secondary' })}>
      ${new URL(result.url).hostname}
    </span>
  `)}
</div>
```

## AI SDK

Render each tool part as a step. `running` is true while tool parts stream and before the reply starts. Set the summary's status and title from the steps. The summary renders open while the steps run, as in [Trace](https://webjs.dev/ui/docs/components/trace#open-state). Because it is a native `<details>`, a person who opens or closes it keeps their choice until the component renders that row again. See [AI SDK](https://webjs.dev/ui/docs/helpers/ai-sdk) for streaming the parts from a server action.

```ts
const running = streaming && !answering;
const failed = steps.filter((part) => part.state === 'output-error').length;
const status = running ? 'running' : failed > 0 ? 'error' : null;

html`<details data-slot="trace-collapsible" ?open=${running} class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
  <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
    <span data-slot="trace-line" data-status=${status} class=${traceLineClass()}>
      <span data-slot="trace-title" class=${traceTitleClass()}>
        ${running ? 'Researching' : `Researched in ${steps.length} steps`}
      </span>
    </span>
  </summary>
  <div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
    <div data-slot="trace" class=${traceClass()}>
      ${steps.map((part) => stepLine(part, streaming))}
    </div>
  </div>
</details>`
```

`stepLine` renders one tool part as a trace line, as in [Tool](https://webjs.dev/ui/docs/ai-elements/tool#states).

## Migrating from AI SDK Elements

If you used ChainOfThought from [AI SDK Elements](https://elements.ai-sdk.dev), its wrapper lives in `components/ai-elements/chain-of-thought.tsx`. In a WebJs app it becomes this pattern, built from WebJs UI components. Each export of the wrapper maps onto a part:

| AI SDK Elements | WebJs UI |
| --- | --- |
| `ChainOfThought` | A trace with a trace collapsible. Open it while the steps run, as `?open=${running}` above does. |
| `ChainOfThoughtHeader` | The collapsible's `<summary>`, holding a trace line with an icon and a title, like "Researched in 3 steps". |
| `ChainOfThoughtContent` | The trace collapsible content, holding a trace for the steps. |
| `ChainOfThoughtStep` | A trace line. Its icon goes in a trace icon, its label in a trace title and its description in a trace description. Status "active" becomes `data-status="running"`, "pending" becomes `data-status="pending"`, and "complete" has no status. |
| `ChainOfThoughtSearchResults` | A `flex flex-wrap gap-1.5` container. |
| `ChainOfThoughtSearchResult` | A badge with `badgeClass({ variant: 'secondary' })`. |
| `ChainOfThoughtImage` | A plain `<img>` inside the step's content. |

## API Reference

See [Trace](https://webjs.dev/ui/docs/components/trace#api-reference).
