# Subagent

Displays a subagent run, with its tool calls and result.

Source: https://webjs.dev/ui/docs/ai-elements/subagent

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.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 { ChevronRightIcon, CircleCheckIcon } from '#lib/ui/lucide.ts';

const question = 'Why does image optimization rerun on every deploy?';
const report =
  'The cache is keyed on the commit SHA, so every deploy misses it and optimizes all 1,240 images again.';
const answer =
  'Image optimization reruns because its cache is keyed on the commit SHA, which changes on every deploy. Key the cache on a hash of public/images instead, and unchanged images will be skipped.';

const steps = [
  {
    command: 'grep -rn cacheKey scripts',
    stdout: 'scripts/optimize-images.ts:14:  const cacheKey = process.env.COMMIT_SHA',
  },
  {
    command: 'sed -n 13,15p scripts/optimize-images.ts',
    stdout:
      'const cacheDir = ".next/cache/images"\nconst cacheKey = process.env.COMMIT_SHA\nconst cached = await restoreCache(cacheDir, cacheKey)',
  },
  {
    command: 'ls public/images | wc -l',
    stdout: '1240',
  },
];

const chevron = () => html`<span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform [[open]>summary>&]:rotate-90')}>${ChevronRightIcon()}</span>`;

// One finished tool call of the subagent, expanding to its output.
function StepRow(step: { command: string; stdout: string }) {
  return html`
    <details data-slot="trace-collapsible" class=${traceCollapsibleClass()}>
      <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()}>Ran ${step.command}</span>
        </span>
        ${chevron()}
      </summary>
      <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()}>${step.stdout}</code></pre>
        </div>
      </div>
    </details>
  `;
}

// The conversation once the subagent and the reply have finished, with the
// subagent's run left open.
export default function SubagentDemo() {
  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()}>
            <details data-slot="trace-collapsible" open class=${traceCollapsibleClass()}>
              <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()}>Ran the research subagent</span>
                </span>
                ${chevron()}
              </summary>
              <div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'flex flex-col gap-3')}>
                <div data-slot="trace" class=${traceClass()}>
                  ${steps.map((step) => StepRow(step))}
                </div>
                <p>${report}</p>
              </div>
            </details>
          </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>
  `;
}
```

Subagent is a line for work the agent hands to a subagent. The run is the title, like "Ran the research agent". Open it for the tool calls the subagent made and what it found.

Subagent is built with a trace, with a trace collapsible for the run and a nested trace for its tool calls.

## Installation

Subagent 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" 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()}>Ran the research agent</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=${cn(traceCollapsibleContentClass(), 'flex flex-col gap-3')}>
      <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()}>Ran grep -rn cacheKey scripts</span>
        </span>
      </div>
      <p>The cache is keyed on the commit SHA.</p>
    </div>
  </details>
</div>
```

## Running

While the subagent runs, the line has `data-status="running"` and its content shows the tool calls so far. Add the result when the subagent finishes.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  traceClass, traceLineClass, traceIconClass, traceTitleClass,
  traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import { ChevronRightIcon, CircleCheckIcon, LoaderCircleIcon } from '#lib/ui/lucide.ts';

export default function SubagentRunning() {
  return html`
    <div data-slot="trace" class=${cn(traceClass(), 'max-w-sm')}>
      <details data-slot="trace-collapsible" open class=${traceCollapsibleClass()}>
        <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
          <span data-slot="trace-line" data-status="running" class=${traceLineClass()}>
            <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${LoaderCircleIcon('animate-spin')}</span>
            <span data-slot="trace-title" class=${traceTitleClass()}>Running the research agent</span>
          </span>
          <span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform [[open]>summary>&]: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()}>Ran grep -rn cacheKey scripts</span>
            </span>
            <span data-slot="trace-line" data-status="running" class=${traceLineClass()}>
              <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${LoaderCircleIcon('animate-spin')}</span>
              <span data-slot="trace-title" class=${traceTitleClass()}>Running sed -n 13,15p scripts/optimize-images.ts</span>
            </span>
          </div>
        </div>
      </details>
    </div>
  `;
}
```

## Details

