# Subagents

> The runs an agent hands to other agents, one line per run. Handles parallel runs, stop and retry, and a summary once each run is done.

Canonical: https://hextaui.com/blocks/subagents
Last updated: 2026-10-29

## Overview

Coding agents like Claude Code, Codex and Cursor hand parts of a job to other agents, often several at once. Subagents gives each of those runs one line that reads like a person delegating: the agent, its task in plain words, a live label of what it’s doing (“Reading auth/session.ts”), a timer and how many tools it has used.

Runs start folded, so a busy reply stays short. Each line keeps saying what its run is doing, and opening it shows the tool calls streaming into a short window that follows the newest step. When a run finishes, its line turns into a past-tense summary such as “Mapped the token refresh flow · 14 tool uses · 32s”, with the first sentence of its report underneath and the full report inside.

Parallel runs share a header that reads “Running 3 agents” with a progress bar, then “3 agents finished in 48s”. Runs can be queued, running, done, failed with a reason and Retry, stopped, or left running in the background. getSubagentFromPart reads an AI SDK tool whose output streams the subagent’s own messages, and the nested steps render with Tool Calls and the report with Markdown.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/subagents
```

## Usage

### With the AI SDK

Make the subagent a tool whose execute is an async generator that yields the subagent’s UI messages, so each one arrives as a preliminary output. getSubagentFromPart turns that part into a run, nested tool parts into Tool Calls steps, and the text after the last tool call into the report. Keep the tool on the server and the rendering in a client component.

```tsx
import type * as React from "react"

import { execFile } from "node:child_process"
import { readFile } from "node:fs/promises"
import { promisify } from "node:util"
import { useChat } from "@ai-sdk/react"
import {
  isToolUIPart,
  readUIMessageStream,
  stepCountIs,
  tool,
  ToolLoopAgent,
  type UIMessage,
} from "ai"
import { z } from "zod"

import { CodeBlock } from "../code-block/code-block"
import type { SubagentProps } from "@/components/blocks/subagents/subagent"
import { getSubagentFromPart } from "@/components/blocks/subagents/subagent-part"
import { Subagents } from "@/components/blocks/subagents/subagents"

const run = promisify(execFile)

const explorer = new ToolLoopAgent({
  model: "anthropic/claude-haiku-4.5",
  instructions:
    "You explore a codebase to answer one question. Read only what you need, then finish with a short report that names the files.",
  stopWhen: stepCountIs(40),
  tools: {
    grep: tool({
      inputSchema: z.object({ pattern: z.string() }),
      execute: async ({ pattern }) =>
        (await run("rg", ["-n", "--max-count", "20", pattern])).stdout,
    }),
    readFile: tool({
      inputSchema: z.object({ path: z.string() }),
      execute: async ({ path }) => ({ content: await readFile(path, "utf8") }),
    }),
  },
})

export const explore = tool({
  description:
    "Hand a self-contained question about the codebase to an explorer agent. Call it several times in one step to explore in parallel.",
  inputSchema: z.object({
    description: z.string().describe("The task in 3 to 6 words"),
    prompt: z.string().describe("Everything the agent needs to know"),
  }),
  execute: async function* ({ prompt }, { abortSignal }) {
    const result = await explorer.stream({ prompt, abortSignal })
    yield* readUIMessageStream({
      stream: result.toUIMessageStream({
        messageMetadata: () => ({ model: "Haiku 4.5" }),
      }),
    })
  },
  toModelOutput: ({ output }) => {
    const report = output?.parts.findLast((part) => part.type === "text")
    return { type: "text", value: report?.text ?? "The agent found nothing." }
  },
})

function AssistantMessage({
  message,
  streaming,
  onStopAll,
}: {
  message: UIMessage
  streaming: boolean
  onStopAll: () => void
}) {
  const blocks: (React.ReactNode | SubagentProps[])[] = []

  message.parts.forEach((part, index) => {
    if (isToolUIPart(part) && part.type === "tool-explore") {
      const run: SubagentProps = getSubagentFromPart(part, {
        stopped: !streaming,
        describeTool: (child) =>
          child.state === "output-available" && child.type === "tool-readFile"
            ? {
                content: (
                  <CodeBlock
                    code={String((child.output as { content: string }).content)}
                    filename={String((child.input as { path: string }).path)}
                    lineNumbers
                    collapseAfter={10}
                  />
                ),
              }
            : undefined,
      })
      const last = blocks.at(-1)
      if (Array.isArray(last)) last.push(run)
      else blocks.push([run])
    } else if (part.type === "text") {
      blocks.push(<p key={index}>{part.text}</p>)
    }
  })

  return (
    <div className="flex flex-col gap-4">
      {blocks.map((block, index) =>
        Array.isArray(block) ? (
          <Subagents key={block[0].id} runs={block} onStopAll={onStopAll} />
        ) : (
          <div key={index}>{block}</div>
        )
      )}
    </div>
  )
}

