Skip to content
Shaken UI
Sign in

Stack Trace

Save

A failed tool call's error with a collapsible list of stack frames that marks app frames, folds library frames, and copies the whole trace.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Stack Trace preview

run_migration failed

1.2 s
  1. resolveTenant /app/src/db/tenants.ts:41:27, your code
  2. applyMigration /app/src/db/migrate.ts:88:19, your code
  3. runPending /app/src/db/migrate.ts:52:5, your code
  4. main /app/scripts/migrate.ts:12:3, your code

Installation

npx @shakenui/cli add stack-trace

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add stack-trace --dry-run

Usage

stack-trace-example.tsx
import { StackTrace } from "@/components/shaken/agent/stack-trace";

const stack = `TypeError: Cannot read properties of undefined (reading 'tenantId')
    at resolveTenant (/app/src/db/tenants.ts:41:27)
    at applyMigration (/app/src/db/migrate.ts:88:19)
    at async Promise.all (index 2)
    at async runPending (/app/src/db/migrate.ts:52:5)
    at async Command.<anonymous> (/app/node_modules/commander/lib/command.js:1092:14)
    at async Command.parseAsync (/app/node_modules/commander/lib/command.js:1078:5)
    at async main (/app/scripts/migrate.ts:12:3)
    at processTicksAndRejections (node:internal/process/task_queues:105:5)`;

export default function StackTraceExample() {
  return <StackTrace tool="run_migration" stack={stack} durationMs={1240} defaultOpen className="w-full max-w-xl" />;
}

API

PropTypeDefaultDescription
stackstring—A raw V8 stack string; parsed into a name, message, and frames.
name / message / framesstring / string / { fn?, file, line?, column?, library? }[]—Pass these instead of, or to override, the parsed stack.
toolstring—The tool call that failed, shown in the header.
durationMsnumber—How long the call ran before failing.
defaultOpenbooleanfalseOpens the frame list initially.
parseStack / isLibraryFramefunctions—The parser and the node_modules and runtime detection, exported for reuse.

Accessibility

  • The error message is a role alert in a red tinted box; the header pairs the failed glyph with the word failed.
  • The frame list is a Base UI Collapsible; its trigger states the frame count and how many are in your code.
  • App frames carry a solid dot and stronger text plus an sr-only your code; library runs fold into a labelled button that reveals them, and a Hide button folds them again.
  • The copy button is labelled and announces Copied. The list height animates in 220ms; instant with reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/stack-trace.tsxstack-trace
  • Also installs step-list@0.3.0registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/stack-trace/0.1.0.json.

agent/stack-trace.tsxShow
agent/stack-trace.tsx
"use client";

import { Collapsible } from "@base-ui/react/collapsible";
import { type ComponentProps, Fragment, useEffect, useMemo, useRef, useState } from "react";
import { StatusGlyph } from "./step-list";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export interface StackFrame {
  /** Function name. Anonymous frames leave it unset. */
  fn?: string;
  /** File path or URL. */
  file: string;
  line?: number;
  column?: number;
  /** Library or runtime code rather than the app's own. Detected from the path when unset. */
  library?: boolean;
}

export interface ParsedStack {
  name: string;
  message: string;
  frames: StackFrame[];
}

