# Terminal

Displays a command the agent runs, with its output as it streams.

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

```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, TerminalIcon } from '#lib/ui/lucide.ts';

const question = 'Run the checks, then build the app.';
const answer = 'Lint and tests pass, and the build compiled both routes.';

const COMMANDS = [
  {
    command: 'pnpm lint',
    output: ['> acme-chat@0.1.0 lint', '> eslint .'],
  },
  {
    command: 'pnpm test',
    output: [
      '> acme-chat@0.1.0 test',
      '> vitest run',
      '',
      ' ✓ lib/ai.test.ts (6 tests) 41ms',
      ' ✓ components/chat.test.tsx (9 tests) 212ms',
      '',
      ' Test Files  2 passed (2)',
      '      Tests  15 passed (15)',
    ],
  },
  {
    command: 'pnpm build',
    output: [
      '> acme-chat@0.1.0 build',
      '> next build',
      '',
      '   ▲ Next.js 16.3.0',
      '   Creating an optimized production build ...',
      ' ✓ Compiled successfully in 4.2s',
      ' ✓ Generating static pages (12/12)',
      '',
      'Route (app)                Size  First Load JS',
      '┌ ○ /                     1.9 kB       112 kB',
      '└ ƒ /api/chat              141 B       102 kB',
    ],
  },
];

// A command that exited with 0. Only the last one renders open once the
// reply has finished.
function CommandRow(entry: { command: string; output: string[] }, open: boolean) {
  return html`
    <details data-slot="trace-collapsible" ?open=${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()}>${TerminalIcon()}</span>
          <span data-slot="trace-title" class=${traceTitleClass()}>Ran ${entry.command}</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="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()}>${entry.output.join('\n')}</code></pre>
        </div>
      </div>
    </details>
  `;
}

// The conversation once every command has exited.
export default function TerminalDemo() {
  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()}>
            ${COMMANDS.map((entry, index) => CommandRow(entry, index === COMMANDS.length - 1))}
          </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>
  `;
}
```

Terminal is a shell command the agent runs, such as a lint, a test run or a build. The line shows the command, and its output streams in underneath while it runs.

Terminal is built with a trace, with a trace collapsible for each command.

## Installation

Terminal is built with the [Trace](https://webjs.dev/ui/docs/components/trace) and [Code Block](https://webjs.dev/ui/docs/components/code-block) components.

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

### Install the following dependencies:

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

### 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 { codeBlockClass, codeBlockCodeClass, codeBlockContentClass } from '#components/ui/code-block.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()}>
          ${TerminalIcon()}
        </span>
        <span data-slot="trace-title" class=${traceTitleClass()}>Ran pnpm build</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="code-block" data-variant="default" data-size="sm" class=${codeBlockClass()}>
        <pre data-slot="code-block-content" data-wrap tabindex="0" class=${cn(codeBlockContentClass(), 'max-h-64')}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
      </div>
    </div>
  </details>
</div>
```

## Exit Code

A command that exits with any code other than `0` failed. Set `data-status="error"`.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  codeBlockClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import {
  traceClass, traceLineClass, traceIconClass, traceTitleClass,
  traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import { ChevronRightIcon, TerminalIcon } from '#lib/ui/lucide.ts';

const LINT_OUTPUT = `> acme-chat@0.1.0 lint
> eslint .

app/api/chat/route.ts
  14:7  error  'model' is assigned a value but never used  no-unused-vars

components/chat.tsx
  42:5  error  React Hook useEffect has a missing dependency: 'messages'  react-hooks/exhaustive-deps

✖ 2 problems (2 errors, 0 warnings)

 ELIFECYCLE  Command failed with exit code 1.`;

export default function TerminalError() {
  return html`
    <div data-slot="trace" class=${cn(traceClass(), 'max-w-sm')}>
      <span data-slot="trace-line" class=${traceLineClass()}>
        <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${TerminalIcon()}</span>
        <span data-slot="trace-title" class=${traceTitleClass()}>Ran pnpm install</span>
      </span>
      <details data-slot="trace-collapsible" open class=${traceCollapsibleClass()}>
        <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
          <span data-slot="trace-line" data-status="error" class=${traceLineClass()}>
            <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${TerminalIcon()}</span>
            <span data-slot="trace-title" class=${traceTitleClass()}>pnpm lint exited with code 1</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="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()}>${LINT_OUTPUT}</code></pre>
          </div>
        </div>
      </details>
    </div>
  `;
}
```

| Command | data-status | Title |
| --- | --- | --- |
| Running | `"running"` | Running pnpm build |
| Exited with `0` | none | Ran pnpm build |
| Exited with another code | `"error"` | pnpm lint exited with code 1 |

The command is a tool call, so its states map the same way as in [Tool](https://webjs.dev/ui/docs/ai-elements/tool#states).

## Open While Running

Open the line once the first output arrives, with `?open=${running && output.length > 0}`, so the output is visible while the command runs. After that the open state is the `<details>` element's own, as in [Trace](https://webjs.dev/ui/docs/components/trace#open-state).

## AI SDK

A tool result arrives only once the command exits. To stream the output while it runs, write it from the tool as a data part with the tool call's id, each time with the output so far. Where your component collects the parts, keep the latest data part for each id, so the output grows in place. See [AI SDK](https://webjs.dev/ui/docs/helpers/ai-sdk) for streaming the parts from a `'use server'` action.

```ts
yield {
  type: 'data-terminal',
  id: toolCallId,
  data: { output },
};
```

On the client, find the data part that matches each tool part.

```ts
function getOutput(message: ChatMessage, toolCallId: string) {
  for (const part of message.parts) {
    if (part.type === 'data-terminal' && part.id === toolCallId) {
      return part.data.output;
    }
  }

  return '';
}
```

## Migrating from AI SDK Elements

If you used Terminal from [AI SDK Elements](https://elements.ai-sdk.dev), its wrapper lives in `components/ai-elements/terminal.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 |
| --- | --- |
| `Terminal` | A trace with a trace collapsible, opened once output arrives while the command runs. |
| `TerminalHeader` | The collapsible's `<summary>`, holding a trace line with `data-status="running"` while the command streams. |
| `TerminalTitle` | A trace icon with the terminal icon and a trace title, like "Ran pnpm build". |
| `TerminalContent` | The trace collapsible content, holding a Code Block with `data-size="sm"` and a `data-wrap` content with `max-h-64` for the output. |
| `TerminalStatus, TerminalActions, TerminalCopyButton, TerminalClearButton` | Markup next to the `<summary>`, not inside it, since a button cannot sit inside a trigger. |

## API Reference

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