export function Chat() {
  const { messages, status, stop } = useChat()
  const busy = status === "submitted" || status === "streaming"

  return messages.map((message, index) =>
    message.role === "assistant" ? (
      <AssistantMessage
        key={message.id}
        message={message}
        streaming={busy && index === messages.length - 1}
        onStopAll={stop}
      />
    ) : null
  )
}
```

### Parallel runs

Pass several runs to Subagents for one header with live progress and Stop all. Wire onStop and onRetry to whatever runs the agents, and the row’s button switches between them as the run’s status changes.

```tsx
"use client"

import * as React from "react"

import type { SubagentProps } from "@/components/blocks/subagents/subagent"
import { Subagents } from "@/components/blocks/subagents/subagents"

const initialRuns: SubagentProps[] = [
  {
    id: "sessions",
    agent: "Explore",
    task: "Trace how sessions are created",
    status: "done",
    duration: 14,
    toolUses: 5,
    preview: "Sessions live in the sid cookie for 7 days.",
  },
  {
    id: "refresh",
    agent: "Explore",
    task: "Map the token refresh flow",
    status: "running",
    calls: [
      { id: "a", kind: "read", status: "done", subject: "middleware.ts" },
      { id: "b", kind: "read", status: "running", subject: "lib/auth/refresh.ts" },
    ],
  },
  {
    id: "changes",
    agent: "General",
    task: "Check recent auth changes",
    status: "failed",
    error: "The model was overloaded and stopped responding.",
  },
]

export function Delegation() {
  const [runs, setRuns] = React.useState(initialRuns)
  const update = (id: string, status: SubagentProps["status"]) =>
    setRuns((current) =>
      current.map((run) =>
        run.id === id ? { ...run, status, error: undefined } : run
      )
    )

  return (
    <Subagents
      runs={runs.map((run) => ({
        ...run,
        onStop: () => update(run.id, "stopped"),
        onRetry: () => update(run.id, "running"),
      }))}
    />
  )
}
```

### From stored data

Render a finished run from history with plain props. A stored duration replaces the live timer, and the report stays one click away.

```tsx
import { Subagent } from "@/components/blocks/subagents/subagent"

const report = `Sessions are created by \`createSession()\` in \`lib/auth/session.ts\`.

- The \`sid\` cookie lasts **7 days**.
- The token inside it expires after **15 minutes**, so refresh keeps people signed in.`

