Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai): stop copying the whole answer on every text chunk #1962

Mergedtombeckenhammerged 3 commits intomain fromrefs/pull/1962/headmerged by AlemTuzlak View on GitHub

Showing 3 changed files with 116 additions and 9 deletions.

x
0 of 3 viewed, 3 left
5 additions and 0 deletions.changeset/chat-text-accumulation.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+'@tanstack/ai': patch
+---
+​
+Stop `chat()` from copying the whole assistant answer on every text chunk. A long reply streamed as small deltas no longer blocks the server for seconds.
20 additions and 9 deletionspackages/ai/src/activities/chat/index.tsModified
View file
@@ -2408,20 +2408,31 @@
// Alignment suppresses already-delivered deltas, so this snapshot is
// what a takeover saves as the full assistant text.
const before = this.accumulatedContent
+ let delta: string
if (typeof extra.content === 'string' && extra.content !== '') {
- this.accumulatedContent = extra.content
+ const next = extra.content
+ this.accumulatedContent = next
+ // `startsWith(before)` flattens the whole rope on every chunk, so a
+ // long answer of small deltas is O(n²) and does not yield. A normal
+ // snapshot is `before` plus this delta; the lengths say so without
+ // reading the text. ponytail: length check. A same-length prefix
+ // rewrite falls out later, when turn text disagrees with
+ // `accumulatedContent` and block order is dropped.
+ if (next.length === before.length + chunk.delta.length) {
+ delta = chunk.delta
+ } else if (!this.turnParts || !next.startsWith(before)) {
+ // A cumulative `content` snapshot rewrote earlier text; order unknown.
+ this.turnParts = null
+ delta = ''
+ } else {