Skip to content
WebJs
Menu

Stack Trace

Displays a failed tool call and its stack frames.

Reset the database and seed it.
Ran pnpm prisma migrate reset --skip-seed
Database reset successful

The following migrations have been applied:

migrations/
  └─ 20260912_init/
  └─ 20260920_add_profiles/
Failed: TypeError: Cannot read properties of undefined (reading 'email')

TypeError: Cannot read properties of undefined (reading 'email')

seedUsers in prisma/seed.ts:27 main in prisma/seed.ts:51
4 framework frames
  1. at Module._compile (node:internal/modules/cjs/loader:1554:14)
  2. at Object.transformer (node_modules/tsx/dist/register.cjs:3:1104)
  3. at Module.load (node:internal/modules/cjs/loader:1289:32)
  4. at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

The migrations ran, but the seed failed in seedUsers. One fixture has no profile, so profile.email is undefined.

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

const question = 'Reset the database and seed it.';
const answer =
  'The migrations ran, but the seed failed in seedUsers. One fixture has no profile, so profile.email is undefined.';

const RESET_OUTPUT = `Database reset successful

The following migrations have been applied:

migrations/
  └─ 20260912_init/
  └─ 20260920_add_profiles/`;

const STACK = `TypeError: Cannot read properties of undefined (reading 'email')
    at seedUsers (prisma/seed.ts:27:34)
    at main (prisma/seed.ts:51:9)
    at Module._compile (node:internal/modules/cjs/loader:1554:14)
    at Object.transformer (node_modules/tsx/dist/register.cjs:3:1104)
    at Module.load (node:internal/modules/cjs/loader:1289:32)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)`;

function parseFrame(line: string) {
  const match = line.match(/^at (.+) \((.+):(\d+):(\d+)\)$/);
  return {
    line,
    name: match?.[1],
    file: match?.[2],
    lineNumber: match?.[3],
    internal: line.includes('node_modules') || line.includes('node:'),
  };
}

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

// A failed command: the error is the title, and the content repeats it above
// the frames, with your own frames as links and the rest folded away.
function StackTrace(stack: string) {
  const [error, ...lines] = stack.split('\n').map((line) => line.trim());
  const frames = lines.map(parseFrame);
  const appFrames = frames.filter((frame) => !frame.internal);
  const internalFrames = frames.filter((frame) => frame.internal);

  return html`
    <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" data-status="error" class=${traceLineClass()}>
          <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${TerminalIcon()}</span>
          <span data-slot="trace-title" class=${traceTitleClass()}>Failed: ${error}</span>
        </span>
        ${chevron()}
      </summary>
      <div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'flex flex-col gap-2')}>
        <p class="font-mono text-xs text-destructive">${error}</p>
        <div data-slot="trace" class=${traceClass()}>
          ${appFrames.map((frame) => html`
            <a href=${'#' + frame.file + ':' + frame.lineNumber}>
              <span data-slot="trace-line" class=${traceLineClass()}>
                <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${FileCodeIcon()}</span>
                <span data-slot="trace-title" class=${traceTitleClass()}>${frame.name} in ${frame.file}:${frame.lineNumber}</span>
              </span>
            </a>
          `)}
          <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()}>${LayersIcon()}</span>
                <span data-slot="trace-title" class=${traceTitleClass()}>${internalFrames.length} framework frames</span>
              </span>
              ${chevron()}
            </summary>
            <div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
              <ol class="flex flex-col gap-1 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs">
                ${internalFrames.map((frame) => html`<li class="whitespace-nowrap">${frame.line}</li>`)}
              </ol>
            </div>
          </details>
        </div>
      </div>
    </details>
  `;
}

// The conversation once the reply has finished streaming.
export default function StackTraceDemo() {
  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" 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 prisma migrate reset --skip-seed</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()}>${RESET_OUTPUT}</code></pre>
                </div>
              </div>
            </details>
            ${StackTrace(STACK)}
          </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

Stack Trace is a line for a tool call that failed. The error is the title, like "Failed: TypeError". Open it for the stack frames, which can link to the file and line.

Stack Trace is built with a trace, with a trace collapsible for the frames.

Installation

Stack Trace is built with the Trace and Code Block components.

pnpm dlx @webjsdev/ui add trace code-block

Usage

import {
  traceClass,
  traceCollapsibleClass,
  traceCollapsibleContentClass,
  traceCollapsibleTriggerClass,
  traceIconClass,
  traceLineClass,
  traceTitleClass,
} from '#components/ui/trace.ts';
const [error, ...frames] = stack.split('\n').map((line) => line.trim());

html`<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" data-status="error" class=${traceLineClass()}>
        <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>
          ${CircleXIcon()}
        </span>
        <span data-slot="trace-title" class=${traceTitleClass()}>Failed: ${error}</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 class="flex flex-col gap-2 rounded-md bg-muted p-3 font-mono text-xs">
        <p class="text-destructive">${error}</p>
        <ol>
          ${frames.map((frame) => html`
            <li class=${frame.includes('node_modules') ? '' : 'text-foreground'}>${frame}</li>
          `)}
        </ol>
      </div>
    </div>
  </details>
</div>`

The title truncates, so repeat the full error at the top of the content. Frames from node_modules stay muted, so your own frames stand out.

Turn your own frames into links that open the file at the line. Fold the framework frames into a collapsible line of their own, so the frames you can fix come first.

Failed: TypeError: Cannot read properties of undefined (reading 'total')

TypeError: Cannot read properties of undefined (reading 'total')

formatInvoice in app/lib/billing.ts:42 InvoiceRow in app/components/invoice-row.tsx:18
4 framework frames
  1. at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
  2. at beginWork (node_modules/react-dom/cjs/react-dom.development.js:19049:16)
  3. at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22776:12)
  4. at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22707:5)
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, CircleXIcon, FileCodeIcon, LayersIcon } from '#lib/ui/lucide.ts';

