@tanstack/ai-react 0.18.1 → 0.19.1

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 (49) hide show
  1. package/README.md +15 -1
  2. package/dist/esm/index.d.ts +1 -1
  3. package/dist/esm/index.js +2 -23
  4. package/dist/esm/mcp-app-resource.js +45 -45
  5. package/dist/esm/mcp-app-resource.js.map +1 -1
  6. package/dist/esm/mcp-apps.js +1 -4
  7. package/dist/esm/types.d.ts +29 -3
  8. package/dist/esm/use-audio-recorder.js +41 -46
  9. package/dist/esm/use-audio-recorder.js.map +1 -1
  10. package/dist/esm/use-chat.js +330 -275
  11. package/dist/esm/use-chat.js.map +1 -1
  12. package/dist/esm/use-generate-audio.d.ts +50 -4
  13. package/dist/esm/use-generate-audio.js +47 -23
  14. package/dist/esm/use-generate-audio.js.map +1 -1
  15. package/dist/esm/use-generate-image.d.ts +50 -4
  16. package/dist/esm/use-generate-image.js +49 -23
  17. package/dist/esm/use-generate-image.js.map +1 -1
  18. package/dist/esm/use-generate-speech.d.ts +50 -4
  19. package/dist/esm/use-generate-speech.js +43 -23
  20. package/dist/esm/use-generate-speech.js.map +1 -1
  21. package/dist/esm/use-generate-video.d.ts +50 -4
  22. package/dist/esm/use-generate-video.js +141 -103
  23. package/dist/esm/use-generate-video.js.map +1 -1
  24. package/dist/esm/use-generation.d.ts +59 -6
  25. package/dist/esm/use-generation.js +113 -90
  26. package/dist/esm/use-generation.js.map +1 -1
  27. package/dist/esm/use-mcp-app-bridge.js +46 -23
  28. package/dist/esm/use-mcp-app-bridge.js.map +1 -1
  29. package/dist/esm/use-realtime-chat.js +185 -185
  30. package/dist/esm/use-realtime-chat.js.map +1 -1
  31. package/dist/esm/use-summarize.d.ts +50 -4
  32. package/dist/esm/use-summarize.js +46 -23
  33. package/dist/esm/use-summarize.js.map +1 -1
  34. package/dist/esm/use-transcription.d.ts +50 -4
  35. package/dist/esm/use-transcription.js +51 -20
  36. package/dist/esm/use-transcription.js.map +1 -1
  37. package/package.json +7 -7
  38. package/src/index.ts +10 -0
  39. package/src/types.ts +44 -0
  40. package/src/use-chat.ts +221 -35
  41. package/src/use-generate-audio.ts +64 -17
  42. package/src/use-generate-image.ts +64 -17
  43. package/src/use-generate-speech.ts +64 -17
  44. package/src/use-generate-video.ts +99 -18
  45. package/src/use-generation.ts +112 -18
  46. package/src/use-summarize.ts +64 -17
  47. package/src/use-transcription.ts +60 -18
  48. package/dist/esm/index.js.map +0 -1
  49. package/dist/esm/mcp-apps.js.map +0 -1
@@ -1,94 +1,117 @@
1
1
  import { GenerationClient } from "@tanstack/ai-client";
2
2
  import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
