ai-client: seeding an in-flight run with initialResumeSnapshot skips the server hydrate when persistence: true #2228
TanStack AI version#
@tanstack/ai-client 1.2.1, @tanstack/ai 1.8.0 (both latest on npm); @tanstack/ai-react 1.1.1 for the first-render point
Framework/Library version#
Node 26.12.0; React with @tanstack/ai-react 1.1.1 (SSR). The repro uses ChatClient directly
Describe the bug and the steps to reproduce it#
A server-rendered page knows the thread's active run (reconstructChat returns activeRun). A fresh ChatClient has no run id until its mount hydrate rejoins the run, and until then stop() sends no cancel (hadLocalStream). The only way to seed a run is initialResumeSnapshot (ChatResumeSnapshot, tagged @internal). With persistence: true and history: { pageSize } it breaks the mount:
- No hydrate.
attach()rejoins the snapshot's run first.hydrateFromServerthen returns early becauseabortControlleris set (chat-client.ts:1286), and nothing calls it again, so the stored thread is never loaded. - The next send posts the whole thread. A rejoin records no known server message ids. Only the hydrate,
loadOlderand a completed send callrememberServerMessageIds(:1347,:3596,:3632). So the follow-up posts[user, assistant, new user]instead of[assistant, new user], which defeatshistory's "a send posts only the new turn". - The first render says the run is finished.
getSnapshot()right after construction hasisLoading: false.useChat(@tanstack/ai-react1.1.1) renders that snapshot first and callsattach()only in an effect, so the server-rendered HTML shows the run as finished. The script measures the snapshot; the React part comes from readinguse-chat.js.
Steps:
- Install
@tanstack/ai-client@1.2.1and@tanstack/ai@1.8.0in an ESM package. - Save the script below as
repro.mjsand runnode repro.mjs.
repro.mjs:
import { ChatClient, fetchServerSentEvents } from '@tanstack/ai-client'
const sse = (chunk) => `data: ${JSON.stringify(chunk)}\n\n`
const tick = (ms = 20) => new Promise((r) => setTimeout(r, ms))
const u1 = { id: 'u1', role: 'user', parts: [{ type: 'text', content: 'Question' }] }
// Fake server. Thread t1 holds u1; run r1 is still generating the answer a1.
function fakeServer(log) {
return async (url, init = {}) => {
const method = init.method ?? 'GET'
const { pathname, searchParams } = new URL(url, 'http://x')
if (method === 'GET' && searchParams.has('threadId')) {
log.push(`${method} ${url}`)
return Response.json({ messages: [u1], activeRun: { runId: 'r1' } })
}
if (method === 'GET' && searchParams.get('runId') === 'r1') {
log.push(`${method} ${url}`)
return new Response(
sse({ type: 'RUN_STARTED', threadId: 't1', runId: 'r1' }) +
sse({ type: 'TEXT_MESSAGE_START', messageId: 'a1', role: 'assistant' }) +
sse({ type: 'TEXT_MESSAGE_CONTENT', messageId: 'a1', delta: 'Answer' }) +
sse({ type: 'TEXT_MESSAGE_END', messageId: 'a1' }) +
sse({ type: 'RUN_FINISHED', threadId: 't1', runId: 'r1' }),
{ headers: { 'Content-Type': 'text/event-stream' } },
)
}
if (method === 'POST' && pathname === '/api/chat') {
const { messages, threadId, runId } = JSON.parse(init.body)
log.push(`${method} ${url} messages=[${messages.map((m) => `${m.role}:${m.id}`).join(', ')}]`)
return new Response(
sse({ type: 'RUN_STARTED', threadId, runId }) + sse({ type: 'RUN_FINISHED', threadId, runId }),
{ headers: { 'Content-Type': 'text/event-stream' } },
)
}
throw new Error(`unexpected request: ${method} ${url}`)
}
}
async function run(label, withSnapshot) {
const log = []
const client = new ChatClient({
threadId: 't1',
persistence: true,
history: { pageSize: 500 },
initialMessages: [u1],
...(withSnapshot && { initialResumeSnapshot: { resumeState: { threadId: 't1', runId: 'r1' } } }),
connection: fetchServerSentEvents('/api/chat', { fetchClient: fakeServer(log) }),
})
// useChat renders this snapshot first (SSR and first client render); attach() runs later, in an effect.
const first = client.getSnapshot()
console.log(`\n[${label}] first render: isLoading=${first.isLoading} status=${first.status}; requests before attach: ${log.length}`)
client.attach()
while (client.isLoading || client.getSnapshot().isHydrating) await tick()
await tick()
console.log(`[${label}] mount requests:\n ${log.join('\n ')}`)
log.length = 0
await client.sendMessage('Follow-up')
console.log(`[${label}] follow-up send:\n ${log.join('\n ')}`)
client.dispose()
}
await run('no snapshot', false)
await run('with initialResumeSnapshot', true)
// Expected (bug):
// [no snapshot] first render: isLoading=false status=ready
// [no snapshot] mount requests:
// GET /api/chat?threadId=t1&limit=500
// GET /api/chat?offset=-1&runId=r1
// [no snapshot] follow-up send:
// POST /api/chat messages=[assistant:a1, user:<new>]
// [with initialResumeSnapshot] first render: isLoading=false status=ready <- run r1 is in flight
// [with initialResumeSnapshot] mount requests:
// GET /api/chat?offset=-1&runId=r1 <- no thread GET
// [with initialResumeSnapshot] follow-up send:
// POST /api/chat messages=[user:u1, assistant:a1, user:<new>] <- whole thread
Output:
[no snapshot] first render: isLoading=false status=ready; requests before attach: 0
[no snapshot] mount requests:
GET /api/chat?threadId=t1&limit=500
GET /api/chat?offset=-1&runId=r1
[no snapshot] follow-up send:
POST /api/chat messages=[assistant:a1, user:msg-1795468459785-0fkb64]
[with initialResumeSnapshot] first render: isLoading=false status=ready; requests before attach: 0
[with initialResumeSnapshot] mount requests:
GET /api/chat?offset=-1&runId=r1
[with initialResumeSnapshot] follow-up send:
POST /api/chat messages=[user:u1, assistant:a1, user:msg-1795468459836-ov7z9u]
Expected: With the snapshot, the mount still sends the thread GET and records the known ids, so the follow-up posts [assistant:a1, user:<new>]. The first snapshot has isLoading: true and the run id, so stop() can cancel at once. A public seed for an active run in server-authoritative mode (for example initialActiveRun: { runId }, or initialResumeSnapshot made public for this case) would cover all three.
Your Minimal, Reproducible Example - (Sandbox Highly Recommended)#
Inline above. Plain Node script, no network: a stub passed as fetchServerSentEvents's fetchClient plays the server and logs each request.
Screenshots or Videos (Optional)#
None.
Do you intend to try to help solve this bug with your own PR?#
Maybe, I'll investigate and start debugging
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 labelsneeds-repro
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelsneeds-repro
I added a minimal, runnable reproduction to the description: a plain Node script with no network, no model and no API key, tested on the current npm releases.
Sign in to join this conversation.
Thanks for the report, @ozolcar! To help us reproduce this, could you add a minimal reproduction?
A runnable example makes fixes dramatically faster — you can fork one of the official examples, or use StackBlitz / CodeSandbox. For TypeScript-only issues, a TS Playground link works too.
Automated triage — a maintainer will follow up.