@tanstack/ai-react 0.15.14 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/esm/index.d.ts +23 -0
  2. package/dist/esm/index.js +34 -0
  3. package/dist/esm/index.js.map +1 -0
  4. package/dist/esm/mcp-apps.d.ts +20 -0
  5. package/dist/esm/mcp-apps.js +52 -0
  6. package/dist/esm/mcp-apps.js.map +1 -0
  7. package/dist/esm/realtime-types.d.ts +109 -0
  8. package/dist/esm/types.d.ts +150 -0
  9. package/dist/esm/use-audio-recorder.d.ts +43 -0
  10. package/dist/esm/use-audio-recorder.js +49 -0
  11. package/dist/esm/use-audio-recorder.js.map +1 -0
  12. package/dist/esm/use-chat.d.ts +4 -0
  13. package/dist/esm/use-chat.js +258 -0
  14. package/dist/esm/use-chat.js.map +1 -0
  15. package/dist/esm/use-generate-audio.d.ts +87 -0
  16. package/dist/esm/use-generate-audio.js +26 -0
  17. package/dist/esm/use-generate-audio.js.map +1 -0
  18. package/dist/esm/use-generate-image.d.ts +89 -0
  19. package/dist/esm/use-generate-image.js +26 -0
  20. package/dist/esm/use-generate-image.js.map +1 -0
  21. package/dist/esm/use-generate-speech.d.ts +83 -0
  22. package/dist/esm/use-generate-speech.js +26 -0
  23. package/dist/esm/use-generate-speech.js.map +1 -0
  24. package/dist/esm/use-generate-video.d.ts +94 -0
  25. package/dist/esm/use-generate-video.js +107 -0
  26. package/dist/esm/use-generate-video.js.map +1 -0
  27. package/dist/esm/use-generation.d.ts +80 -0
  28. package/dist/esm/use-generation.js +94 -0
  29. package/dist/esm/use-generation.js.map +1 -0
  30. package/dist/esm/use-mcp-app-bridge.d.ts +25 -0
  31. package/dist/esm/use-mcp-app-bridge.js +26 -0
  32. package/dist/esm/use-mcp-app-bridge.js.map +1 -0
  33. package/dist/esm/use-realtime-chat.d.ts +42 -0
  34. package/dist/esm/use-realtime-chat.js +189 -0
  35. package/dist/esm/use-realtime-chat.js.map +1 -0
  36. package/dist/esm/use-summarize.d.ts +86 -0
  37. package/dist/esm/use-summarize.js +26 -0
  38. package/dist/esm/use-summarize.js.map +1 -0
  39. package/dist/esm/use-transcription.d.ts +91 -0
  40. package/dist/esm/use-transcription.js +23 -0
  41. package/dist/esm/use-transcription.js.map +1 -0
  42. package/package.json +15 -4
  43. package/src/index.ts +11 -0
  44. package/src/mcp-apps.tsx +88 -0
  45. package/src/use-audio-recorder.ts +112 -0
  46. package/src/use-generate-audio.ts +5 -8
  47. package/src/use-generate-image.ts +5 -8
  48. package/src/use-generate-speech.ts +7 -7
  49. package/src/use-generate-video.ts +18 -9
  50. package/src/use-generation.ts +17 -6
  51. package/src/use-mcp-app-bridge.ts +60 -0
  52. package/src/use-summarize.ts +7 -8
  53. package/src/use-transcription.ts +9 -11