3
- import { useId, useState, useRef, useMemo, useEffect, useCallback } from "react";
3
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
4
+ //#region src/use-generation.ts
5
+ /**
6
+ * Generic React hook for one-shot generation tasks.
7
+ *
8
+ * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
9
+ * `useTranscription`, and `useSummarize`. You can also use it directly
10
+ * for custom generation types.
11
+ *
12
+ * @template TInput - The input type for the generation request
13
+ * @template TResult - The result type returned by the generation
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
18
+ * connection: fetchServerSentEvents('/api/generate/custom'),
19
+ * })
20
+ *
21
+ * await generate({ prompt: 'Hello' })
22
+ * ```
23
+ */
4
24
  function useGeneration(options) {
5
- const hookId = useId();
6
- const clientId = options.id || hookId;
7
- const [result, setResult] = useState(null);
8
- const [isLoading, setIsLoading] = useState(false);
9
- const [error, setError] = useState(void 0);
10
- const [status, setStatus] = useState("idle");
11
- const optionsRef = useRef(options);
12
- optionsRef.current = options;
13
- const client = useMemo(() => {
14
- const opts = optionsRef.current;
15
- const clientOptions = {
16
- id: clientId,
17
- body: opts.body,
18
- devtoolsBridgeFactory: createGenerationDevtoolsBridge,
19
- devtools: {
20
- hookName: "useGeneration",
21
- framework: "react",
22
- ...opts.devtools
23
- },
24
- // The transform's raw return type (`TTransformed`) and the stored output
25
- // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
26
- // the cast bridges the relationship that the conditional type hides.
27
- onResult: ((r) => optionsRef.current.onResult?.(r)),
28
- onError: (e) => {
29
- optionsRef.current.onError?.(e);
30
- },
31
- onProgress: (p, m) => {
32
- optionsRef.current.onProgress?.(p, m);
33
- },
34
- onChunk: (c) => {
35
- optionsRef.current.onChunk?.(c);
36
- },
37
- onResultChange: setResult,
38
- onLoadingChange: setIsLoading,
39
- onErrorChange: setError,
40
- onStatusChange: setStatus
41
- };
42
- if (opts.connection) {
43
- return new GenerationClient({
44
- ...clientOptions,
45
- connection: opts.connection
46
- });
47
- }
48
- if (opts.fetcher) {
49
- return new GenerationClient({
50
- ...clientOptions,
51
- fetcher: opts.fetcher
52
- });
53
- }
54
- throw new Error(
55
- "useGeneration requires either a connection or fetcher option"
56
- );
57
- }, [clientId]);
58
- useEffect(() => {
59
- client.updateOptions({
60
- ...options.body !== void 0 && { body: options.body }
61
- });
62
- }, [client, options.body]);
63
- useEffect(() => {
64
- client.mountDevtools();
65
- return () => {
66
- client.dispose();
67
- };
68
- }, [client]);
69
- const generate = useCallback(
70
- async (input) => {
71
- await client.generate(input);
72
- },
73
- [client]
74
- );
75
- const stop = useCallback(() => {
76
- client.stop();
77
- }, [client]);
78
- const reset = useCallback(() => {
79
- client.reset();
80
- }, [client]);
81
- return {
82
- generate,
83
- result,
84
- isLoading,
85
- error,
86
- status,
87
- stop,
88
- reset
89
- };
25
+ const hookId = useId();
26
+ const clientIdentity = options.threadId ?? options.id ?? hookId;
27
+ const [result, setResult] = useState(null);
28
+ const [isLoading, setIsLoading] = useState(false);
29
+ const [error, setError] = useState(void 0);
30
+ const [status, setStatus] = useState("idle");
31
+ const [runId, setRunId] = useState(null);
32
+ const optionsRef = useRef(options);
33
+ optionsRef.current = options;
34
+ const disposedRef = useRef(false);
35
+ const client = useMemo(() => {
36
+ const opts = optionsRef.current;
37
+ const clientOptions = {
38
+ body: opts.body,
39
+ ...opts.threadId !== void 0 ? { threadId: opts.threadId } : { id: opts.id ?? hookId },
40
+ ...opts.persistence !== void 0 && { persistence: opts.persistence },
41
+ ...opts.hydrateGeneration !== void 0 && { hydrateGeneration: opts.hydrateGeneration },
42
+ ...opts.joinRun !== void 0 && { joinRun: opts.joinRun },
43
+ ...opts.reconstructResult ? { reconstructResult: opts.reconstructResult } : {},
44
+ devtoolsBridgeFactory: createGenerationDevtoolsBridge,
45
+ devtools: {
46
+ hookName: "useGeneration",
47
+ framework: "react",
48
+ ...opts.devtools
49
+ },
50
+ onResult: ((r) => optionsRef.current.onResult?.(r)),
51
+ onError: (e) => {
52
+ if (!disposedRef.current) optionsRef.current.onError?.(e);
53
+ },
54
+ onProgress: (p, m) => {
55
+ if (!disposedRef.current) optionsRef.current.onProgress?.(p, m);
56
+ },
57
+ onChunk: (c) => {
58
+ if (!disposedRef.current) optionsRef.current.onChunk?.(c);
59
+ },
60
+ onResultChange: (r) => {
61
+ if (!disposedRef.current) setResult(r);
62
+ },
63
+ onLoadingChange: (l) => {
64
+ if (!disposedRef.current) setIsLoading(l);
65
+ },
66
+ onErrorChange: (e) => {
67
+ if (!disposedRef.current) setError(e);
68
+ },
69
+ onStatusChange: (s) => {
70
+ if (!disposedRef.current) setStatus(s);
71
+ },
72
+ onResumeStateChange: (rs) => {
73
+ if (!disposedRef.current) setRunId(rs?.runId ?? null);
74
+ }
75
+ };
76
+ if (opts.connection) return new GenerationClient({
77
+ ...clientOptions,
78
+ connection: opts.connection
79
+ });
80
+ if (opts.fetcher) return new GenerationClient({
81
+ ...clientOptions,
82
+ fetcher: opts.fetcher
83
+ });
84
+ throw new Error("useGeneration requires either a connection or fetcher option");
85
+ }, [clientIdentity, hookId]);
86
+ useEffect(() => {
87
+ client.updateOptions({ ...options.body !== void 0 && { body: options.body } });
88
+ }, [client, options.body]);
89
+ useEffect(() => {
90
+ disposedRef.current = false;
91
+ client.mountDevtools();
92
+ return () => {
93
+ disposedRef.current = true;
94
+ client.dispose();
95
+ };
96
+ }, [client]);
97
+ return {
98
+ generate: useCallback(async (input) => {
99
+ await client.generate(input);
100
+ }, [client]),
101
+ result,
102
+ isLoading,
103
+ error,
104
+ status,
105
+ stop: useCallback(() => {
106
+ client.stop();
107
+ }, [client]),
108
+ reset: useCallback(() => {
109
+ client.reset();
110
+ }, [client]),
111
+ runId
112
+ };
90
113
  }
