Open History to see the last commit
1import { ByokBlockedError, ByokMissingError } from '@tanstack/ai/byok'
2import { byokFallbackProviderId } from './byok/client'
3import {
4 prepareResolvedByokHeaders,
5 resolveByokProviderId,
6} from './byok/resolve'
7import {
8 GENERATION_EVENTS,
9 GENERATION_STREAM_TRUNCATED_MESSAGE,
10 GENERATION_UNRESTORABLE_RESULT_MESSAGE,
11 clientStateFromResumeStatus,
12 createGenerationHydrationError,
13 createGenerationResultSnapshot,
14 parseGenerationResumeSnapshot,
15 updateGenerationResumeSnapshot,
16} from './generation-types'
17import { createNoOpGenerationDevtoolsBridge } from './devtools-noop'
18import { parseSSEResponse } from './sse-parser'
19import { restoreInboundChunk } from '@tanstack/ai/client'
20import type { StreamChunk } from '@tanstack/ai/client'
21import type { ByokClient } from './byok'
22import type {
23 ConnectConnectionAdapter,
24 GenerationHydrationResult,
25 RunAgentInputContext,
26} from './connection-adapters'
27import type {
28 AIDevtoolsClientMetadata,
29 AIDevtoolsGenerationProgress,
30 GenerationDevtoolsBridge,
31 GenerationDevtoolsBridgeOptions,
32} from './devtools'
33import type {
34 GenerationClientOptions,
35 GenerationClientState,
36 GenerationFetcher,
37 GenerationPersistenceOptions,
38 GenerationRestoredResult,
39 GenerationResumeSnapshot,
40 GenerationResumeState,
41 GenerationTransport,
42} from './generation-types'
43
44/**
45 * Callbacks stored in a ref so hooks can update them without recreating the client.
46 */
47// All optional fields explicitly allow `| undefined` so callers can spread
48// option bags (where each callback may be `undefined`) into the callbacks
49// ref under `exactOptionalPropertyTypes`.
50interface GenerationCallbacks<TResult, TOutput> {
51 onResult?: ((result: TResult) => TOutput | null | void) | undefined
52 onError?: ((error: Error) => void) | undefined
53 onProgress?: ((progress: number, message?: string) => void) | undefined
54 onChunk?: ((chunk: StreamChunk) => void) | undefined
55 onResultChange?: ((result: TOutput | null) => void) | undefined
56 onLoadingChange?: ((isLoading: boolean) => void) | undefined
57 onErrorChange?: ((error: Error | undefined) => void) | undefined
58 onStatusChange?: ((status: GenerationClientState) => void) | undefined
59 onResumeSnapshotChange?:
60 | ((snapshot: GenerationResumeSnapshot | undefined) => void)
61 | undefined
62 onResumeStateChange?:
63 | ((resumeState: GenerationResumeState | null) => void)
64 | undefined
65 reconstructResult?:
66 | ((restored: GenerationRestoredResult) => TResult | null)
67 | undefined
68}
69
70/**
71 * A lightweight, generic client for one-shot generation tasks
72 * (image, speech, transcription, summarize).
73 *
74 * Supports two transport modes:
75 * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom).
76 * Server wraps results in StreamChunk events with CUSTOM event names.
77 * - **Fetcher** — Direct async function call. No streaming protocol needed.
78 *
79 * @template TInput - The input type for the generation request
80 * @template TResult - The result type returned by the generation
81 *
82 * @example
83 * ```typescript
84 * // With streaming connection adapter
85 * const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({
86 * connection: fetchServerSentEvents('/api/generate/image'),
87 * onResultChange: setResult,
88 * onLoadingChange: setIsLoading,
89 * })
90 *
91 * // With fetcher (direct)
92 * const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({
93 * fetcher: async (input) => {
94 * const res = await fetch('/api/generate/image', {
95 * method: 'POST',
96 * body: JSON.stringify(input),
97 * })
98 * return res.json()
99 * },
100 * })
101 *
102 * await client.generate({ prompt: 'A sunset over mountains' })
103 * ```
104 */
105export class GenerationClient<
106 TInput extends Record<string, any>,
107 TResult,
108 TOutput = TResult,
109> {
110 private readonly connection: ConnectConnectionAdapter | undefined
111 private readonly fetcher: GenerationFetcher<TInput, TResult> | undefined
112 // Persistence handlers supplied as options (e.g. alongside a `fetcher`), used
113 // when the connection doesn't carry its own — the connection's handlers take
114 // precedence when both exist.
115 private readonly hydrateGenerationHandler:
116 | ConnectConnectionAdapter['hydrateGeneration']
117 | undefined
118 private readonly joinRunHandler:
119 | ConnectConnectionAdapter['joinRun']
120 | undefined
121 private uniqueId: string
122 private readonly devtoolsMetadata: AIDevtoolsClientMetadata
123 private readonly devtoolsBridge: GenerationDevtoolsBridge<TOutput>
124 private threadId: string
125 private readonly persistenceScope: string | undefined
126 // Server-driven mode (`persistence: true`): no local snapshot store; on mount
127 // the client hydrates the last generation for `threadId` from the server.
128 private readonly serverDriven: boolean = false
129 private body: Record<string, any>
130 private byok: ByokClient | undefined
131 private byokProvider: (() => string | undefined) | undefined
132 private result: TOutput | null = null
133 private input: TInput | null = null
134 private progress: AIDevtoolsGenerationProgress | null = null
135 private isLoading = false
136 private error: Error | undefined = undefined
137 private status: GenerationClientState = 'idle'
138 private resumeSnapshot: GenerationResumeSnapshot | undefined
139 private lastEmittedResumeState: string | undefined
140 private abortController: AbortController | null = null
141 private rejoinedRunId: string | undefined
142 private readonly callbacksRef: GenerationCallbacks<TResult, TOutput>
143 private devtoolsMounted = false
144 private disposed = false
145 private serverHydrationStarted = false
146
147 constructor(
148 options: Omit<
149 GenerationClientOptions<TInput, TResult, TOutput>,
150 'persistence' | 'threadId'
151 > &
152 GenerationPersistenceOptions &
153 GenerationTransport<TInput, TResult>,
154 ) {
155 // `threadId` is the only identity. Do not mint a random id during
156 // construct: hooks build this client during render.
157 this.threadId = options.threadId ?? ''
158 this.uniqueId = this.threadId
159 // The persistence scope is the explicit `threadId` and nothing else.
160 // The types require it whenever `persistence` is set. This field keeps a
161 // generated wire id from becoming a storage key for JS callers.
162 this.persistenceScope = options.threadId
163 this.connection = options.connection
164 this.fetcher = options.fetcher
165 this.hydrateGenerationHandler = options.hydrateGeneration
166 this.joinRunHandler = options.joinRun
167 this.body = options.body ?? {}
168 this.byok = options.byok
169 this.byokProvider = options.byokProvider
170 // `persistence` is `false`/omitted (ephemeral) or `true` (server-driven:
171 // hydrate the last generation for `threadId` from the server on mount).
172 this.serverDriven = options.persistence === true
173 // The types require `threadId` alongside `persistence`, so this only fires
174 // for JS callers. Warn rather than fall back silently: keying on the
175 // generated wire id would write a different slot every reload, restoring
176 // nothing while accumulating orphaned records.
177 if (options.persistence && !this.persistenceScope) {
178 console.warn(
179 '[TanStack AI] `persistence` needs a stable `threadId` to key on. Without one nothing will be restored after a reload. Pass a `threadId` derived from your own domain (e.g. `product-123-hero`).',
180 )
181 }
182 this.callbacksRef = {
183 onResult: options.onResult,
184 onError: options.onError,
185 onProgress: options.onProgress,
186 onChunk: options.onChunk,
187 onResultChange: options.onResultChange,
188 onLoadingChange: options.onLoadingChange,
189 onErrorChange: options.onErrorChange,
190 onStatusChange: options.onStatusChange,
191 onResumeSnapshotChange: options.onResumeSnapshotChange,
192 onResumeStateChange: options.onResumeStateChange,
193 reconstructResult: options.reconstructResult,
194 }
195
196 this.devtoolsMetadata = this.createDevtoolsMetadata(options.devtools)
197 this.devtoolsBridge = (
198 options.devtoolsBridgeFactory ?? createNoOpGenerationDevtoolsBridge
199 )<TOutput>(this.buildDevtoolsBridgeOptions())
200
201 // Mount hydration (`maybeHydrateFromServer`) is deliberately NOT run here. The framework
202 // hooks build this client inside `useMemo`, so the constructor executes in
203 // React's render phase; hydrating here would re-fire the hydrate GET on
204 // every discarded/speculative render, flooding the connection pool when
205 // several clients mount together. It is kicked off once from
206 // `mountDevtools`, which the hooks call from a commit-phase mount effect.
207 }
208
209 private buildDevtoolsBridgeOptions(): GenerationDevtoolsBridgeOptions<TOutput> {
210 const client = this
211 return {
212 get hookId() {
213 return client.uniqueId
214 },
215 get clientId() {
216 return client.uniqueId
217 },
218 get threadId() {
219 return client.threadId
220 },
221 metadata: this.devtoolsMetadata,
222 getCoreState: () => ({
223 input: this.input,
224 result: this.result,
225 progress: this.progress,
226 status: this.status,
227 isLoading: this.isLoading,
228 ...(this.error ? { error: this.error.message } : {}),
229 }),
230 }
231 }
232
233 mountDevtools(): void {
234 this.ensureThreadId()
235 // Mounting revives a disposed client. Framework hooks call this from
236 // their mount effect, so a dispose → remount cycle (e.g. React
237 // StrictMode's mount → cleanup → mount replay against the same memoized
238 // client) leaves the client usable again.
239 this.disposed = false
240 this.maybeHydrateFromServer()
241 // Re-attach to an in-flight run whose snapshot is already loaded — the
242 // remount case. On the FIRST mount the snapshot loads asynchronously and
243 // `repaintRestoredSnapshot` starts the rejoin; on a StrictMode remount the
244 // snapshot is already present but the prior rejoin was aborted by
245 // `dispose()`, so retrigger it here. Guarded by `rejoinInFlight`'s own
246 // dedupe/in-flight checks, so this never double-joins.
247 this.maybeResumeInFlight()
248 if (this.devtoolsMounted) {
249 return
250 }
251
252 this.devtoolsMounted = true
253 this.devtoolsBridge.emitRegistered()
254 this.devtoolsBridge.emitSnapshot()
255 }
256
257 /**
258 * Trigger a generation request.
259 * Only one generation can be in-flight at a time; calling generate()
260 * while already generating will be a no-op.
261 */
262 async generate(input: TInput): Promise<void> {
263 if (this.disposed) return
264 if (this.isLoading) return
265 this.mountDevtools()
266
267 this.input = input
268 this.progress = null
269 const runId = this.devtoolsBridge.beginRun(input)
270 this.setIsLoading(true)
271 this.setStatus('generating')
272 this.setError(undefined)
273
274 const abortController = new AbortController()
275 this.abortController = abortController
276 const { signal } = abortController
277
278 try {
279 let headers: Record<string, string> | undefined
280 if (this.byok) {
281 const provider = resolveByokProviderId(
282 this.byokProvider,
283 this.body.provider,
284 byokFallbackProviderId(this.byok),
285 )
286 headers = await prepareResolvedByokHeaders(this.byok, provider)
287 }
288
289 if (this.fetcher) {
290 // Direct fetch path
291 const result = await this.fetcher(
292 input,
293 headers === undefined ? { signal } : { signal, headers },
294 )
295 if (signal.aborted) return
296 if (result instanceof Response) {
297 // Server function returned SSE Response — parse stream
298 await this.processStream(
299 parseSSEResponse(result, signal),
300 runId,
301 signal,
302 )
303 } else {
304 this.devtoolsBridge.ensureRunStarted(runId)
305 this.setResult(result)
306 this.setStatus('success')
307 this.completePlainFetcherResumeSnapshot(result)
308 }
309 } else if (this.connection) {
310 // Streaming adapter path
311 const mergedData = { ...this.body, ...input }
312 const stream = this.connection.connect(
313 [],
314 mergedData,
315 signal,
316 this.createRunContext(runId, headers),
317 )
318 await this.processStream(stream, runId, signal)
319 } else {
320 throw new Error(
321 'GenerationClient requires either a connection or fetcher option',
322 )
323 }
324 if (!signal.aborted && this.status === 'success') {
325 // Bump progress to 100 on successful completion so devtools
326 // snapshots reflect the final state. The bridge mirrors this in
327 // the run's recorded progress, but the snapshot reads `progress`
328 // from the client's core state.
329 this.progress = completeProgressValue(this.progress)
330 this.devtoolsBridge.finishRun(
331 this.devtoolsBridge.getActiveRunId() ?? runId,
332 'run:completed',
333 'completed',
334 )
335 }
336 } catch (err: unknown) {
337 if (signal.aborted) return
338 const error = err instanceof Error ? err : new Error(String(err))
339 if (error instanceof ByokMissingError) {
340 this.byok?.request(error.provider, 'missing')
341 }
342 if (error instanceof ByokBlockedError && error.reason === 'locked') {
343 this.byok?.request(error.provider, 'locked')
344 }
345 this.setError(error)
346 this.setStatus('error')
347 this.recordResumeSnapshotError(error)
348 this.devtoolsBridge.finishRun(
349 this.devtoolsBridge.getActiveRunId() ?? runId,
350 'run:errored',
351 'errored',
352 error.message,
353 )
354 this.callbacksRef.onError?.(error)
355 } finally {
356 if (this.abortController === abortController) {
357 this.abortController = null
358 this.setIsLoading(false)
359 }
360 }
361 }
362
363 /**
364 * Process a stream of AG-UI events from the streaming connection adapter.
365 *
366 * Throws {@link GENERATION_STREAM_TRUNCATED_MESSAGE} when the iteration ends
367 * without a terminal chunk. A `for await` over a stream that simply stops —
368 * proxy idle timeout, server restart, a durable log missing its terminal
369 * append — returns normally and would otherwise leave the caller's `status`
370 * on `generating` forever, with the persisted snapshot still `running` so
371 * every reload rejoins the same dead run. Throwing routes it through the
372 * caller's error path instead, which settles the status and rewrites the
373 * snapshot so nothing chases it again.
374 */
375 private async processStream(
376 source: AsyncIterable<StreamChunk>,
377 fallbackRunId: string,
378 signal: AbortSignal,
379 ): Promise<void> {
380 let streamRunId: string | undefined
381 let sawTerminalChunk = false
382
383 for await (const raw of source) {
384 if (signal.aborted) break
385
386 const chunk = restoreInboundChunk(raw)
387 this.callbacksRef.onChunk?.(chunk)
388 this.observeResumeSnapshot(chunk)
389 const chunkRunId =
390 'runId' in chunk && typeof chunk.runId === 'string'
391 ? chunk.runId
392 : undefined
393
394 // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- AG-UI EventType has ~22 variants; this consumer only handles the subset relevant to generation lifecycle.
395 switch (chunk.type) {
396 case 'RUN_STARTED': {
397 streamRunId = chunk.runId
398 this.devtoolsBridge.ensureRunStarted(chunk.runId)
399 break
400 }
401 case 'CUSTOM': {
402 this.devtoolsBridge.ensureRunStarted(streamRunId ?? fallbackRunId)
403 if (chunk.name === GENERATION_EVENTS.RESULT) {
404 this.setResult(chunk.value as TResult)
405 } else if (chunk.name === GENERATION_EVENTS.PROGRESS) {
406 const { progress, message } = chunk.value as {
407 progress: number
408 message?: string
409 }
410 this.setProgress(progress, message)
411 }
412 break
413 }
414 case 'RUN_FINISHED': {
415 streamRunId = chunk.runId
416 sawTerminalChunk = true
417 this.devtoolsBridge.ensureRunStarted(chunk.runId)
418 this.setStatus('success')
419 break
420 }
421 case 'RUN_ERROR': {
422 this.devtoolsBridge.ensureRunStarted(
423 chunkRunId ?? streamRunId ?? fallbackRunId,
424 )
425 // Spec RUN_ERROR message. Missing message uses this fallback.
426 const msg =
427 (chunk.message as string | undefined) || 'An error occurred'
428 throw new Error(msg)
429 }
430 default:
431 break
432 }
433 }
434
435 // An aborted read is a deliberate stop/dispose, not a truncation.
436 if (!sawTerminalChunk && !signal.aborted) {
437 throw new Error(GENERATION_STREAM_TRUNCATED_MESSAGE)
438 }
439 }
440
441 /**
442 * Abort any in-flight generation request.
443 */
444 stop(): void {
445 const runId = this.devtoolsBridge.getActiveRunId()
446 if (this.abortController) {
447 this.abortController.abort()
448 this.abortController = null
449 }
450 this.setIsLoading(false)
451 if (this.status === 'generating') {
452 this.setStatus('idle')
453 if (runId) {
454 this.devtoolsBridge.finishRun(runId, 'run:cancelled', 'cancelled')
455 }
456 }
457 // A stopped run is no longer resumable. Without this the in-memory
458 // snapshot stays `running`, and a remount's `maybeResumeInFlight` would
459 // rejoin a run the user just cancelled.
460 if (this.resumeSnapshot && this.resumeSnapshot.status === 'running') {
461 this.resumeSnapshot = {
462 ...this.resumeSnapshot,
463 resumeState: null,
464 status: 'idle',
465 }
466 this.notifyResumeSnapshotChanged()
467 }
468 }
469
470 /**
471 * Clear the result, error, and return to idle state. Also drops the client's
472 * in-memory resume snapshot, so a remount restores nothing. The server-side
473 * record is untouched — this client no longer writes one — so a full page
474 * reload under `persistence: true` re-hydrates the last generation again.
475 */
476 reset(): void {
477 this.stop()
478 this.setResult(null)
479 this.input = null
480 this.progress = null
481 this.devtoolsBridge.resetRuns()
482 this.setError(undefined)
483 this.setStatus('idle')
484 this.clearResumeSnapshot()
485 this.devtoolsBridge.emitState()
486 }
487
488 /**
489 * Update options without recreating the client.
490 */
491 updateOptions(
492 options: Partial<
493 Pick<
494 GenerationClientOptions<TInput, TResult, TOutput>,
495 | 'body'
496 | 'byok'
497 | 'byokProvider'
498 | 'onResult'
499 | 'onError'
500 | 'onProgress'
501 | 'onChunk'
502 >
503 >,
504 ): void {
505 if (options.body !== undefined) {
506 this.body = options.body ?? {}
507 }
508 if (options.byok !== undefined) {
509 this.byok = options.byok
510 }
511 if (options.byokProvider !== undefined) {
512 this.byokProvider = options.byokProvider
513 }
514 if (options.onResult !== undefined) {
515 this.callbacksRef.onResult = options.onResult
516 }
517 if (options.onError !== undefined) {
518 this.callbacksRef.onError = options.onError
519 }
520 if (options.onProgress !== undefined) {
521 this.callbacksRef.onProgress = options.onProgress
522 }
523 if (options.onChunk !== undefined) {
524 this.callbacksRef.onChunk = options.onChunk
525 }
526 }
527
528 dispose(): void {
529 this.disposed = true
530 // Teardown, NOT a user cancel: abort in-flight DELIVERY (this reader) but
531 // do NOT call `stop()` — `stop()` marks the run non-resumable and wipes the
532 // `running` snapshot, which is correct for a Stop button but wrong for an
533 // unmount / React StrictMode dispose. Clearing it here would destroy the
534 // in-memory resume state, so a remount of this same client instance could
535 // never rejoin. (A real page revisit re-hydrates from the server instead.)
536 // The run itself survives server-side (durable delivery), so the snapshot
537 // must stay `running` for the remount to resume it.
538 if (this.abortController) {
539 this.abortController.abort()
540 this.abortController = null
541 }
542 this.setIsLoading(false)
543 this.devtoolsBridge.dispose()
544 this.devtoolsMounted = false
545 // Re-arm mount hydration + rejoin so a remount resumes from the (preserved)
546 // snapshot. `mountDevtools` re-runs the hydration entry point and
547 // `maybeResumeInFlight`, both individually guarded.
548 this.serverHydrationStarted = false
549 this.rejoinedRunId = undefined
550 }
551
552 // ===========================
553 // Getters
554 // ===========================
555
556 getResult(): TOutput | null {
557 return this.result
558 }
559
560 getIsLoading(): boolean {
561 return this.isLoading
562 }
563
564 getError(): Error | undefined {
565 return this.error
566 }
567
568 getStatus(): GenerationClientState {
569 return this.status
570 }
571
572 getResumeSnapshot(): GenerationResumeSnapshot | undefined {
573 return this.resumeSnapshot
574 ? {
575 ...this.resumeSnapshot,
576 ...(this.resumeSnapshot.pendingArtifacts
577 ? { pendingArtifacts: [...this.resumeSnapshot.pendingArtifacts] }
578 : {}),
579 ...(this.resumeSnapshot.result
580 ? {
581 result: {
582 ...this.resumeSnapshot.result,
583 ...(this.resumeSnapshot.result.artifacts
584 ? { artifacts: [...this.resumeSnapshot.result.artifacts] }
585 : {}),
586 },
587 }
588 : {}),
589 ...(this.resumeSnapshot.error
590 ? { error: { ...this.resumeSnapshot.error } }
591 : {}),
592 ...(this.resumeSnapshot.lastEvent
593 ? { lastEvent: { ...this.resumeSnapshot.lastEvent } }
594 : {}),
595 }
596 : undefined
597 }
598
599 // ===========================
600 // Private state setters
601 // ===========================
602
603 private setResult(rawResult: TResult | null): void {
604 if (rawResult === null) {
605 this.result = null
606 this.callbacksRef.onResultChange?.(null)
607 this.devtoolsBridge.recordResultChange()
608 return
609 }
610
611 if (this.callbacksRef.onResult) {
612 const transformed = this.callbacksRef.onResult(rawResult)
613 if (transformed === null) {
614 // null return → keep previous result unchanged, just re-emit
615 this.devtoolsBridge.emitState()
616 return
617 }
618 if (transformed !== undefined) {
619 // Non-null, non-undefined → use transformed value
620 this.result = transformed
621 this.callbacksRef.onResultChange?.(this.result)
622 this.devtoolsBridge.recordResultChange()
623 return
624 }
625 }
626
627 // No onResult callback, or callback returned void → use raw value as
628 // TOutput. When the caller did not supply an onResult transform,
629 // `TOutput` defaults to `TResult`, so the runtime cast is sound.
630 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- TOutput defaults to TResult when no onResult transform is supplied
631 this.result = rawResult as unknown as TOutput
632 this.callbacksRef.onResultChange?.(this.result)
633 this.devtoolsBridge.recordResultChange()
634 }
635
636 private setIsLoading(isLoading: boolean): void {
637 this.isLoading = isLoading
638 this.callbacksRef.onLoadingChange?.(isLoading)
639 this.devtoolsBridge.recordLoadingChange()
640 }
641
642 private setError(error: Error | undefined): void {
643 this.error = error
644 this.callbacksRef.onErrorChange?.(error)
645 this.devtoolsBridge.recordErrorChange(error)
646 }
647
648 private setStatus(status: GenerationClientState): void {
649 this.status = status
650 this.callbacksRef.onStatusChange?.(status)
651 this.devtoolsBridge.recordStatusChange(status)
652 }
653
654 private setProgress(value: number, message?: string): void {
655 this.progress = {
656 value,
657 ...(message ? { message } : {}),
658 }
659 if (message === undefined) {
660 this.callbacksRef.onProgress?.(value)
661 } else {
662 this.callbacksRef.onProgress?.(value, message)
663 }
664 this.devtoolsBridge.recordProgressChange()
665 }
666
667 private createDevtoolsMetadata(
668 metadata?: Partial<AIDevtoolsClientMetadata>,
669 ): AIDevtoolsClientMetadata {
670 return {
671 hookName: metadata?.hookName ?? 'useGeneration',
672 ...(metadata?.framework ? { framework: metadata.framework } : {}),
673 ...(metadata?.outputKind ? { outputKind: metadata.outputKind } : {}),
674 ...(metadata?.name ? { name: metadata.name } : {}),
675 }
676 }
677
678 private ensureThreadId(): string {
679 if (!this.threadId) {
680 this.threadId = this.generateUniqueId('generation')
681 }
682 this.uniqueId = this.threadId
683 return this.threadId
684 }
685
686 private generateUniqueId(prefix: string): string {
687 return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`
688 }
689
690 private createRunContext(
691 runId: string,
692 headers?: Record<string, string>,
693 ): RunAgentInputContext {
694 return {
695 threadId: this.threadId,
696 runId,
697 ...(headers ? { headers } : {}),
698 }
699 }
700
701 private observeResumeSnapshot(chunk: StreamChunk): void {
702 this.resumeSnapshot = updateGenerationResumeSnapshot(
703 this.resumeSnapshot,
704 chunk,
705 )
706 this.notifyResumeSnapshotChanged()
707 }
708
709 /**
710 * Notify the (internal) snapshot listener AND emit the public resume state.
711 * The snapshot stays internal (persistence + devtools); the hook consumes
712 * `resumeState`, mirroring the chat client.
713 */
714 private notifyResumeSnapshotChanged(): void {
715 this.callbacksRef.onResumeSnapshotChange?.(this.resumeSnapshot)
716 this.emitResumeState()
717 }
718
719 /**
720 * Derive the public `resumeState` from the internal snapshot: the in-flight
721 * run identity, with any in-flight artifact refs folded under it. `null` once
722 * no run is in flight.
723 *
724 * The snapshot is rebuilt for every chunk, so emitting unconditionally would
725 * hand each framework hook a fresh object per chunk and re-render the
726 * component on every stream event. `resumeState` only changes at run
727 * boundaries and when artifacts land, so skip the notification unless it
728 * materially changed — same gate the persistence writes use.
729 */
730 private emitResumeState(): void {
731 const snapshot = this.resumeSnapshot
732 const state = snapshot?.resumeState
733 const resumeState: GenerationResumeState | null = state
734 ? {
735 ...state,
736 ...(snapshot?.pendingArtifacts && snapshot.pendingArtifacts.length > 0
737 ? { pendingArtifacts: [...snapshot.pendingArtifacts] }
738 : {}),
739 }
740 : null
741 const signature = JSON.stringify(resumeState)
742 if (signature === this.lastEmittedResumeState) {
743 return
744 }
745 this.lastEmittedResumeState = signature
746 this.callbacksRef.onResumeStateChange?.(resumeState)
747 }
748
749 /**
750 * Repaint the normal fields from a restored snapshot (client store or server
751 * hydrate), so a reload presents the run in `result` / `status` / `error`
752 * exactly as a just-finished run would, never a bolt-on snapshot object.
753 * `isLoading` stays false: the client never auto-tails a restored run. The
754 * snapshot is not re-persisted here (it came from storage / the server).
755 *
756 * When the activity's mapper DECLINES a `complete` snapshot the repaint
757 * settles as an error instead: `success` with a `null` result is a state no
758 * consumer can render, and it hides the real cause (an output artifact
759 * persisted without a serve URL). A decline on any other status is expected —
760 * a `running` snapshot has no result yet, the rejoin will deliver it.
761 */
762 private repaintFromSnapshot(snapshot: GenerationResumeSnapshot): void {
763 this.resumeSnapshot = snapshot
764 this.notifyResumeSnapshotChanged()
765 this.setStatus(clientStateFromResumeStatus(snapshot.status))
766 this.setError(
767 snapshot.error
768 ? Object.assign(
769 new Error(snapshot.error.message),
770 snapshot.error.code ? { code: snapshot.error.code } : {},
771 )
772 : undefined,
773 )
774 const restored = this.reconstructRestoredResult(snapshot)
775 if (restored !== null) {
776 this.setResult(restored)
777 } else if (
778 this.callbacksRef.reconstructResult &&
779 snapshot.status === 'complete'
780 ) {
781 this.reportUnrestorableResult()
782 }
783 }
784
785 /**
786 * Report a `complete` snapshot the activity's mapper could not rebuild.
787 * Runs after the status/error repaint above, so it wins over the snapshot's
788 * own `complete` status.
789 */
790 private reportUnrestorableResult(): void {
791 const error = new Error(GENERATION_UNRESTORABLE_RESULT_MESSAGE)
792 this.setStatus('error')
793 this.setError(error)
794 this.callbacksRef.onError?.(error)
795 }
796
797 /**
798 * Repaint a restored snapshot (client store or server hydrate) and, when it
799 * reports a run still in flight, tail that run to completion via `joinRun`
800 * (from the connection, or the `joinRun` option when the transport can't
801 * carry one).
802 *
803 * A `running` snapshot that no `joinRun` handler can tail is repainted as an
804 * interrupted error instead of a `generating` status that would never
805 * settle: an interrupted generation cannot be resumed, only re-run.
806 */
807 private repaintRestoredSnapshot(
808 snapshot: GenerationResumeSnapshot,
809 activeRunId?: string,
810 ): void {
811 if (snapshot.status !== 'running') {
812 this.repaintFromSnapshot(snapshot)
813 return
814 }
815 const joinRun = this.connection?.joinRun ?? this.joinRunHandler
816 const runId = activeRunId ?? snapshot.resumeState?.runId
817 if (runId && joinRun) {
818 this.repaintFromSnapshot(snapshot)
819 this.rejoinInFlight(runId)
820 return
821 }
822 this.repaintFromSnapshot({
823 ...snapshot,
824 resumeState: null,
825 status: 'error',
826 error: {
827 message:
828 'The previous generation was interrupted before it finished and cannot be resumed — generate again to retry.',
829 },
830 })
831 }
832
833 /**
834 * Build the restorable result shape from the snapshot and hand it to the
835 * per-activity `reconstructResult` mapper (injected by the specialized
836 * client/hook, which knows the concrete result type).
837 *
838 * Returns `null` both when no mapper is set (nothing to rebuild — `result`
839 * simply stays null) and when the mapper declines. The caller distinguishes
840 * the two: see {@link repaintFromSnapshot}.
841 */
842 private reconstructRestoredResult(
843 snapshot: GenerationResumeSnapshot,
844 ): TResult | null {
845 const build = this.callbacksRef.reconstructResult
846 if (!build) return null
847 const result = snapshot.result
848 const restored: GenerationRestoredResult = {
849 ...(result?.id !== undefined ? { id: result.id } : {}),
850 ...(result?.model !== undefined ? { model: result.model } : {}),
851 ...(result?.status !== undefined ? { status: result.status } : {}),
852 ...(result?.providerJobId !== undefined
853 ? { providerJobId: result.providerJobId }
854 : {}),
855 ...(result?.expiresAt !== undefined
856 ? { expiresAt: result.expiresAt }
857 : {}),
858 ...(result?.text !== undefined ? { text: result.text } : {}),
859 ...(result?.usage !== undefined ? { usage: result.usage } : {}),
860 ...(snapshot.activity !== undefined
861 ? { activity: snapshot.activity }
862 : {}),
863 artifacts: result?.artifacts ?? [],
864 }
865 return build(restored)
866 }
867
868 /**
869 * The plain (non-Response) fetcher path never observes stream chunks, so
870 * the terminal snapshot is built here from the fetcher's own result. A
871 * stale `error` from a previous run is intentionally dropped — this run
872 * succeeded.
873 */
874 private completePlainFetcherResumeSnapshot(rawResult: unknown): void {
875 const previous = this.resumeSnapshot
876 const result = createGenerationResultSnapshot(rawResult)
877 this.resumeSnapshot = {
878 schemaVersion: 1,
879 resumeState: null,
880 status: 'complete',
881 ...(previous?.activity ? { activity: previous.activity } : {}),
882 ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0
883 ? { pendingArtifacts: [...previous.pendingArtifacts] }
884 : {}),
885 ...(result
886 ? { result }
887 : previous?.result
888 ? { result: { ...previous.result } }
889 : {}),
890 }
891 this.notifyResumeSnapshotChanged()
892 }
893
894 /**
895 * Records a transport-level failure (network drop, throwing callback) in
896 * the snapshot. Without this, only a server-emitted RUN_ERROR chunk would
897 * mark the snapshot `error`, leaving a persisted record that claims the
898 * run is still in flight.
899 */
900 private recordResumeSnapshotError(error: Error): void {
901 // Surface the failure on the OBSERVABLE fields FIRST: a rejoin (or live
902 // stream) that emits RUN_ERROR has already flipped the snapshot to `error`
903 // via `observeResumeSnapshot`, so the early-return below would otherwise
904 // skip this and leave `status` stuck on `generating` — the run would look
905 // like it is still going forever. The guard avoids a duplicate `error`
906 // emission on the live `generate()` path, which sets the status itself.
907 if (this.status !== 'error') this.setStatus('error')
908 this.setError(error)
909 if (this.resumeSnapshot?.status === 'error') return
910 if (!this.resumeSnapshot && !this.serverDriven) return
911 const previous = this.resumeSnapshot
912 this.resumeSnapshot = {
913 schemaVersion: 1,
914 resumeState: null,
915 status: 'error',
916 ...(previous?.activity ? { activity: previous.activity } : {}),
917 ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0
918 ? { pendingArtifacts: [...previous.pendingArtifacts] }
919 : {}),
920 ...(previous?.result ? { result: { ...previous.result } } : {}),
921 error: { message: error.message },
922 }
923 this.notifyResumeSnapshotChanged()
924 }
925
926 /**
927 * Drop the client's in-memory snapshot and re-emit. Purely local — this
928 * client writes no storage, so nothing persisted is removed.
929 */
930 private clearResumeSnapshot(): void {
931 this.resumeSnapshot = undefined
932 this.lastEmittedResumeState = undefined
933 this.notifyResumeSnapshotChanged()
934 }
935
936 /**
937 * Server-driven mount hydration entry point (`persistence: true`). Runs at
938 * most once, from the commit-phase mount path (`mountDevtools`) — never the
939 * constructor / render phase — so remounts and speculative renders can't
940 * re-fire the hydrate GET.
941 */
942 private maybeHydrateFromServer(): void {
943 if (!this.serverDriven || this.serverHydrationStarted) return
944 this.serverHydrationStarted = true
945 if (this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler) {
946 this.hydrateFromServer()
947 } else {
948 // `persistence: true` without any hydrate source can never restore
949 // anything — warn rather than silently no-op.
950 console.warn(
951 '[TanStack AI] `persistence: true` (server-driven) needs a `hydrateGeneration` handler — either a connection that implements one (e.g. `fetchServerSentEvents` / `fetchHttpStream`, or `stream()` / `rpcStream()` with persistence handlers) or the `hydrateGeneration` option. Without one, nothing is persisted or restored.',
952 )
953 }
954 }
955
956 /**
957 * Server-driven mount hydration (`persistence: true`). The client holds no
958 * local snapshot; on mount it asks the server — keyed by the stable threadId —
959 * for the last generation's resume snapshot, validates it, and repaints it. It
960 * never auto-starts a run, and never blocks: a `generate()` that starts first
961 * owns the client and hydration backs off, mirroring the chat client.
962 *
963 * A genuine **miss** (the server reports no record for the thread) is silent —
964 * a fresh thread is not an error. A genuine **failure** (transport error, a
965 * 403 from the authorize gate, a malformed body, a record the client's own
966 * validator rejects) is surfaced through `status` / `error` / `onError`, so a
967 * broken server is distinguishable from an empty one and the app can retry.
968 */
969 private hydrateFromServer(): void {
970 const hydrate =
971 this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler
972 if (!hydrate) return
973 // A send that already started owns the client; don't stomp it.
974 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return
975 void (async () => {
976 let res: GenerationHydrationResult
977 try {
978 res = await hydrate(this.threadId)
979 } catch (cause) {
980 this.failHydration(
981 createGenerationHydrationError(
982 'the request to the server did not succeed',
983 cause,
984 ),
985 )
986 return
987 }
988 // No record for this thread — a fresh thread, not a failure.
989 if (!res.resumeSnapshot) return
990 const snapshot = parseGenerationResumeSnapshot(res.resumeSnapshot)
991 if (!snapshot) {
992 this.failHydration(
993 createGenerationHydrationError(
994 'the server returned a record this client cannot read (unknown schema version, or a missing/invalid `status` or `resumeState`)',
995 ),
996 )
997 return
998 }
999 // Re-check: a send may have started while the fetch was in flight.
1000 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle')
1001 return
1002 // A run still generating on the server: re-attach and finish it in place.
1003 this.repaintRestoredSnapshot(snapshot, res.activeRun?.runId)
1004 })()
1005 }
1006
1007 /**
1008 * Surface a hydration failure on the observable fields. Skipped when a
1009 * `generate()` took ownership while the hydrate GET was in flight — the live
1010 * run's state must win over a stale mount-time failure.
1011 */
1012 private failHydration(error: Error): void {
1013 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return
1014 this.setStatus('error')
1015 this.setError(error)
1016 this.callbacksRef.onError?.(error)
1017 }
1018
1019 /**
1020 * Re-attach to an already-loaded `running` snapshot (the remount case). Safe
1021 * to call repeatedly: `rejoinInFlight` dedupes on `rejoinedRunId` and bails
1022 * when a run is already in flight, so on the first mount (where the rejoin was
1023 * already started from `repaintRestoredSnapshot`) this is a no-op.
1024 */
1025 private maybeResumeInFlight(): void {
1026 if (this.resumeSnapshot?.status !== 'running') return
1027 const runId = this.resumeSnapshot.resumeState?.runId
1028 if (runId) this.rejoinInFlight(runId)
1029 }
1030
1031 /**
1032 * Re-attach to a run that is still generating and stream it to completion,
1033 * mirroring the chat client's mount-time rejoin. Reuses `processStream`, so
1034 * `result` / `progress` / `status` repaint from the replayed chunks exactly as
1035 * a live run does. Best-effort: a live `generate()` owns the client and is
1036 * never stomped, and the same run is only rejoined once.
1037 */
1038 private rejoinInFlight(runId: string): void {
1039 const joinRun = this.connection?.joinRun ?? this.joinRunHandler
1040 if (!joinRun) return
1041 if (this.rejoinedRunId === runId) return
1042 // A fresh send (or an in-progress rejoin) owns the client.
1043 if (this.isLoading || this.abortController) return
1044 this.rejoinedRunId = runId
1045 const controller = new AbortController()
1046 this.abortController = controller
1047 this.setIsLoading(true)
1048 this.setStatus('generating')
1049 void (async () => {
1050 try {
1051 await this.processStream(
1052 joinRun(runId, controller.signal),
1053 runId,
1054 controller.signal,
1055 )
1056 } catch (error) {
1057 if (!controller.signal.aborted) {
1058 const failure =
1059 error instanceof Error ? error : new Error(String(error))
1060 // Settles `status`/`error` AND rewrites the snapshot to a terminal
1061 // `error` with a null `resumeState`, so the next mount does not
1062 // rejoin this run again.
1063 this.recordResumeSnapshotError(failure)
1064 this.callbacksRef.onError?.(failure)
1065 }
1066 } finally {
1067 // Only reset if this rejoin still owns the client: a `stop()` +
1068 // fresh `generate()` may have replaced the controller while the tail
1069 // was settling, and that live run owns `isLoading` now.
1070 if (this.abortController === controller) {
1071 this.abortController = null
1072 this.setIsLoading(false)
1073 }
1074 }
1075 })()
1076 }
1077}
1078
1079function completeProgressValue(
1080 progress: AIDevtoolsGenerationProgress | null,
1081): AIDevtoolsGenerationProgress | null {
1082 if (!progress) return null
1083 const message = progress.message
1084 return {
1085 value: 100,
1086 ...(message ? { message } : {}),
1087 }
1088}