const libraryPattern = /(node_modules|^node:|^internal\/|\(native\)|webpack-internal:\/\/\/\(?\.?\/?node_modules)/;

/** Whether a frame belongs to a dependency or the runtime. */
export function isLibraryFrame(frame: StackFrame): boolean {
  // Frames without a real path, such as `Promise.all (index 2)`, come from the runtime.
  return frame.library ?? (libraryPattern.test(frame.file) || !/[/\\.]/.test(frame.file));
}

/**
 * Parses a V8 style stack (`Error: message` followed by `    at fn (file:line:col)` lines)
 * into a name, a message, and frames. Lines it does not recognize are skipped.
 */
export function parseStack(stack: string): ParsedStack {
  const lines = stack.split("\n");
  const head: string[] = [];
  const frames: StackFrame[] = [];
  for (const raw of lines) {
    const line = raw.trim();
    const match = /^at (?:(?:async )?(.+?) \()?(.+?)(?::(\d+))?(?::(\d+))?\)?$/.exec(line);
    if (match && line.startsWith("at ")) {
      frames.push({ fn: match[1], file: match[2] ?? "", line: match[3] ? Number(match[3]) : undefined, column: match[4] ? Number(match[4]) : undefined });
    } else if (!frames.length && line) {
      head.push(line);
    }
  }
  const first = head.join("\n");
  const colon = first.indexOf(": ");
  const name = colon > 0 && /^[\w$.]+$/.test(first.slice(0, colon)) ? first.slice(0, colon) : "Error";
  const message = name === "Error" && colon <= 0 ? first : first.slice(colon + 2);
  return { name, message, frames };
}

function formatFrame(frame: StackFrame): string {
  const location = [frame.file, frame.line, frame.column].filter((part) => part !== undefined).join(":");
  return frame.fn ? `    at ${frame.fn} (${location})` : `    at ${location}`;
}

export interface StackTraceProps extends Omit<ComponentProps<"section">, "children"> {
  /** Error class, for example `TypeError`. */
  name?: string;
  message?: string;
  /** Frames, innermost first. Or pass `stack` and let it parse. */
  frames?: StackFrame[];
  /** A raw V8 stack string. Used for the name, message, and frames that are not passed. */
  stack?: string;
  /** The tool call that failed, shown in the header. */
  tool?: string;
  /** How long the call ran before failing. */
  durationMs?: number;
  /** Opens the frame list initially. */
  defaultOpen?: boolean;
}

/**
 * A failed tool call's error: the error name and message, then a collapsible list of stack
 * frames. Frames from the app's own code are emphasized and marked; runs of library frames fold
 * into one row until the reader asks for them. Copy puts the whole trace on the clipboard.
 */
export function StackTrace({
  name: nameProp,
  message: messageProp,
  frames: framesProp,
  stack,
  tool,
  durationMs,
  defaultOpen = false,
  className,
  ...props
}: StackTraceProps) {
  const parsed = useMemo(() => (stack ? parseStack(stack) : undefined), [stack]);
  const name = nameProp ?? parsed?.name ?? "Error";
  const message = messageProp ?? parsed?.message ?? "";
  const frames = framesProp ?? parsed?.frames ?? [];
  const [showLibrary, setShowLibrary] = useState(false);
  const appCount = frames.filter((frame) => !isLibraryFrame(frame)).length;
  const libraryCount = frames.length - appCount;
  const copyText = `${name}: ${message}\n${frames.map(formatFrame).join("\n")}`;

  // Consecutive library frames fold into one group while they are hidden.
  const groups = useMemo(() => {
    const result: { library: boolean; frames: { frame: StackFrame; index: number }[] }[] = [];
    frames.forEach((frame, index) => {
      const library = isLibraryFrame(frame);
      const last = result[result.length - 1];
      if (last && last.library === library) last.frames.push({ frame, index });
      else result.push({ library, frames: [{ frame, index }] });
    });
    return result;
  }, [frames]);

  return (
    <section
      aria-label={tool ? `${tool} failed` : `${name}: ${message}`}
      className={cx(
        "overflow-hidden rounded-xl border border-red-500/35 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      <header className="flex items-center gap-2.5 py-2.5 pr-2.5 pl-4">
        <StatusGlyph kind="failed" />
        <p className="min-w-0 flex-1 truncate text-sm">
          {tool ? (
            <>
              <span className="font-mono text-[13px] font-medium">{tool}</span>
              <span className="text-zinc-600 dark:text-zinc-400"> failed</span>
            </>
          ) : (
            <span className="font-medium">Failed</span>
          )}
        </p>
        {durationMs != null ? <span className="font-mono text-xs text-zinc-500 tabular-nums">{formatDuration(durationMs)}</span> : null}
        <CopyButton text={copyText} label="Copy error and stack trace" />
      </header>

      <div className="px-4 pb-4">
        <p role="alert" className="rounded-lg border border-red-500/35 bg-red-500/[0.08] px-3 py-2.5 font-mono text-xs leading-relaxed break-words text-red-700 dark:text-red-300">
          <span className="font-semibold">{name}</span>
          {message ? `: ${message}` : null}
        </p>
      </div>

      {frames.length ? (
        <Collapsible.Root defaultOpen={defaultOpen} className="border-t border-zinc-950/[0.07] dark:border-white/[0.08]">
          <Collapsible.Trigger
            className={cx(
              "group flex w-full cursor-pointer items-center justify-between gap-3 px-4 py-2.5 text-left text-xs font-medium select-none",
              "text-zinc-600 transition-colors duration-150 hover:bg-zinc-950/[0.03] hover:text-zinc-950 motion-reduce:transition-none",
              "dark:text-zinc-400 dark:hover:bg-white/[0.04] dark:hover:text-white",
              "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
            )}
          >
            <span>
              Stack trace
              <span className="ml-2 font-normal text-zinc-500 tabular-nums">
                {frames.length} {frames.length === 1 ? "frame" : "frames"}, {appCount} in your code
              </span>
            </span>
            <svg
              aria-hidden="true"
              viewBox="0 0 16 16"
              className={`size-4 shrink-0 text-zinc-500 transition-transform duration-200 ${ease} group-data-panel-open:rotate-180 motion-reduce:transition-none`}
            >
              <path d="m4.5 6.25 3.5 3.5 3.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </Collapsible.Trigger>
          <Collapsible.Panel
            className={cx(
              "h-(--collapsible-panel-height) overflow-hidden",
              `transition-[height,opacity] duration-220 ${ease} motion-reduce:transition-none`,
              "data-starting-style:h-0 data-starting-style:opacity-0",
              "data-ending-style:h-0 data-ending-style:opacity-0 data-ending-style:duration-180",
            )}
          >
            <ol className="pb-2" aria-label="Stack frames">
              {groups.map((group) =>
                group.library && !showLibrary ? (
                  <li key={`fold-${group.frames[0]?.index}`}>
                    <button
                      type="button"
                      onClick={() => setShowLibrary(true)}
                      className={cx(
                        "flex w-full cursor-pointer items-center gap-2.5 px-4 py-1 text-left font-mono text-[11px] text-zinc-500",
                        "transition-colors duration-150 hover:bg-zinc-950/[0.03] hover:text-zinc-700 motion-reduce:transition-none dark:hover:bg-white/[0.04] dark:hover:text-zinc-300",
                        "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
                      )}
                    >
                      <span aria-hidden="true" className="flex w-1.5 justify-center">
                        <span className="h-3 border-l border-dashed border-zinc-400 dark:border-zinc-600" />
                      </span>
                      {group.frames.length} library {group.frames.length === 1 ? "frame" : "frames"}
                    </button>
                  </li>
                ) : (
                  <Fragment key={`group-${group.frames[0]?.index}`}>
                    {group.frames.map(({ frame, index }) => (
                      <FrameRow key={index} frame={frame} library={group.library} />
                    ))}
                  </Fragment>
                ),
              )}
            </ol>
            {libraryCount > 0 && showLibrary ? (
              <div className="px-4 pb-3">
                <button
                  type="button"
                  onClick={() => setShowLibrary(false)}
                  className={cx(
                    "-ml-1.5 inline-flex h-7 cursor-pointer items-center rounded-md px-1.5 text-xs font-medium text-zinc-600",
                    "transition-colors duration-150 hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-reduce:transition-none",
                    "dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
                    "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                  )}
                >
                  Hide {libraryCount} library {libraryCount === 1 ? "frame" : "frames"}
                </button>
              </div>
            ) : null}
          </Collapsible.Panel>
        </Collapsible.Root>
      ) : null}
    </section>
  );
}

function FrameRow({ frame, library }: { frame: StackFrame; library: boolean }) {
  const location = [frame.file, frame.line, frame.column].filter((part) => part !== undefined).join(":");
  return (
    <li className="grid grid-cols-[0.375rem_minmax(0,1fr)] items-start gap-x-2.5 px-4 py-1">
      <span aria-hidden="true" className="flex h-4 items-center">
        {library ? null : <span className="size-1.5 rounded-full bg-zinc-950 dark:bg-white" />}
      </span>
      <span className="min-w-0 font-mono text-xs leading-4 break-words">
        <span className={library ? "text-zinc-500" : "font-medium text-zinc-950 dark:text-white"}>{frame.fn ?? "<anonymous>"}</span>{" "}
        <span className={library ? "text-zinc-400 dark:text-zinc-600" : "text-zinc-600 dark:text-zinc-400"}>{location}</span>
        <span className="sr-only">{library ? ", library" : ", your code"}</span>
      </span>
    </li>
  );
}

/** An icon button that copies text and confirms with a check for 1.5s; the confirmation is announced. */
function CopyButton({ text, label }: { text: string; label: string }) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  async function copy() {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setCopied(false), 1500);
    } catch {
      setCopied(false);
    }
  }

  return (
    <button
      type="button"
      onClick={copy}
      aria-label={label}
      className={cx(
        "inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-zinc-500",
        "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
      )}
    >
      <svg
        key={copied ? "copied" : "copy"}
        aria-hidden="true"
        viewBox="0 0 16 16"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={cx(
          "size-4 transition-[opacity,scale] duration-200 starting:scale-90 starting:opacity-0 motion-reduce:transition-none",
          ease,
          copied && "text-emerald-600 dark:text-emerald-400",
        )}
      >
        {copied ? (
          <path d="m3.75 8.5 2.75 2.75 5.75-6.5" />
        ) : (
          <>
            <rect x="5.25" y="5.25" width="8" height="8" rx="1.75" />
            <path d="M10.75 5.25V3.5c0-.97-.78-1.75-1.75-1.75H3.5c-.97 0-1.75.78-1.75 1.75V9c0 .97.78 1.75 1.75 1.75h1.75" />
          </>
        )}
      </svg>
      <span className="sr-only" aria-live="polite">
        {copied ? "Copied" : ""}
      </span>
    </button>
  );
}

function formatDuration(ms: number): string {
  return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
}