91
- export {
92
- useGeneration
93
- };
94
- //# sourceMappingURL=use-generation.js.map
114
+ //#endregion
115
+ export { useGeneration };
116
+
117
+ //# sourceMappingURL=use-generation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-generation.js","sources":["../../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The output type after optional transform (defaults to TResult)\n */\nexport interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerationReturn<TOutput> {\n /** Trigger a generation request */\n generate: (input: Record<string, any>) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: TOutput | null\n /** Whether a generation is currently in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation client */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * Generic React hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\n * ```\n */\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target;\n // local source is `Record<string, any> | undefined`). Callbacks\n // wrap optional ones in non-returning bodies so `?.()`'s\n // implicit `undefined` doesn't pollute the function return type.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n hookName: 'useGeneration',\n framework: 'react',\n ...opts.devtools,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n optionsRef.current.onChunk?.(c)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n }\n\n if (opts.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Cleanup on unmount\n useEffect(() => {\n client.mountDevtools()\n\n return () => {\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: TInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate: generate as (input: Record<string, any>) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AAgGO,SAAS,cAKd,SAG6E;AAE7E,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA4B,MAAS;AAC/D,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,MAAM;AAElE,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAM,OAAO,WAAW;AAMxB,UAAM,gBAAmE;AAAA,MACvE,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,UAAU;AAAA,QACV,WAAW;AAAA,QACX,GAAG,KAAK;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKV,WAAW,CAAC,MAAe,WAAW,QAAQ,WAAW,CAAC;AAAA,MAG1D,SAAS,CAAC,MAAa;AACrB,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,YAAY,CAAC,GAAW,MAAe;AACrC,mBAAW,QAAQ,aAAa,GAAG,CAAC;AAAA,MACtC;AAAA,MACA,SAAS,CAAC,MAAmB;AAC3B,mBAAW,QAAQ,UAAU,CAAC;AAAA,MAChC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,IAAA;AAGlB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,iBAA2C;AAAA,QACpD,GAAG;AAAA,QACH,SAAS,KAAK;AAAA,MAAA,CACf;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,QAAQ,CAAC;AAGb,YAAU,MAAM;AAEd,WAAO,cAAc;AAAA,MACnB,GAAI,QAAQ,SAAS,UAAa,EAAE,MAAM,QAAQ,KAAA;AAAA,IAAK,CACxD;AAAA,EACH,GAAG,CAAC,QAAQ,QAAQ,IAAI,CAAC;AAGzB,YAAU,MAAM;AACd,WAAO,cAAA;AAEP,WAAO,MAAM;AACX,aAAO,QAAA;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,WAAW;AAAA,IACf,OAAO,UAAkB;AACvB,YAAM,OAAO,SAAS,KAAK;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAGT,QAAM,OAAO,YAAY,MAAM;AAC7B,WAAO,KAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,QAAQ,YAAY,MAAM;AAC9B,WAAO,MAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"use-generation.js","names":[],"sources":["../../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The output type after optional transform (defaults to TResult)\n */\nexport interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations, where\n * it falls back to `id` purely to satisfy the wire.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n /**\n * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized hook (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (after optional transform)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface UseGenerationReturn<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: TOutput | null\n /** Whether a generation is currently in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation client */\n status: GenerationClientState\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: string | null\n}\n\n/**\n * Generic React hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\n * ```\n */\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<\n UseGenerationOptions<TInput, TResult>,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: TResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerationReturn<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = useId()\n // Single identity: prefer `threadId`; deprecated `id` only when no threadId.\n const clientIdentity = options.threadId ?? options.id ?? hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [status, setStatus] = useState<GenerationClientState>('idle')\n const [runId, setRunId] = useState<string | null>(null)\n\n const optionsRef = useRef(options)\n optionsRef.current = options\n const disposedRef = useRef(false)\n\n const client = useMemo(() => {\n const opts = optionsRef.current\n\n // Conditional spread for `body` (strict-optional in target;\n // local source is `Record<string, any> | undefined`). Callbacks\n // wrap optional ones in non-returning bodies so `?.()`'s\n // implicit `undefined` doesn't pollute the function return type.\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n body: opts.body,\n ...(opts.threadId !== undefined\n ? { threadId: opts.threadId }\n : { id: opts.id ?? hookId }),\n ...(opts.persistence !== undefined && { persistence: opts.persistence }),\n ...(opts.hydrateGeneration !== undefined && {\n hydrateGeneration: opts.hydrateGeneration,\n }),\n ...(opts.joinRun !== undefined && { joinRun: opts.joinRun }),\n ...(opts.reconstructResult\n ? { reconstructResult: opts.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n hookName: 'useGeneration',\n framework: 'react',\n ...opts.devtools,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposedRef.current) optionsRef.current.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposedRef.current) optionsRef.current.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposedRef.current) optionsRef.current.onChunk?.(c)\n },\n onResultChange: (r) => {\n if (!disposedRef.current) setResult(r)\n },\n onLoadingChange: (l) => {\n if (!disposedRef.current) setIsLoading(l)\n },\n onErrorChange: (e) => {\n if (!disposedRef.current) setError(e)\n },\n onStatusChange: (s) => {\n if (!disposedRef.current) setStatus(s)\n },\n onResumeStateChange: (rs) => {\n if (!disposedRef.current) setRunId(rs?.runId ?? null)\n },\n }\n\n if (opts.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n }, [clientIdentity, hookId])\n\n // Sync body changes without recreating client\n useEffect(() => {\n // Conditional spread: target uses strict-optional `body?: T`.\n client.updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n })\n }, [client, options.body])\n\n // Mount devtools and clean up on unmount. Generation runs are never\n // auto-started on mount — persisted state is only displayed. Mounting\n // revives the client after a StrictMode dispose → remount replay.\n useEffect(() => {\n disposedRef.current = false\n client.mountDevtools()\n\n return () => {\n disposedRef.current = true\n client.dispose()\n }\n }, [client])\n\n const generate = useCallback(\n async (input: TInput) => {\n await client.generate(input)\n },\n [client],\n )\n\n const stop = useCallback(() => {\n client.stop()\n }, [client])\n\n const reset = useCallback(() => {\n client.reset()\n }, [client])\n\n return {\n generate,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":"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"}
@@ -1,26 +1,49 @@
1
- import { useRef, useMemo } from "react";
2
1
  import { createMcpAppBridge } from "@tanstack/ai-client";