export function SessionsRun() {
  return (
    <Subagent
      id="sessions"
      agent="Explore"
      task="Trace how sessions are created"
      model="Haiku 4.5"
      status="done"
      duration={14}
      calls={[
        { id: "1", kind: "search", status: "done", subject: "createSession", meta: "4 results" },
        { id: "2", kind: "read", status: "done", subject: "lib/auth/session.ts" },
        { id: "3", kind: "read", status: "done", subject: "lib/auth/cookies.ts" },
      ]}
      result={report}
    />
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `Subagents` | A group of runs with a summary header, progress, Stop all and announcements. |
| `Subagent` | One run: status mark, agent, task, live label, tool count, timer and its Stop or Retry button. |
| `SubagentMark` | The status mark on its own: an orb while running, then a check, alert or stop icon. |
| `getSubagentFromPart` | Maps an AI SDK tool part with streamed subagent messages to a run. |

## API reference

### Subagents

Also accepts every section prop except children. One run renders without the header.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `runs` | `SubagentProps[]` | – | Runs in the order they were started. They keep their place as they finish. |
| `label` | `string` | `"Subagents"` | Names the region and its progress bar. |
| `duration` | `number` | – | Stored total seconds, for history. Defaults to the time measured while the runs worked. |
| `defaultOpen` | `boolean` | `true` | Start with the runs listed under the header. |
| `onStopAll` | `() => void` | – | Called from Stop all. Without it, Stop all calls each running run’s onStop. |

### Subagent

Also accepts every div prop except children.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | – | Stable id, usually the toolCallId. |
| `task` | `string` | – | What the agent was asked to do, in a few words: “Map the token refresh flow”. |
| `status` | `SubagentStatus` | – | queued, running, done, failed or stopped. |
| `agent` | `string` | – | The agent’s type or name, such as Explore or Plan. |
| `title` | `string` | – | Replaces the task on the line while the run works. |
| `doneTitle` | `string` | – | The line once done. Defaults to the task in the past tense when its first word is a known verb. |
| `prompt` | `string` | – | The full instructions, shown at the top when opened. |
| `calls` | `ToolCallProps[]` | – | The run’s steps, rendered with Tool Calls. |
| `activity` | `string` | – | Replaces the live label, which otherwise comes from the newest busy step. |
| `result` | `string` | – | The final report, as Markdown. |
| `resultStreaming` | `boolean` | – | The report is still arriving. |
| `preview` | `string` | – | One line for the collapsed run. Defaults to the report’s first sentence. |
| `error` | `string` | – | Why the run failed, shown on the line and in full when opened. |
| `toolUses` | `number` | – | Overrides the count, which defaults to the number of calls. |
| `model` | `string` | – | Shown as a badge on wider screens. |
| `duration` | `number` | – | Stored seconds, for history. |
| `startedAt` | `number` | – | When a run that is already working started, in milliseconds, so the timer doesn’t restart on mount. |
| `background` | `boolean` | – | The run keeps working while the chat goes on. It shows a Background badge and stays folded. |
| `defaultOpen` | `boolean` | `false` | Start the run open to its tool calls and report. |
| `onStop` | `() => void` | – | Shows Stop while the run is queued or running. |
| `onRetry` | `() => void` | – | Shows Retry once the run failed or was stopped. |

### getSubagentFromPart(part, options)

Returns a run from a tool part. Pass the result straight to Subagent or into Subagents’ runs.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `part` | `ToolUIPart \| DynamicToolUIPart` | – | The subagent’s tool part. Its output is a UI message whose parts hold reasoning, tool calls and text. |
| `options.stopped` | `boolean` | `false` | The chat stopped, so an unfinished run reads Stopped. |
| `options.describeTool` | `(part) => Partial<ToolCallProps>` | – | Adds a kind, subject or view per nested tool. Common names like readFile, grep and bash are guessed for you. |
| `options.agent` | `string` | – | Agent name. Defaults to subagent_type in the input, then the tool name. |
| `options.model` | `string` | – | Model badge. Defaults to model in the message metadata. |

## Keyboard

| Key | Action |
| --- | --- |
| `Enter` `Space` | Opens or closes a run, or the list under the group header. |
| `Tab` | Moves from a run to its Stop or Retry button, and from the header to Stop all. |

## Accessibility

- Each run’s header is a button with aria-expanded whose name reads the agent, task, live label, tool count and time.
- The group is a labelled region with aria-busy while agents work. A polite live region announces when a run starts again, finishes, fails or stops, and then the group summary. Tool steps and timer ticks stay quiet.
- Stop and Retry are real buttons named after their run, such as “Stop Explore: Map the token refresh flow”. When a button goes away, focus moves back to the run’s header.
- Status is never color alone: each state has its own mark and wording. With reduced motion, the orb holds still and lines change without sliding.

## Built with

The free HextaUI components Subagents is made from. Each one installs on its own.

- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Collapsible](https://hextaui.com/docs/collapsible) - A panel that shows and hides with height motion you can reverse mid-way, without jumping the layout.
- [Progress](https://hextaui.com/docs/progress) - A bar or ring that shows how far a task has come, eases between updates and slides while the total is unknown.
- [Spinner](https://hextaui.com/docs/spinner) - A loading indicator with Apple-style ticks or a breathing ring that can wait before showing and stay long enough not to flicker.
- [Tooltip](https://hextaui.com/docs/tooltip) - A short hint on hover or keyboard focus that opens after a brief rest, switches instantly between neighbours and shows shortcuts.

## Code

7 files, added to components/blocks/subagents.
