Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai-persistence): an activity row started before the merge goes after its turn #2252

Draftozolcar(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/2252/headopened View on GitHub

Showing 3 changed files with 28 additions and 0 deletions (loading 1).

x
0 of 3 viewed, 3 left
5 additions and 0 deletions.changeset/persistence-early-activity-index.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+'@tanstack/ai-persistence': patch
+---
+​
+Put a new activity row that sits after every request message after every merged message. Before, `withPersistence` kept the index such a row had against the request alone. This happened on every run with an event sent from `setup` (for example `withSandbox`'s `sandbox.starting`), because that event starts the run before the stored thread is merged. On reload, the run's activity row then showed near the top of the thread. An activity row that the request carries after its last message, and that the store does not have yet, also goes after that message now; before, it reconstructed one slot early.
23 additions and 0 deletionspackages/ai-persistence/src/middleware.tsModified
View file
@@ -2490,12 +2490,35 @@
storedCutoff(stored, config.messages),
).map((record) => [record.id, record]),
+ // A new row after every request message goes after every merged
+ // message. This covers a row the run started before this merge: an
+ // event sent from setup drains RUN_STARTED early, so the row was
+ // indexed against the request alone (#2246). `index` counts the
+ // earlier activity rows too, so subtract them. The engine indexed
+ // against the request as received, which is `ctx.messages` during
+ // init, not `config.messages` after earlier middleware.
+ // ponytail: assumes one row per index, like keptActivities.
+ const requestUi = modelMessagesToUIMessages([...ctx.messages]).length
+ const tail = new Set(
+ [...(ctx.activities ?? [])]
+ .sort((a, b) => a.index - b.index)
+ .filter(
+ (record, earlier) =>
+ !byId.has(record.id) && record.index - earlier >= requestUi,
+ ),
+ )
// Same merge as the messages: an inbound row replaces the stored row