2
+ import { useMemo, useRef } from "react";
3
+ //#region src/use-mcp-app-bridge.ts
4
+ /**
5
+ * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for
6
+ * the given `threadId`/`callEndpoint`, while always invoking the latest
7
+ * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating
8
+ * the bridge on every render and the stale-closure / `exhaustive-deps` dance
9
+ * you'd otherwise write by hand:
10
+ *
11
+ * ```tsx
12
+ * const { sendMessage } = useChat({ threadId, connection })
13
+ * const bridge = useMcpAppBridge({
14
+ * threadId,
15
+ * callEndpoint: '/api/mcp-apps-call',
16
+ * chat: { sendMessage: async (content) => void sendMessage(content) },
17
+ * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
18
+ * })
19
+ * // pass `bridge` to <MCPAppResource bridge={bridge} … />
20
+ * ```
21
+ *
22
+ * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or
23
+ * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`
24
+ * each render does not churn it.
25
+ */
3
26
  function useMcpAppBridge(options) {
4
- const { threadId, callEndpoint, chat, fetchImpl, onLink } = options;
5
- const chatRef = useRef(chat);
6
- chatRef.current = chat;
7
- const onLinkRef = useRef(onLink);
8
- onLinkRef.current = onLink;
9
- const hasOnLink = onLink != null;
10
- return useMemo(
11
- () => createMcpAppBridge({
12
- threadId,
13
- callEndpoint,
14
- fetchImpl,
15
- chat: {
16
- sendMessage: (content, body) => chatRef.current.sendMessage(content, body)
17
- },
18
- onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : void 0
19
- }),
20
- [threadId, callEndpoint, fetchImpl, hasOnLink]
21
- );
27
+ const { threadId, callEndpoint, chat, fetchImpl, onLink } = options;
28
+ const chatRef = useRef(chat);
29
+ chatRef.current = chat;
30
+ const onLinkRef = useRef(onLink);
31
+ onLinkRef.current = onLink;
32
+ const hasOnLink = onLink != null;
33
+ return useMemo(() => createMcpAppBridge({
34
+ threadId,
35
+ callEndpoint,
36
+ fetchImpl,
37
+ chat: { sendMessage: (content, body) => chatRef.current.sendMessage(content, body) },
38
+ onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : void 0
39
+ }), [
40
+ threadId,
41
+ callEndpoint,
42
+ fetchImpl,
43
+ hasOnLink
44
+ ]);
22
45
  }
