# Stack Trace (/docs/agent-ui/components/stack-trace)

Use a stack trace when a tool call or a test fails with an error, so readers see what went wrong and where. It's a step: a header with the error's name and message, over a panel of frames in which each run of library frames folds into one row.

<Example caption="Press 2 library frames to show the frames from libraries and Node.js. Focus a frame and use the arrow keys to move between frames, then press Enter to open one.">
<Basic />

```tsx
"use client";

import { StackTrace } from "@/components/ui/stack-trace";

const stack = `TypeError: Cannot read properties of undefined (reading 'port')
    at readConfig (/app/src/config/read.ts:12:9)
    at loadPlugins (/app/node_modules/plugin-host/dist/index.js:88:14)
    at PluginHost.start (/app/node_modules/plugin-host/dist/host.js:31:5)
    at startServer (/app/src/server.ts:41:3)
    at main (/app/src/index.ts:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)`;

export default function StackTraceExample() {
  return (
    <StackTrace
      stack={stack}
      onOpenFrame={(frame) => console.log("open", frame.file, frame.line)}
      className="w-full max-w-xl"
    />
  );
}
```
</Example>

## Installation [#installation]

```bash tab="React"
npx shadcn@latest add @kind-ui/stack-trace
```

```bash tab="Web Components"
npx shadcn@latest add @kind-ui/stack-trace-web
```

## Composition [#composition]

```text
StackTrace
├── StackTraceTrigger
│   ├── StackTraceIcon
│   └── StackTraceTitle
└── StackTraceContent
    └── div[data-stack-trace-panel]
        ├── StackTraceMessage
        ├── StackTraceList
        │   ├── StackTraceFrame
        │   │   └── StackTraceFrameOpen
        │   │       ├── StackTraceFrameFunction
        │   │       └── StackTraceFrameLocation
        │   └── StackTraceGroup
        │       ├── StackTraceLibrary
        │       └── StackTraceLibraryFrames
        │           └── StackTraceFrame
        └── StackTraceCopy
```

`StackTraceTrigger` opens and closes the trace, with the error mark in `StackTraceIcon` and the message's first line in `StackTraceTitle`, the error's name set apart. `StackTraceContent` holds the panel, a `div` with `data-stack-trace-panel` that the stylesheet draws. In it, `StackTraceMessage` shows the message's other lines, and `StackTraceList` renders a `StackTraceFrame` for each app frame and a `StackTraceGroup` for each run of library frames. A frame shows its function in `StackTraceFrameFunction` and its file in `StackTraceFrameLocation`, inside a `StackTraceFrameOpen` button while you pass `onOpenFrame`. A group's `StackTraceLibrary` shows or folds the frames in its `StackTraceLibraryFrames`. `StackTraceCopy` sits in the panel's corner.

## Usage [#usage]

### Frames [#frames]

Pass `stack`, a JavaScript stack trace's text as V8, SpiderMonkey or JavaScriptCore write it, and the trace reads the message and frames from it. A line it can't read stays as a frame showing the line itself. For another language, or frames you've already parsed, pass `frames` instead, each with its `raw` line and any of `fn`, `file`, `line` and `column`, and pass `message` for the error.

```tsx
<StackTrace message="ValueError: bad port" frames={[{ raw: 'File "app.py", line 3', fn: "main", file: "app.py", line: 3 }]} />
```

The title is the message's first line, or `label` if you pass one, and a name before its first colon, like `TypeError`, shows apart. A frame shows its function and its file's last two segments with line and column; the whole path shows when you hover it.

### Library Frames [#library-frames]

A frame is a library frame when its `library` says so, else when its file is under `node_modules/` or starts with `node:` or `internal/`. App frames read in full color and library frames quieter. Each run of library frames folds into one row, "N library frames"; pressing any of them shows every library frame in place, and pressing again folds them. Find in page reveals them too. Pass `defaultShowLibraryFrames` to start with them shown, or control them with `showLibraryFrames` and `onShowLibraryFramesChange`.

### Opening a Frame [#opening-a-frame]

Pass `onOpenFrame` and each frame becomes a button. Pressing one, or Enter on a focused one, calls `onOpenFrame` with the frame and its index as `details.index`, so you can open the file in your editor. The trace never opens anything itself.

```tsx
<StackTrace stack={error.stack} onOpenFrame={(frame) => openInEditor(frame.file, frame.line)} />
```

### Status and Copying [#status-and-copying]

The status is `error` unless you pass `status`, and the trace starts open; pass `defaultOpen={false}` to show just its header. **Copy stack trace** shows once there's a message or a frame, copies the message and the frames' raw lines, and shows a check for 2 seconds. Pass `onCopy` to hear about it; cancel its `details` to copy something else yourself.

### Keyboard and Motion [#keyboard-and-motion]

Tab reaches the header, each "N library frames" row and **Copy stack trace**. While you pass `onOpenFrame`, the frames are one Tab stop too: the arrow keys, Home and End move between them, skipping folded library frames. The trace opens and closes with the step's height animation, as library frames do; under `prefers-reduced-motion`, or with `motion="reduced"`, they fade over 120 ms, and with `motion="none"` nothing moves.

