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

queueing.md

178 lines5.9 KB

1---
2title: Message Queue
3id: message-queue
4order: 4
5description: "Choose what happens when the user sends a message while a reply still streams: queue it, drop it, or interrupt the reply."
6keywords:
7 - tanstack ai
8 - message queue
9 - queue
10 - whenBusy
11 - interrupt
12 - sendMessage
13 - cancelQueued
14---
15​
16Queueing decides what happens when the user sends a message while a reply is still streaming: wait, ignore it, or stop the current run.
17​
18`useChat` has a message queue for this. By default, the new message waits and sends after the current run succeeds.
19​
20## Quick setup
21​
22### 1. Show the queue next to the messages
23​
24`useChat` returns `queue` apart from `messages`. `cancelQueued(id)` removes an item before it sends:
25​
26```tsx
27import { useState } from "react";
28import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
29​
30export function Chat() {
31 const [input, setInput] = useState("");
32 const { messages, queue, sendMessage, cancelQueued } = useChat({
33 connection: fetchServerSentEvents("/api/chat"),
34 threadId: "support-chat",
35 queue: { whenBusy: "queue", maxSize: 5 },
36 });
37​
38 return (
39 <>
40 {messages.map((message) => (
41 <div key={message.id}>
42 {message.parts.map((part, index) =>
43 part.type === "text" ? <p key={index}>{part.content}</p> : null,
44 )}
45 </div>
46 ))}
47​
48 {queue.map((item) => (
49 <div key={item.id} className="pending">
50 {typeof item.content === "string" ? item.content : "[attachment]"}
51 <button type="button" onClick={() => cancelQueued(item.id)}>
52 Cancel
53 </button>
54 </div>
55 ))}
56​
57 <form
58 onSubmit={(event) => {
59 event.preventDefault();
60 if (input.trim() === "") {
61 return;
62 }
63 sendMessage(input);
64 setInput("");
65 }}
66 >
67 <input
68 value={input}
69 onChange={(event) => setInput(event.target.value)}
70 />
71 <button type="submit">Send</button>
72 </form>
73 </>
74 );
76```
77​
78The send button stays active during a stream. Give `queue` items a different style from `messages`, so the user can see what is still waiting.
79​
80### 2. Pick the rule for a busy send
81​
82Set `whenBusy` in the `queue` option. A string is a short form of `{ whenBusy }`, so `queue: "interrupt"` also works.
83​
84- `"queue"` (default): hold the message. It sends after the current run succeeds.
85- `"drop"`: ignore the send. The promise still resolves, but the message never shows in `queue` or `messages`. If you want the user to try again, keep the composer text.
86- `"interrupt"`: stop the current stream and send the new message now. Messages that already wait in the queue stay there. They send after the interrupting message succeeds.
87​
88### 3. Change the rule for one send
89​
90Pass options as the second argument to `sendMessage`:
91​
92```tsx
93import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
94​
95export function InterruptButton() {
96 const { sendMessage } = useChat({
97 connection: fetchServerSentEvents("/api/chat"),
98 threadId: "support-chat",
99 });
100​
101 return (
102 <button
103 type="button"
104 onClick={() =>
105 sendMessage("Never mind, do this instead", {
106 whenBusy: "interrupt",
107 body: { source: "composer" },
108 })
109 }
110 >
111 Do this instead
112 </button>
113 );
115```
116​
117`body` is extra JSON for this one request. The client merges it into `forwardedProps`.
118​
119## How it works
120​
121The client is busy in three cases:
122​
123- a stream is active
124- a send is in progress
125- the queue is sending its items
126​
127A send that arrives while the client is busy follows `whenBusy`. The queue sends its items only after a run ends with success. If the run fails or stops, the queue empties without sending.
128​
129## Advanced
130​
131### All queue options
132​
133| Option | Values | Default | What it does |
134| --- | --- | --- | --- |
135| `whenBusy` | `"queue"`, `"drop"`, `"interrupt"` | `"queue"` | The rule for a send while the client is busy. |
136| `drain` | `"fifo"`, `"batch"` | `"fifo"` | `"fifo"` sends queued items one at a time, in order. `"batch"` merges the queue into one send. |
137| `maxSize` | a non-negative integer | no limit | How many messages can wait. `0` means that nothing waits. |
138| `onOverflow` | `"reject"`, `"drop-oldest"` | `"reject"` | `"reject"` ignores a send when the queue is full. `"drop-oldest"` removes the oldest item to make room. |
139​
140How `"batch"` merges the items:
141​
142- Text items join with `\n`.
143- Multimodal parts stay in order.
144- The `body` of the last item wins.
145​
146### A strategy function
147​
148For control over each send, pass a function as `queue`. It gets the pending message, the reason the client is busy, and the current queue. It returns an action:
149​
150```tsx
151import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
152​
153export function useQueuedChat() {
154 return useChat({
155 connection: fetchServerSentEvents("/api/chat"),
156 threadId: "support-chat",
157 queue: ({ pending, busyReason, queued }) => {
158 // Let the user cut in with a message that starts with "!".
159 if (typeof pending.content === "string" && pending.content.startsWith("!")) {
160 return { action: "interrupt" };
161 }
162 // Keep at most 3 waiting messages during a stream.
163 if (busyReason === "streaming" && queued.length >= 3) {
164 return { action: "drop" };
165 }
166 return { action: "queue" };
167 },
168 });
170```
171​
172`busyReason` is one of `"streaming"`, `"sendInFlight"`, or `"draining"`. A strategy function always sends the queue in FIFO order. A `whenBusy` on one `sendMessage` call still wins over the function.
173​
174### When the queue sends and when it empties
175​
176- **Send.** The queue sends its items only after a stream ends with success. This includes the end of tool continuations.
177- **Empty without sending.** The queue empties when the active run fails or stops (`stop()` or a real stream error). It also empties on `clear()`, `unsubscribe()`, and `reload()`.
178- **`interrupt` keeps the queue.** Items that already wait stay in the queue. They send after the interrupting turn succeeds.