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

generation-client.ts

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