Skip to content
WebJs
Menu

Chain of Thought

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

Why is the checkout deploy so slow?
Researched in 3 steps
Read the build log for dpl_8Kx2
install    41s
compile    38s
images   3m 52s
Searched the web for next.js image cache key
Searched the code for cacheKey
next.config.tsscripts/optimize-images.ts

Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead.

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>
  `;
}
View Code

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, Code Block and Badge components.

pnpm dlx @webjsdev/ui add trace code-block badge

Usage

import {
  traceClass,
  traceCollapsibleClass,
  traceCollapsibleContentClass,
  traceCollapsibleTriggerClass,
  traceIconClass,
  traceLineClass,
  traceTitleClass,
} from '#components/ui/trace.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.

Stepdata-statusTitle
Running"running"Searching for …
Done, with detailnoneSearched for …
Done, links outnoneRead 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.

<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. 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 for streaming the parts from a server action.

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.

Migrating from AI SDK Elements

If you used ChainOfThought from AI SDK Elements, 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 ElementsWebJs UI
ChainOfThoughtA trace with a trace collapsible. Open it while the steps run, as ?open=${running} above does.
ChainOfThoughtHeaderThe collapsible's <summary>, holding a trace line with an icon and a title, like "Researched in 3 steps".
ChainOfThoughtContentThe trace collapsible content, holding a trace for the steps.
ChainOfThoughtStepA 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.
ChainOfThoughtSearchResultsA flex flex-wrap gap-1.5 container.
ChainOfThoughtSearchResultA badge with badgeClass({ variant: 'secondary' }).
ChainOfThoughtImageA plain <img> inside the step's content.

API Reference

See Trace.