Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

custom-events.md

279 lines11.1 KB

1---
2title: Custom Events Reference
3id: custom-events
4order: 1
5description: "Send your own progress events from a tool to the UI. Read every CUSTOM event that TanStack AI emits with a plain if, with full types."
6keywords:
7 - tanstack ai
8 - custom events
9 - KnownCustomEvent
10 - ChatStream
11 - ag-ui protocol
12 - CUSTOM event
13 - stream narrowing
14---
15​
16A `CUSTOM` event carries app data on the `chat()` stream, such as progress during a 20-second tool. This page shows the event shape.
17​
18A `CUSTOM` event carries a `name` and a `value` next to the normal chat chunks. Your server sends one with `emitCustomEvent`. Your client reads it with `onCustomEvent`. TanStack AI also sends its own `CUSTOM` events, and this page lists all of them.
19​
20## Quick setup
21​
22### 1. Emit an event from a server tool
23​
24The tool gets `emitCustomEvent` on its second argument:
25​
26```ts
27// tools.ts
28import { toolDefinition } from "@tanstack/ai";
29import { z } from "zod";
30​
31export const importRows = toolDefinition({
32 name: "importRows",
33 description: "Import rows into the dataset, reporting progress as it runs",
34 inputSchema: z.object({ rows: z.array(z.string()) }),
35}).server(async ({ rows }, context) => {
36 for (let i = 0; i < rows.length; i++) {
37 context?.emitCustomEvent("my-app:progress", {
38 done: i + 1,
39 total: rows.length,
40 });
41 }
42 return { imported: rows.length };
43});
44```
45​
46### 2. Add the tool to the server route
47​
48```ts
49// api/chat.ts
50import {
51 chat,
52 chatParamsFromRequest,
53 toServerSentEventsResponse,
54} from "@tanstack/ai";
55import { openaiText } from "@tanstack/ai-openai";
56import { importRows } from "./tools";
57​
58export async function POST(request: Request) {
59 const params = await chatParamsFromRequest(request);
60 const stream = chat({
61 adapter: openaiText("gpt-6.1-sol"),
62 messages: params.messages,
63 threadId: params.threadId,
64 tools: [importRows],
65 });
66 return toServerSentEventsResponse(stream);
68```
69​
70### 3. Read the event in the client
71​
72Pass `onCustomEvent` to `useChat`. It gets the event name, the value, and the `toolCallId` of the tool that sent it:
73​
74```tsx
75import { useState } from "react";
76import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
77​
78export function Chat() {
79 const [progress, setProgress] = useState("");
80 const { sendMessage } = useChat({
81 connection: fetchServerSentEvents("/api/chat"),
82 threadId: "support-chat",
83 onCustomEvent: (name, value) => {
84 if (
85 name === "my-app:progress" &&
86 typeof value === "object" &&
87 value !== null &&
88 "done" in value &&
89 "total" in value
90 ) {
91 setProgress(`${String(value.done)} of ${String(value.total)}`);
92 }
93 },
94 });
95​
96 return (
97 <>
98 <button onClick={() => sendMessage("Import rows a, b, and c")}>
99 Import
100 </button>
101 <p>{progress}</p>
102 </>
103 );
105```
106​
107Click the button. The text counts up while the tool runs.
108​
109## How it works
110​
111Every `CUSTOM` chunk has `type: "CUSTOM"`, a `name`, and a `value`. Events from your code and events from TanStack AI use the same chunk shape and travel on the same stream.
112​
113On the server, `chat()` returns the `ChatStream` type. In `ChatStream`, every built-in event has a literal `name` and a typed `value`. Check `chunk.type`, then compare `chunk.name` to a string. You do not import a guard:
114​
115```ts
116import { chat } from "@tanstack/ai";
117import { openaiText } from "@tanstack/ai-openai";
118​
119const stream = chat({
120 adapter: openaiText("gpt-6.1-sol"),
121 messages: [{ role: "user", content: "Hello" }],
122 threadId: "thread-1",
123});
124​
125for await (const chunk of stream) {
126 if (chunk.type === "CUSTOM" && chunk.name === "sandbox.file.diff") {
127 console.log(chunk.value.path, chunk.value.diff);
128 } else if (
129 chunk.type === "CUSTOM" &&
130 chunk.name === "structured-output.complete"
131 ) {
132 console.log(chunk.value.object);
133 }
135```
136​
137Your own event names are not in `ChatStream`. To read them on the server, see [Read your own events on the server](#read-your-own-events-on-the-server).
138​
139## Built-in events
140​
141Each interface extends the base `CustomEvent` (`type: 'CUSTOM'` and an optional `model`) with a literal `name` and a concrete `value`. `@tanstack/ai` exports each interface and their union, `KnownCustomEvent`.
142​
143| Interface | `name` | `value` | Emitted when |
144| --- | --- | --- | --- |
145| `SandboxFileCustomEvent` | `sandbox.file` | `{ type: 'create' \| 'change' \| 'delete'; path: string; timestamp: number }` | For each file create, change, or delete in an active [sandbox](../sandbox/events) |
146| `SandboxFileDiffEvent` | `sandbox.file.diff` | `{ path: string; diff: string }` | For each file change. Turn it on with `fileEvents: { diff: true }` |
147| `FileChangedEvent` | `file.changed` | `{ path: string; diff: string }` | A harness adapter (Grok Build, Claude Code, and more), once after the run completes |
148| `SessionIdEvent` | `` `${string}.session-id` `` | `{ sessionId: string }` | A harness adapter, once when it creates or resumes its session in the sandbox |
149| `CodeModeExecutionStartedEvent` | `code_mode:execution_started` | `{ timestamp: number; codeLength: number }` | [Code Mode](../code-mode/code-mode), when sandbox execution starts |
150| `CodeModeConsoleEvent` | `code_mode:console` | `{ level: 'log' \| 'warn' \| 'error' \| 'info'; message: string; timestamp: number }` | Code Mode, for each `console.*` call in the sandbox |
151| `CodeModeExternalCallEvent` | `code_mode:external_call` | `{ function: string; args: unknown; timestamp: number }` | Code Mode, before a bound `external_*` function runs |
152| `CodeModeExternalResultEvent` | `code_mode:external_result` | `{ function: string; result: unknown; duration: number }` | Code Mode, after an `external_*` call succeeds |
153| `CodeModeExternalErrorEvent` | `code_mode:external_error` | `{ function: string; error: string; duration: number }` | Code Mode, when an `external_*` call throws |
154| `CodeModeSnippetCallEvent` | `code_mode:snippet_call` | `{ snippet: string; input: unknown; timestamp: number }` | [Code Mode with Snippets](../code-mode/code-mode-with-snippets), before a snippet runs |
155| `CodeModeSnippetResultEvent` | `code_mode:snippet_result` | `{ snippet: string; result: unknown; duration: number; timestamp: number }` | Code Mode with Snippets, after a snippet succeeds |
156| `CodeModeSnippetErrorEvent` | `code_mode:snippet_error` | `{ snippet: string; error: string; duration: number; timestamp: number }` | Code Mode with Snippets, when a snippet throws |
157| `SnippetRegisteredEvent` | `snippet:registered` | `{ id: string; name: string; description: string; timestamp: number }` | When a snippet goes into the tool registry |
158| `StructuredOutputStartEvent` | `structured-output.start` | `{ messageId: string }` | [`chat({ outputSchema, stream: true })`](../structured-outputs/streaming), once for each structured message |
159| `StructuredOutputCompleteEvent<T>` | `structured-output.complete` | `{ object: T; raw: string; reasoning?: string }` | Structured-output streaming, once with the validated object |
160| `UIResourceEvent` | `ui-resource` | `{ resource; serverId?: string; toolCallId: string; toolName: string; meta?: Record<string, unknown> }` | An MCP tool returns a `ui://` resource ([MCP Apps](../mcp/apps)) |
161​
162Harness `*.session-id` events and the two `structured-output.*` events are always `CUSTOM` events. They are not fields on `RUN_FINISHED`.
163​
164Where each group of events is shown in use:
165​
166- Sandbox and harness events: [Sandbox Events](../sandbox/events) and [Observability](../sandbox/observability).
167- Code Mode events: [Showing Code Mode in the UI](../code-mode/client-integration).
168- Structured output events: [Streaming structured output](../structured-outputs/streaming).
169​
170## Advanced
171​
172### Emit from chat middleware
173​
174Chat middleware gets the same `emitCustomEvent` on `ChatMiddlewareContext`. The engine yields the chunk while the hook still runs. So a long `onConfig` can send `prepare` before its work is done:
175​
176```ts
177import { type ChatMiddleware } from "@tanstack/ai";
178​
179async function prepare() {
180 await new Promise<void>((resolve) => {
181 setTimeout(resolve, 1);
182 });
184​
185const progress: ChatMiddleware = {
186 name: "progress",
187 async onConfig(ctx) {
188 if (ctx.phase !== "beforeModel") return;
189 ctx.emitCustomEvent("my-app:progress", { step: "prepare" });
190 await prepare();
191 ctx.emitCustomEvent("my-app:progress", { step: "ready" });
192 },
193};
194```
195​
196### Durability and batching
197​
198With durability on the response, each `CUSTOM` event flushes when you emit it. So `prepare` reaches the client while `prepare()` still runs.
199​
200These high-volume names stay in the durability batch with later chunks:
201​
202- `process.stdout`
203- `process.stderr`
204- `sandbox.file`
205- `sandbox.file.diff`
206​
207To keep one of your own events in the batch, pass `{ batch: true }`:
208​
209```ts
210import { type ChatMiddleware } from "@tanstack/ai";
211​
212const noisy: ChatMiddleware = {
213 name: "noisy",
214 async onConfig(ctx) {
215 ctx.emitCustomEvent("my-app:ticks", { n: 1 }, { batch: true });
216 },
217};
218```
219​
220### Why `ChatStream` narrows
221​
222`chat()` returns `ChatStream` when you do not pass `outputSchema` and do not set `stream: false`:
223​
224```ts
225import { chat } from "@tanstack/ai";
226import { openaiText } from "@tanstack/ai-openai";
227import type { ChatStream } from "@tanstack/ai";
228​
229const stream: ChatStream = chat({
230 adapter: openaiText("gpt-6.1-sol"),
231 messages: [{ role: "user", content: "Hello" }],
232 threadId: "thread-1",
233});
234```
235​
236This is the definition:
237​
238```ts ignore
239type ChatStream = AsyncIterable<Exclude<StreamChunk, CustomEvent> | KnownCustomEvent>
240```
241​
242`StreamChunk` is the raw AG-UI event union. It has one generic `CUSTOM` member, `CustomEvent`, with `name: string` and `value: any`. With that member in the union, a check on `chunk.name` still leaves `chunk.value` typed `any`.
243​
244`ChatStream` fixes this in two steps:
245​
2461. `Exclude<StreamChunk, CustomEvent>` removes the generic member.
2472. `| KnownCustomEvent` adds back each built-in event, with a literal `name` and a concrete `value`.
248​
249`StructuredOutputStream` uses the same approach.
250​
251### Read your own events on the server
252​
253`'my-app:progress'` is not a literal name in `KnownCustomEvent`, so `ChatStream` does not include it. `ChatStream` has no generic fallback member, because that member gives `value: any` to every other event.
254​
255The event still arrives at runtime. To read it with types, annotate the stream as `StreamChunk`. The generic member gives `value: any`, so you do not need a cast:
256​
257```ts ignore
258import { chat } from "@tanstack/ai";
259import { openaiText } from "@tanstack/ai-openai";
260import type { StreamChunk } from "@tanstack/ai";
261import { importRows } from "./tools";
262​
263const stream: AsyncIterable<StreamChunk> = chat({
264 adapter: openaiText("gpt-6.1-sol"),
265 messages: [{ role: "user", content: "Import these rows" }],
266 threadId: "thread-1",
267 tools: [importRows],
268});
269​
270for await (const chunk of stream) {
271 if (chunk.type === "CUSTOM" && chunk.name === "my-app:progress") {
272 console.log(chunk.value.done, chunk.value.total);
273 }
275```
276​
277Use `ChatStream` to read the built-in events with full types. Use `StreamChunk` for the branches that read your own events.
278​
279For the standard AG-UI events that this union extends, see [Stream Events](../chat/stream-events). For the `metadata.tanstack` fields a custom server sends, see [Event metadata](./metadata).