# 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]

<Steps>
  <Step>
    ### Install the LangGraph Python SDK

    <Tabs className="p-0 m-0" groupId="python-pm" items={['uv', 'poetry', 'pip', 'conda']} default="uv">
    <Tab value="uv">
    ```bash
    uv add copilotkit
    ```
    </Tab>
    <Tab value="poetry">
    ```bash
    poetry add copilotkit
    ```
    </Tab>

    <Tab value="pip">

    ```bash
    pip install copilotkit --extra-index-url https://copilotkit.gateway.scarf.sh/simple/
    ```
    </Tab>

    <Tab value="conda">
    ```bash
    conda install copilotkit -c copilotkit-channel
    ```
    </Tab>

</Tabs>

  </Step>
  <Step>
    ### Wire CopilotKit middleware into your graph

    Programmatic control (`copilotkit.runAgent`, `agent.subscribe`,
    `agent.addMessage`) drives runs through the same agent your chat UI
    uses, so the backend wiring is the same one-line `CopilotKitMiddleware`
    setup.

~~~~python title="frontend_tools.py"
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from copilotkit import CopilotKitMiddleware

graph = create_agent(
    model=ChatOpenAI(reasoning_effort="none", model="gpt-6-luna"),
    tools=[],
    middleware=[CopilotKitMiddleware()],
    system_prompt="You are a helpful, concise assistant.",
)
~~~~

    For the headless `useInterrupt` pattern, also use LangGraph's native
    `interrupt(...)` inside a graph node and resume with
    `forwardedProps: { command: { resume, interruptEvent } }` from the
    frontend.

  </Step>
</Steps>

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, { useEffect, useMemo, useRef, useState } from "react";
import {
  CopilotKit,
  CopilotChat,
  useAgent,
  useConfigureSuggestions,
  useCopilotKit,
} from "@copilotkit/react-core/v2";
import { generateFallbackSlots } from "../_shared/interrupt-fallback-slots";
import type { TimeSlot } from "../_shared/interrupt-fallback-slots";

const INTERRUPT_EVENT_NAME = "on_interrupt";

type InterruptPayload = {
  topic?: string;
  attendee?: string;
  slots?: TimeSlot[];
};

type InterruptEvent = {
  name: string;
  value: InterruptPayload;
};

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

function Layout() {
  const { pending, resolve } = useHeadlessInterrupt("interrupt-headless");

  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",
  });

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

function useHeadlessInterrupt(agentId: string): {
  pending: InterruptEvent | null;
  resolve: (response: unknown) => Promise<unknown>;
} {
  const { copilotkit } = useCopilotKit();
  const { agent } = useAgent({ agentId });
  const [pending, setPending] = useState<InterruptEvent | null>(null);
  const pendingRef = useRef<InterruptEvent | null>(null);
  pendingRef.current = pending;

  useEffect(() => {
    let local: InterruptEvent | null = null;
    const sub = agent.subscribe({
      onCustomEvent: ({ event }) => {
        if (event.name === INTERRUPT_EVENT_NAME) {
          // The AG-UI adapter JSON-stringifies interrupt values, so
          // parse when the value arrives as a string.
          const raw = event.value ?? {};
          local = {
            name: event.name,
            value: (typeof raw === "string"
              ? JSON.parse(raw)
              : raw) as InterruptPayload,
          };
        }
      },
      onRunStartedEvent: () => {
        local = null;
        setPending(null);
      },
      onRunFinalized: () => {
        if (local) {
          setPending(local);
          local = null;
        }
      },
      onRunFailed: () => {
        local = null;
        setPending(null);
      },
    });
    return () => sub.unsubscribe();
  }, [agent]);

  const resolve = useMemo(
    () => async (response: unknown) => {
      const snapshot = pendingRef.current;
      try {
        return await copilotkit.runAgent({
          agent,
          forwardedProps: {
            command: {
              resume: response,
              interruptEvent: snapshot?.value,
            },
          },
        });
      } catch (err) {
        // Catastrophic rejection (network error, auth failure, validation
        // reject) may fire before the run starts, so onRunFailed never runs.
        // Clear pending here so the popup unmounts. Symmetric with the
        // framework resolve catch + onRunFailed handler — all write null,
        // no race. Caller still sees the rethrow.
        console.error(
          "[interrupt-headless] resume runAgent rejected; clearing pending + rethrowing",
          err,
        );
        setPending(null);
        throw err;
      }
    },
    [agent, copilotkit],
  );

  return { pending, resolve };
}
```

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>;
}
```
