Skip to content

Stack Trace

Shows an error with the frames from your own code first and the framework frames folded away.

Reset the database and seed it.

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

seedUsers in prisma/seed.ts:27main in prisma/seed.ts:51

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

Installation

pnpm dlx shadcn@latest add @silkware/ai-stack-trace

To copy the pattern by hand, install the components it composes:

pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/code-block @silkware/message @silkware/trace

Then the packages:

pnpm add ai @ai-sdk/react @shadcn/helpers lucide-react

Copy the source into components/ai-elements/stack-trace.tsx. The file also needs @/lib/ai:

components/ai-elements/stack-trace.tsx
"use client"
import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import { FileCodeIcon, LayersIcon, TerminalIcon } from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Message, MessageContent } from "@/components/ui/message"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    runCommand: {      input: { command: string }      output: { stdout: string }    }  }>
type ToolPart = Extract<  ChatMessage["parts"][number],  { type: "tool-runCommand" }>
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)`
const chat = createChat<ChatMessage>()  .user("Reset the database and seed it.")  .assistant(({ writer }) => {    writer      .tool("runCommand", {        input: { command: "pnpm prisma migrate reset --skip-seed" },      })      .sleep(900)      .output({        stdout: `Database reset successful
The following migrations have been applied:
migrations/  └─ 20260912_init/  └─ 20260920_add_profiles/`,      })    writer      .tool("runCommand", { input: { command: "pnpm prisma db seed" } })      .sleep(1200)      .error(STACK)    writer.text(      "The migrations ran, but the seed failed in seedUsers. One fixture has no profile, so profile.email is undefined."    )  })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
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:"),  }}
function StackTrace({ stack }: { 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 (    <TraceCollapsible defaultExpanded>      <TraceCollapsibleTrigger>        <TraceLine status="error">          <TraceIcon>            <TerminalIcon />          </TraceIcon>          <TraceTitle>Failed: {error}</TraceTitle>        </TraceLine>      </TraceCollapsibleTrigger>      <TraceCollapsibleContent className="flex flex-col gap-2">        <p className="font-mono text-xs text-destructive">{error}</p>        <Trace>          {appFrames.map((frame) => (            <a key={frame.line} href={`#${frame.file}:${frame.lineNumber}`}>              <TraceLine>                <TraceIcon>                  <FileCodeIcon />                </TraceIcon>                <TraceTitle>                  {frame.name} in {frame.file}:{frame.lineNumber}                </TraceTitle>              </TraceLine>            </a>          ))}          <TraceCollapsible>            <TraceCollapsibleTrigger>              <TraceLine>                <TraceIcon>                  <LayersIcon />                </TraceIcon>                <TraceTitle>                  {internalFrames.length} framework frames                </TraceTitle>              </TraceLine>            </TraceCollapsibleTrigger>            <TraceCollapsibleContent>              <ol className="flex flex-col gap-1 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs">                {internalFrames.map((frame) => (                  <li key={frame.line} className="whitespace-nowrap">                    {frame.line}                  </li>                ))}              </ol>            </TraceCollapsibleContent>          </TraceCollapsible>        </Trace>      </TraceCollapsibleContent>    </TraceCollapsible>  )}
function CommandRow({  part,  streaming,}: {  part: ToolPart  streaming: boolean}) {  const command = part.input?.command
  if (part.state === "output-error") {    return <StackTrace stack={part.errorText} />  }
  if (part.state === "output-available") {    return (      <TraceCollapsible>        <TraceCollapsibleTrigger>          <TraceLine>            <TraceIcon>              <TerminalIcon />            </TraceIcon>            <TraceTitle>Ran {command}</TraceTitle>          </TraceLine>        </TraceCollapsibleTrigger>        <TraceCollapsibleContent>          <CodeBlock size="sm">            <CodeBlockContent wrap className="max-h-64">              {part.output.stdout}            </CodeBlockContent>          </CodeBlock>        </TraceCollapsibleContent>      </TraceCollapsible>    )  }
  return (    <TraceLine status={streaming ? "running" : "error"}>      <TraceIcon>        <TerminalIcon />      </TraceIcon>      <TraceTitle>        {streaming ? "Running" : "Failed to run"} {command}      </TraceTitle>    </TraceLine>  )}
export function StackTraceDemo() {  const { messages, sendMessage, setMessages, status } = useChat({    messages: transcript,    transport,  })  const busy = status === "submitted" || status === "streaming"
  return (    <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">      {messages.map((message) => {        if (message.role === "user") {          return (            <Message key={message.id} align="end">              <MessageContent>                <Bubble align="end" variant="muted">                  <BubbleContent>{getMessageText(message)}</BubbleContent>                </Bubble>              </MessageContent>            </Message>          )        }
        const streaming = busy && message === messages.at(-1)        const tools = message.parts.filter(          (part) => part.type === "tool-runCommand"        )        const text = getMessageText(message)
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {tools.length > 0 && (                <Trace>                  {tools.map((part) => (                    <CommandRow                      key={part.toolCallId}                      part={part}                      streaming={streaming}                    />                  ))}                </Trace>              )}              {text && <p>{text}</p>}            </MessageContent>          </Message>        )      })}      {!busy && (        <Button          variant="outline"          size="sm"          className="mt-auto self-start"          onPress={() => {            setMessages([])            sendMessage(question)          }}        >          Replay        </Button>      )}    </div>  )}

