streamText: a stable hook awaited before the result settles
The gap
A library that persists a generation (we save every step to a database) needs
to finish its write for the last step before anyone can observe that the
generation ended: before fullStream yields finish, and before text,
steps and finishReason resolve. If the write fails, the caller should see
that failure where it sees other stream errors.
No stable callback gives this today (ai 7.0.153):
onEndruns aftertext,stepsandfinishReasonhave resolved, isn't called when the stream is aborted or no step finished, and a throw in it doesn't reject anything.onChunkis awaited before the result settles, but the part is forwarded first, sofullStreamreaders seefinishbefore the write ends. A throw in it doesn't reject anything either.onStepEndruns beforestopWhen, so it can't know whether this step is the last one.
The one thing that works is an experimental_transform that awaits the write
when it sees finish and only then enqueues it. That puts a core persistence
path on an experimental API.
A related gap: transforms run once per retry segment, and a transform's
flush can't tell a segment that ended because a transform called
stopStream from one that ended at a retry boundary. To fail a step that
stopStream cut off, before text resolves, we wrap every transform's
stopStream to record that it was called.
Minimal repro
import { streamText } from "ai";
import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const model = () =>
new MockLanguageModelV4({
doStream: async () => ({
stream: simulateReadableStream({
chunks: [
{ type: "stream-start", warnings: [] },
{ type: "text-start", id: "1" },
{ type: "text-delta", id: "1", delta: "Hello" },
{ type: "text-end", id: "1" },
{
type: "finish",
finishReason: { unified: "stop", raw: "stop" },
usage: {
inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
outputTokens: { total: 1, text: 1, reasoning: 0 },
},
},
],
}),
}),
});
// onEnd: `text` resolves while the write is still running.
let saved = false;
const a = streamText({
model: model(),
prompt: "Hi",
onEnd: async () => {
await sleep(100);
saved = true;
},
});
console.log(await a.text, saved); // "Hello" false
// onChunk: `fullStream` yields `finish` before the write ends.
saved = false;
const b = streamText({
model: model(),
prompt: "Hi",
onChunk: async ({ chunk }) => {
if (chunk.type !== "finish") return;
await sleep(100);
saved = true;
},
});
for await (const part of b.fullStream) {
if (part.type === "finish") console.log(saved); // false
}
// A failed write can't fail the result.
const c = streamText({
model: model(),
prompt: "Hi",
onEnd: async () => {
throw new Error("save failed");
},
});
console.log(await c.text); // "Hello", no rejection
Only an experimental_transform that awaits before enqueueing finish makes
saved true in both places.
The hook we'd want
Either of these would let us drop the transform:
-
Stabilise
experimental_transformastransform, documenting that parts reachfullStreamand the result only after the transform passes them on, that it runs per retry segment, and thatflushruns at a segment's end. Passflushthe reason the segment ended ("finish","stop","error"or"retry"). -
An
onBeforeEndcallback, awaited once after the lastonStepEndand beforefinishis emitted and the result promises settle, including when the stream ends withoutfinish:onBeforeEnd?: (event: { reason: "finish" | "stop" | "error" | "abort"; steps: StepResult<TOOLS>[]; error?: unknown; }) => PromiseLike<void> | void;A throw in it would error the stream and reject
text,stepsand the other result promises with that error.
Option 2 is narrower and covers both gaps: reason: "stop" replaces our
stopStream wrapper, and the throw semantics replace our own error plumbing.
Identify issue type
Identified as Feature
Confidence: High
Rationale
The issue requests a new lifecycle capability and stronger completion/error semantics, rather than reporting a failure of existing promised behavior.
Evidence
- Requests either stabilizing experimental_transform with segment-end metadata or adding an awaited onBeforeEnd callback.
- Needs persistence to complete before finish is emitted and result promises resolve, with write failures propagated to callers.
- Describes limitations of existing callbacks without claiming they violate documented guarantees.