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