Open History to see the last commit
1import { getChunkRunId } from './connection-adapters'
2import type { StreamChunk } from '@tanstack/ai/client'
3import type {
4 ChatClientPersistence,
5 ChatPersistedState,
6 ChatResumeSnapshot,
7 UIMessage,
8} from './types'
9
10// `StreamChunk` is a discriminated union; `toolCallId` / `messageId` /
11// `parentMessageId` exist on only some members. Narrow with `in` (matching
12// `getChunkRunId`) instead of asserting a shape, so the field's real type is
13// preserved and a protocol rename can't be read past silently.
14function getChunkToolCallId(chunk: StreamChunk): string | undefined {
15 return 'toolCallId' in chunk && typeof chunk.toolCallId === 'string'
16 ? chunk.toolCallId
17 : undefined
18}
19
20function getChunkMessageId(chunk: StreamChunk): string | undefined {
21 return 'messageId' in chunk && typeof chunk.messageId === 'string'
22 ? chunk.messageId
23 : undefined
24}
25
26function getChunkParentMessageId(chunk: StreamChunk): string | undefined {
27 return 'parentMessageId' in chunk && typeof chunk.parentMessageId === 'string'
28 ? chunk.parentMessageId
29 : undefined
30}
31
32/**
33 * Encapsulates everything persistence-related for `ChatClient` so the client
34 * itself stays focused on streaming and message state.
35 *
36 * Two responsibilities live here:
37 *
38 * 1. **Storage orchestration** — hydrate from `getItem(id)` on creation, save a
39 * combined `{ messages, resume? }` record via `setItem` on every change
40 * through an ordered write queue, and `removeItem(id)` on clear (or when
41 * both the transcript and resume pointer are empty). A generation counter
42 * discards stale writes when a removal or a newer conversation supersedes
43 * an in-flight async operation.
44 * 2. **Clear-during-stream suppression** — when a conversation is cleared while a
45 * stream is still producing, late chunks for the cleared run(s) must not
46 * repopulate the now-empty state. The persistor tracks the cleared ids and
47 * decides, per chunk, whether the client should ignore it.
48 *
49 * All adapter calls are best-effort: a throwing or rejecting adapter is swallowed
50 * so storage problems never break the chat.
51 */
52export class ChatPersistor {
53 // --- storage queue state ---
54 private skipNextPersist = false
55 private generation = 0
56 private queue: Promise<void> = Promise.resolve()
57 private queuePending = false
58 // Bumped on every message change; lets an in-flight async hydration detect
59 // that the message list moved on and avoid clobbering it.
60 private messagesGeneration = 0
61 // Latest messages + resume snapshot, written together as one combined record
62 // so a full page reload restores both from a single adapter key.
63 private lastMessages: Array<UIMessage> = []
64 private lastResume: ChatResumeSnapshot | null = null
65 // The stored value is in the 0.x format (a bare `UIMessage[]`). 1.0 does not
66 // read it, and must not overwrite it either, so writes stop until a clear.
67 private legacyStored = false
68
69 // --- clear-during-stream suppression state ---
70 private readonly clearedMessageIds = new Set<string>()
71 private readonly clearedRunIds = new Set<string>()
72 private readonly ignoredActiveRunIds = new Set<string>()
73 private readonly clearedToolCallIds = new Set<string>()
74 private currentRunlessRunId: string | null = null
75
76 constructor(
77 private readonly adapter: ChatClientPersistence,
78 private readonly id: string,
79 private readonly applyMessages: (messages: Array<UIMessage>) => void,
80 private readonly applyResume?: (snapshot: ChatResumeSnapshot) => void,
81 ) {}
82
83 /** Persist the current state as one combined `{ messages, resume? }` record. */
84 private writeState(): void {
85 if (this.legacyStored) return
86 const messages = [...this.lastMessages]
87 // Nothing to persist (no transcript, no resume pointer): remove the key
88 // rather than writing an empty `{ messages: [] }`, so a cleared
89 // conversation does not leave a stale record behind.
90 if (messages.length === 0 && !this.lastResume) {
91 const generation = this.generation
92 this.runOperation(() => {
93 if (generation !== this.generation) {
94 return
95 }
96 return this.adapter.removeItem(this.id)
97 })
98 return
99 }
100 const generation = this.generation
101 const state: ChatPersistedState = {
102 messages,
103 ...(this.lastResume ? { resume: this.lastResume } : {}),
104 }
105 this.runOperation(() => {
106 if (generation !== this.generation) {
107 return
108 }
109 return this.adapter.setItem(this.id, state)
110 })
111 }
112
113 // ---------------------------------------------------------------------------
114 // Storage orchestration
115 // ---------------------------------------------------------------------------
116
117 /** Validate a raw `getItem` result. */
118 private normalize(
119 raw: ChatPersistedState | null | undefined,
120 ): ChatPersistedState | undefined {
121 if (Array.isArray(raw)) {
122 this.legacyStored = true
123 console.error(
124 `[TanStack AI] The stored chat for threadId "${this.id}" is in the 0.x format (a bare message array). TanStack AI 1.0 does not read this format, so the chat starts empty and the stored value is not overwritten. Clear the chat or the stored value to start saving again.`,
125 )
126 return undefined
127 }
128 if (raw && Array.isArray(raw.messages)) return raw
129 return undefined
130 }
131
132 /**
133 * Synchronously read the persisted state for constructor-time hydration.
134 * Returns the normalized combined record, or a promise of it for async stores.
135 */
136 readInitial():
137 | ChatPersistedState
138 | undefined
139 | Promise<ChatPersistedState | undefined> {
140 try {
141 const raw = this.adapter.getItem(this.id)
142 if (raw instanceof Promise) {
143 return raw.then((value) => this.normalize(value)).catch(() => undefined)
144 }
145 const state = this.normalize(raw)
146 if (state) {
147 this.lastMessages = state.messages
148 this.lastResume = state.resume ?? null
149 }
150 return state
151 } catch {
152 return undefined
153 }
154 }
155
156 /**
157 * Apply state from an async `getItem` once it resolves, unless the message
158 * list has already changed since hydration began. Returns a promise that
159 * settles (never rejects) when it is done, or `undefined` for sync state.
160 */
161 hydrateAsync(
162 persistedState:
163 | ChatPersistedState
164 | undefined
165 | Promise<ChatPersistedState | undefined>,
166 ): Promise<void> | undefined {
167 if (!(persistedState instanceof Promise)) {
168 return undefined
169 }
170
171 const hydrationGeneration = this.messagesGeneration
172 return persistedState
173 .then((state) => {
174 if (!state || this.messagesGeneration !== hydrationGeneration) {
175 return
176 }
177 this.lastResume = state.resume ?? null
178 this.lastMessages = state.messages
179 this.applyMessages(state.messages)
180 if (state.resume && this.applyResume) {
181 this.applyResume(state.resume)
182 }
183 })
184 .catch(() => {
185 // Persistence adapters are best-effort and must not break chat setup.
186 })
187 }
188
189 /**
190 * Record a message-list change and queue a combined write for it. Skips a
191 * single write after {@link beginClear} so the clear's empty snapshot isn't
192 * persisted between `clearMessages()` and {@link remove}.
193 */
194 notifyMessagesChanged(messages: Array<UIMessage>): void {
195 this.messagesGeneration++
196 this.lastMessages = [...messages]
197 if (this.skipNextPersist) {
198 this.skipNextPersist = false
199 return
200 }
201 this.writeState()
202 }
203
204 /**
205 * Record the current resume snapshot (which run to rejoin / which interrupts
206 * are pending) and persist it alongside the messages. Pass `null` to clear it
207 * once the run reaches a non-interrupt terminal.
208 */
209 persistResumeSnapshot(snapshot: ChatResumeSnapshot | null): void {
210 this.lastResume = snapshot
211 if (this.skipNextPersist) {
212 return
213 }
214 this.writeState()
215 }
216
217 /** Remove the persisted conversation. Invalidates any queued writes. */
218 remove(): void {
219 this.legacyStored = false
220 this.lastMessages = []
221 this.lastResume = null
222 const generation = ++this.generation
223 this.runOperation(() => {
224 if (generation !== this.generation) {
225 return
226 }
227 return this.adapter.removeItem(this.id)
228 })
229 }
230
231 private runOperation(operation: () => void | Promise<void>): void {
232 if (this.queuePending) {
233 const queued = this.queue.then(operation).catch(() => {
234 // Persistence adapters are best-effort and must not break chat updates.
235 })
236 this.queue = queued
237 void queued.finally(() => {
238 if (this.queue === queued) {
239 this.queuePending = false
240 }
241 })
242 return
243 }
244
245 try {
246 const result = operation()
247 if (result instanceof Promise) {
248 this.queuePending = true
249 const queued = result.catch(() => {
250 // Persistence adapters are best-effort and must not break chat updates.
251 })
252 this.queue = queued
253 void queued.finally(() => {
254 if (this.queue === queued) {
255 this.queuePending = false
256 }
257 })
258 }
259 } catch {
260 // Persistence adapters are best-effort and must not break chat updates.
261 }
262 }
263
264 // ---------------------------------------------------------------------------
265 // Clear-during-stream suppression
266 // ---------------------------------------------------------------------------
267
268 /**
269 * Capture the message/run ids that exist at the moment of a clear so chunks
270 * still arriving for them can be ignored.
271 */
272 snapshotClear(context: {
273 messages: Array<UIMessage>
274 activeRunIds: Set<string>
275 currentRunId: string | null
276 }): void {
277 for (const message of context.messages) {
278 this.clearedMessageIds.add(message.id)
279 }
280 for (const runId of context.activeRunIds) {
281 this.clearedRunIds.add(runId)
282 this.ignoredActiveRunIds.add(runId)
283 }
284 if (context.currentRunId) {
285 this.clearedRunIds.add(context.currentRunId)
286 this.ignoredActiveRunIds.add(context.currentRunId)
287 }
288 }
289
290 /** Mark that the next persisted message change (the clear itself) is skipped. */
291 beginClear(): void {
292 this.skipNextPersist = true
293 }
294
295 /** Whether a chunk belongs to cleared state and should not be processed. */
296 shouldIgnoreChunk(chunk: StreamChunk): boolean {
297 const runId = getChunkRunId(chunk)
298 if (runId && this.clearedRunIds.has(runId)) {
299 if (chunk.type === 'RUN_STARTED') {
300 this.ignoredActiveRunIds.add(runId)
301 this.currentRunlessRunId = runId
302 }
303 this.markIgnoredChunkIds(chunk)
304 return true
305 }
306
307 if (runId && this.ignoredActiveRunIds.has(runId)) {
308 this.markIgnoredChunkIds(chunk)
309 return true
310 }
311
312 if (this.isRunlessChunkFromIgnoredRun(chunk)) {
313 this.markIgnoredChunkIds(chunk)
314 return true
315 }
316
317 const toolCallId = getChunkToolCallId(chunk)
318 if (toolCallId && this.clearedToolCallIds.has(toolCallId)) {
319 return true
320 }
321
322 const parentMessageId = getChunkParentMessageId(chunk)
323 if (parentMessageId && this.clearedMessageIds.has(parentMessageId)) {
324 if (toolCallId) {
325 this.clearedToolCallIds.add(toolCallId)
326 }
327 return true
328 }
329
330 const messageId = getChunkMessageId(chunk)
331 if (!messageId) {
332 return false
333 }
334 if (this.clearedMessageIds.has(messageId)) {
335 return true
336 }
337
338 return false
339 }
340
341 /**
342 * The owning client calls this when a run starts so runless content chunks
343 * (adapters that omit `runId` on content events) can be attributed to it.
344 */
345 onRunStarted(runId: string): void {
346 this.currentRunlessRunId = runId
347 }
348
349 /** Forget a settled run, advancing the runless pointer to another ignored run. */
350 onRunSettled(runId: string): void {
351 this.ignoredActiveRunIds.delete(runId)
352 this.clearedRunIds.delete(runId)
353 if (this.currentRunlessRunId === runId) {
354 this.currentRunlessRunId =
355 this.ignoredActiveRunIds.values().next().value ?? null
356 }
357 }
358
359 /** A session-level (runId-less) RUN_ERROR clears all ignored-run tracking. */
360 onSessionRunError(): void {
361 this.ignoredActiveRunIds.clear()
362 this.currentRunlessRunId = null
363 }
364
365 /** Clear the ignored-active-run markers (mirrors a session-generating reset). */
366 resetIgnored(): void {
367 this.ignoredActiveRunIds.clear()
368 }
369
370 /**
371 * Consume the current runless run id (if any), forgetting it. Used when an
372 * ignored, runId-less RUN_ERROR drains the run the client is still tracking.
373 */
374 takeRunlessRunId(): string | null {
375 const runId = this.currentRunlessRunId
376 if (!runId) return null
377 this.ignoredActiveRunIds.delete(runId)
378 this.clearedRunIds.delete(runId)
379 // Advance to another still-ignored run (mirroring `onRunSettled`) so that
380 // when two cleared runs drain concurrently, draining one via a runId-less
381 // RUN_ERROR doesn't stop suppressing the other's runless content.
382 this.currentRunlessRunId =
383 this.ignoredActiveRunIds.values().next().value ?? null
384 return runId
385 }
386
387 private markIgnoredChunkIds(chunk: StreamChunk): void {
388 const messageId = getChunkMessageId(chunk)
389 if (messageId) {
390 this.clearedMessageIds.add(messageId)
391 }
392 const toolCallId = getChunkToolCallId(chunk)
393 if (toolCallId) {
394 this.clearedToolCallIds.add(toolCallId)
395 }
396 }
397
398 private isRunlessChunkFromIgnoredRun(chunk: StreamChunk): boolean {
399 const runId = getChunkRunId(chunk)
400 if (runId || !this.currentRunlessRunId) return false
401 if (
402 !this.ignoredActiveRunIds.has(this.currentRunlessRunId) &&
403 !this.clearedRunIds.has(this.currentRunlessRunId)
404 ) {
405 return false
406 }
407 return (
408 chunk.type === 'TEXT_MESSAGE_START' ||
409 chunk.type === 'TEXT_MESSAGE_CONTENT' ||
410 chunk.type === 'TEXT_MESSAGE_CHUNK' ||
411 chunk.type === 'TOOL_CALL_START' ||
412 chunk.type === 'TOOL_CALL_ARGS' ||
413 chunk.type === 'TOOL_CALL_END' ||
414 chunk.type === 'TOOL_CALL_RESULT' ||
415 chunk.type === 'TOOL_CALL_CHUNK' ||
416 chunk.type === 'MESSAGES_SNAPSHOT' ||
417 chunk.type === 'RUN_ERROR'
418 )
419 }
420}