# Headless Interrupts

> Resolve agent interrupts from any UI, without a useInterrupt render slot.

<!-- interactive demo: interrupt-headless -->

## What is this? [#what-is-this]

Sometimes the agent's question belongs outside the chat, in a dashboard, a
side panel, or a modal. A headless interrupt lets any component show the
question and resume the run with the answer. No chat needs to be mounted.

This page shows how to resolve an interrupt without the chat. You build the
resolver from the same hooks that `useInterrupt` uses. It can be a button
grid, a form, a modal, or a keyboard shortcut.

The underlying primitive is the interrupt call of your agent framework. How
it reaches the client depends on the agent framework, and there are two
headless shapes to match:

- An agent framework that surfaces the pause as an `on_interrupt` custom event
  (LangGraph): subscribe to that event and resume the run by calling
  `copilotkit.runAgent({...})` with the matching `resume` payload.
- An agent framework that finishes the run with a standard AG-UI interrupt
  outcome (AWS Strands): the run's final `RUN_FINISHED` carries
  `outcome: { type: "interrupt", interrupts: [...] }`. Call `useInterrupt` with
  `renderInChat: false` and place the element it returns wherever you like;
  `resolve(...)` resumes the run.

Either way, no chat surface is required.

## When should I use this? [#when-should-i-use-this]

- **Testing / Playwright fixtures**: a deterministic, chat-less button
  grid is easier to drive than a chat surface where the picker only
  appears after an LLM call.
- **Non-chat UIs**: dashboards, side panels, inspector surfaces, or
  any place where you want the _agent's interrupt_ without the _chat
  transcript_.
- **Custom flow control**: when you need to know exactly when the
  interrupt arrived (e.g. to gate other UI) and when it was resolved.
- **Research / debugging**: when you want to observe the raw AG-UI
  custom events without the abstraction layer.

If you just want "a picker in chat", just use
[`useInterrupt`](./useInterrupt). For pauses that the model decides on, use
[`useHumanInTheLoop`](../human-in-the-loop).

## Use `useInterrupt` without the chat [#use-useinterrupt-without-the-chat]

The simplest headless pattern uses `useInterrupt` with `renderInChat: false`.
Instead of publishing the element into `<CopilotChat>`, the hook returns the
interrupt element directly so you can place it anywhere in your tree. This
panel starts the run itself and shows the slot buttons while the agent waits:

```tsx
const SLOTS = [
  { iso: "2026-11-03T15:00:00Z", label: "Tue 3 PM" },
  { iso: "2026-11-04T10:00:00Z", label: "Wed 10 AM" },
];

function HeadlessInterruptPanel() {
  const { copilotkit } = useCopilotKit();
  const { agent } = useAgent({ agentId: "interrupt-headless" });

  const kickOff = (prompt: string) => {
    agent.addMessage({ id: crypto.randomUUID(), role: "user", content: prompt });
    void copilotkit.runAgent({ agent });
  };

  const interruptElement = useInterrupt({
    renderInChat: false,
    render: ({ interrupt, resolve, cancel }) => (
      <div>
        <p>Pick a slot for {interrupt?.message ?? "a call"}:</p>
        {SLOTS.map((s) => (
          <button key={s.iso} onClick={() => resolve({ chosen_time: s.iso, chosen_label: s.label })}>
            {s.label}
          </button>
        ))}
        <button onClick={() => cancel()}>Cancel</button>
      </div>
    ),
  });

  if (interruptElement) {
    return interruptElement;
  }

  return <button onClick={() => kickOff("Book a call with sales.")}>Book call</button>;
}
```

`interrupt` carries the primary AG-UI `Interrupt` object
(`{ id, reason, message?, responseSchema?, expiresAt?, ... }`).
`resolve(payload)` submits the user's response and resumes the agent.
`cancel()` cancels the interrupt and resumes. Both return a
`Promise<RunAgentResult | void>`. They resolve to void while waiting on further interrupts
when more than one is open.

Click **Book call**. When the agent pauses, the slot buttons replace the
button. Pick a slot. The run resumes, and the **Book call** button comes back.

## Subscribe to the interrupt yourself [#subscribe-to-the-interrupt-yourself]

Internally, `useInterrupt` composes two public APIs:

1. **`agent.subscribe({ onCustomEvent, onRunStartedEvent, onRunFinishedEvent, onRunFinalized, onRunFailed })`**:
   every `AbstractAgent` exposes an AG-UI event subscription.
   Standard interrupts arrive on `onRunFinishedEvent` with
   `{ outcome: { type: "interrupt", interrupts: [...] } }`. Custom-event
   interrupts (the LangGraph default) arrive as a custom event named
   `on_interrupt`.
