Skip to content

Test Results

Summarises a test run by suite and by test, and opens the error of each failure.

Run the checkout tests.
charges the saved card
Expected 2 charge attempts, received 1

  at Object.<anonymous> (src/payment.test.ts:58:22)

One test failed. The payment client does not retry a declined card, so the second charge attempt never happens.

Installation

pnpm dlx shadcn@latest add @silkware/ai-test-results

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/test-results.tsx. The file also needs @/lib/ai:

components/ai-elements/test-results.tsx
"use client"
import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import {  CheckIcon,  CircleDashedIcon,  FileCodeIcon,  FlaskConicalIcon,  XIcon,} 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 Test = {  name: string  status: "passed" | "failed" | "skipped"  error?: string}
type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    runTests: {      input: { command: string }      output: { suites: { name: string; tests: Test[] }[] }    }  }>
type ToolPart = Extract<ChatMessage["parts"][number], { type: "tool-runTests" }>
const chat = createChat<ChatMessage>()  .user("Run the checkout tests.")  .assistant(({ writer }) => {    writer      .tool("runTests", { input: { command: "pnpm test checkout" } })      .sleep(1500)      .output({        suites: [          {            name: "cart.test.ts",            tests: [              { name: "adds an item", status: "passed" },              { name: "removes an item", status: "passed" },              { name: "applies a discount code", status: "passed" },            ],          },          {            name: "payment.test.ts",            tests: [              { name: "charges the saved card", status: "passed" },              {                name: "retries a declined card",                status: "failed",                error: `Expected 2 charge attempts, received 1
  at Object.<anonymous> (src/payment.test.ts:58:22)`,              },            ],          },        ],      })    writer.text(      "One test failed. The payment client does not retry a declined card, so the second charge attempt never happens."    )  })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function countTests(tests: Test[]) {  return {    total: tests.length,    failed: tests.filter((test) => test.status === "failed").length,    skipped: tests.filter((test) => test.status === "skipped").length,  }}
function formatCounts({  total,  failed,  skipped,}: ReturnType<typeof countTests>) {  return [    `${total} tests`,    failed > 0 && `${failed} failed`,    skipped > 0 && `${skipped} skipped`,  ]    .filter(Boolean)    .join(", ")}
function TestRow({ test }: { test: Test }) {  if (test.status === "failed") {    return (      <TraceCollapsible defaultExpanded>        <TraceCollapsibleTrigger>          <TraceLine status="error">            <TraceIcon>              <XIcon />            </TraceIcon>            <TraceTitle>{test.name}</TraceTitle>          </TraceLine>        </TraceCollapsibleTrigger>        <TraceCollapsibleContent>          <CodeBlock size="sm">            <CodeBlockContent wrap className="max-h-64">              {test.error}            </CodeBlockContent>          </CodeBlock>        </TraceCollapsibleContent>      </TraceCollapsible>    )  }
  return (    <TraceLine>      <TraceIcon>        {test.status === "skipped" ? <CircleDashedIcon /> : <CheckIcon />}      </TraceIcon>      <TraceTitle>        {test.status === "skipped" ? `Skipped ${test.name}` : test.name}      </TraceTitle>    </TraceLine>  )}
function TestResultsRow({  part,  streaming,}: {  part: ToolPart  streaming: boolean}) {  const command = part.input?.command
  if (part.state !== "output-available") {    const running = streaming && part.state !== "output-error"
    return (      <TraceLine status={running ? "running" : "error"}>        <TraceIcon>          <FlaskConicalIcon />        </TraceIcon>        <TraceTitle>          {running ? "Running" : "Failed to run"} {command}        </TraceTitle>      </TraceLine>    )  }
  const { suites } = part.output  const summary = countTests(suites.flatMap((suite) => suite.tests))
  return (    <TraceCollapsible defaultExpanded={summary.failed > 0}>      <TraceCollapsibleTrigger>        <TraceLine status={summary.failed > 0 ? "error" : undefined}>          <TraceIcon>            <FlaskConicalIcon />          </TraceIcon>          <TraceTitle>Ran {formatCounts(summary)}</TraceTitle>        </TraceLine>      </TraceCollapsibleTrigger>      <TraceCollapsibleContent>        <Trace>          {suites.map((suite) => {            const counts = countTests(suite.tests)
            return (              <TraceCollapsible                key={suite.name}                defaultExpanded={counts.failed > 0}              >                <TraceCollapsibleTrigger>                  <TraceLine status={counts.failed > 0 ? "error" : undefined}>                    <TraceIcon>                      <FileCodeIcon />                    </TraceIcon>                    <TraceTitle>                      {suite.name}, {formatCounts(counts)}                    </TraceTitle>                  </TraceLine>                </TraceCollapsibleTrigger>                <TraceCollapsibleContent>                  <Trace>                    {suite.tests.map((test) => (                      <TestRow key={test.name} test={test} />                    ))}                  </Trace>                </TraceCollapsibleContent>              </TraceCollapsible>            )          })}        </Trace>      </TraceCollapsibleContent>    </TraceCollapsible>  )}
