Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai): run onAbort when a chat() consumer stops iterating #2098

Mergedaayushbtw(GitHub profile, opens in a new tab)merged 4 commits intomain fromrefs/pull/2098/headmerged by tombeckenham View on GitHub

Showing 9 changed files with 14 additions and 3 deletions (loading 5).

x
0 of 9 viewed, 9 left
5 additions and 0 deletions.changeset/chat-consumer-stop-onabort.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+'@tanstack/ai': patch
+---
+​
+A `chat()` consumer that stops iterating (`break` or `return()`) now runs the middleware `onAbort` hook, so every run gets exactly one terminal hook. Stopping at a client-tool or approval pause's `RUN_FINISHED` chunk runs `onFinish`, as a drained pause does, so the paused state (such as a `withSandbox` sandbox) is kept. Stopping at a `RUN_ERROR` chunk runs `onError`.
8 additions and 2 deletionsdocs/advanced/middleware-advanced.mdModified
View file
@@ -785,12 +785,18 @@
| Hook | When it runs |
| --- | --- |
| `onFinish` | The run completed normally |
-| `onAbort` | The run was aborted: by `ctx.abort()`, by an external `AbortSignal`, or by an `abort` decision from `onBeforeToolCall` |
+| `onAbort` | The run was aborted: by `ctx.abort()`, by an external `AbortSignal`, by an `abort` decision from `onBeforeToolCall`, or by a consumer that stopped iterating (`break` or `return()`) |
| `onError` | An error was not handled |
​
`onFinish` also runs when the call pauses for a client tool or an approval. The run is not complete yet. To tell a pause from a completion, look in `onChunk` for a `RUN_FINISHED` chunk with `outcome.type === 'interrupt'`.
​
-`onAbort` gets `info.cancelRequested`. It is `true` only when an explicit cancel aborted the run, never when the client only disconnected.
+When a consumer stops iterating, the chunk it stopped at decides the hook:
+​
+- A `RUN_FINISHED` chunk with `outcome.type === 'interrupt'`: `onFinish`.
+- A `RUN_ERROR` chunk: `onError`.
+- Any other chunk, including the final `RUN_FINISHED` of a completed run: `onAbort`.
+​
+`onAbort` gets `info.cancelRequested`. It is `true` only when an explicit cancel aborted the run. It is `false` when the client disconnected or the consumer stopped iterating. A consumer stop has no `info.reason`.
​
```typescript
import { type ChatMiddleware } from "@tanstack/ai";