Pausing the Agent for Input
Pause an agent run, hand control to a custom Vue component, and resume with the user's answer.
What is this?
Some agent steps need a person's answer before the run can continue, such as approving a payment or picking a meeting time. useInterrupt pauses the run, shows your Vue component, and resumes the run with the answer. How the pause works depends on your agent framework.
LangGraph ships a first-class interrupt() primitive that lets a running node suspend itself and hand control to the client. The run is frozen server-side until the client resolves the interrupt with a payload, at which point the node resumes as if interrupt() had returned that payload.
CopilotKit's useInterrupt is the frontend half of that contract: it subscribes to the paused run, exposes reactive interrupt state, and resumes the agent with the user's answer.
When should I use this?
Reach for useInterrupt when the pause is a graph-enforced checkpoint where the code path must stop and wait for a human, not an LLM-initiated tool call. Typical cases:
- A sensitive action (payments, irreversible writes) must be approved
- A required piece of state isn't known and can only be collected from the user
- The agent explicitly reaches an approval node in a longer workflow
- You want the server-side contract to be
interrupt(...)and resume with a payload
For LLM-initiated pauses where the model decides on the fly to ask the user, prefer useHumanInTheLoop.
The backend: interrupt() inside a tool
useHumanInTheLoop: nothing to wire on the agent
The AG-UI Mastra adapter forwards each tool you register with
useHumanInTheLoop to the agent as a client tool. When the model calls
it, the run hands control to the browser, and the user's answer comes
back as the tool result. Do not declare the tool on the Mastra agent.
useInterrupt: return suspend() from a tool
A Mastra tool pauses with suspend(), not interrupt(). Declare a
suspendSchema for the payload your UI reads and a resumeSchema for
the answer it sends back. The @ag-ui/mastra bridge sends the pause to
the frontend as an AG-UI interrupt. When the user answers, Mastra runs
execute again with the answer in resumeData.
// Native interrupt backend for the `gen-ui-interrupt` + `interrupt-headless`
// cells (OSS-383). Unlike the old Strategy-B workaround (a frontend-only
// `schedule_meeting` satisfied by `useHumanInTheLoop`), this is a REAL Mastra
// suspend tool: the model calls `schedule_meeting`, the tool `suspend()`s with
// a time-picker payload, and the @ag-ui/mastra bridge maps that to an AG-UI
// interrupt (legacy `on_interrupt` CUSTOM event + the standard `RUN_FINISHED`
// interrupt-outcome, on by default in the v1 bridge). The frontend `useInterrupt`
// hook renders the picker and `resolve(...)`s, which resumes the run — the tool's
// `execute` is re-invoked with `resumeData` carrying the user's selection.
//
// Load-bearing (see the Mastra capability-map memory):
// - `return suspend(...)` DIRECTLY. `await suspend(); return x` completes the
// tool, so under fast streaming the agentic loop continues past the pause.
// - Resume needs instance `storage` (configured on `new Mastra({ storage })`)
// and the suspend-chunk runId — both handled by the bridge + src/mastra/index.ts.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export interface InterruptTimeSlot {
label: string;
iso: string;
}
// Mirror of `src/app/demos/_shared/interrupt-fallback-slots.ts` so the backend
// supplies future-relative candidate slots inside the suspend payload (the
// frontend only falls back to its own generator if these are absent).
function atLocal(date: Date, hour: number, minute = 0): Date {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
hour,
minute,
0,
0,
);
}
function nextMonday(from: Date): Date {
const day = from.getDay();
let offset = (1 - day + 7) % 7;
if (offset <= 1) offset += 7;
const next = new Date(from);
next.setDate(from.getDate() + offset);
return next;
}
export function generateCandidateSlots(
now: Date = new Date(),
): InterruptTimeSlot[] {
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
const monday = nextMonday(now);
const candidates: Array<[string, Date]> = [
["Tomorrow 10:00 AM", atLocal(tomorrow, 10)],
["Tomorrow 2:00 PM", atLocal(tomorrow, 14)],
["Monday 9:00 AM", atLocal(monday, 9)],
["Monday 3:30 PM", atLocal(monday, 15, 30)],
];
return candidates.map(([label, date]) => ({
label,
iso: date.toISOString(),
}));
}
export const scheduleMeetingInterruptTool = createTool({
id: "schedule_meeting",
description:
"Ask the user to pick a meeting time. Surfaces an interactive time-picker " +
"to the user and returns their selection. Call this whenever the user asks " +
"to book or schedule a meeting.",
inputSchema: z.object({
topic: z
.string()
.describe("What the meeting is about (e.g. 'Intro with sales')."),
attendee: z
.string()
.optional()
.describe("Who the meeting is with (e.g. 'Alice'), if known."),
}),
suspendSchema: z.object({
topic: z.string(),
attendee: z.string().optional(),
slots: z.array(z.object({ label: z.string(), iso: z.string() })),
}),
resumeSchema: z.object({
chosen_time: z.string().optional(),
chosen_label: z.string().optional(),
cancelled: z.boolean().optional(),
}),
// Mastra createTool execute signature is `(inputData, executionContext)`:
// the validated INPUT is the first arg; the ToolExecutionContext is the
// second. `suspend` / `resumeData` live under `executionContext.agent`
// (the `AgentToolExecutionContext` sub-object), NOT at the top level.
// Destructuring them off `executionContext` directly yields `undefined`, so
// `return suspend(...)` throws `suspend is not a function`; the model gets a
// tool-error, re-calls, and the loop spins to the step cap with no
// `tool-call-suspended` chunk. Mirrors the proven @ag-ui/mastra dojo tool.
execute: async (inputData, executionContext) => {
const { suspend, resumeData } = executionContext?.agent ?? {};
// Second pass: the user resolved the interrupt — the run resumes here with
// their selection. Return a short confirmation the agent narrates.
if (resumeData) {
if (resumeData.cancelled) {
return "The user cancelled — no meeting was scheduled.";
}
const when =
resumeData.chosen_label ?? resumeData.chosen_time ?? "the chosen time";
return `Scheduled "${inputData.topic}" for ${when}.`;
}
// First pass: suspend with the picker payload. Returned directly so the
// agentic loop pauses here instead of continuing.
return suspend?.({
topic: inputData.topic,
attendee: inputData.attendee,
slots: generateCandidateSlots(),
});
},
});Two details fail without an error:
suspendandresumeDataare onexecutionContext.agent, the second argument ofexecute. Read from the top level of the context, they areundefined, and the model retries the tool until the run reaches its step limit.return suspend(...)directly. Withawait suspend()followed by anotherreturn, the tool completes and the agent keeps going past the pause.
Give the Mastra instance storage
Resume reloads the paused run from storage, so the Mastra instance that
registers the agent needs storage:
import { Mastra } from "@mastra/core/mastra";
import { LibSQLStore } from "@mastra/libsql";
export const mastra = new Mastra({
agents: { interruptAgent },
storage: new LibSQLStore({
id: "mastra-storage",
url: ":memory:",
}),
});Read the payload under suspendPayload
The bridge wraps your suspend() value, so useInterrupt does not
receive it as is:
- In the custom-event flow,
event.valueis a JSON string. Parse it and readsuspendPayload. - In the standard AG-UI flow, the payload is in
interrupt.metadata.mastra.suspendPayload.
useInterrupt({
render: ({ interrupt, event, resolve }) => {
const payload = interrupt
? interrupt.metadata?.mastra?.suspendPayload
: JSON.parse(event.value).suspendPayload;
return (
<div>
<p>Pick a time for {payload?.topic}</p>
<button onClick={() => resolve({ chosen_time: "Tomorrow 10:00 AM" })}>
Tomorrow 10:00 AM
</button>
<button onClick={() => resolve({ cancelled: true })}>Cancel</button>
</div>
);
},
});Whatever you pass to resolve(...) arrives in the tool as resumeData,
so shape it to match the tool's resumeSchema.
The agent can expose a schedule_meeting tool that issues an interrupt with the meeting context. The run stops until the client resolves the interrupt. The resolve payload becomes the return value of interrupt(). The tool turns that value into a result for the model.
Two things to note:
- The payload, for example
{ "topic": topic, "attendee": attendee }, is what the Vue frontend receives asevent.value. The LangGraph adapter sends it as a JSON string, so parse it before you read fields. Keep it a plain, serializable object containing the pause-time context the UI needs. - The return-side contract, such as
{ chosen_label, chosen_time }or{ cancelled: true }, is entirely yours. The client can send any serializable resolve payload; the tool gives it meaning and must validate it before a side effect.
The frontend: useInterrupt and the chat slot
Register useInterrupt in a descendant component. With the default renderInChat: true, the composable publishes the pending interrupt to CopilotChat; render it through the #interrupt scoped slot and call resolve(...) to resume:
<script setup lang="ts">
import { CopilotChat, useInterrupt } from "@copilotkit/vue/v2";
type MeetingPayload = { topic?: string; attendee?: string };
// The LangGraph adapter sends the interrupt value as a JSON string.
function readValue(value: unknown): MeetingPayload {
if (typeof value !== "string") return (value ?? {}) as MeetingPayload;
try {
return JSON.parse(value) as MeetingPayload;
} catch {
return {};
}
}
useInterrupt({
agentId: "gen-ui-interrupt",
});
</script>
<template>
<CopilotChat agent-id="gen-ui-interrupt">
<template #interrupt="{ event, resolve }">
<section>
<p>Pick a time for {{ readValue(event.value).topic ?? "a call" }}</p>
<button
@click="resolve({ chosen_label: 'Tomorrow', chosen_time: '2026-09-01T09:00:00Z' })"
>
Tomorrow at 09:00
</button>
<button @click="resolve({ cancelled: true })">Cancel</button>
</section>
</template>
</CopilotChat>
</template>Whatever you pass to resolve is round-tripped back to the agent as the return value of the matching interrupt.
Ask the agent to book a call. The picker appears in the chat. Click Tomorrow at 09:00, and the agent confirms the booked time.
Key props
agentId: must match a runtime-registered agent. If omitted, the composable uses the agent of the surrounding chat configuration, then"default". A mismatch means the interrupt never appears.renderInChat: whentrue,slotPropsare published to the chat's#interruptslot. Set it tofalsewhen your own component renders the returned refs elsewhere. See Headless interrupts.handler: optionally preprocesses the interrupt, can resolve it early, and exposes its return value asresult.enabled: filters interrupt shapes before they are surfaced.
The Vue #interrupt slot receives { event, result, resolve }. For the complete standard-interrupt surface (including interrupt, interrupts, and cancel), use the composable's returned slotProps with renderInChat: false.
Multiple interrupts? Add a type and gate with enabled
If your graph issues more than one kind of interrupt, tag each payload with a type field and install one useInterrupt per shape, each gated by enabled:
// The LangGraph adapter sends the interrupt value as a JSON string.
function readValue(value: unknown): Record<string, unknown> {
if (typeof value !== "string") return (value ?? {}) as Record<string, unknown>;
try {
return JSON.parse(value) as Record<string, unknown>;
} catch {
return {};
}
}
useInterrupt({
agentId: "gen-ui-interrupt",
enabled: (event) => readValue(event.value).type === "ask",
});
useInterrupt({
agentId: "gen-ui-interrupt",
enabled: (event) => readValue(event.value).type === "approval",
});Preprocess with handler
For cases where the interrupt can sometimes be resolved without user input, pass a handler that runs before the UI is rendered. The handler can call resolve(...) itself to resume the agent early, or return a value exposed as result:
const { slotProps } = useInterrupt({
agentId: "gen-ui-interrupt",
renderInChat: false,
handler: async ({ event, resolve }) => {
const department = await lookupUserDepartment();
// readValue is the helper from the previous sample.
const required = readValue(event.value).accessDepartment;
if (required === department || department === "admin") {
await resolve({ code: "AUTH_BY_DEPARTMENT" });
return;
}
return { department };
},
});AG-UI standard interrupt flow vs. legacy
This section is a reference for developers who write interrupt UI for their own agent. The Vue useInterrupt reference lists every option. useInterrupt handles two kinds of interrupt, and your agent framework decides which kind it sends.
Standard flow (RUN_FINISHED with outcome.type === "interrupt")
When the agent backend conforms to the AG-UI protocol, it signals an interrupt by emitting a RUN_FINISHED event whose outcome carries the interrupts array:
outcome.type === "interrupt"
outcome.interrupts // Interrupt[]The composable detects this on onRunFinishedEvent and exposes the interrupts after onRunFinalized fires. slotProps.value contains:
interrupt: the primaryInterrupt(interrupts[0]), with shape{ id, reason, message?, toolCallId?, responseSchema?, expiresAt?, metadata? }.interrupts: the full open set.resolve(payload?, interruptId?): records a resolved response for the targeted interrupt. The run resumes once every open interrupt has a response.cancel(interruptId?): records a cancelled response for the targeted interrupt. The same accumulate-then-submit logic applies.
Legacy flow (on_interrupt custom event)
Agents can emit a custom on_interrupt event. The LangGraph adapter does this by default. The composable exposes its payload in event.value, with interrupt set to null and interrupts to []. Calling resolve(payload) resumes via forwardedProps.command. cancel() dismisses the interrupt without resuming because the custom-event flow has no cancel response.
Priority
If both signals appear on the same run, the standard flow wins.
Approve / Cancel example
<script setup lang="ts">
import { useInterrupt } from "@copilotkit/vue/v2";
const { slotProps } = useInterrupt({ renderInChat: false });
</script>
<template>
<section v-if="slotProps">
<p>{{ slotProps.interrupt?.message ?? "Approve this action?" }}</p>
<button @click="slotProps.resolve({ approved: true })">Approve</button>
<button @click="slotProps.cancel()">Cancel</button>
</section>
</template>Both methods return the RunAgentResult once the run restarts, or void while waiting for responses to other open interrupts.
Multi-interrupt behavior
Some agents issue more than one interrupt in a single run. Each interrupt has its own id; address them individually:
<template>
<ul v-if="slotProps">
<li v-for="item in slotProps.interrupts" :key="item.id">
{{ item.message }}
<button @click="slotProps.resolve({ ok: true }, item.id)">Approve</button>
<button @click="slotProps.cancel(item.id)">Cancel</button>
</li>
</ul>
</template>The agent run resumes only after every open interrupt has been addressed. If you omit interruptId, the primary interrupt is targeted; Vue warns when several are open.
responseSchema: surface only, no client-side validation
The Interrupt type exposes a responseSchema JSON Schema that the agent can use to describe the expected payload. useInterrupt surfaces it on interrupt.responseSchema for your UI to read, but it does not validate resolve payloads against it. Validation is the agent's responsibility on resume.
Provider setup
The component calling useInterrupt must be a descendant of CopilotKitProvider:
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue/v2";
import MeetingChat from "./components/MeetingChat.vue";
</script>
<template>
<CopilotKitProvider runtime-url="/api/copilotkit">
<MeetingChat />
</CopilotKitProvider>
</template>How is this guide?