@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.
- package/README.md +15 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +2 -23
- package/dist/esm/mcp-app-resource.js +45 -45
- package/dist/esm/mcp-app-resource.js.map +1 -1
- package/dist/esm/mcp-apps.js +1 -4
- package/dist/esm/types.d.ts +29 -3
- package/dist/esm/use-audio-recorder.js +41 -46
- package/dist/esm/use-audio-recorder.js.map +1 -1
- package/dist/esm/use-chat.js +330 -275
- package/dist/esm/use-chat.js.map +1 -1
- package/dist/esm/use-generate-audio.d.ts +50 -4
- package/dist/esm/use-generate-audio.js +47 -23
- package/dist/esm/use-generate-audio.js.map +1 -1
- package/dist/esm/use-generate-image.d.ts +50 -4
- package/dist/esm/use-generate-image.js +49 -23
- package/dist/esm/use-generate-image.js.map +1 -1
- package/dist/esm/use-generate-speech.d.ts +50 -4
- package/dist/esm/use-generate-speech.js +43 -23
- package/dist/esm/use-generate-speech.js.map +1 -1
- package/dist/esm/use-generate-video.d.ts +50 -4
- package/dist/esm/use-generate-video.js +141 -103
- package/dist/esm/use-generate-video.js.map +1 -1
- package/dist/esm/use-generation.d.ts +59 -6
- package/dist/esm/use-generation.js +113 -90
- package/dist/esm/use-generation.js.map +1 -1
- package/dist/esm/use-mcp-app-bridge.js +46 -23
- package/dist/esm/use-mcp-app-bridge.js.map +1 -1
- package/dist/esm/use-realtime-chat.js +185 -185
- package/dist/esm/use-realtime-chat.js.map +1 -1
- package/dist/esm/use-summarize.d.ts +50 -4
- package/dist/esm/use-summarize.js +46 -23
- package/dist/esm/use-summarize.js.map +1 -1
- package/dist/esm/use-transcription.d.ts +50 -4
- package/dist/esm/use-transcription.js +51 -20
- package/dist/esm/use-transcription.js.map +1 -1
- package/package.json +7 -7
- package/src/index.ts +10 -0
- package/src/types.ts +44 -0
- package/src/use-chat.ts +221 -35
- package/src/use-generate-audio.ts +64 -17
- package/src/use-generate-image.ts +64 -17
- package/src/use-generate-speech.ts +64 -17
- package/src/use-generate-video.ts +99 -18
- package/src/use-generation.ts +112 -18
- package/src/use-summarize.ts +64 -17
- package/src/use-transcription.ts +60 -18
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/mcp-apps.js.map +0 -1
|
@@ -1,26 +1,46 @@
|
|
|
1
1
|
import { useGeneration } from "./use-generation.js";
|
|
2
|
+
import { reconstructSpeechResult } from "@tanstack/ai-client";
|
|
3
|
+
//#region src/use-generate-speech.ts
|
|
4
|
+
/**
|
|
5
|
+
* React hook for generating speech (text-to-speech) using AI models.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```tsx
|
|
9
|
+
* import { useGenerateSpeech } from '@tanstack/ai-react'
|
|
10
|
+
* import { fetchServerSentEvents } from '@tanstack/ai-client'
|
|
11
|
+
*
|
|
12
|
+
* function SpeechGenerator() {
|
|
13
|
+
* const { generate, result, isLoading } = useGenerateSpeech({
|
|
14
|
+
* connection: fetchServerSentEvents('/api/generate/speech'),
|
|
15
|
+
* })
|
|
16
|
+
*
|
|
17
|
+
* return (
|
|
18
|
+
* <div>
|
|
19
|
+
* <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>
|
|
20
|
+
* Generate Speech
|
|
21
|
+
* </button>
|
|
22
|
+
* {result && (
|
|
23
|
+
* <audio src={`data:audio/${result.format};base64,${result.audio}`} controls />
|
|
24
|
+
* )}
|
|
25
|
+
* </div>
|
|
26
|
+
* )
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
2
30
|
function useGenerateSpeech(options) {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
generate,
|
|
15
|
-
result,
|
|
16
|
-
isLoading,
|
|
17
|
-
error,
|
|
18
|
-
status,
|
|
19
|
-
stop,
|
|
20
|
-
reset
|
|
21
|
-
};
|
|
31
|
+
const devtools = {
|
|
32
|
+
...options.devtools,
|
|
33
|
+
framework: "react",
|
|
34
|
+
hookName: "useGenerateSpeech",
|
|
35
|
+
outputKind: "audio"
|
|
36
|
+
};
|
|
37
|
+
return useGeneration({
|
|
38
|
+
...options,
|
|
39
|
+
devtools,
|
|
40
|
+
reconstructResult: reconstructSpeechResult
|
|
41
|
+
});
|
|
22
42
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
//# sourceMappingURL=use-generate-speech.js.map
|
|
43
|
+
//#endregion
|
|
44
|
+
export { useGenerateSpeech };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=use-generate-speech.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-speech.js","sources":["../../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The output type after optional transform (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\n
|
|
1
|
+
{"version":3,"file":"use-generate-speech.js","names":[],"sources":["../../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The output type after optional transform (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\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 speech is generated. 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: TTSResult) => 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 useGenerateSpeech hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: TOutput | null\n /** Whether generation is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\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 * React hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function SpeechGenerator() {\n * const { generate, result, isLoading } = useGenerateSpeech({\n * connection: fetchServerSentEvents('/api/generate/speech'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>\n * Generate Speech\n * </button>\n * {result && (\n * <audio src={`data:audio/${result.format};base64,${result.audio}`} controls />\n * )}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateSpeech<TTransformed = void>(\n options: Omit<\n UseGenerateSpeechOptions,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: TTSResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'react',\n hookName: 'useGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const generation = useGeneration<\n SpeechGenerateInput,\n TTSResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSpeechResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA,SAAgB,kBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;CACd;CAWA,OAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;CACrB,CAEO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from '@tanstack/ai-client';
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, GenerationPersistenceOptions, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGenerateVideo hook.
|
|
5
5
|
*/
|
|
@@ -8,12 +8,51 @@ export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
8
8
|
connection?: ConnectConnectionAdapter;
|
|
9
9
|
/** Direct async function that returns a completed video result */
|
|
10
10
|
fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
13
|
+
*/
|
|
12
14
|
id?: string;
|
|
13
15
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
14
16
|
body?: Record<string, any>;
|
|
15
17
|
/** Display options for TanStack AI Devtools. */
|
|
16
18
|
devtools?: AIDevtoolsDisplayOptions;
|
|
19
|
+
/**
|
|
20
|
+
* How this generation persists across reloads.
|
|
21
|
+
* - Omit / `false`: ephemeral, in-memory only.
|
|
22
|
+
* - `true`: server-driven — on mount the client hydrates the last generation
|
|
23
|
+
* for its `threadId` from the server (needs a connection with a
|
|
24
|
+
* `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
|
|
25
|
+
*/
|
|
26
|
+
persistence?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The **scope** this generation belongs to: a stable, app-chosen name for the
|
|
29
|
+
* slot successive runs fill — not a link to a chat conversation.
|
|
30
|
+
*
|
|
31
|
+
* The hook starts empty and produces many runs over its life; each gets its
|
|
32
|
+
* own `runId`, but all belong to one scope. Persistence keys on this, so
|
|
33
|
+
* derive it from your own domain and keep it identical across reloads (e.g.
|
|
34
|
+
* `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
|
|
35
|
+
* id on the wire, which the protocol requires.
|
|
36
|
+
*
|
|
37
|
+
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
38
|
+
* scope has nothing to restore to. Optional for ephemeral generations, where
|
|
39
|
+
* it falls back to `id` purely to satisfy the wire.
|
|
40
|
+
*/
|
|
41
|
+
threadId?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Server-driven hydration handler for `persistence: true` when the
|
|
44
|
+
* connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
|
|
45
|
+
* `rpcStream()` adapter built without handlers) — typically a one-line
|
|
46
|
+
* server-function call. The connection's own handler takes precedence.
|
|
47
|
+
*/
|
|
48
|
+
hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
|
|
49
|
+
/**
|
|
50
|
+
* Re-attach handler that replays a run still generating to completion on
|
|
51
|
+
* mount, when the connection doesn't carry one. Without it, a restored
|
|
52
|
+
* `running` snapshot surfaces as an (interrupted) error. The connection's
|
|
53
|
+
* own handler takes precedence.
|
|
54
|
+
*/
|
|
55
|
+
joinRun?: ConnectConnectionAdapter['joinRun'];
|
|
17
56
|
/**
|
|
18
57
|
* Callback when video generation completes. Can optionally return a transformed value.
|
|
19
58
|
*
|
|
@@ -57,6 +96,13 @@ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
57
96
|
stop: () => void;
|
|
58
97
|
/** Clear all state and return to idle */
|
|
59
98
|
reset: () => void;
|
|
99
|
+
/**
|
|
100
|
+
* The id of the generation job currently running, or `null` when nothing is in
|
|
101
|
+
* flight. Each call to `generate` is one job with its own id. Pass it to your
|
|
102
|
+
* own endpoint to cancel or poll the provider job — `stop()` only aborts the
|
|
103
|
+
* local stream, it does not stop work already running on the provider.
|
|
104
|
+
*/
|
|
105
|
+
runId: string | null;
|
|
60
106
|
}
|
|
61
107
|
/**
|
|
62
108
|
* React hook for generating videos using AI models.
|
|
@@ -89,6 +135,6 @@ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
89
135
|
* }
|
|
90
136
|
* ```
|
|
91
137
|
*/
|
|
92
|
-
export declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult'> & {
|
|
138
|
+
export declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
|
|
93
139
|
onResult?: (result: VideoGenerateResult) => TTransformed;
|
|
94
|
-
}): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
140
|
+
} & GenerationPersistenceOptions): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
@@ -1,107 +1,145 @@
|
|
|
1
1
|
import { VideoGenerationClient } from "@tanstack/ai-client";
|
|
2
2
|
import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
3
|
-
import {
|
|
3
|
+
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
|
4
|
+
//#region src/use-generate-video.ts
|
|
5
|
+
/**
|
|
6
|
+
* React hook for generating videos using AI models.
|
|
7
|
+
*
|
|
8
|
+
* Video generation is asynchronous: a job is created, then polled for status
|
|
9
|
+
* until completion. This hook handles the full lifecycle.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import { useGenerateVideo } from '@tanstack/ai-react'
|
|
14
|
+
* import { fetchServerSentEvents } from '@tanstack/ai-client'
|
|
15
|
+
*
|
|
16
|
+
* function VideoGenerator() {
|
|
17
|
+
* const { generate, result, videoStatus, isLoading } = useGenerateVideo({
|
|
18
|
+
* connection: fetchServerSentEvents('/api/generate/video'),
|
|
19
|
+
* onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),
|
|
20
|
+
* })
|
|
21
|
+
*
|
|
22
|
+
* return (
|
|
23
|
+
* <div>
|
|
24
|
+
* <button onClick={() => generate({ prompt: 'A flying car over a city' })}>
|
|
25
|
+
* Generate Video
|
|
26
|
+
* </button>
|
|
27
|
+
* {isLoading && videoStatus && (
|
|
28
|
+
* <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>
|
|
29
|
+
* )}
|
|
30
|
+
* {result && <video src={result.url} controls />}
|
|
31
|
+
* </div>
|
|
32
|
+
* )
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
4
36
|
function useGenerateVideo(options) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
37
|
+
const hookId = useId();
|
|
38
|
+
const clientIdentity = options.threadId ?? options.id ?? hookId;
|
|
39
|
+
const [result, setResult] = useState(null);
|
|
40
|
+
const [jobId, setJobId] = useState(null);
|
|
41
|
+
const [videoStatus, setVideoStatus] = useState(null);
|
|
42
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
43
|
+
const [error, setError] = useState(void 0);
|
|
44
|
+
const [status, setStatus] = useState("idle");
|
|
45
|
+
const [runId, setRunId] = useState(null);
|
|
46
|
+
const optionsRef = useRef(options);
|
|
47
|
+
optionsRef.current = options;
|
|
48
|
+
const disposedRef = useRef(false);
|
|
49
|
+
const client = useMemo(() => {
|
|
50
|
+
const opts = optionsRef.current;
|
|
51
|
+
const baseOptions = {
|
|
52
|
+
body: opts.body,
|
|
53
|
+
...opts.threadId !== void 0 ? { threadId: opts.threadId } : { id: opts.id ?? hookId },
|
|
54
|
+
...opts.persistence !== void 0 && { persistence: opts.persistence },
|
|
55
|
+
...opts.hydrateGeneration !== void 0 && { hydrateGeneration: opts.hydrateGeneration },
|
|
56
|
+
...opts.joinRun !== void 0 && { joinRun: opts.joinRun },
|
|
57
|
+
devtoolsBridgeFactory: createVideoDevtoolsBridge,
|
|
58
|
+
devtools: {
|
|
59
|
+
...opts.devtools,
|
|
60
|
+
framework: "react",
|
|
61
|
+
hookName: "useGenerateVideo",
|
|
62
|
+
outputKind: "video"
|
|
63
|
+
},
|
|
64
|
+
onResult: ((r) => optionsRef.current.onResult?.(r)),
|
|
65
|
+
onError: (e) => {
|
|
66
|
+
if (!disposedRef.current) optionsRef.current.onError?.(e);
|
|
67
|
+
},
|
|
68
|
+
onProgress: (p, m) => {
|
|
69
|
+
if (!disposedRef.current) optionsRef.current.onProgress?.(p, m);
|
|
70
|
+
},
|
|
71
|
+
onChunk: (c) => {
|
|
72
|
+
if (!disposedRef.current) optionsRef.current.onChunk?.(c);
|
|
73
|
+
},
|
|
74
|
+
onJobCreated: (id) => {
|
|
75
|
+
if (!disposedRef.current) optionsRef.current.onJobCreated?.(id);
|
|
76
|
+
},
|
|
77
|
+
onStatusUpdate: (s) => {
|
|
78
|
+
if (!disposedRef.current) optionsRef.current.onStatusUpdate?.(s);
|
|
79
|
+
},
|
|
80
|
+
onResultChange: (r) => {
|
|
81
|
+
if (!disposedRef.current) setResult(r);
|
|
82
|
+
},
|
|
83
|
+
onLoadingChange: (l) => {
|
|
84
|
+
if (!disposedRef.current) setIsLoading(l);
|
|
85
|
+
},
|
|
86
|
+
onErrorChange: (e) => {
|
|
87
|
+
if (!disposedRef.current) setError(e);
|
|
88
|
+
},
|
|
89
|
+
onStatusChange: (s) => {
|
|
90
|
+
if (!disposedRef.current) setStatus(s);
|
|
91
|
+
},
|
|
92
|
+
onJobIdChange: (id) => {
|
|
93
|
+
if (!disposedRef.current) setJobId(id);
|
|
94
|
+
},
|
|
95
|
+
onVideoStatusChange: (s) => {
|
|
96
|
+
if (!disposedRef.current) setVideoStatus(s);
|
|
97
|
+
},
|
|
98
|
+
onResumeStateChange: (rs) => {
|
|
99
|
+
if (!disposedRef.current) setRunId(rs?.runId ?? null);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
if (opts.connection) return new VideoGenerationClient({
|
|
103
|
+
...baseOptions,
|
|
104
|
+
connection: opts.connection
|
|
105
|
+
});
|
|
106
|
+
if (opts.fetcher) return new VideoGenerationClient({
|
|
107
|
+
...baseOptions,
|
|
108
|
+
fetcher: opts.fetcher
|
|
109
|
+
});
|
|
110
|
+
throw new Error("useGenerateVideo requires either a connection or fetcher option");
|
|
111
|
+
}, [clientIdentity, hookId]);
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
client.updateOptions({ ...options.body !== void 0 && { body: options.body } });
|
|
114
|
+
}, [client, options.body]);
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
disposedRef.current = false;
|
|
117
|
+
client.mountDevtools();
|
|
118
|
+
return () => {
|
|
119
|
+
disposedRef.current = true;
|
|
120
|
+
client.dispose();
|
|
121
|
+
};
|
|
122
|
+
}, [client]);
|
|
123
|
+
return {
|
|
124
|
+
generate: useCallback(async (input) => {
|
|
125
|
+
await client.generate(input);
|
|
126
|
+
}, [client]),
|
|
127
|
+
result,
|
|
128
|
+
jobId,
|
|
129
|
+
videoStatus,
|
|
130
|
+
isLoading,
|
|
131
|
+
error,
|
|
132
|
+
status,
|
|
133
|
+
stop: useCallback(() => {
|
|
134
|
+
client.stop();
|
|
135
|
+
}, [client]),
|
|
136
|
+
reset: useCallback(() => {
|
|
137
|
+
client.reset();
|
|
138
|
+
}, [client]),
|
|
139
|
+
runId
|
|
140
|
+
};
|
|
103
141
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
//# sourceMappingURL=use-generate-video.js.map
|
|
142
|
+
//#endregion
|
|
143
|
+
export { useGenerateVideo };
|
|
144
|
+
|
|
145
|
+
//# sourceMappingURL=use-generate-video.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-video.js","sources":["../../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } 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 GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateVideo hook.\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\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 video generation completes. 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: VideoGenerateResult) => 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 when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => 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 useGenerateVideo hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: TOutput | null\n /** The current job ID, or null */\n jobId: string | null\n /** Current video generation status info, or null */\n videoStatus: VideoStatusInfo | null\n /** Whether generation/polling is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading && videoStatus && (\n * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>\n * )}\n * {result && <video src={result.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function useGenerateVideo<TTransformed = void>(\n options: Omit<UseGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = useId()\n const clientId = options.id || hookId\n\n const [result, setResult] = useState<TOutput | null>(null)\n const [jobId, setJobId] = useState<string | null>(null)\n const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | 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 // Optional callbacks are wrapped in non-returning bodies so\n // `?.()`'s implicit `undefined` doesn't widen the function\n // return type (which `exactOptionalPropertyTypes` rejects\n // against the strict-optional target).\n const baseOptions = {\n id: clientId,\n body: opts.body,\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...opts.devtools,\n framework: 'react',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\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: VideoGenerateResult) =>\n optionsRef.current.onResult?.(r)) as (\n result: VideoGenerateResult,\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 onJobCreated: (id: string) => {\n optionsRef.current.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n optionsRef.current.onStatusUpdate?.(s)\n },\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n onJobIdChange: setJobId,\n onVideoStatusChange: setVideoStatus,\n }\n\n if (opts.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo 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: VideoGenerateInput) => {\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 jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";;;AA6GO,SAAS,iBACd,SAKA;AAKA,QAAM,SAAS,MAAA;AACf,QAAM,WAAW,QAAQ,MAAM;AAE/B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,IAAI;AACzD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AACtD,QAAM,CAAC,aAAa,cAAc,IAAI,SAAiC,IAAI;AAC3E,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;AAOxB,UAAM,cAAc;AAAA,MAClB,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,uBAAuB;AAAA,MACvB,UAAU;AAAA,QACR,GAAG,KAAK;AAAA,QACR,WAAW;AAAA,QACX,UAAU;AAAA,QACV,YAAY;AAAA,MAAA;AAAA;AAAA;AAAA;AAAA,MAKd,WAAW,CAAC,MACV,WAAW,QAAQ,WAAW,CAAC;AAAA,MAGjC,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,cAAc,CAAC,OAAe;AAC5B,mBAAW,QAAQ,eAAe,EAAE;AAAA,MACtC;AAAA,MACA,gBAAgB,CAAC,MAAuB;AACtC,mBAAW,QAAQ,iBAAiB,CAAC;AAAA,MACvC;AAAA,MACA,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,eAAe;AAAA,MACf,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,IAAA;AAGvB,QAAI,KAAK,YAAY;AACnB,aAAO,IAAI,sBAA+B;AAAA,QACxC,GAAG;AAAA,QACH,YAAY,KAAK;AAAA,MAAA,CAClB;AAAA,IACH;AAEA,QAAI,KAAK,SAAS;AAChB,aAAO,IAAI,sBAA+B;AAAA,QACxC,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,UAA8B;AACnC,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,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"use-generate-video.js","names":[],"sources":["../../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } 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 GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useGenerateVideo hook.\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\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 video generation completes. 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: VideoGenerateResult) => 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 when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => 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 useGenerateVideo hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: TOutput | null\n /** The current job ID, or null */\n jobId: string | null\n /** Current video generation status info, or null */\n videoStatus: VideoStatusInfo | null\n /** Whether generation/polling is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state 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 * React hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading && videoStatus && (\n * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>\n * )}\n * {result && <video src={result.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function useGenerateVideo<TTransformed = void>(\n options: Omit<\n UseGenerateVideoOptions,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\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 [jobId, setJobId] = useState<string | null>(null)\n const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | 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 // Optional callbacks are wrapped in non-returning bodies so\n // `?.()`'s implicit `undefined` doesn't widen the function\n // return type (which `exactOptionalPropertyTypes` rejects\n // against the strict-optional target).\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n const baseOptions = {\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 devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...opts.devtools,\n framework: 'react',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\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: VideoGenerateResult) =>\n optionsRef.current.onResult?.(r)) as (\n result: VideoGenerateResult,\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 onJobCreated: (id: string) => {\n if (!disposedRef.current) optionsRef.current.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposedRef.current) optionsRef.current.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposedRef.current) setResult(r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposedRef.current) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposedRef.current) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposedRef.current) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposedRef.current) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposedRef.current) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposedRef.current) setRunId(rs?.runId ?? null)\n },\n }\n\n if (opts.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: opts.connection,\n })\n }\n\n if (opts.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: opts.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo 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: VideoGenerateInput) => {\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 jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":"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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, GenerationPersistenceOptions, GenerationRestoredResult, InferGenerationOutputFromReturn } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useGeneration hook.
|
|
5
5
|
*
|
|
@@ -14,12 +14,51 @@ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
14
14
|
connection?: ConnectConnectionAdapter;
|
|
15
15
|
/** Direct async function for one-shot generation (no streaming protocol needed) */
|
|
16
16
|
fetcher?: GenerationFetcher<TInput, TResult>;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
19
|
+
*/
|
|
18
20
|
id?: string;
|
|
19
21
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
20
22
|
body?: Record<string, any>;
|
|
21
23
|
/** Display options for TanStack AI Devtools. */
|
|
22
24
|
devtools?: AIDevtoolsDisplayOptions;
|
|
25
|
+
/**
|
|
26
|
+
* How this generation persists across reloads.
|
|
27
|
+
* - Omit / `false`: ephemeral, in-memory only.
|
|
28
|
+
* - `true`: server-driven — on mount the client hydrates the last generation
|
|
29
|
+
* for its `threadId` from the server (needs a connection with a
|
|
30
|
+
* `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
|
|
31
|
+
*/
|
|
32
|
+
persistence?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The **scope** this generation belongs to: a stable, app-chosen name for the
|
|
35
|
+
* slot successive runs fill — not a link to a chat conversation.
|
|
36
|
+
*
|
|
37
|
+
* The hook starts empty and produces many runs over its life; each gets its
|
|
38
|
+
* own `runId`, but all belong to one scope. Persistence keys on this, so
|
|
39
|
+
* derive it from your own domain and keep it identical across reloads (e.g.
|
|
40
|
+
* `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
|
|
41
|
+
* id on the wire, which the protocol requires.
|
|
42
|
+
*
|
|
43
|
+
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
44
|
+
* scope has nothing to restore to. Optional for ephemeral generations, where
|
|
45
|
+
* it falls back to `id` purely to satisfy the wire.
|
|
46
|
+
*/
|
|
47
|
+
threadId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Server-driven hydration handler for `persistence: true` when the
|
|
50
|
+
* connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
|
|
51
|
+
* `rpcStream()` adapter built without handlers) — typically a one-line
|
|
52
|
+
* server-function call. The connection's own handler takes precedence.
|
|
53
|
+
*/
|
|
54
|
+
hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
|
|
55
|
+
/**
|
|
56
|
+
* Re-attach handler that replays a run still generating to completion on
|
|
57
|
+
* mount, when the connection doesn't carry one. Without it, a restored
|
|
58
|
+
* `running` snapshot surfaces as an (interrupted) error. The connection's
|
|
59
|
+
* own handler takes precedence.
|
|
60
|
+
*/
|
|
61
|
+
joinRun?: ConnectConnectionAdapter['joinRun'];
|
|
23
62
|
/**
|
|
24
63
|
* Callback when a result is received. Can optionally return a transformed value.
|
|
25
64
|
*
|
|
@@ -34,15 +73,22 @@ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
34
73
|
onProgress?: (progress: number, message?: string) => void;
|
|
35
74
|
/** Callback for each stream chunk (connect-based adapter mode only) */
|
|
36
75
|
onChunk?: (chunk: StreamChunk) => void;
|
|
76
|
+
/**
|
|
77
|
+
* @internal Rebuild a typed result from a restored snapshot, injected by each
|
|
78
|
+
* specialized hook (image / speech / audio / transcription / summarize).
|
|
79
|
+
* Forwarded to the client so a server-hydrate restore repaints `result`.
|
|
80
|
+
*/
|
|
81
|
+
reconstructResult?: (restored: GenerationRestoredResult) => TResult | null;
|
|
37
82
|
}
|
|
38
83
|
/**
|
|
39
84
|
* Return type for the useGeneration hook.
|
|
40
85
|
*
|
|
41
86
|
* @template TOutput - The output type (after optional transform)
|
|
87
|
+
* @template TInput - The input type accepted by `generate` (defaults to any object)
|
|
42
88
|
*/
|
|
43
|
-
export interface UseGenerationReturn<TOutput> {
|
|
89
|
+
export interface UseGenerationReturn<TOutput, TInput extends Record<string, any> = Record<string, any>> {
|
|
44
90
|
/** Trigger a generation request */
|
|
45
|
-
generate: (input:
|
|
91
|
+
generate: (input: TInput) => Promise<void>;
|
|
46
92
|
/** The generation result, or null if not yet generated */
|
|
47
93
|
result: TOutput | null;
|
|
48
94
|
/** Whether a generation is currently in progress */
|
|
@@ -55,6 +101,13 @@ export interface UseGenerationReturn<TOutput> {
|
|
|
55
101
|
stop: () => void;
|
|
56
102
|
/** Clear result, error, and return to idle */
|
|
57
103
|
reset: () => void;
|
|
104
|
+
/**
|
|
105
|
+
* The id of the generation job currently running, or `null` when nothing is in
|
|
106
|
+
* flight. Each call to `generate` is one job with its own id. Pass it to your
|
|
107
|
+
* own endpoint to cancel or poll the provider job — `stop()` only aborts the
|
|
108
|
+
* local stream, it does not stop work already running on the provider.
|
|
109
|
+
*/
|
|
110
|
+
runId: string | null;
|
|
58
111
|
}
|
|
59
112
|
/**
|
|
60
113
|
* Generic React hook for one-shot generation tasks.
|
|
@@ -75,6 +128,6 @@ export interface UseGenerationReturn<TOutput> {
|
|
|
75
128
|
* await generate({ prompt: 'Hello' })
|
|
76
129
|
* ```
|
|
77
130
|
*/
|
|
78
|
-
export declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
|
|
131
|
+
export declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
|
|
79
132
|
onResult?: (result: TResult) => TTransformed;
|
|
80
|
-
}): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed
|
|
133
|
+
} & GenerationPersistenceOptions): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>, TInput>;
|