Put the task the subagent was given at the top of the content, with its model and tools as [Badge](https://webjs.dev/ui/docs/components/badge) items. Show how long it ran in a trace description after the title.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { badgeClass } from '#components/ui/badge.ts';
import {
  traceClass, traceLineClass, traceIconClass, traceTitleClass, traceDescriptionClass,
  traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import { ChevronRightIcon, CircleCheckIcon } from '#lib/ui/lucide.ts';

export default function SubagentDetails() {
  return html`
    <div data-slot="trace" class=${cn(traceClass(), 'max-w-sm')}>
      <details data-slot="trace-collapsible" open class=${traceCollapsibleClass()}>
        <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()}>Ran the research agent</span>
            <span data-slot="trace-description" class=${traceDescriptionClass()}>48s</span>
          </span>
          <span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform [[open]>summary>&]:rotate-90')}>${ChevronRightIcon()}</span>
        </summary>
        <div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'flex flex-col gap-3')}>
          <div class="flex flex-wrap gap-1.5">
            <span data-slot="badge" data-variant="secondary" class=${badgeClass({ variant: 'secondary' })}>anthropic/claude-sonnet-4.5</span>
            <span data-slot="badge" data-variant="outline" class=${cn(badgeClass({ variant: 'outline' }), 'font-mono')}>runCommand</span>
          </div>
          <p>Find out why image optimization reruns on every deploy.</p>
          <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()}>Ran grep -rn cacheKey scripts</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()}>Ran sed -n 13,15p scripts/optimize-images.ts</span>
            </span>
          </div>
          <p>The cache is keyed on the commit SHA.</p>
        </div>
      </details>
    </div>
  `;
}
```

## AI SDK

With the AI SDK, a subagent is a tool whose `execute` yields the subagent's `UIMessage` as it streams. Render the tool part as the line and `part.output.parts` as the nested trace. Map each nested tool part as in [Tool](https://webjs.dev/ui/docs/ai-elements/tool#states), and see [AI SDK](https://webjs.dev/ui/docs/helpers/ai-sdk) for streaming the parts from a `'use server'` action.

Each yield is a preliminary output: the part is `output-available` with `preliminary: true`. The final output replaces it, so check `preliminary` before you show "Ran".

| Tool part state | Trace line data-status | Title |
| --- | --- | --- |
| `input-streaming`, `input-available` | `"running"` while the chat streams | Running … |
| `output-available` with `preliminary: true` | `"running"` while the chat streams | Running … |
| `output-available` | none | Ran … |
| `output-error`, or a running state after the chat stops | `"error"` | Failed to run … |

```ts
function subagentRow(part: SubagentToolPart, streaming: boolean) {
  const done = part.state === 'output-available' && !part.preliminary;
  const running = !done && part.state !== 'output-error' && streaming;
  const parts = part.state === 'output-available' ? part.output.parts : [];

  return html`<details data-slot="trace-collapsible" open class=${traceCollapsibleClass()}>
    <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
      <span data-slot="trace-line" data-status=${done ? null : running ? 'running' : 'error'} class=${traceLineClass()}>
        <span data-slot="trace-title" class=${traceTitleClass()}>${done ? 'Ran' : running ? 'Running' : 'Failed to run'} the research agent</span>
      </span>
    </summary>
    <div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
      <div data-slot="trace" class=${traceClass()}>${parts.map((nested) => toolRow(nested, running))}</div>
    </div>
  </details>`;
}
```

## Migrating from AI SDK Elements

If you used Agent from [AI SDK Elements](https://elements.ai-sdk.dev), its wrapper lives in `components/ai-elements/agent.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 |
| --- | --- |
| `Agent` | A trace with a trace collapsible. |
| `AgentHeader` | The collapsible's `<summary>`, holding a trace line, a trace icon and a trace title with the name, like "Ran the research agent". Show the model in a badge. |
| `AgentContent` | The trace collapsible content. |
| `AgentTools, AgentTool` | A trace, with a trace line for each tool call, instead of an Accordion. |
| `AgentInstructions` | A paragraph at the top of the content. |
| `AgentOutput` | A Code Block with `data-size="sm"`. |

## API Reference

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