## API Reference [#api-reference]

### StackTraceOptions

| Prop                         | Type                                                                                                                 | Description                                                                                                                                                                                    |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kind?`                      | `string \| undefined`                                                                                                | Written as `data-kind`, for styling by step type.                                                                                                                                              |
| `open?`                      | `boolean \| undefined`                                                                                               | Whether the content shows. Passing it controls it: change it in `onOpenChange`.                                                                                                                |
| `onOpenChange?`              | `((open: boolean, details: ChangeDetails<StepOpenChangeReason>) => void) \| undefined`                               | Called when the step opens or closes, with what caused it.                                                                                                                                     |
| `autoOpen?`                  | `"never" \| "running"`                                                                                               | With `"running"`, the step opens while running or awaiting input and closes on completion, until someone toggles it. With `"never"`, only a person or your code opens it. Default: `"running"` |
| `durationSeconds?`           | `number \| undefined`                                                                                                | Written as `--kind-step-duration`.                                                                                                                                                             |
| `motion?`                    | `"auto" \| "none" \| "reduced"`                                                                                      | `"auto"` follows `prefers-reduced-motion`. Default: `"auto"`                                                                                                                                   |
| `message?`                   | `string \| undefined`                                                                                                | The error's message, its name first, as in `"TypeError: x is undefined"`. Defaults to the lines of `stack` before its first frame.                                                             |
| `frames?`                    | `StackFrame[] \| undefined`                                                                                          | The frames as data, innermost first, from any language. Takes the place of `stack`'s.                                                                                                          |
| `stack?`                     | `string \| undefined`                                                                                                | A JavaScript stack trace's text, as V8, SpiderMonkey or JavaScriptCore write it. A line it can't read stays as a raw frame.                                                                    |
| `label?`                     | `string \| undefined`                                                                                                | The title, which also names it in announcements. Defaults to the message's first line, else "Error".                                                                                           |
| `status?`                    | `"awaiting-input" \| "cancelled" \| "complete" \| "error" \| "pending" \| "running"`                                 | Default: `"error"`                                                                                                                                                                             |
| `defaultOpen?`               | `boolean \| undefined`                                                                                               | Whether the frames show at first, when `open` isn't passed. Default: `true`                                                                                                                    |
| `showLibraryFrames?`         | `boolean \| undefined`                                                                                               | Whether library frames show. Passing it controls it: change it in `onShowLibraryFramesChange`.                                                                                                 |
| `defaultShowLibraryFrames?`  | `boolean \| undefined`                                                                                               | Whether library frames show at first, when `showLibraryFrames` isn't passed. Default: `false`                                                                                                  |
| `onShowLibraryFramesChange?` | `((show: boolean, details: ChangeDetails<StackTraceLibraryChangeReason>) => void) \| undefined`                      | Called when library frames show or fold, with what caused it.                                                                                                                                  |
| `onOpenFrame?`               | `((frame: StackFrame, details: ChangeDetails<StackTraceOpenFrameReason> & { index: number; }) => void) \| undefined` | Called when someone opens a frame, with its index among the frames as `details.index`. Makes each frame a button.                                                                              |
| `onCopy?`                    | `((text: string, details: ChangeDetails<StackTraceCopyReason>) => void) \| undefined`                                | Called before the message and raw frames are copied. Cancel it to copy something else yourself.                                                                                                |

### Agent [#agent]

An agent connected with `createAgent` finds the trace by its title and reads `open`, `status` and `showLibraryFrames`. It can `expand` and `collapse` the trace, `copy` it while there's something to copy, which calls `onCopy` too, and, while there are library frames, `toggleLibraryFrames`. While you pass `onOpenFrame`, it can `openFrame` by index or by a frame's function and location, and a frame that isn't there is refused.

### StackTraceAgentActions

| Prop                  | Type                                                                 | Description                                                                                                                                   |
| --------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `expand`              | `() => boolean`                                                      | Opens the step. Returns whether the change was accepted.                                                                                      |
| `collapse`            | `() => boolean`                                                      | Closes the step. Returns whether the change was accepted.                                                                                     |
| `copy`                | `((event?: Event) => Promise<boolean>) \| undefined`                 | Copies the message and the raw frames, and resolves with whether the clipboard write went through. Only while there's either.                 |
| `toggleLibraryFrames` | `((event?: Event) => boolean) \| undefined`                          | Shows folded library frames, or folds them. Returns whether the change was accepted. Only while there are library frames.                     |
| `openFrame`           | `((index: number \| string, event?: Event) => boolean) \| undefined` | Calls `onOpenFrame` with the `index`th frame, counted from 0. Returns false for an index outside the frames. Only while `onOpenFrame` is set. |

<Caption>
Runs in React and Web Components. On `<kind-stack-trace>`, set `frames` as a property; the other props are kebab-case attributes, and the `can-open-frame` attribute offers `onOpenFrame`, which is the `openframe` event. `onOpenChange` is `openchange`, `onShowLibraryFramesChange` is `showlibraryframeschange` and `onCopy` is `stackcopy`.
</Caption>