`onFinish` from `createUIMessageStream` not called when aborted
Description
I noticed that the onFinish callback from createUIMessageStream isn't called when streamText gets aborted through the abortSignal. However, onFinish from toUIMessageStream does get called. Example:
const resultStream = createUIMessageStream<ChatMessage>({
execute: ({ writer: dataStream }) => {
const result = streamText({
abortSignal: AbortSignal.any([requestAbortSignal, responseAbortSignal.signal]),
...
});
const uiMessageStream = result.toUIMessageStream<ChatMessage>({
originalMessages: uiMessages,
onFinish: () => {
// DOES get called when aborted
// also when the request completes normally the response has no id here!!
}
});
dataStream.merge(uiMessageStream);
},
onFinish: async () => {
// NOT called when aborted
},
});
I also noticed that the response message in the onFinish from toUIMessageStream doesn't have an id and it's an empty string when the response completes successfully.
AI SDK Version
Using [email protected].
Ok, I figured out that when I set generateMessageId that it generates a message id for the response message passed to the onFinish from toUIMessageStream.
Still curious if it's expected that the onFinish from createUIMessageStream doesn't get called when it gets aborted.
I think this can be resolved by adding consumeStream to the onFinish handler.
import {consumeStream} from "ai";
// ...
return result.toUIMessageStreamResponse({
onFinish: async ({ isAborted }) => {
if (isAborted) {
console.log('Stream was aborted');
// Handle abort-specific cleanup
} else {
console.log('Stream completed normally');
// Handle normal completion
}
},
consumeSseStream: consumeStream, // here
});
}
But I am not using toUIMessageStreamResponse but createUIMessageStream. Is that the same?
Ah wait, I misunderstood. I think I understand now. I'll try that out 👍
Yep that works now 👍 🙏
@nicoalbanese our case is a bit different, we're using createUIMessageStream and pipeUIMessageStreamToResponse without toUIMessageStream where would the consumeStream go in this case? thank you!
Identify issue type
Identified as None
Confidence: High
Rationale
The reported failure was resolved through the existing stream-consumption configuration, and the remaining discussion is usage guidance rather than a product change or confirmed bug.
Evidence
- Maintainer explained that passing
consumeStreamasconsumeSseStreamenables abort handling andonFinish. - The reporter confirmed the suggested configuration works.
- The remaining comment asks how to apply the same setup with different stream APIs, making it a support question rather than a confirmed SDK defect.