2. **`copilotkit.runAgent({ agent, resume })`** (standard) or
   **`copilotkit.runAgent({ agent, forwardedProps: { command: { resume, interruptEvent } } })`** (custom event):
   the same call `useInterrupt`'s `resolve()` / `cancel()` makes to resume a paused run.

The code below depends on how your agent pauses. Where the agent framework pauses
with a custom event, it is a hand-rolled hook over the raw
subscription; where it pauses with a standard AG-UI interrupt, the same
`useInterrupt` call with `renderInChat: false` is all that is needed, and the
snippet shows that instead. Either way, the raw primitives remain available
when you want full control (testing fixtures, custom accumulation logic):

```typescript title="src/app/demos/interrupt-headless/page.tsx"
import React from "react";
import {
  CopilotKit,
  CopilotChat,
  useConfigureSuggestions,
  useInterrupt,
} from "@copilotkit/react-core/v2";
import { generateFallbackSlots } from "../_shared/interrupt-fallback-slots";
import type { TimeSlot } from "../_shared/interrupt-fallback-slots";

// Shape the backend `schedule_meeting` tool suspends with, wrapped by the
// @ag-ui/mastra bridge under `mastra_suspend`.
type SuspendPayload = {
  topic?: string;
  attendee?: string;
  slots?: TimeSlot[];
};

export default function InterruptHeadlessDemo() {
  return (
    <CopilotKit runtimeUrl="/api/copilotkit" agent="interrupt-headless">
      <Layout />
    </CopilotKit>
  );
}

function Layout() {
  useConfigureSuggestions({
    suggestions: [
      {
        title: "Book a call with sales",
        message: "Book an intro call with the sales team to discuss pricing.",
      },
      {
        title: "Schedule a 1:1 with Alice",
        message: "Schedule a 1:1 with Alice next week to review Q2 goals.",
      },
    ],
    available: "always",
  });

  // Headless: the hook RETURNS the interrupt element (or null) instead of
  // publishing it into the chat, so we can place it in the app surface.
  const interruptEl = useInterrupt({
    agentId: "interrupt-headless",
    renderInChat: false,
    render: ({ event, resolve }) => {
      // Mastra wraps the suspend value as `{ type: "mastra_suspend",
      // suspendPayload, ... }`, JSON-stringified — parse then read
      // `suspendPayload` (not the raw wrapper).
      const raw = event.value ?? {};
      const parsed = (typeof raw === "string" ? JSON.parse(raw) : raw) as {
        suspendPayload?: SuspendPayload;
      } & SuspendPayload;
      const payload: SuspendPayload = parsed.suspendPayload ?? parsed;
      return (
        <TimeSlotPopup
          payload={payload}
          onPick={(slot) =>
            setTimeout(
              () =>
                resolve({ chosen_time: slot.iso, chosen_label: slot.label }),
              500,
            )
          }
          onCancel={() => setTimeout(() => resolve({ cancelled: true }), 500)}
        />
      );
    },
  });

  return (
    <div className="grid h-screen grid-cols-[1fr_420px] bg-[#FAFAFC] dark:bg-background">
      <AppSurface interruptEl={interruptEl} />
      <div className="border-l border-[#DBDBE5] bg-white dark:border-border dark:bg-background">
        <CopilotChat agentId="interrupt-headless" className="h-full" />
      </div>
    </div>
  );
}
```

A few things the hand-rolled variant is careful about:

- It stages the incoming event in a local ref and only commits
  it to React state on `onRunFinalized`, mirroring `useInterrupt`,
  which doesn't surface the interrupt until the run has actually paused
  (not just when the event fires mid-stream).
- `onRunStartedEvent` clears any stale pending state, so kicking off a
  new turn always starts from a clean slate.
- `onRunFailed` drops the staged event so a transport hiccup doesn't
  leave the UI stuck showing a picker for a run that never paused.

The same panel, built on the `useHeadlessInterrupt` hook from the snippet:

```tsx
// SLOTS is the list from the previous sample.
function HeadlessInterruptPanelRaw() {
  const { copilotkit } = useCopilotKit();
  const { agent } = useAgent({ agentId: "interrupt-headless" });
  const { pending, resolve } = useHeadlessInterrupt("interrupt-headless");

  const kickOff = (prompt: string) => {
    agent.addMessage({ id: crypto.randomUUID(), role: "user", content: prompt });
    void copilotkit.runAgent({ agent });
  };

  if (pending) {
    return (
      <div>
        <p>Pick a slot for {pending.value.topic ?? "a call"}:</p>
        {SLOTS.map((s) => (
          <button key={s.iso} onClick={() => resolve({ chosen_time: s.iso, chosen_label: s.label })}>
            {s.label}
          </button>
        ))}
        <button onClick={() => resolve({ cancelled: true })}>Cancel</button>
      </div>
    );
  }

  return <button onClick={() => kickOff("Book a call with sales.")}>Book call</button>;
}
```