23
- export {
24
- useMcpAppBridge
25
- };
26
- //# sourceMappingURL=use-mcp-app-bridge.js.map
46
+ //#endregion
47
+ export { useMcpAppBridge };
48
+
49
+ //# sourceMappingURL=use-mcp-app-bridge.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-mcp-app-bridge.js","sources":["../../src/use-mcp-app-bridge.ts"],"sourcesContent":["import { useMemo, useRef } from 'react'\nimport { createMcpAppBridge } from '@tanstack/ai-client'\nimport type {\n CreateMcpAppBridgeOptions,\n McpAppBridge,\n} from '@tanstack/ai-client'\n\nexport type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions\n\n/**\n * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for\n * the given `threadId`/`callEndpoint`, while always invoking the latest\n * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating\n * the bridge on every render and the stale-closure / `exhaustive-deps` dance\n * you'd otherwise write by hand:\n *\n * ```tsx\n * const { sendMessage } = useChat({ threadId, connection })\n * const bridge = useMcpAppBridge({\n * threadId,\n * callEndpoint: '/api/mcp-apps-call',\n * chat: { sendMessage: async (content) => void sendMessage(content) },\n * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),\n * })\n * // pass `bridge` to <MCPAppResource bridge={bridge} … />\n * ```\n *\n * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or\n * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`\n * each render does not churn it.\n */\nexport function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {\n const { threadId, callEndpoint, chat, fetchImpl, onLink } = options\n\n // Latest-value refs so the bridge identity stays stable but its callbacks are\n // never stale (the bridge calls `.current` at invocation time, not creation).\n const chatRef = useRef(chat)\n chatRef.current = chat\n const onLinkRef = useRef(onLink)\n onLinkRef.current = onLink\n\n // Whether a link handler was supplied governs the bridge's link behavior\n // (forward vs. display-only warn), so it's part of the bridge's identity.\n const hasOnLink = onLink != null\n\n return useMemo(\n () =>\n createMcpAppBridge({\n threadId,\n callEndpoint,\n fetchImpl,\n chat: {\n sendMessage: (content, body) =>\n chatRef.current.sendMessage(content, body),\n },\n onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,\n }),\n [threadId, callEndpoint, fetchImpl, hasOnLink],\n )\n}\n"],"names":[],"mappings":";;AA+BO,SAAS,gBAAgB,SAA+C;AAC7E,QAAM,EAAE,UAAU,cAAc,MAAM,WAAW,WAAW;AAI5D,QAAM,UAAU,OAAO,IAAI;AAC3B,UAAQ,UAAU;AAClB,QAAM,YAAY,OAAO,MAAM;AAC/B,YAAU,UAAU;AAIpB,QAAM,YAAY,UAAU;AAE5B,SAAO;AAAA,IACL,MACE,mBAAmB;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA,MAAM;AAAA,QACJ,aAAa,CAAC,SAAS,SACrB,QAAQ,QAAQ,YAAY,SAAS,IAAI;AAAA,MAAA;AAAA,MAE7C,QAAQ,YAAY,CAAC,QAAQ,UAAU,UAAU,GAAG,IAAI;AAAA,IAAA,CACzD;AAAA,IACH,CAAC,UAAU,cAAc,WAAW,SAAS;AAAA,EAAA;AAEjD;"}
1
+ {"version":3,"file":"use-mcp-app-bridge.js","names":[],"sources":["../../src/use-mcp-app-bridge.ts"],"sourcesContent":["import { useMemo, useRef } from 'react'\nimport { createMcpAppBridge } from '@tanstack/ai-client'\nimport type {\n CreateMcpAppBridgeOptions,\n McpAppBridge,\n} from '@tanstack/ai-client'\n\nexport type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions\n\n/**\n * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for\n * the given `threadId`/`callEndpoint`, while always invoking the latest\n * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating\n * the bridge on every render and the stale-closure / `exhaustive-deps` dance\n * you'd otherwise write by hand:\n *\n * ```tsx\n * const { sendMessage } = useChat({ threadId, connection })\n * const bridge = useMcpAppBridge({\n * threadId,\n * callEndpoint: '/api/mcp-apps-call',\n * chat: { sendMessage: async (content) => void sendMessage(content) },\n * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),\n * })\n * // pass `bridge` to <MCPAppResource bridge={bridge} … />\n * ```\n *\n * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or\n * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`\n * each render does not churn it.\n */\nexport function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {\n const { threadId, callEndpoint, chat, fetchImpl, onLink } = options\n\n // Latest-value refs so the bridge identity stays stable but its callbacks are\n // never stale (the bridge calls `.current` at invocation time, not creation).\n const chatRef = useRef(chat)\n chatRef.current = chat\n const onLinkRef = useRef(onLink)\n onLinkRef.current = onLink\n\n // Whether a link handler was supplied governs the bridge's link behavior\n // (forward vs. display-only warn), so it's part of the bridge's identity.\n const hasOnLink = onLink != null\n\n return useMemo(\n () =>\n createMcpAppBridge({\n threadId,\n callEndpoint,\n fetchImpl,\n chat: {\n sendMessage: (content, body) =>\n chatRef.current.sendMessage(content, body),\n },\n onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,\n }),\n [threadId, callEndpoint, fetchImpl, hasOnLink],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,gBAAgB,SAA+C;CAC7E,MAAM,EAAE,UAAU,cAAc,MAAM,WAAW,WAAW;CAI5D,MAAM,UAAU,OAAO,IAAI;CAC3B,QAAQ,UAAU;CAClB,MAAM,YAAY,OAAO,MAAM;CAC/B,UAAU,UAAU;CAIpB,MAAM,YAAY,UAAU;CAE5B,OAAO,cAEH,mBAAmB;EACjB;EACA;EACA;EACA,MAAM,EACJ,cAAc,SAAS,SACrB,QAAQ,QAAQ,YAAY,SAAS,IAAI,EAC7C;EACA,QAAQ,aAAa,QAAQ,UAAU,UAAU,GAAG,IAAI,KAAA;CAC1D,CAAC,GACH;EAAC;EAAU;EAAc;EAAW;CAAS,CAC/C;AACF"}