@@ -0,0 +1,112 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
+ import { AudioRecorder } from '@tanstack/ai-client'
3
+ import type {
4
+ AudioRecorderOptions,
5
+ AudioRecording,
6
+ InferAudioRecordingOutput,
7
+ } from '@tanstack/ai-client'
8
+
9
+ export type UseAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {
10
+ /**
11
+ * Optional transform applied to the recording when `stop()` resolves. Its
12
+ * (awaited) return value becomes `recording` and the resolved value of
13
+ * `stop()`. Return nothing to keep the raw `AudioRecording`.
14
+ */
15
+ onComplete?: TOnComplete
16
+ }
17
+
18
+ export interface UseAudioRecorderReturn<TOutput> {
19
+ /** Latest recording (transformed if `onComplete` provided), or null. */
20
+ recording: TOutput | null
21
+ /** True while actively capturing audio. */
22
+ isRecording: boolean
23
+ /** Whether the browser supports recording (getUserMedia + MediaRecorder). */
24
+ isSupported: boolean
25
+ /** Acquire the mic and begin recording. */
26
+ start: () => Promise<void>
27
+ /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */
28
+ stop: () => Promise<TOutput>
29
+ /** Discard the in-progress recording and release the mic. */
30
+ cancel: () => void
31
+ }
32
+
33
+ /**
34
+ * React hook for recording an audio message. The resolved
35
+ * {@link AudioRecording} carries `.part` (an audio content part for
36
+ * `useChat.sendMessage`) and `.base64` (for the generation hooks).
37
+ *
38
+ * Errors are delivered via `onError`. `start()` and `stop()` also reject on
39
+ * failure (and `stop()` rejects with `Recording cancelled` if the component
40
+ * unmounts while a stop is in flight) — handle one channel, not both.
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * const { isRecording, start, stop, recording } = useAudioRecorder()
45
+ * const { sendMessage } = useChat({ connection })
46
+ * // ...
47
+ * const rec = await stop()
48
+ * sendMessage({ content: [rec.part] })
49
+ * ```
50
+ */
51
+ export function useAudioRecorder<
52
+ TOnComplete extends (recording: AudioRecording) => unknown,
53
+ >(
54
+ options: UseAudioRecorderOptions<TOnComplete>,
55
+ ): UseAudioRecorderReturn<InferAudioRecordingOutput<TOnComplete>>
56
+ export function useAudioRecorder(
57
+ options?: UseAudioRecorderOptions<undefined>,
58
+ ): UseAudioRecorderReturn<AudioRecording>
59
+ export function useAudioRecorder(
60
+ options: UseAudioRecorderOptions<(recording: AudioRecording) => unknown> = {},
61
+ ): UseAudioRecorderReturn<unknown> {
62
+ const [isRecording, setIsRecording] = useState(false)
63
+ const [recording, setRecording] = useState<unknown>(null)
64
+ // Read the freshest callbacks at fire time without recreating the recorder.
65
+ const optionsRef = useRef(options)
66
+ optionsRef.current = options
67
+
68
+ const recorder = useMemo(
69
+ () =>
70
+ new AudioRecorder({
71
+ ...(options.audio !== undefined && { audio: options.audio }),
72
+ ...(options.mimeType !== undefined && { mimeType: options.mimeType }),
73
+ onError: (err) => optionsRef.current.onError?.(err),
74
+ }),
75
+ // Recorder config (audio/mimeType) is captured once at mount, matching the
76
+ // other hooks' create-once pattern.
77
+ [],
78
+ )
79
+
80
+ useEffect(() => {
81
+ const unsubscribe = recorder.subscribe((state) => {
82
+ setIsRecording(state === 'recording')
83
+ })
84
+ return () => {
85
+ unsubscribe()
86
+ recorder.cancel()
87
+ }
88
+ }, [recorder])
89
+
90
+ const start = useCallback(() => recorder.start(), [recorder])
91
+ const stop = useCallback(async () => {
92
+ const recording = await recorder.stop()
93
+ const transformed = await optionsRef.current.onComplete?.(recording)
94
+ // Only `undefined` (returning nothing) falls back to the raw recording, so
95
+ // a transform that returns null is preserved — matching the inferred type,
96
+ // which excludes only undefined/void/null from the transform's return.
97
+ const output = transformed === undefined ? recording : transformed
98
+ setRecording(() => output)
99
+ return output
100
+ }, [recorder])
101
+ const cancel = useCallback(() => recorder.cancel(), [recorder])
102
+
103
+ return {
104
+ recording,
105
+ isRecording,
106
+ // recording is client-only; if SSR'd, gate UI on a mounted flag.
107
+ isSupported: AudioRecorder.isSupported(),
108
+ start,
109
+ stop,
110
+ cancel,
111
+ }
112
+ }
@@ -6,7 +6,7 @@ import type {
6
6
  ConnectConnectionAdapter,
7
7
  GenerationClientState,
8
8
  GenerationFetcher,
9
- InferGenerationOutput,
9
+ InferGenerationOutputFromReturn,
10
10
  } from '@tanstack/ai-client'
