withPersistence keeps the pre-merge index of an activity started before the init onConfig (e.g. after withSandbox's sandbox.starting) #2246
TanStack AI version#
@tanstack/ai 1.8.0, @tanstack/ai-persistence 1.1.0, @tanstack/ai-sandbox 1.5.0 (withPersistence on main has the same line)
Framework/Library version#
Node 26.12.0, server only (no UI framework involved)
Describe the bug and the steps to reproduce it#
With withPersistence, an activity row that a run starts before the init onConfig merge keeps the index it got against the request's messages, not the merged thread. On reload, reconstructChat puts that row near the top of the thread.
It happens on every run with withSandbox from @tanstack/ai-sandbox 1.2.0 or later. withSandbox sends sandbox.starting from setup, runWhileYielding drains it, and the drain sends a synthetic RUN_STARTED first, still in the init phase. A middleware that starts an activity on RUN_STARTED (an ACTIVITY_SNAPSHOT returned from onChunk) now runs before withPersistence.onConfig has merged the stored thread. The engine indexes the row against interleaveActivityRecords(modelMessagesToUIMessages(this.messages), this.activities), which at that point is the request alone. Then onConfig keeps that index:
const index = byId.get(record.id)?.index ?? record.index;
So the first follow-up's row is stored at 1 instead of 4, the next at 1 instead of 7, and so on. Sending the full transcript as messages reduces the error but does not remove it: the request has the messages but not the stored activity rows, so the indices come out 1, 3, 5.
Steps:
- Install
@tanstack/ai@1.8.0and@tanstack/ai-persistence@1.1.0in an ESM package. - Save the script below as
repro.mjsand runnode repro.mjs.
repro.mjs:
import { chat } from "@tanstack/ai";
import { memoryPersistence, withPersistence } from "@tanstack/ai-persistence";
const adapter = (turn) => ({
kind: "text", name: "fake", model: "m",
async *chatStream(o) {
const b = { runId: o.runId, threadId: o.threadId, timestamp: Date.now() };
yield { ...b, type: "RUN_STARTED" };
yield { ...b, type: "TEXT_MESSAGE_START", messageId: `a-${turn}`, role: "assistant" };
yield { ...b, type: "TEXT_MESSAGE_CONTENT", messageId: `a-${turn}`, delta: "answer" };
yield { ...b, type: "TEXT_MESSAGE_END", messageId: `a-${turn}` };
yield { ...b, type: "RUN_FINISHED", finishReason: "stop" };
},
});
// Starts one activity per run, as a trail or progress row does.
const research = {
name: "research",
onChunk: (ctx, c) => c.type === "RUN_STARTED"
? [c, { type: "ACTIVITY_SNAPSHOT", messageId: `research-${ctx.runId}`, activityType: "r", content: {}, timestamp: Date.now() }]
: undefined,
};
// What withSandbox 1.2.0+ does in setup.
const setupEvent = { name: "setup-event", setup: (ctx) => ctx.emitCustomEvent("sandbox.starting", {}) };
for (const early of [false, true]) {
const p = memoryPersistence();
for (const turn of [1, 2, 3]) {
for await (const _ of chat({
adapter: adapter(turn), threadId: "t", runId: `run-${turn}`,
messages: [{ id: `u-${turn}`, role: "user", content: `q${turn}` }],
middleware: [...(early ? [setupEvent] : []), withPersistence(p), research],
})) {}
}
console.log(early, (await p.stores.activities.loadActivities("t")).map((r) => r.index));
}
// false [ 1, 4, 7 ]
// true [ 1, 1, 1 ]
Expected: [1, 4, 7] in both cases: each run's row right after its user turn.
A possible fix. In onConfig, a record that is not in the store and whose index is at or past the end of the request's transcript was started before the merge. Move it by the difference between the merged transcript's end and the request's:
const kept = keptActivities(await activityStore.loadActivities(ctx.threadId), stored, storedCutoff(stored, config.messages));
const byId = new Map(kept.map((record) => [record.id, record]));
const requestEnd = modelMessagesToUIMessages(config.messages).length;
const early = (ctx.activities ?? []).filter((record) => !byId.has(record.id) && record.index >= requestEnd);
const tailStart = Math.min(...early.map((record) => record.index));
const mergedEnd = modelMessagesToUIMessages(patch.messages).length + kept.length;
for (const record of ctx.activities ?? []) {
const index = byId.get(record.id)?.index ?? (early.includes(record) ? mergedEnd + record.index - tailStart : record.index);
byId.set(record.id, { ...record, index });
}
We run this as a local patch. Another option is for the engine not to send RUN_STARTED before the init config is applied, but that would delay sandbox.starting, whose point is to show a pending state early.
Your Minimal, Reproducible Example - (Sandbox Highly Recommended)#
Inline above. Plain Node script, no network, no model. setup-event stands in for withSandbox, so @tanstack/ai-sandbox is not needed to reproduce it.
Screenshots or Videos (Optional)#
None.
Do you intend to try to help solve this bug with your own PR?#
Yes, I think I know how to fix it and will discuss it in the comments of this issue
Terms & Code of Conduct#
- I agree to follow this project's Code of Conduct
- I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
ozolcar(GitHub profile, opens in a new tab) linked this to #2252
github-actions[bot](GitHub profile, opens in a new tab) added labelshas-pr
Sign in to join this conversation.