# AI human handoff

> In-chat escalation card with live queue countdown, shared context summary, support avatar stack, cancel option, and specialist join state.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-handoff`
- File: `src/components/haze/blocks/ai-handoff.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-handoff

## Use when
- Transferring an AI support thread to a human billing or account specialist with visible queue progress
- Showing users the exact account facts shared with the incoming agent for transparency
- Allowing users to cancel escalation and stay with the AI assistant before a specialist connects

## Avoid when
- Presenting a general multi-turn AI chat interface without live queue escalation; use ai-chat or chat-thread
- Connecting an external API integration or OAuth workspace rather than a human agent; use ai-connect

## Alternatives
- [ai-chat](https://hazeui.com/blocks/ai-chat.md)
- [ai-connect](https://hazeui.com/blocks/ai-connect.md)
- [chat-thread](https://hazeui.com/ui/chat-thread.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-handoff" | no | Unique prefix for the section heading and aria-labelledby reference. |
| heading | `string` | "Human specialist handoff" | no | Screen-reader section heading for landmark navigation. |
| userPrompt | `string` | "I got charged twice for October" | no | User message triggering escalation to a human specialist. |
| assistantReply | `string` | "I can see both charges. Refunds need someone on the billing team..." | no | Assistant reply confirming escalation and context transfer. |
| department | `string` | "Billing" | no | Target support queue name displayed in the card header. |
| specialistName | `string` | "Tessa" | no | Name of the human specialist who joins when the queue reaches zero. |
| specialistRole | `string` | "Billing specialist" | no | Role subtitle shown on the specialist arrival banner. |
| specialistMessage | `string` | "Hi! I can see both $24.00 charges on INV-2291..." | no | Opening message from the human specialist after joining. |
| waitEstimate | `string` | "Usually replies in about 2 min" | no | Typical response wait estimate displayed beside the team initials stack. |
| contextItems | `string[]` | 3 factual account summary items | no | Bullet points explaining what context is passed to the human specialist. |
| teamInitials | `string[]` | ["N", "T", "A"] | no | Support team initials rendered in the overlapping avatar stack. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Queue position updates (3rd, 2nd, 1st, Connected), cancellations, and specialist arrival are announced politely through a dedicated role="status" live region.
- Cancelling handoff or rejoining the queue keeps keyboard focus on the next available action without trapping or losing focus.
- Key Tab: Move to Keep chatting with AI during queuing, Rejoin queue when paused, or Replay handoff once connected
- Key Enter / Space: Cancel escalation, rejoin the billing queue, or replay the live specialist handoff

## Agent prompts

### Install and use

Install the Haze UI block "AI human handoff" with `npx shadcn@latest add @haze/ai-handoff`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiHandoff from "@/components/haze/blocks/ai-handoff.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-handoff.md

### Customize with real content

Adapt the Haze ai-handoff block for our product. Replace the demo values of these props with our real content: id, heading, userPrompt, assistantReply, department, specialistName, specialistRole, specialistMessage, waitEstimate, contextItems, teamInitials, class. Keep the layout, the heading level rules and these accessibility details: Queue position updates (3rd, 2nd, 1st, Connected), cancellations, and specialist arrival are announced politely through a dedicated role="status" live region. Cancelling handoff or rejoining the queue keeps keyboard focus on the next available action without trapping or losing focus. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-handoff, check it fits: use it when transferring an ai support thread to a human billing or account specialist with visible queue progress; showing users the exact account facts shared with the incoming agent for transparency; allowing users to cancel escalation and stay with the ai assistant before a specialist connects. Avoid it when presenting a general multi-turn ai chat interface without live queue escalation; use ai-chat or chat-thread; connecting an external api integration or oauth workspace rather than a human agent; use ai-connect. Alternatives: @haze/ai-chat, @haze/ai-connect, @haze/chat-thread.

## Example requests that should lead here
- Create an AI human handoff card with a live 3rd-to-Connected queue countdown, shared context summary bullets, team initials stack, and specialist join transition
- Build a billing escalation bubble inside a support chat with a Keep chatting with AI cancel button and Replay handoff control

## Source

```astro
---
import { Check, Headphones, RotateCcw } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  userPrompt?: string;
  assistantReply?: string;
  department?: string;
  specialistName?: string;
  specialistRole?: string;
  specialistMessage?: string;
  waitEstimate?: string;
  contextItems?: string[];
  teamInitials?: string[];
  class?: string;
}

const {
  id = "haze-ai-handoff",
  heading = "Human specialist handoff",
  userPrompt = "I got charged twice for October",
  assistantReply = "I can see both charges. Refunds need someone on the billing team, so I'm handing you over with the details.",
  department = "Billing",
  specialistName = "Tessa",
  specialistRole = "Billing specialist",
  specialistMessage = "Hi! I can see both $24.00 charges on INV-2291. I'm refunding the duplicate to your card ending 4242 now.",
  waitEstimate = "Usually replies in about 2 min",
  contextItems = [
    "Two charges of $24.00 on Nov 3",
    "Invoice INV-2291, card ending 4242",
    "You'd like one of them refunded",
  ],
  teamInitials = ["N", "T", "A"],
  class: className,
} = Astro.props;

const specialistInitial = specialistName.slice(0, 1).toUpperCase();
const avatarTones = [
  "bg-muted text-foreground",
  "bg-muted text-foreground",
  "bg-muted text-foreground",
];
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-handoff
  data-department={department}
  data-specialist={specialistName}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-md space-y-3.5">
    <div class="flex justify-end">
      <p class="max-w-[85%] rounded-2xl bg-muted px-4 py-2.5 text-sm/5 text-foreground">
        {userPrompt}
      </p>
    </div>

    <p class="text-[0.9375rem]/6 text-pretty text-foreground">
      {assistantReply}
    </p>

    <div class="overflow-hidden rounded-2xl border border-border bg-muted/40 p-1.5">
      <div class="flex items-center justify-between gap-2 px-3 py-2 text-xs/5">
        <h3 class="inline-flex min-w-0 items-center gap-2 text-muted-foreground">
          <Headphones class="size-3.5 shrink-0" aria-hidden="true" />
          <span class="truncate">
            Handing over to <strong class="font-semibold text-foreground">{department}</strong>
          </span>
        </h3>
        <span data-hnd-pos class="shrink-0 text-muted-foreground tabular-nums">3rd in line</span>
      </div>

      <div class="overflow-hidden rounded-xl border border-border bg-card">
        <div class="p-4">
          <p class="text-xs/5 text-muted-foreground">
            They'll see this, so you won't repeat yourself
          </p>
          <ul role="list" class="mt-3.5 space-y-2.5 text-sm/5 text-foreground">
            {
              contextItems.map((item) => (
                <li class="flex items-start gap-2.5">
                  <span
                    class="mt-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-full bg-success/14 text-success"
                    aria-hidden="true"
                  >
                    <Check class="size-2.5" />
                  </span>
                  <span class="min-w-0">{item}</span>
                </li>
              ))
            }
          </ul>
        </div>

        <div data-hnd-queue-row class="flex items-center gap-2.5 border-t border-border px-4 py-3">
          <div class="flex shrink-0 -space-x-2" aria-hidden="true">
            {
              teamInitials.map((initial, idx) => (
                <span
                  class={cn(
                    "inline-flex size-7 items-center justify-center rounded-full text-xs font-semibold ring-2 ring-card",
                    avatarTones[idx % avatarTones.length],
                  )}
                >
                  {initial}
                </span>
              ))
            }
          </div>
          <span class="min-w-0 truncate text-xs/5 text-muted-foreground">{waitEstimate}</span>
        </div>

        <div data-hnd-cancelled hidden class="flex flex-wrap items-center justify-between gap-2 border-t border-border px-4 py-3 animate-rise">
          <p class="text-xs/5 text-muted-foreground">Handoff paused · Staying with AI</p>
          <button
            type="button"
            data-hnd-rejoin
            class="inline-flex h-7 cursor-pointer items-center gap-1 rounded-full border border-frame bg-field px-3 text-xs/5 font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97]"
          >
            <RotateCcw class="size-3" aria-hidden="true" />
            Rejoin queue
          </button>
        </div>

        <div data-hnd-connected hidden class="space-y-3 border-t border-border p-4 animate-rise">
          <div class="flex flex-wrap items-center justify-between gap-2">
            <span class="inline-flex items-center gap-2 text-xs/5 font-semibold text-success">
              <span class="inline-flex size-5 items-center justify-center rounded-full bg-success/14 text-success" aria-hidden="true">
                <Check class="size-3" />
              </span>
              {specialistName} joined the chat
            </span>
            <span class="text-xs/4 text-muted-foreground">{specialistRole}</span>
          </div>

          <div class="flex items-start gap-2.5">
            <span
              class="mt-0.5 inline-flex size-7 shrink-0 items-center justify-center rounded-full bg-success/14 text-xs font-semibold text-success"
              aria-hidden="true"
            >
              {specialistInitial}
            </span>
            <p class="min-w-0 flex-1 rounded-2xl bg-muted/60 px-3.5 py-2.5 text-sm/5 text-pretty text-foreground">
              {specialistMessage}
            </p>
          </div>
        </div>
      </div>

      <div class="flex justify-end px-2 pt-1.5 pb-0.5">
        <button
          type="button"
          data-hnd-cancel
          class="inline-flex min-h-8 cursor-pointer items-center rounded-lg px-2 py-1 text-xs/5 text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
        >
          Keep chatting with AI
        </button>

        <button
          type="button"
          data-hnd-replay
          hidden
          class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 py-1 text-xs/5 text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
        >
          <RotateCcw class="size-3" aria-hidden="true" />
          Replay
        </button>
      </div>
    </div>

    <p data-hnd-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  function initAiHandoffs() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-handoff]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const department = root.dataset.department ?? "Billing";
      const specialist = root.dataset.specialist ?? "Tessa";

      const posEl = root.querySelector<HTMLElement>("[data-hnd-pos]");
      const queueRow = root.querySelector<HTMLElement>("[data-hnd-queue-row]");
      const cancelBtn = root.querySelector<HTMLButtonElement>("[data-hnd-cancel]");
      const cancelledBox = root.querySelector<HTMLElement>("[data-hnd-cancelled]");
      const rejoinBtn = root.querySelector<HTMLButtonElement>("[data-hnd-rejoin]");
      const connectedBox = root.querySelector<HTMLElement>("[data-hnd-connected]");
      const replayBtn = root.querySelector<HTMLButtonElement>("[data-hnd-replay]");
      const status = root.querySelector<HTMLElement>("[data-hnd-status]");

      const steps = ["3rd in line", "2nd in line", "1st in line"];

      let stepIndex = 0;
      let timer: number | undefined;

      const clearTimer = () => {
        if (timer !== undefined) {
          window.clearTimeout(timer);
          timer = undefined;
        }
      };

      const setPosTone = (connected: boolean) => {
        if (!posEl) return;
        posEl.classList.toggle("text-success", connected);
        posEl.classList.toggle("font-medium", connected);
        posEl.classList.toggle("text-muted-foreground", !connected);
      };

      const showConnected = () => {
        clearTimer();
        if (posEl) posEl.textContent = "Connected";
        setPosTone(true);
        if (queueRow) queueRow.hidden = true;
        if (cancelledBox) cancelledBox.hidden = true;
        if (connectedBox) connectedBox.hidden = false;
        if (cancelBtn) cancelBtn.hidden = true;
        if (replayBtn) replayBtn.hidden = false;
        if (status) status.textContent = `${specialist} from ${department} joined the chat.`;
      };

      const scheduleNext = () => {
        clearTimer();
        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        const delay = reduced ? 1800 : 1600;
        timer = window.setTimeout(() => {
          stepIndex += 1;
          if (stepIndex < steps.length) {
            const label = steps[stepIndex];
            if (posEl) posEl.textContent = label;
            if (status) status.textContent = `Queue updated: ${label} for ${department}.`;
            scheduleNext();
          } else {
            showConnected();
          }
        }, delay);
      };

      const startQueue = (announce = false) => {
        clearTimer();
        stepIndex = 0;
        if (posEl) posEl.textContent = steps[0];
        setPosTone(false);
        if (queueRow) queueRow.hidden = false;
        if (cancelledBox) cancelledBox.hidden = true;
        if (connectedBox) connectedBox.hidden = true;
        if (cancelBtn) cancelBtn.hidden = false;
        if (replayBtn) replayBtn.hidden = true;
        if (announce && status) status.textContent = `Joined ${department} handoff queue: 3rd in line.`;
        scheduleNext();
      };

      cancelBtn?.addEventListener("click", () => {
        clearTimer();
        if (posEl) posEl.textContent = "Paused";
        setPosTone(false);
        if (queueRow) queueRow.hidden = true;
        if (connectedBox) connectedBox.hidden = true;
        if (cancelledBox) cancelledBox.hidden = false;
        if (cancelBtn) cancelBtn.hidden = true;
        if (replayBtn) replayBtn.hidden = true;
        if (status) status.textContent = "Escalation cancelled. Continuing with AI assistant.";
        rejoinBtn?.focus();
      });

      rejoinBtn?.addEventListener("click", () => {
        startQueue(true);
        cancelBtn?.focus();
      });

      replayBtn?.addEventListener("click", () => {
        startQueue(true);
        cancelBtn?.focus();
      });

      startQueue(false);
    });
  }

  initAiHandoffs();
  document.addEventListener("astro:page-load", initAiHandoffs);
</script>
```
