Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

generation-client.ts

1,210 lines43.3 KB

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