Usage

Split the stack into the error line and its frames, parse each frame and keep the frames from your code apart from the ones in node_modules or Node itself.

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 [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)

The error is the title of an error line. Each frame from your code is a link, and the framework frames sit in a collapsed group:

<TraceCollapsible defaultExpanded>  <TraceCollapsibleTrigger>    <TraceLine status="error">      <TraceIcon>        <TerminalIcon />      </TraceIcon>      <TraceTitle>Failed: {error}</TraceTitle>    </TraceLine>  </TraceCollapsibleTrigger>  <TraceCollapsibleContent className="flex flex-col gap-2">    <p className="font-mono text-xs text-destructive">{error}</p>    <Trace>      {appFrames.map((frame) => (        <a key={frame.line} href={`#${frame.file}:${frame.lineNumber}`}>          <TraceLine>            <TraceIcon>              <FileCodeIcon />            </TraceIcon>            <TraceTitle>{frame.name} in {frame.file}:{frame.lineNumber}</TraceTitle>          </TraceLine>        </a>      ))}    </Trace>  </TraceCollapsibleContent></TraceCollapsible>

The href of a frame is a placeholder anchor. Point it at your editor, repository or source viewer. The parser matches the at name (file:line:column) form that Node prints; a frame in another form (an anonymous function, a different runtime) gets no name or file, so adapt parseFrame to the stacks you receive.

Examples

Framework frames

The frames from node_modules are counted and folded into one group, so a long stack shows only the frames the person can change.

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

formatInvoice in app/lib/billing.ts:42InvoiceRow in app/components/invoice-row.tsx:18

Short stack

When every frame is from your own code there is nothing to fold. Show the frames as links and leave the group out.

AI SDK

A stack trace is the errorText of a failed tool call. When a tool throws, its part moves to output-error and errorText holds the message, and a stack when the tool puts one there. The demo renders that text with StackTrace:

if (part.state === "output-error") {  return <StackTrace stack={part.errorText} />}

errorText is a string, so the error reaches the browser only if your server sends it. By default the AI SDK sends a generic message for errors in the stream and hides the details. If you want the person to see the stack, return it from execute as a handled result, or set onError on the stream response to pass it through. Do that only for stacks you are willing to show.

return result.toUIMessageStreamResponse({  onError: (error) => (error instanceof Error ? (error.stack ?? error.message) : String(error)),})

Stack frames reveal file paths and package versions. Strip anything that is not the person's business before it leaves the server.

Scripted streams in development

error on a scripted tool call resolves it as a failure with the text you give:

writer  .tool("runCommand", { input: { command: "pnpm prisma db seed" } })  .sleep(1200)  .error(STACK)

Accessibility

KeyAction
EnterOpens or closes the error, or the group of framework frames. On a frame, follows its link.
SpaceOpens or closes the error, or the group of framework frames.
TabMoves focus to the next frame link or control.

The composed components provide:

  • Real buttons with aria-expanded for the error and for the framework group.
  • Real links for the frames, which are in the tab order.
  • A visible focus ring on the triggers.

You provide:

  • The failure in words. The title starts with "Failed:" and repeats the error, so the crimson is not the only signal.
  • A link target that works, and a title that says where it goes. "seedUsers in prisma/seed.ts:27" reads well out loud; a bare path does not.
  • Error text that is safe to show.

Guidelines

When to use

  • When a call threw an error and the person needs to find the line in their own code.
  • When the stack is longer than a screen and most of it is framework code.

When not to use

  • For a failed test with an assertion message. Use Test Results.
  • For the full output of a command that failed. Use Terminal.
  • For an error the person can fix without reading a stack, such as a missing field. Say it in the message.

Content

  • Show the error message first, unchanged.
  • Put the frames from the person's code first, in the order they were called, and say how many frames are folded.
  • Link each frame to the source. A frame that cannot open in an editor is still a path the person can search.
  • Do not remove frames from the stack. Fold them.
Do

Show the error, link the frames from your own code and fold the rest with a count.

Don’t

Don’t print the whole stack as one block of text. The line the person needs is lost in the framework frames.

Human in the loop

  • A stack trace is the record of a failure. Show it even when the agent plans to retry, and say whether it will.
  • Do not let the agent retry a call that failed after changing something without telling the person: a seed that half ran has already written rows. Say what was changed before the error.
  • When the agent proposes a fix to the code the stack points at, show the change and ask before it writes the file, with Confirmation.

Composition

ComponentWhat it does here
TraceLays out the error line, the frames and the collapsibles, and carries the error status.
Code BlockShows command output next to a stack, in the demo.
MessagePlaces the conversation in turns.
BubbleWraps the person's own message.
ButtonThe replay control of the demo.

components/ai-elements/stack-trace.tsx exports StackTraceDemo, a scripted chat that runs two commands, the second of which fails with a stack. Copy StackTrace, parseFrame and CommandRow into your app and replace the scripted chat with useChat against your route.