# Trace

Displays the steps an agent takes, such as reasoning, tool calls and sources, as a list of lines.

```tsx
"use client"

import { useEffect, useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Button } from "@/components/ui/button"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { Spinner } from "@/components/ui/spinner"
import { VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { states } from "@/theme/states"
import { color } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { ArrowUpRightIcon } from "@phosphor-icons/react/dist/csr/ArrowUpRight"
import { CheckCircleIcon } from "@phosphor-icons/react/dist/csr/CheckCircle"
import { GlobeIcon } from "@phosphor-icons/react/dist/csr/Globe"
import { WarningCircleIcon } from "@phosphor-icons/react/dist/csr/WarningCircle"

const styles = stylex.create({
  reasoning: { whiteSpace: "pre-wrap" },
  error: { color: color.destructive },
})

const reasoning =
  "The date test passes on my machine and fails in CI. CI runs in UTC, so the formatter may depend on the local time zone. I should check the last change to the formatter, then run the test in UTC."

const tick = 50
const charMs = 15
const thought = reasoning.length * charMs

const commands = [
  {
    command: "git log --oneline -1 -- src/lib/format-date.ts",
    output: "3f2c1ab Show event times in the local zone",
    start: thought + 200,
    end: thought + 900,
  },
  {
    command: "npx vitest run src/lib/format-date.test.ts",
    output: " ✓ src/lib/format-date.test.ts (4 tests) 9ms\n Test Files  1 passed (1)",
    start: thought + 1000,
    end: thought + 1900,
  },
  {
    command: "TZ=UTC npx vitest run src/lib/format-date.test.ts",
    output:
      " FAIL  src/lib/format-date.test.ts > formatDate > keeps the day of an evening event\nAssertionError: expected 'Mar 4' to be 'Mar 3'",
    failed: true,
    start: thought + 2000,
    end: thought + 3200,
  },
]

const sources = [
  {
    title: "Intl.DateTimeFormat | MDN",
    url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat",
  },
  { title: "Getting Started | vitest.dev", url: "https://vitest.dev/guide/" },
]

const sourcesAt = thought + 3300
const answerAt = sourcesAt + 1000

function ThinkingRow({ text, running }: { text: string; running: boolean }) {
  const [open, setOpen] = useState<boolean>()

  const line = (
    <TraceLine status={running ? "running" : undefined}>
      <TraceIcon>{running ? <Spinner /> : <CheckCircleIcon />}</TraceIcon>
      <TraceTitle>{running ? "Thinking" : "Thought for 3s"}</TraceTitle>
    </TraceLine>
  )

  if (text.length === 0) return line

  return (
    <TraceCollapsible open={open ?? running} onOpenChange={setOpen}>
      <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
      <TraceCollapsibleContent xstyle={styles.reasoning}>{text}</TraceCollapsibleContent>
    </TraceCollapsible>
  )
}

function CommandRow({
  command,
  output,
  failed = false,
  running,
}: {
  command: string
  output: string
  failed?: boolean
  running: boolean
}) {
  if (running) {
    return (
      <TraceLine status="running">
        <TraceIcon>
          <Spinner />
        </TraceIcon>
        <TraceTitle>Running {command}</TraceTitle>
      </TraceLine>
    )
  }

  return (
    <TraceCollapsible defaultOpen={failed}>
      <TraceCollapsibleTrigger>
        <TraceLine status={failed ? "error" : undefined}>
          <TraceIcon>{failed ? <WarningCircleIcon /> : <CheckCircleIcon />}</TraceIcon>
          <TraceTitle>
            {failed ? "Error running" : "Ran"} {command}
          </TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent>
        <CodeBlock defaultWrap>
          <Pre xstyle={failed && styles.error}>
            <code>{output}</code>
          </Pre>
        </CodeBlock>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}

function SourcesRow({ running }: { running: boolean }) {
  return (
    <TraceCollapsible>
      <TraceCollapsibleTrigger>
        <TraceLine status={running ? "running" : undefined}>
          <TraceIcon>{running ? <Spinner /> : <GlobeIcon />}</TraceIcon>
          <TraceTitle>
            {running ? "Using" : "Used"} {sources.length} sources
          </TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent>
        <Trace>
          {sources.map((source) => (
            <TraceLine
              key={source.url}
              render={<a href={source.url} target="_blank" rel="noreferrer" />}
            >
              <TraceIcon>
                <GlobeIcon />
              </TraceIcon>
              <TraceTitle>
                {source.title}
                <span {...stylex.props(states.srOnly)}> (opens in a new tab)</span>
              </TraceTitle>
              <TraceIcon>
                <ArrowUpRightIcon />
              </TraceIcon>
            </TraceLine>
          ))}
        </Trace>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}

export default function TraceDemo() {
  const [run, setRun] = useState(0)
  const [time, setTime] = useState(answerAt)
  const busy = time < answerAt

  useEffect(() => {
    if (!busy) return
    const timeout = setTimeout(() => setTime((elapsed) => Math.min(elapsed + tick, answerAt)), tick)
    return () => clearTimeout(timeout)
  }, [busy, time])

  return (
    <VStack align="start" justify="between" gap={4} minHeight="18rem" xstyle={widths.sm}>
      <VStack gap={4} width="100%">
        <Trace key={run}>
          <ThinkingRow
            text={reasoning.slice(0, Math.floor(time / charMs))}
            running={time < thought}
          />
          {commands
            .filter((step) => time >= step.start)
            .map((step) => (
              <CommandRow
                key={step.command}
                command={step.command}
                output={step.output}
                failed={step.failed}
                running={time < step.end}
              />
            ))}
          {time >= sourcesAt && <SourcesRow running={busy} />}
        </Trace>
        {!busy && (
          <Text render={<p />} size="sm">
            The formatter uses the machine's time zone, so in UTC an evening event moves to the next
            day. Pass the event's time zone to Intl.DateTimeFormat and the test passes in CI too.
          </Text>
        )}
      </VStack>
      {!busy && (
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            setRun((count) => count + 1)
            setTime(0)
          }}
        >
          Replay
        </Button>
      )}
    </VStack>
  )
}
```