11
11
 
12
12
  /**
@@ -93,15 +93,12 @@ export interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> {
93
93
  * }
94
94
  * ```
95
95
  */
96
- export function useGenerateAudio<
97
- TOnResult extends ((result: AudioGenerationResult) => any) | undefined =
98
- undefined,
99
- >(
96
+ export function useGenerateAudio<TTransformed = void>(
100
97
  options: Omit<UseGenerateAudioOptions, 'onResult'> & {
101
- onResult?: TOnResult
98
+ onResult?: (result: AudioGenerationResult) => TTransformed
102
99
  },
103
100
  ): UseGenerateAudioReturn<
104
- InferGenerationOutput<AudioGenerationResult, TOnResult>
101
+ InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>
105
102
  > {
106
103
  const devtools = {
107
104
  ...options.devtools,
@@ -110,7 +107,7 @@ export function useGenerateAudio<
110
107
  outputKind: 'audio' as const,
111
108
  }
112
109
  const { generate, result, isLoading, error, status, stop, reset } =
113
- useGeneration<AudioGenerateInput, AudioGenerationResult, TOnResult>({
110
+ useGeneration<AudioGenerateInput, AudioGenerationResult, TTransformed>({
114
111
  ...options,
115
112
  devtools,
116
113
  })
@@ -6,7 +6,7 @@ import type {
6
6
  GenerationClientState,
7
7
  GenerationFetcher,
8
8
  ImageGenerateInput,
9
- InferGenerationOutput,
9
+ InferGenerationOutputFromReturn,
10
10
  } from '@tanstack/ai-client'
11
11
 
12
12
  /**
@@ -95,15 +95,12 @@ export interface UseGenerateImageReturn<TOutput = ImageGenerationResult> {
95
95
  * }
96
96
  * ```
97
97
  */
98
- export function useGenerateImage<
99
- TOnResult extends ((result: ImageGenerationResult) => any) | undefined =
100
- undefined,
101
- >(
98
+ export function useGenerateImage<TTransformed = void>(
102
99
  options: Omit<UseGenerateImageOptions, 'onResult'> & {
103
- onResult?: TOnResult
100
+ onResult?: (result: ImageGenerationResult) => TTransformed
104
101
  },
105
102
  ): UseGenerateImageReturn<
106
- InferGenerationOutput<ImageGenerationResult, TOnResult>
103
+ InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>
107
104
  > {
108
105
  const devtools = {
109
106
  ...options.devtools,
@@ -112,7 +109,7 @@ export function useGenerateImage<
112
109
  outputKind: 'image' as const,
113
110
  }
114
111
  const { generate, result, isLoading, error, status, stop, reset } =
115
- useGeneration<ImageGenerateInput, ImageGenerationResult, TOnResult>({
112
+ useGeneration<ImageGenerateInput, ImageGenerationResult, TTransformed>({
116
113
  ...options,
117
114
  devtools,
118
115
  })
@@ -5,7 +5,7 @@ import type {
5
5
  ConnectConnectionAdapter,
6
6
  GenerationClientState,
7
7
  GenerationFetcher,
8
- InferGenerationOutput,
8
+ InferGenerationOutputFromReturn,
9
9
  SpeechGenerateInput,
10
10
  } from '@tanstack/ai-client'
11
11
 
@@ -89,13 +89,13 @@ export interface UseGenerateSpeechReturn<TOutput = TTSResult> {
89
89
  * }
90
90
  * ```
91
91
  */
92
- export function useGenerateSpeech<
93
- TOnResult extends ((result: TTSResult) => any) | undefined = undefined,
94
- >(
92
+ export function useGenerateSpeech<TTransformed = void>(
95
93
  options: Omit<UseGenerateSpeechOptions, 'onResult'> & {
96
- onResult?: TOnResult
94
+ onResult?: (result: TTSResult) => TTransformed
97
95
  },
98
- ): UseGenerateSpeechReturn<InferGenerationOutput<TTSResult, TOnResult>> {
96
+ ): UseGenerateSpeechReturn<
97
+ InferGenerationOutputFromReturn<TTSResult, TTransformed>
98
+ > {
99
99
  const devtools = {
100
100
  ...options.devtools,
101
101
  framework: 'react',
@@ -103,7 +103,7 @@ export function useGenerateSpeech<
103
103
  outputKind: 'audio' as const,
104
104
  }
105
105
  const { generate, result, isLoading, error, status, stop, reset } =
106
- useGeneration<SpeechGenerateInput, TTSResult, TOnResult>({
106
+ useGeneration<SpeechGenerateInput, TTSResult, TTransformed>({
107
107
  ...options,
108
108
  devtools,
109
109
  })
@@ -7,7 +7,7 @@ import type {
7
7
  ConnectConnectionAdapter,
8
8
  GenerationClientState,
9
9
  GenerationFetcher,
10
- InferGenerationOutput,
10
+ InferGenerationOutputFromReturn,
11
11
  VideoGenerateInput,
12
12
  VideoGenerateResult,
13
13
  VideoStatusInfo,
@@ -104,17 +104,20 @@ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
104
104
  * }
105
105
  * ```
106
106
  */
107
- export function useGenerateVideo<
108
- TOnResult extends ((result: VideoGenerateResult) => any) | undefined =
109
- undefined,
110
- >(
107
+ // `TTransformed` infers from the `onResult` return position so the callback
108
+ // parameter is typed as `VideoGenerateResult` and `result` narrows to the
109
+ // transform's return. See issue #848.
110
+ export function useGenerateVideo<TTransformed = void>(
111
111
  options: Omit<UseGenerateVideoOptions, 'onResult'> & {
112
- onResult?: TOnResult
112
+ onResult?: (result: VideoGenerateResult) => TTransformed
113
113
  },
114
114
  ): UseGenerateVideoReturn<
115
- InferGenerationOutput<VideoGenerateResult, TOnResult>
115
+ InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>
116
116
  > {
117
- type TOutput = InferGenerationOutput<VideoGenerateResult, TOnResult>
117
+ type TOutput = InferGenerationOutputFromReturn<
118
+ VideoGenerateResult,
119
+ TTransformed
120
+ >
118
121
  const hookId = useId()
119
122
  const clientId = options.id || hookId
120
123
 
@@ -146,7 +149,13 @@ export function useGenerateVideo<
146
149
  hookName: 'useGenerateVideo',
147
150
  outputKind: 'video' as const,
148
151
  },
149
- onResult: (r: VideoGenerateResult) => optionsRef.current.onResult?.(r),
152
+ // The transform's raw return type (`TTransformed`) and the stored output
153
+ // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
154
+ // the cast bridges the relationship that the conditional type hides.
155
+ onResult: ((r: VideoGenerateResult) =>
156
+ optionsRef.current.onResult?.(r)) as (
157
+ result: VideoGenerateResult,
158
+ ) => TOutput | null | void,
150
159
  onError: (e: Error) => {
151
160
  optionsRef.current.onError?.(e)
152
161
  },
@@ -8,7 +8,7 @@ import type {
8
8
  GenerationClientOptions,
9
9
  GenerationClientState,
10
10
  GenerationFetcher,
11
- InferGenerationOutput,
11
+ InferGenerationOutputFromReturn,
12
12
  } from '@tanstack/ai-client'
13
13
 
14
14
  /**
@@ -88,16 +88,22 @@ export interface UseGenerationReturn<TOutput> {
88
88
  * await generate({ prompt: 'Hello' })
89
89
  * ```
90
90
  */
91
+ // `TTransformed` infers from the `onResult` return position (a covariant
92
+ // inference site that works even for an optional nested property), which types
93
+ // the callback parameter as `TResult` and narrows `result`. Inferring the
94
+ // whole callback as a defaulted type parameter instead collapses to the
95
+ // default, leaving the parameter `any` — a hard error under `strict`. See
96
+ // issue #848.
91
97
  export function useGeneration<
92
98
  TInput extends Record<string, any>,
93
99
  TResult,
94
- TOnResult extends ((result: TResult) => any) | undefined = undefined,
100
+ TTransformed = void,
95
101
  >(
96
102
  options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
97
- onResult?: TOnResult
103
+ onResult?: (result: TResult) => TTransformed
98
104
  },
99
- ): UseGenerationReturn<InferGenerationOutput<TResult, TOnResult>> {
100
- type TOutput = InferGenerationOutput<TResult, TOnResult>
105
+ ): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>> {
106
+ type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
101
107
  const hookId = useId()
102
108
  const clientId = options.id || hookId
103
109
 
@@ -125,7 +131,12 @@ export function useGeneration<
125
131
  framework: 'react',
126
132
  ...opts.devtools,
127
133
  },
128
- onResult: (r: TResult) => optionsRef.current.onResult?.(r),
134
+ // The transform's raw return type (`TTransformed`) and the stored output
135
+ // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
136
+ // the cast bridges the relationship that the conditional type hides.
137
+ onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (
138
+ result: TResult,
139
+ ) => TOutput | null | void,
129
140
  onError: (e: Error) => {
130
141
  optionsRef.current.onError?.(e)
131
142
  },
@@ -0,0 +1,60 @@
1
+ import { useMemo, useRef } from 'react'
2
+ import { createMcpAppBridge } from '@tanstack/ai-client'
3
+ import type {
4
+ CreateMcpAppBridgeOptions,
5
+ McpAppBridge,
6
+ } from '@tanstack/ai-client'
7
+
8
+ export type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions
9
+
10
+ /**
11
+ * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for
12
+ * the given `threadId`/`callEndpoint`, while always invoking the latest
13
+ * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating
14
+ * the bridge on every render and the stale-closure / `exhaustive-deps` dance
15
+ * you'd otherwise write by hand:
16
+ *
17
+ * ```tsx
18
+ * const { sendMessage } = useChat({ threadId, connection })
19
+ * const bridge = useMcpAppBridge({
20
+ * threadId,
21
+ * callEndpoint: '/api/mcp-apps-call',
22
+ * chat: { sendMessage: async (content) => void sendMessage(content) },
23
+ * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
24
+ * })
25
+ * // pass `bridge` to <MCPAppResource bridge={bridge} … />
26
+ * ```
27
+ *
28
+ * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or
29
+ * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`
30
+ * each render does not churn it.
31
+ */
32
+ export function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {
33
+ const { threadId, callEndpoint, chat, fetchImpl, onLink } = options
34
+
35
+ // Latest-value refs so the bridge identity stays stable but its callbacks are
36
+ // never stale (the bridge calls `.current` at invocation time, not creation).
37
+ const chatRef = useRef(chat)
38
+ chatRef.current = chat
39
+ const onLinkRef = useRef(onLink)
40
+ onLinkRef.current = onLink
41
+
42
+ // Whether a link handler was supplied governs the bridge's link behavior
43
+ // (forward vs. display-only warn), so it's part of the bridge's identity.
44
+ const hasOnLink = onLink != null
45
+
46
+ return useMemo(
47
+ () =>
48
+ createMcpAppBridge({
49
+ threadId,
50
+ callEndpoint,
51
+ fetchImpl,
52
+ chat: {
53
+ sendMessage: (content, body) =>
54
+ chatRef.current.sendMessage(content, body),
55
+ },
56
+ onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,
57
+ }),
58
+ [threadId, callEndpoint, fetchImpl, hasOnLink],
59
+ )
60
+ }
@@ -5,7 +5,7 @@ import type {
5
5
  ConnectConnectionAdapter,
6
6
  GenerationClientState,
7
7
  GenerationFetcher,
8
- InferGenerationOutput,
8
+ InferGenerationOutputFromReturn,
9
9
  SummarizeGenerateInput,
10
10
  } from '@tanstack/ai-client'
11
11
 
@@ -92,14 +92,13 @@ export interface UseSummarizeReturn<TOutput = SummarizationResult> {
92
92
  * }
93
93
  * ```
94
94
  */
95
- export function useSummarize<
96
- TOnResult extends ((result: SummarizationResult) => any) | undefined =
97
- undefined,
98
- >(
95
+ export function useSummarize<TTransformed = void>(
99
96
  options: Omit<UseSummarizeOptions, 'onResult'> & {
100
- onResult?: TOnResult
97
+ onResult?: (result: SummarizationResult) => TTransformed
101
98
  },
102
- ): UseSummarizeReturn<InferGenerationOutput<SummarizationResult, TOnResult>> {
99
+ ): UseSummarizeReturn<
100
+ InferGenerationOutputFromReturn<SummarizationResult, TTransformed>
101
+ > {
103
102
  const devtools = {
104
103
  ...options.devtools,
105
104
  framework: 'react',
@@ -107,7 +106,7 @@ export function useSummarize<
107
106
  outputKind: 'text' as const,
108
107
  }
109
108
  const { generate, result, isLoading, error, status, stop, reset } =
110
- useGeneration<SummarizeGenerateInput, SummarizationResult, TOnResult>({
109
+ useGeneration<SummarizeGenerateInput, SummarizationResult, TTransformed>({
111
110
  ...options,
112
111
  devtools,
113
112
  })
@@ -5,7 +5,7 @@ import type {
5
5
  ConnectConnectionAdapter,
6
6
  GenerationClientState,
7
7
  GenerationFetcher,
8
- InferGenerationOutput,
8
+ InferGenerationOutputFromReturn,
9
9
  TranscriptionGenerateInput,
10
10
  } from '@tanstack/ai-client'
11
11
 
@@ -97,15 +97,12 @@ export interface UseTranscriptionReturn<TOutput = TranscriptionResult> {
97
97
  * }
98
98
  * ```
99
99
  */
100
- export function useTranscription<
101
- TOnResult extends ((result: TranscriptionResult) => any) | undefined =
102
- undefined,
103
- >(
100
+ export function useTranscription<TTransformed = void>(
104
101
  options: Omit<UseTranscriptionOptions, 'onResult'> & {
105
- onResult?: TOnResult
102
+ onResult?: (result: TranscriptionResult) => TTransformed
106
103
  },
107
104
  ): UseTranscriptionReturn<
108
- InferGenerationOutput<TranscriptionResult, TOnResult>
105
+ InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>
109
106
  > {
110
107
  const devtools = {
111
108
  ...options.devtools,
@@ -114,10 +111,11 @@ export function useTranscription<
114
111
  outputKind: 'text' as const,
115
112
  }
116
113
  const { generate, result, isLoading, error, status, stop, reset } =
117
- useGeneration<TranscriptionGenerateInput, TranscriptionResult, TOnResult>({
118
- ...options,
119
- devtools,
120
- })
114
+ useGeneration<
115
+ TranscriptionGenerateInput,
116
+ TranscriptionResult,
117
+ TTransformed
118
+ >({ ...options, devtools })
121
119
 
122
120
  return {
123
121
  generate: generate as (input: TranscriptionGenerateInput) => Promise<void>,