const STACK = `TypeError: Cannot read properties of undefined (reading 'total')
    at formatInvoice (app/lib/billing.ts:42:31)
    at InvoiceRow (app/components/invoice-row.tsx:18:12)
    at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
    at beginWork (node_modules/react-dom/cjs/react-dom.development.js:19049:16)
    at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22776:12)
    at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22707:5)`;

function parseFrame(line: string) {
  const match = line.match(/^at (.+) \((.+):(\d+):(\d+)\)$/);
  return {
    line,
    name: match?.[1],
    file: match?.[2],
    lineNumber: match?.[3],
    internal: line.includes('node_modules'),
  };
}

const [error, ...lines] = STACK.split('\n').map((line) => line.trim());
const frames = lines.map(parseFrame);
const appFrames = frames.filter((frame) => !frame.internal);
const internalFrames = frames.filter((frame) => frame.internal);

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

export default function StackTraceFrames() {
  return html`
    <div data-slot="trace" class=${cn(traceClass(), 'max-w-sm')}>
      <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" data-status="error" class=${traceLineClass()}>
            <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${CircleXIcon()}</span>
            <span data-slot="trace-title" class=${traceTitleClass()}>Failed: ${error}</span>
          </span>
          ${chevron()}
        </summary>
        <div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'flex flex-col gap-2')}>
          <p class="font-mono text-xs text-destructive">${error}</p>
          <div data-slot="trace" class=${traceClass()}>
            ${appFrames.map((frame) => html`
              <a href=${'#' + frame.file + ':' + frame.lineNumber}>
                <span data-slot="trace-line" class=${traceLineClass()}>
                  <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${FileCodeIcon()}</span>
                  <span data-slot="trace-title" class=${traceTitleClass()}>${frame.name} in ${frame.file}:${frame.lineNumber}</span>
                </span>
              </a>
            `)}
            <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()}>${LayersIcon()}</span>
                  <span data-slot="trace-title" class=${traceTitleClass()}>${internalFrames.length} framework frames</span>
                </span>
                ${chevron()}
              </summary>
              <div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
                <ol class="flex flex-col gap-1 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs">
                  ${internalFrames.map((frame) => html`<li class="whitespace-nowrap">${frame.line}</li>`)}
                </ol>
              </div>
            </details>
          </div>
        </div>
      </details>
    </div>
  `;
}
View Code

AI SDK

When a tool throws, its part is output-error, and by default errorText is only the error message, with no frames. Where your 'use server' action streams the parts (see AI SDK), catch the tool's error and put error.stack in the part yourself.

modules/chat/utils/error-text.server.ts
function errorText(error: unknown) {
  if (!(error instanceof Error)) return String(error);
  return process.env.NODE_ENV === 'production' ? error.message : (error.stack ?? error.message);
}

A stack shows file paths from your server, so only send it in development, as above. A WebJs action that throws in production already sends the client a generic message and a digest, never the stack.

function toolRow(part: ToolPart) {
  if (part.state === 'output-error') {
    const [error, ...frames] = part.errorText.split('\n').map((line) => line.trim());
    return html`<details data-slot="trace-collapsible" class=${traceCollapsibleClass()}>…</details>`;
  }
  // …
}

Map the other tool states as in Tool.

Migrating from AI SDK Elements

If you used Stack Trace from AI SDK Elements, its wrapper lives in components/ai-elements/stack-trace.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
StackTraceA trace with a trace collapsible. Its open state is the <details> element's own open, and the parsing stays yours.
StackTraceHeaderThe collapsible's <summary>, holding a trace line with data-status="error" and a trace icon.
StackTraceErrorA trace title, like "Failed: TypeError: …". Keep the error type and message as spans inside it.
StackTraceContentThe trace collapsible content.
StackTraceFramesThe frames as a list in a muted, monospace block, with the frames from node_modules dimmed and your own frames as links.
StackTraceExpandButtonNothing, since the whole line opens the frames.
StackTraceActions, StackTraceCopyButtonButtons next to the <summary>, not inside it, since a button cannot sit inside a trigger.

API Reference

See Trace.