`Trace` renders a stack of lines. A line holds an icon and a title, and can
also carry a description and a status. A line can open to reveal more detail,
act as a link, or be the trigger of a dialog or sheet. Every line has the same
shape, so reasoning, tool calls, sources and plans built from it look and
behave the same.

Use it for the steps an agent takes, such as calling a tool, running a
subagent or editing a file. Use [Marker](https://www.arene.style/docs/components/marker) for notes and
dividers between turns.

## Installation

**Command**

```bash
npx shadcn@latest add @arene/trace
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Collapsible](https://www.arene.style/docs/components/collapsible).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex @phosphor-icons/react clsx
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `state-styles.ts` from the same
   page. The trace also needs `interop.css`, which sizes the icons inside a line.

3. Install [Collapsible](https://www.arene.style/docs/components/collapsible), which an expanding line
   is built on, and [Shimmer](https://www.arene.style/docs/utilities/shimmer), which sweeps the title of
   a running line.

4. Paste this source into the file named in its title.

   ```tsx title="components/ui/trace.tsx"
   "use client"

   import { createContext, use, type ComponentProps } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"

   import {
     Collapsible,
     CollapsibleContent,
     CollapsibleTrigger,
     collapsibleStyles,
   } from "@/components/ui/collapsible"
   import { shimmerStyles } from "@/lib/shimmer"
   import { states } from "@/theme/states"
   import { color, duration, ease, font, leading, radius, space, text } from "@/theme/tokens.stylex"

   const styles = stylex.create({
     root: {
       display: "flex",
       flexDirection: "column",
       gap: space.s2,
       width: "100%",
       minWidth: 0,
       "--arene-icon-size": space.s4,
     },
     trigger: {
       display: "flex",
       width: "fit-content",
       maxWidth: "100%",
       minWidth: 0,
       borderRadius: radius.md,
       cursor: "pointer",
       "--arene-trace-line-color": { default: null, ":hover": color.foreground },
     },
     line: {
       display: "flex",
       alignItems: "center",
       gap: space.s2,
       width: "fit-content",
       maxWidth: "100%",
       minWidth: 0,
       borderRadius: radius.md,
       fontSize: text.sm,
       lineHeight: leading.sm,
       textAlign: "start",
       color: {
         default: `var(--arene-trace-line-color, ${color.mutedForeground})`,
         ":is(a, button):hover": color.foreground,
       },
       cursor: { default: null, ":is(a, button)": "pointer" },
       transitionProperty: "color",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
     },
     icon: {
       display: "flex",
       flexShrink: 0,
       alignItems: "center",
       justifyContent: "center",
       width: `var(--arene-icon-size, ${space.s4})`,
       height: `var(--arene-icon-size, ${space.s4})`,
       marginInlineStart: { default: `calc(-1 * ${space.s1})`, ":first-child": 0 },
     },
     title: {
       minWidth: 0,
       overflow: "hidden",
       textOverflow: "ellipsis",
       whiteSpace: "nowrap",
     },
     description: {
       flexShrink: 0,
       fontFamily: font.mono,
       fontSize: text.xs,
       lineHeight: leading.xs,
       color: `color-mix(in oklab, ${color.mutedForeground} 70%, transparent)`,
     },
     collapsible: { minWidth: 0 },
     content: {
       minWidth: 0,
       paddingBlockStart: space.s2,
       paddingBlockEnd: space.s1,
       paddingInlineStart: `calc(var(--arene-icon-size, ${space.s4}) / 2 - 1px)`,
     },
     contentInner: {
       minWidth: 0,
       borderInlineStartWidth: 1,
       borderInlineStartStyle: "solid",
       borderInlineStartColor: color.border,
       paddingInlineStart: space.s4,
       paddingInlineEnd: space.s1,
       fontSize: text.sm,
       lineHeight: leading.sm,
       color: color.mutedForeground,
       overflowWrap: "break-word",
     },
   })

   const statuses = stylex.create({
     running: {},
     error: { color: color.destructive },
     pending: { opacity: 0.6 },
   })

   const traceStyles = {
     base: styles.root,
     line: [styles.line, states.rowFocusRing],
     statuses,
     icon: styles.icon,
     title: styles.title,
     description: styles.description,
     content: styles.contentInner,
   }

   type TraceStatus = keyof typeof statuses

   const TraceLineContext = createContext<TraceStatus | undefined>(undefined)

   const TraceTriggerContext = createContext(false)

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   function Trace({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"div"> & Overrides) {
     const sx = stylex.props(styles.root, xstyle)
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "trace",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type TraceLineProps = useRender.ComponentProps<"span", { status: TraceStatus | undefined }> &
     Overrides & { status?: TraceStatus }

   function TraceLine({
     render,
     ref,
     status,
     style,
     xstyle,
     className,
     children,
     ...props
   }: TraceLineProps) {
     const inTrigger = use(TraceTriggerContext)
     const sx = stylex.props(traceStyles.line, status && statuses[status], xstyle)
     const element = useRender({
       defaultTagName: "span",
       render,
       ref,
       state: { status },
       props: {
         "data-slot": "trace-line",
         ...sx,
         ...props,
         className: clsx("arene-icons", sx.className, className),
         style: { ...sx.style, ...style },
         children: (
           <>
             {children}
             {inTrigger && (
               <TraceIcon>
                 <CaretRightIcon {...stylex.props(collapsibleStyles.chevronInline)} />
               </TraceIcon>
             )}
           </>
         ),
       },
     })
     return <TraceLineContext value={status}>{element}</TraceLineContext>
   }

   function TraceIcon({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"span"> & Overrides) {
     const sx = stylex.props(styles.icon, xstyle)
     return useRender({
       defaultTagName: "span",
       render,
       ref,
       props: {
         "data-slot": "trace-icon",
         "aria-hidden": "true",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function TraceTitle({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"span"> & Overrides) {
     const status = use(TraceLineContext)
     const sx = stylex.props(styles.title, status === "running" && shimmerStyles.base, xstyle)
     return useRender({
       defaultTagName: "span",
       render,
       ref,
       props: {
         "data-slot": "trace-title",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function TraceDescription({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"span"> & Overrides) {
     const sx = stylex.props(styles.description, xstyle)
     return useRender({
       defaultTagName: "span",
       render,
       ref,
       props: {
         "data-slot": "trace-description",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function TraceCollapsible({ xstyle, ...props }: ComponentProps<typeof Collapsible>) {
     return (
       <Collapsible data-slot="trace-collapsible" xstyle={[styles.collapsible, xstyle]} {...props} />
     )
   }

   function TraceCollapsibleTrigger({
     xstyle,
     children,
     ...props
   }: ComponentProps<typeof CollapsibleTrigger>) {
     return (
       <CollapsibleTrigger
         data-slot="trace-collapsible-trigger"
         xstyle={[styles.trigger, states.rowFocusRing, xstyle]}
         {...props}
       >
         <TraceTriggerContext value={true}>{children}</TraceTriggerContext>
       </CollapsibleTrigger>
     )
   }

   function TraceCollapsibleContent({
     xstyle,
     className,
     children,
     ...props
   }: ComponentProps<typeof CollapsibleContent>) {
     const sx = stylex.props(styles.contentInner, xstyle)
     return (
       <CollapsibleContent data-slot="trace-collapsible-content" xstyle={styles.content} {...props}>
         <div
           data-slot="trace-collapsible-content-inner"
           {...sx}
           className={clsx(sx.className, className)}
         >
           {children}
         </div>
       </CollapsibleContent>
     )
   }

   export {
     Trace,
     TraceCollapsible,
     TraceCollapsibleContent,
     TraceCollapsibleTrigger,
     TraceDescription,
     TraceIcon,
     TraceLine,
     TraceTitle,
     traceStyles,
     type TraceStatus,
   }
   ```

5. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
```

```tsx
<Trace>
  <TraceLine>
    <TraceIcon>
      <MagnifyingGlassIcon />
    </TraceIcon>
    <TraceTitle>Searched for timeZone</TraceTitle>
  </TraceLine>
</Trace>
```

For a line that reveals detail when it opens, wrap it in a `TraceCollapsible`:

```tsx
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
```

```tsx
<Trace>
  <TraceCollapsible>
    <TraceCollapsibleTrigger>
      <TraceLine>
        <TraceIcon>
          <TerminalIcon />
        </TraceIcon>
        <TraceTitle>Ran npx tsc --version</TraceTitle>
      </TraceLine>
    </TraceCollapsibleTrigger>
    <TraceCollapsibleContent>Version 7.0.2</TraceCollapsibleContent>
  </TraceCollapsible>
</Trace>
```

## Composition

```text
Trace
└── TraceLine
    ├── TraceIcon
    ├── TraceTitle
    ├── TraceDescription
    └── TraceIcon
```

A line that expands:

```text
Trace
└── TraceCollapsible
    ├── TraceCollapsibleTrigger
    │   └── TraceLine
    └── TraceCollapsibleContent
```

`TraceLine` is always the line. To make it a link or open a dialog, render it
as that element with `render`. A line rendered as an `a` or a `button` shows a
pointer, lights up on hover and shows a ring on keyboard focus:

```tsx
<TraceLine render={<a href="/docs" />}>…</TraceLine>
```

To make it expand, wrap it in `TraceCollapsibleTrigger`, which styles itself
and adds the chevron.

## Line

A `TraceLine` on its own is a step with no detail to show. It reads as plain
text and does not change on hover.

```tsx
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { GitBranchIcon } from "@phosphor-icons/react/dist/csr/GitBranch"

export default function TraceStatic() {
  return (
    <Trace xstyle={widths.sm}>
      <TraceLine>
        <TraceIcon>
          <GitBranchIcon />
        </TraceIcon>
        <TraceTitle>Created branch fix/event-time-zone</TraceTitle>
      </TraceLine>
    </Trace>
  )
}
```

## Status

Set `status` on `TraceLine` when a step is running, has failed or has not
started yet.

```tsx
import { Spinner } from "@/components/ui/spinner"
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { CheckCircleIcon } from "@phosphor-icons/react/dist/csr/CheckCircle"
import { CircleIcon } from "@phosphor-icons/react/dist/csr/Circle"
import { WarningCircleIcon } from "@phosphor-icons/react/dist/csr/WarningCircle"

export default function TraceStatus() {
  return (
    <Trace xstyle={widths.sm}>
      <TraceLine>
        <TraceIcon>
          <CheckCircleIcon />
        </TraceIcon>
        <TraceTitle>Ran npm ci</TraceTitle>
      </TraceLine>
      <TraceLine status="error">
        <TraceIcon>
          <WarningCircleIcon />
        </TraceIcon>
        <TraceTitle>Error running tsc --noEmit</TraceTitle>
      </TraceLine>
      <TraceLine status="running">
        <TraceIcon>
          <Spinner />
        </TraceIcon>
        <TraceTitle>Running npx vitest</TraceTitle>
      </TraceLine>
      <TraceLine status="pending">
        <TraceIcon>
          <CircleIcon />
        </TraceIcon>
        <TraceTitle>Run git push</TraceTitle>
      </TraceLine>
    </Trace>
  )
}
```

| Status      | Marks                                                                         |
| ----------- | ----------------------------------------------------------------------------- |
| none        | Finished work, such as "Ran npm ci".                                          |
| `"error"`   | Failed work. The title names the failure, as in "Error running tsc --noEmit". |
| `"running"` | Work under way, titled in the present tense, as in "Running npx vitest".      |
| `"pending"` | Work not yet started, such as a step in a plan: "Run git push".               |

An error line turns destructive and keeps that colour on hover. A pending line
is dimmed. A running line sweeps its title with
[`shimmerStyles.base`](https://www.arene.style/docs/utilities/shimmer). The icon is yours to choose;
the examples use a [Spinner](https://www.arene.style/docs/components/spinner) while a step runs.

## Description

A `TraceDescription` placed after the `TraceTitle` holds secondary text, such
as a diff stat, a duration or a count. It is set in the mono face at the
metadata size, and it does not truncate: the title gives way first.

```tsx
import { Trace, TraceDescription, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"
import { PencilSimpleIcon } from "@phosphor-icons/react/dist/csr/PencilSimple"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"

export default function TraceDescriptionDemo() {
  return (
    <Trace xstyle={widths.sm}>
      <TraceLine>
        <TraceIcon>
          <PencilSimpleIcon />
        </TraceIcon>
        <TraceTitle>Edited apps/web/src/features/events/format-event-date.ts</TraceTitle>
        <TraceDescription>+9 −3</TraceDescription>
      </TraceLine>
      <TraceLine>
        <TraceIcon>
          <TerminalIcon />
        </TraceIcon>
        <TraceTitle>Ran npx vitest run</TraceTitle>
        <TraceDescription>6s</TraceDescription>
      </TraceLine>
      <TraceLine>
        <TraceIcon>
          <MagnifyingGlassIcon />
        </TraceIcon>
        <TraceTitle>Searched for toLocaleDateString</TraceTitle>
        <TraceDescription>5 results</TraceDescription>
      </TraceLine>
    </Trace>
  )
}
```

## Collapsible

A line wrapped in a `TraceCollapsible` reveals more detail when it opens. The
`TraceLine` goes inside `TraceCollapsibleTrigger`, and the detail goes in
`TraceCollapsibleContent`. The trigger adds a chevron to the end of the line,
which turns when the row opens, and the content hangs under the title behind a
hairline guide.

```tsx
import { CodeBlock, Pre } from "@/components/ui/code-block"
import {
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"

export default function TraceCollapsibleDemo() {
  return (
    <TraceCollapsible xstyle={widths.sm}>
      <TraceCollapsibleTrigger>
        <TraceLine>
          <TraceIcon>
            <TerminalIcon />
          </TraceIcon>
          <TraceTitle>Ran npx tsc --version</TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent>
        <CodeBlock defaultWrap>
          <Pre>
            <code>{"$ npx tsc --version\nVersion 7.0.2"}</code>
          </Pre>
        </CodeBlock>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}
```

`TraceCollapsibleContent` mutes its text. A block with its own surface keeps
its own colour: a [Code Block](https://www.arene.style/docs/components/code-block) sets the foreground
colour on its panel, so the output in the examples is not muted.

## Open state

Rows start closed. Pass `defaultOpen` to `TraceCollapsible` for a row that
starts open, or pair `open` with `onOpenChange` to control it.

```tsx
"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { VStack } from "@/components/ui/stack"
import {
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"

function Output({ children }: { children: string }) {
  return (
    <CodeBlock defaultWrap>
      <Pre>
        <code>{children}</code>
      </Pre>
    </CodeBlock>
  )
}

export default function TraceOpen() {
  const [open, setOpen] = useState(false)

  return (
    <VStack align="start" gap={4} xstyle={widths.sm}>
      <TraceCollapsible defaultOpen>
        <TraceCollapsibleTrigger>
          <TraceLine>
            <TraceIcon>
              <TerminalIcon />
            </TraceIcon>
            <TraceTitle>Ran git status --short</TraceTitle>
          </TraceLine>
        </TraceCollapsibleTrigger>
        <TraceCollapsibleContent>
          <Output>{"$ git status --short\n M src/lib/format-date.ts"}</Output>
        </TraceCollapsibleContent>
      </TraceCollapsible>
      <TraceCollapsible open={open} onOpenChange={setOpen}>
        <TraceCollapsibleTrigger>
          <TraceLine>
            <TraceIcon>
              <TerminalIcon />
            </TraceIcon>
            <TraceTitle>Ran git log --oneline -2</TraceTitle>
          </TraceLine>
        </TraceCollapsibleTrigger>
        <TraceCollapsibleContent>
          <Output>
            {
              "$ git log --oneline -2\n3f2c1ab Show event times in the local zone\n9d81e0c Add the events list"
            }
          </Output>
        </TraceCollapsibleContent>
      </TraceCollapsible>
      <Button variant="outline" size="sm" onClick={() => setOpen(!open)}>
        {open ? "Hide" : "Show"} the git log
      </Button>
    </VStack>
  )
}
```

To keep a row open while it streams, unless the reader has toggled it, pass
`open ?? running`. The thinking row in the demo at the top of the page does
this: it opens while the reasoning streams in and closes when it ends, unless
the reader has opened or closed it themselves.

```tsx
const [open, setOpen] = useState<boolean>()

<TraceCollapsible open={open ?? running} onOpenChange={setOpen}>
  <TraceCollapsibleTrigger>
    <TraceLine status={running ? "running" : undefined}>…</TraceLine>
  </TraceCollapsibleTrigger>
  <TraceCollapsibleContent>{text}</TraceCollapsibleContent>
</TraceCollapsible>
```

## Link

Render the `TraceLine` as an anchor, or as your router's link component. For a
new tab, end the line with an arrow-up-right icon and add "(opens in a new tab)"
to the title, visually hidden with `states.srOnly`.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { states } from "@/theme/states"
import { widths } from "@/theme/widths"
import { ArrowUpRightIcon } from "@phosphor-icons/react/dist/csr/ArrowUpRight"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { FileTextIcon } from "@phosphor-icons/react/dist/csr/FileText"
import { GlobeIcon } from "@phosphor-icons/react/dist/csr/Globe"

export default function TraceLink() {
  return (
    <Trace xstyle={widths.sm}>
      <TraceLine render={<a href="#link" />}>
        <TraceIcon>
          <FileTextIcon />
        </TraceIcon>
        <TraceTitle>Read src/lib/format-date.test.ts</TraceTitle>
        <TraceIcon>
          <CaretRightIcon />
        </TraceIcon>
      </TraceLine>
      <TraceLine render={<a href="https://vitest.dev/guide/" target="_blank" rel="noreferrer" />}>
        <TraceIcon>
          <GlobeIcon />
        </TraceIcon>
        <TraceTitle>
          Getting Started | vitest.dev
          <span {...stylex.props(states.srOnly)}> (opens in a new tab)</span>
        </TraceTitle>
        <TraceIcon>
          <ArrowUpRightIcon />
        </TraceIcon>
      </TraceLine>
    </Trace>
  )
}
```

```tsx
<TraceLine render={<a href="https://vitest.dev/guide/" target="_blank" rel="noreferrer" />}>
  <TraceTitle>
    Getting Started
    <span {...stylex.props(states.srOnly)}> (opens in a new tab)</span>
  </TraceTitle>
  <TraceIcon>
    <ArrowUpRightIcon />
  </TraceIcon>
</TraceLine>
```

## Dialog

Render the `TraceLine` as the [Dialog](https://www.arene.style/docs/components/dialog)'s trigger. The
dialog handles its open state, Escape and returning focus. The trigger goes in
the line's `render`, not the other way round: a trigger expects to render a
native `button`, and the line is a `span` by default.

```tsx
import * as stylex from "@stylexjs/stylex"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { states } from "@/theme/states"
import { widths } from "@/theme/widths"
import { ArrowUpRightIcon } from "@phosphor-icons/react/dist/csr/ArrowUpRight"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { GlobeIcon } from "@phosphor-icons/react/dist/csr/Globe"

const results = [
  {
    title: "Intl.DateTimeFormat | MDN",
    url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat",
  },
  {
    title: "Date | MDN",
    url: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date",
  },
  { title: "Command-line API | nodejs.org", url: "https://nodejs.org/api/cli.html" },
]

export default function TraceDialog() {
  return (
    <Trace xstyle={widths.sm}>
      <Dialog>
        <TraceLine render={<DialogTrigger />}>
          <TraceIcon>
            <GlobeIcon />
          </TraceIcon>
          <TraceTitle>Searched the web for time zone handling</TraceTitle>
          <TraceIcon>
            <CaretRightIcon />
          </TraceIcon>
        </TraceLine>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Searched the web for time zone handling</DialogTitle>
            <DialogDescription>The response cites these three pages.</DialogDescription>
          </DialogHeader>
          <Trace>
            {results.map((result) => (
              <TraceLine
                key={result.url}
                render={<a href={result.url} target="_blank" rel="noreferrer" />}
              >
                <TraceIcon>
                  <GlobeIcon />
                </TraceIcon>
                <TraceTitle>
                  {result.title}
                  <span {...stylex.props(states.srOnly)}> (opens in a new tab)</span>
                </TraceTitle>
                <TraceIcon>
                  <ArrowUpRightIcon />
                </TraceIcon>
              </TraceLine>
            ))}
          </Trace>
        </DialogContent>
      </Dialog>
    </Trace>
  )
}
```

```tsx
<Dialog>
  <TraceLine render={<DialogTrigger />}>
    <TraceTitle>Searched the web for time zone handling</TraceTitle>
    <TraceIcon>
      <CaretRightIcon />
    </TraceIcon>
  </TraceLine>
  <DialogContent>…</DialogContent>
</Dialog>
```

## Sheet

The same shape as the dialog, with a [Sheet](https://www.arene.style/docs/components/sheet). A
[Drawer](https://www.arene.style/docs/components/drawer) or [Popover](https://www.arene.style/docs/components/popover) works
the same way.

```tsx
import * as stylex from "@stylexjs/stylex"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet"
import { VStack } from "@/components/ui/stack"
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { color, font, leading, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { FileMagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/FileMagnifyingGlass"

const styles = stylex.create({
  file: {
    fontFamily: font.mono,
    fontSize: text.xs,
    lineHeight: leading.xs,
    color: color.foreground,
  },
})

const files = [
  "apps/web/src/lib/docs.ts",
  "apps/web/src/config/site.ts",
  "apps/web/vite.config.ts",
  "apps/web/package.json",
]

export default function TraceSheet() {
  return (
    <Trace xstyle={widths.sm}>
      <Sheet>
        <TraceLine render={<SheetTrigger />}>
          <TraceIcon>
            <FileMagnifyingGlassIcon />
          </TraceIcon>
          <TraceTitle>Explored {files.length} files</TraceTitle>
          <TraceIcon>
            <CaretRightIcon />
          </TraceIcon>
        </TraceLine>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Explored {files.length} files</SheetTitle>
            <SheetDescription>Files read while preparing the response.</SheetDescription>
          </SheetHeader>
          <VStack render={<ul />} gap={2} paddingInline={4}>
            {files.map((file) => (
              <li key={file} {...stylex.props(styles.file)}>
                {file}
              </li>
            ))}
          </VStack>
        </SheetContent>
      </Sheet>
    </Trace>
  )
}
```

## Group

Put lines that sit next to each other in a `Trace`. It stacks them with a
small gap and gives every row the full width to truncate in.

```tsx
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { FileTextIcon } from "@phosphor-icons/react/dist/csr/FileText"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"

export default function TraceGroup() {
  return (
    <Trace xstyle={widths.sm}>
      <TraceLine>
        <TraceIcon>
          <MagnifyingGlassIcon />
        </TraceIcon>
        <TraceTitle>Searched for timeZone</TraceTitle>
      </TraceLine>
      <TraceLine>
        <TraceIcon>
          <FileTextIcon />
        </TraceIcon>
        <TraceTitle>Read src/lib/format-date.ts</TraceTitle>
      </TraceLine>
      <TraceLine>
        <TraceIcon>
          <TerminalIcon />
        </TraceIcon>
        <TraceTitle>Ran npx vitest run</TraceTitle>
      </TraceLine>
    </Trace>
  )
}
```

## Sources

A collapsible row whose content is a `Trace` of [link](#link) lines, one per
source the agent read.

```tsx
import * as stylex from "@stylexjs/stylex"
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { states } from "@/theme/states"
import { widths } from "@/theme/widths"
import { ArrowUpRightIcon } from "@phosphor-icons/react/dist/csr/ArrowUpRight"
import { GlobeIcon } from "@phosphor-icons/react/dist/csr/Globe"

const sources = [
  {
    title: "Intl.DateTimeFormat | MDN",
    href: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat",
  },
  {
    title: "Getting Started | vitest.dev",
    href: "https://vitest.dev/guide/",
  },
  {
    title: "Command-line API | nodejs.org",
    href: "https://nodejs.org/api/cli.html",
  },
]

export default function TraceSources() {
  return (
    <TraceCollapsible defaultOpen xstyle={widths.sm}>
      <TraceCollapsibleTrigger>
        <TraceLine>
          <TraceIcon>
            <GlobeIcon />
          </TraceIcon>
          <TraceTitle>Used {sources.length} sources</TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent>
        <Trace>
          {sources.map((source) => (
            <TraceLine
              key={source.href}
              render={<a href={source.href} target="_blank" rel="noreferrer" />}
            >
              <TraceIcon>
                <GlobeIcon />
              </TraceIcon>
              <TraceTitle>
                {source.title}
                <span {...stylex.props(states.srOnly)}> (opens in a new tab)</span>
              </TraceTitle>
              <TraceIcon>
                <ArrowUpRightIcon />
              </TraceIcon>
            </TraceLine>
          ))}
        </Trace>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}
```

## Nesting

A row's content can hold another `Trace`, so a summary expands into steps and a
step into its output. Derive the parent's title and status from the rows
inside it. Pass `keepMounted` to a `TraceCollapsibleContent` that holds rows, so
the rows inside keep their open state while the parent is closed.

```tsx
import { Badge } from "@/components/ui/badge"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { HStack } from "@/components/ui/stack"
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { widths } from "@/theme/widths"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { FileTextIcon } from "@phosphor-icons/react/dist/csr/FileText"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"

export default function TraceSteps() {
  return (
    <TraceCollapsible defaultOpen xstyle={widths.sm}>
      <TraceCollapsibleTrigger>
        <TraceLine status="running">
          <TraceTitle>Looking into the flaky date test</TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent keepMounted>
        <Trace>
          <TraceCollapsible>
            <TraceCollapsibleTrigger>
              <TraceLine>
                <TraceIcon>
                  <MagnifyingGlassIcon />
                </TraceIcon>
                <TraceTitle>Searched for the failing test name</TraceTitle>
              </TraceLine>
            </TraceCollapsibleTrigger>
            <TraceCollapsibleContent>
              <HStack gap={1.5} wrap="wrap">
                <Badge variant="secondary">vitest.dev</Badge>
                <Badge variant="secondary">developer.mozilla.org</Badge>
              </HStack>
            </TraceCollapsibleContent>
          </TraceCollapsible>
          <TraceLine render={<a href="#steps" />}>
            <TraceIcon>
              <FileTextIcon />
            </TraceIcon>
            <TraceTitle>Read the last ten CI runs</TraceTitle>
            <TraceIcon>
              <CaretRightIcon />
            </TraceIcon>
          </TraceLine>
          <TraceCollapsible>
            <TraceCollapsibleTrigger>
              <TraceLine status="running">
                <TraceIcon>
                  <MagnifyingGlassIcon />
                </TraceIcon>
                <TraceTitle>Searching for timeZone</TraceTitle>
              </TraceLine>
            </TraceCollapsibleTrigger>
            <TraceCollapsibleContent>
              <CodeBlock defaultWrap>
                <Pre>
                  <code>timeZone toLocaleDateString</code>
                </Pre>
              </CodeBlock>
            </TraceCollapsibleContent>
          </TraceCollapsible>
        </Trace>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}
```

## Whole turn

A full turn nests three levels: the turn, a summary, then the rows. Prose that
falls between steps goes between two `Trace` lists.

```tsx
import * as stylex from "@stylexjs/stylex"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceDescription,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace"
import { color } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
import { BrainIcon } from "@phosphor-icons/react/dist/csr/Brain"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { FileTextIcon } from "@phosphor-icons/react/dist/csr/FileText"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"

const styles = stylex.create({
  reasoning: { whiteSpace: "pre-wrap" },
  error: { color: color.destructive },
})

export default function TraceTurn() {
  return (
    <TraceCollapsible defaultOpen xstyle={widths.sm}>
      <TraceCollapsibleTrigger>
        <TraceLine status="error">
          <TraceTitle>Finished in 1m 38s with 1 error</TraceTitle>
        </TraceLine>
      </TraceCollapsibleTrigger>
      <TraceCollapsibleContent keepMounted>
        <VStack gap={2}>
          <Trace>
            <TraceCollapsible>
              <TraceCollapsibleTrigger>
                <TraceLine>
                  <TraceIcon>
                    <BrainIcon />
                  </TraceIcon>
                  <TraceTitle>Thought</TraceTitle>
                  <TraceDescription>12s</TraceDescription>
                </TraceLine>
              </TraceCollapsibleTrigger>
              <TraceCollapsibleContent xstyle={styles.reasoning}>
                I should run the tests and the type checker before I touch the formatter.
              </TraceCollapsibleContent>
            </TraceCollapsible>
            <TraceCollapsible defaultOpen>
              <TraceCollapsibleTrigger>
                <TraceLine status="error">
                  <TraceIcon>
                    <TerminalIcon />
                  </TraceIcon>
                  <TraceTitle>Ran 2 checks, 1 with errors</TraceTitle>
                </TraceLine>
              </TraceCollapsibleTrigger>
              <TraceCollapsibleContent keepMounted>
                <Trace>
                  <TraceLine>
                    <TraceIcon>
                      <TerminalIcon />
                    </TraceIcon>
                    <TraceTitle>Ran npx vitest run</TraceTitle>
                  </TraceLine>
                  <TraceCollapsible>
                    <TraceCollapsibleTrigger>
                      <TraceLine status="error">
                        <TraceIcon>
                          <TerminalIcon />
                        </TraceIcon>
                        <TraceTitle>Error running npx tsc --noEmit</TraceTitle>
                      </TraceLine>
                    </TraceCollapsibleTrigger>
                    <TraceCollapsibleContent>
                      <CodeBlock defaultWrap>
                        <Pre xstyle={styles.error}>
                          <code>
                            {
                              "src/lib/format-date.ts(14,5): error TS2322: Type 'string | undefined' is not assignable to type 'string'."
                            }
                          </code>
                        </Pre>
                      </CodeBlock>
                    </TraceCollapsibleContent>
                  </TraceCollapsible>
                </Trace>
              </TraceCollapsibleContent>
            </TraceCollapsible>
          </Trace>
          <Text render={<p />}>The tests pass and the types do not. Reading the formatter.</Text>
          <Trace>
            <TraceLine render={<a href="#turn" />}>
              <TraceIcon>
                <FileTextIcon />
              </TraceIcon>
              <TraceTitle>Read src/lib/format-date.ts</TraceTitle>
              <TraceIcon>
                <CaretRightIcon />
              </TraceIcon>
            </TraceLine>
          </Trace>
        </VStack>
      </TraceCollapsibleContent>
    </TraceCollapsible>
  )
}
```

## Accessibility

`Trace` does not add any roles. A line takes its semantics from whatever
element wraps it.

- Outside any wrapper, a `TraceLine` renders a `span`. Screen readers read it
  as plain text, and keyboard focus skips it.
- Inside a `TraceCollapsibleTrigger` it is the content of a button with
  `aria-expanded`. Rendered as a link, or as the trigger of a dialog or sheet,
  it is that element, with its keyboard and focus behaviour.
- `TraceIcon` is hidden from assistive technology, so `TraceTitle` is the
  accessible name. Write it as a sentence that says what happened, such as
  "Edited format-date.ts", not just "format-date.ts".
- Status is shown with colour and motion, so put it in the title too: "Running
  tsc --noEmit" while it runs, "Error running tsc --noEmit" when it fails.
- For a line that changes from running to done while it streams, pass
  `role="status"` to the line, so assistive technology announces the new
  title. The line has to stay mounted, because a live region announces changes
  inside it, not a region that replaces it, and it cannot sit in a trigger,
  whose content is the button's name. Leave the role off the `Trace`: a status
  region is read whole on every change, so when its rows stream detail, like
  the reasoning in the demo at the top of the page, each chunk reads the list
  again. Inside a [Message Scroller](https://www.arene.style/docs/components/message-scroller), the
  transcript's log announces each row when it is added.
- When the reader prefers reduced motion, a running title does not shimmer.
  Its text still describes the work in progress.

## API reference

Pass `render` to replace a part's element or compose it with another component.
Every part also takes `xstyle` and `className`. `Trace`, `TraceLine`,
`TraceIcon`, `TraceTitle` and `TraceDescription` take `style` as real inline
CSS, merged over the compiled styles.

### Trace

A `div` that stacks its rows.

### TraceLine

One line: icons, a title and a description. It is a `span`, so it is not a
button or a tab stop until `render` makes it an `a` or a `button`.

| Prop     | Type                                | Default |
| -------- | ----------------------------------- | ------- |
| `status` | `"running" \| "error" \| "pending"` | —       |

### TraceIcon

A decorative icon slot, hidden from assistive technology. Before the title it
names the action; after it, it is the indicator, and it sits closer to the text
before it.

### TraceTitle

One sentence on one line. It truncates, and it shimmers while its line is
running.

### TraceDescription

Text that follows the title, such as a duration or a count. It does not
truncate.

### TraceCollapsible

A row that expands. It wraps [Collapsible](https://www.arene.style/docs/components/collapsible) and
accepts its props.

| Prop           | Type                               | Default |
| -------------- | ---------------------------------- | ------- |
| `open`         | `boolean`                          | —       |
| `defaultOpen`  | `boolean`                          | `false` |
| `onOpenChange` | `(open: boolean, details) => void` | —       |

### TraceCollapsibleTrigger

The button that toggles the row. Put a `TraceLine` inside it; the line
adds the chevron. It wraps `CollapsibleTrigger` and accepts its props.

### TraceCollapsibleContent

The panel an expanding row reveals. It wraps `CollapsibleContent` and accepts
its props.

| Prop          | Type      | Default |
| ------------- | --------- | ------- |
| `keepMounted` | `boolean` | `false` |

`xstyle` and `className` apply to the inner element that draws the guide line,
and `style` to the animated panel.

### traceStyles

The style map behind the component, exported so you can apply the same styles
to any element.

| Key           | Description                                                       |
| ------------- | ----------------------------------------------------------------- |
| `base`        | The stacked list                                                  |
| `line`        | The row: icon gap, type, the muted colour, link and button styles |
| `statuses`    | One entry per `status`, keyed by its name                         |
| `icon`        | The icon slot                                                     |
| `title`       | The truncating title                                              |
| `description` | The mono metadata after the title                                 |
| `content`     | The indented, guide-lined detail of an expanding row              |

### Data attributes

| Attribute                                     | On                  | Effect                     |
| --------------------------------------------- | ------------------- | -------------------------- |
| `data-slot="trace"`                           | the root            | Targets the list           |
| `data-slot="trace-line"`                      | the line            | Targets a line             |
| `data-status`                                 | the line            | Reflects the `status` prop |
| `data-slot="trace-icon"`                      | the icon slot       | Targets an icon            |
| `data-slot="trace-title"`                     | the title           | Targets the title          |
| `data-slot="trace-description"`               | the description     | Targets the description    |
| `data-slot="trace-collapsible"`               | an expanding row    | Targets the row            |
| `data-slot="trace-collapsible-trigger"`       | its trigger         | Targets the button         |
| `data-slot="trace-collapsible-content"`       | its animated panel  | Targets the panel          |
| `data-slot="trace-collapsible-content-inner"` | the guide-lined box | Targets the detail         |

### CSS variables

| Variable            | On       | Effect                                                                            |
| ------------------- | -------- | --------------------------------------------------------------------------------- |
| `--arene-icon-size` | the root | The icon size, `1rem`. The guide under an expanding row follows the icon's centre |

Set it with `style` on `Trace`, or on a `TraceCollapsible` to resize one row.

Cast the object to `CSSProperties`, as [Sidebar](https://www.arene.style/docs/components/sidebar#width)
does. `xstyle` rejects a StyleX entry that sets only custom properties.