export function TestResultsDemo() {  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-runTests"        )        const text = getMessageText(message)
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {tools.length > 0 && (                <Trace>                  {tools.map((part) => (                    <TestResultsRow                      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

The result is three levels of collapsible: the run, each suite and each failed test. The run and a suite open by default when they hold a failure, and a passing suite stays closed.

import { CheckIcon, FlaskConicalIcon, XIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
<TraceCollapsible defaultExpanded={summary.failed > 0}>  <TraceCollapsibleTrigger>    <TraceLine status={summary.failed > 0 ? "error" : undefined}>      <TraceIcon>        <FlaskConicalIcon />      </TraceIcon>      <TraceTitle>Ran {formatCounts(summary)}</TraceTitle>    </TraceLine>  </TraceCollapsibleTrigger>  <TraceCollapsibleContent>    <Trace>{suites}</Trace>  </TraceCollapsibleContent></TraceCollapsible>

formatCounts writes the line as words: "5 tests, 1 failed". A skipped test is listed with the word "Skipped" in front of its name.

Examples

Suites

Two suites with failures and a skipped test. A suite with a failure is open, and each failed test holds its error message in a code block.

creates a user
Skipped deletes a user
connects to the database

All passed

When nothing failed, the whole result stays closed: one line with the count. The person opens it only if they want to see the names.

AI SDK

A test run is a tool call. The input is the command and the output is the structure of the result:

import type { UIDataTypes, UIMessage } from "ai"
type Test = {  name: string  status: "passed" | "failed" | "skipped"  error?: string}
type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    runTests: {      input: { command: string }      output: { suites: { name: string; tests: Test[] }[] }    }  }>

Render by state. While the call has no output, show a running line; when it has output, count the tests and render the suites:

if (part.state !== "output-available") {  const running = streaming && part.state !== "output-error"
  return (    <TraceLine status={running ? "running" : "error"}>      <TraceIcon>        <FlaskConicalIcon />      </TraceIcon>      <TraceTitle>        {running ? "Running" : "Failed to run"} {part.input?.command}      </TraceTitle>    </TraceLine>  )}
const { suites } = part.output

A run that could not start (a missing config, a crash) is output-error and is different from a run with failed tests, which is output-available. Show both as failures, with different words.

On the server, parse your runner's JSON report into this shape inside execute, and return it. Return only what the person reads: names, statuses and the error text of failures.

Scripted streams in development

const chat = createChat<ChatMessage>()  .user("Run the checkout tests.")  .assistant(({ writer }) => {    writer      .tool("runTests", { input: { command: "pnpm test checkout" } })      .sleep(1500)      .output({ suites })  })

Accessibility

KeyAction
EnterOpens or closes the focused run, suite or failed test.
SpaceOpens or closes the focused run, suite or failed test.
TabMoves focus to the next line that can open, or into the error block of an open test: the block is focusable so it can be scrolled.

The composed components provide:

  • Real buttons with aria-expanded for every level that opens, each with a visible focus ring.
  • A code block for each error message.

You provide:

  • The outcome of each test in words. A failed test has the cross icon and the crimson colour, and its suite title says "1 failed". A skipped test says "Skipped" in its title. A passed test has only the check icon, which is decoration: a suite that lists no failures has passed.
  • Counts in every title, so a collapsed level still says how it went.
  • Error text that stands alone: the assertion and the location, not only a stack.

Guidelines

When to use

  • When the agent ran a test suite and the person needs to know whether it passed and what failed.
  • To show the exact error of each failure, next to the test that produced it.

When not to use

  • For the raw output of the test command. Use Terminal.
  • For a crash with a stack trace. Use Stack Trace.
  • For a checklist the agent works through. Use Queue.

Content

  • Lead with the count: "Ran 7 tests, 2 failed". Say "all passed" when none failed.
  • Name tests by what they check: "charges the saved card", not "test_3".
  • Show the error of a failed test in full, and keep the location in it.
  • Do not hide skipped tests. A skip is a decision someone made, and the person may want to see it.
Do

Open the failures and keep passing suites closed, with the count in every title.

Don’t

Don’t report "Tests failed" without which test and why. The person cannot act on it.

Human in the loop

  • A test run is safe to start without asking. A run against a real database, a paid API or a shared environment is not; ask first with Confirmation.
  • Do not let the agent present a failing run as a success. The line shows the failure count, and the message says what the agent will do about it.
  • If the agent changes a test or its expected value to make a run pass, say so, and show the change. A person must be able to see that a test was edited.
  • Keep the result in the transcript, so the person can compare the run before and after a fix.

Composition

ComponentWhat it does here
TraceLays out the run, suites and tests, and carries the running and error status.
Code BlockShows the error message of a failed test.
MessagePlaces the conversation in turns.
BubbleWraps the person's own message.
ButtonThe replay control of the demo.

components/ai-elements/test-results.tsx exports TestResultsDemo, a scripted chat that calls runTests and renders its output with TestResultsRow, TestRow, countTests and formatCounts. Copy those into your app and replace the scripted chat with useChat against your route.