@tanstack/ai-solid 0.16.3 → 0.18.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 +2 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/types.d.ts +9 -9
- package/dist/use-chat.d.ts +2 -2
- package/dist/use-chat.js +7 -4
- package/dist/use-chat.js.map +1 -1
- package/dist/use-generate-audio.d.ts +1 -5
- package/dist/use-generate-audio.js.map +1 -1
- package/dist/use-generate-image.d.ts +1 -5
- package/dist/use-generate-image.js.map +1 -1
- package/dist/use-generate-speech.d.ts +1 -5
- package/dist/use-generate-speech.js.map +1 -1
- package/dist/use-generate-video.d.ts +3 -7
- package/dist/use-generate-video.js +5 -4
- package/dist/use-generate-video.js.map +1 -1
- package/dist/use-generation.d.ts +3 -7
- package/dist/use-generation.js +7 -4
- package/dist/use-generation.js.map +1 -1
- package/dist/use-summarize.d.ts +1 -5
- package/dist/use-summarize.js.map +1 -1
- package/dist/use-transcription.d.ts +1 -5
- package/dist/use-transcription.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +2 -0
- package/src/types.ts +21 -11
- package/src/use-chat.ts +36 -19
- package/src/use-generate-audio.ts +1 -5
- package/src/use-generate-image.ts +1 -5
- package/src/use-generate-speech.ts +1 -5
- package/src/use-generate-video.ts +13 -17
- package/src/use-generation.ts +21 -17
- package/src/use-summarize.ts +1 -5
- package/src/use-transcription.ts +1 -5
package/README.md
CHANGED
|
@@ -87,8 +87,7 @@ interface UseChatOptions {
|
|
|
87
87
|
|
|
88
88
|
// Configuration
|
|
89
89
|
initialMessages?: UIMessage[] // Starting messages
|
|
90
|
-
|
|
91
|
-
threadId?: string // AG-UI thread ID (auto-generated if omitted)
|
|
90
|
+
threadId?: string // The only chat identity. Required when persistence is on. Minted after mount if omitted.
|
|
92
91
|
forwardedProps?: Record<string, any> // Forwarded to AG-UI RunAgentInput.forwardedProps
|
|
93
92
|
/** @deprecated Use `forwardedProps` instead. */
|
|
94
93
|
body?: Record<string, any>
|
|
@@ -408,7 +407,7 @@ export const Route = createFileRoute('/api/chat')({
|
|
|
408
407
|
return toServerSentEventsResponse(
|
|
409
408
|
chat({
|
|
410
409
|
adapter: anthropicText(),
|
|
411
|
-
model: 'claude-sonnet-4-
|
|
410
|
+
model: 'claude-sonnet-4-6',
|
|
412
411
|
messages,
|
|
413
412
|
tools, // Tools with execute functions
|
|
414
413
|
}),
|
package/dist/index.d.ts
CHANGED
|
@@ -8,5 +8,5 @@ import { UseTranscriptionOptions, UseTranscriptionReturn, useTranscription } fro
|
|
|
8
8
|
import { UseSummarizeOptions, UseSummarizeReturn, useSummarize } from "./use-summarize.js";
|
|
9
9
|
import { UseGenerateVideoOptions, UseGenerateVideoReturn, useGenerateVideo } from "./use-generate-video.js";
|
|
10
10
|
import { UseAudioRecorderOptions, UseAudioRecorderReturn, useAudioRecorder } from "./use-audio-recorder.js";
|
|
11
|
-
import { AudioGenerateInput, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatStorageAdapter, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, IndexedDBPersistenceOptions, InferChatMessages, RunAgentInputContext, SpeechGenerateInput, StorageUnavailableError, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WebStoragePersistenceOptions, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
12
|
-
export { type AudioGenerateInput, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type IndexedDBPersistenceOptions, type InferChatMessages, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, type SubscribeConnectionAdapter, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, type UseAudioRecorderOptions, type UseAudioRecorderReturn, type UseChatOptions, type UseChatReturn, type UseGenerateAudioOptions, type UseGenerateAudioReturn, type UseGenerateImageOptions, type UseGenerateImageReturn, type UseGenerateSpeechOptions, type UseGenerateSpeechReturn, type UseGenerateVideoOptions, type UseGenerateVideoReturn, type UseGenerationOptions, type UseGenerationReturn, type UseSummarizeOptions, type UseSummarizeReturn, type UseTranscriptionOptions, type UseTranscriptionReturn, type VideoGenerateInput, type VideoGenerateResult, type VideoStatusInfo, type WebStoragePersistenceOptions, type WhenBusy, type XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
|
|
11
|
+
import { AudioGenerateInput, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatStorageAdapter, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, IndexedDBPersistenceOptions, InferChatMessages, RunAgentInputContext, SpeechGenerateInput, StorageUnavailableError, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WebSocketConnectionOptions, WebStoragePersistenceOptions, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
12
|
+
export { type AudioGenerateInput, type ChatClientPersistence, type ChatPersistedState, type ChatPersistenceOption, type ChatRequestBody, type ChatStorageAdapter, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type IndexedDBPersistenceOptions, type InferChatMessages, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, StorageUnavailableError, type SubscribeConnectionAdapter, type SummarizeGenerateInput, type TranscriptionGenerateInput, type UIMessage, type UseAudioRecorderOptions, type UseAudioRecorderReturn, type UseChatOptions, type UseChatReturn, type UseGenerateAudioOptions, type UseGenerateAudioReturn, type UseGenerateImageOptions, type UseGenerateImageReturn, type UseGenerateSpeechOptions, type UseGenerateSpeechReturn, type UseGenerateVideoOptions, type UseGenerateVideoReturn, type UseGenerationOptions, type UseGenerationReturn, type UseSummarizeOptions, type UseSummarizeReturn, type UseTranscriptionOptions, type UseTranscriptionReturn, type VideoGenerateInput, type VideoGenerateResult, type VideoStatusInfo, type WebSocketConnectionOptions, type WebStoragePersistenceOptions, type WhenBusy, type XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, webSocket, xhrHttpStream, xhrServerSentEvents };
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,6 @@ import { useTranscription } from "./use-transcription.js";
|
|
|
7
7
|
import { useSummarize } from "./use-summarize.js";
|
|
8
8
|
import { useGenerateVideo } from "./use-generate-video.js";
|
|
9
9
|
import { useAudioRecorder } from "./use-audio-recorder.js";
|
|
10
|
-
import { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
10
|
+
import { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, webSocket, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
|
|
11
11
|
|
|
12
|
-
export { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
|
|
12
|
+
export { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, webSocket, xhrHttpStream, xhrServerSentEvents };
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Accessor } from "solid-js";
|
|
2
|
-
import { AIDevtoolsDisplayOptions, BoundInterrupts, ChatClientOptions, ChatClientState,
|
|
3
|
-
import { AnyClientTool, InferSchemaType, ModelMessage, RunAgentResumeItem, SchemaInput } from "@tanstack/ai";
|
|
2
|
+
import { AIDevtoolsDisplayOptions, BoundInterrupts, ChatClientOptions, ChatClientState, ChatInterruptState, ChatRequestBody, ChatResumeState, ClientContextOptionFromTools, ConnectionStatus, DistributedOmit, InferredClientContext, MultimodalContent, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, ResolvableChatInterrupt, SendMessageOptions, UIMessage, WhenBusy } from "@tanstack/ai-client";
|
|
3
|
+
import { AnyClientTool, InferSchemaType, InterruptDefinition, ModelMessage, RunAgentResumeItem, SchemaInput } from "@tanstack/ai";
|
|
4
4
|
|
|
5
5
|
//#region src/types.d.ts
|
|
6
6
|
|
|
@@ -31,7 +31,7 @@ type DeepPartial<T> = T extends ReadonlyArray<infer U> ? Array<DeepPartial<U>> :
|
|
|
31
31
|
* Note: Connection and body changes will recreate the ChatClient instance.
|
|
32
32
|
* To update these options, remount the component or use a key prop.
|
|
33
33
|
*/
|
|
34
|
-
type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientOptions<TTools, TContext>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'onResumeStateChange' | 'onRunIdChange' | 'context' | 'devtools'
|
|
34
|
+
type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = DistributedOmit<ChatClientOptions<TTools, TContext, TInterrupts>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'onResumeStateChange' | 'onRunIdChange' | 'context' | 'devtools'> & {
|
|
35
35
|
/** Display options for TanStack AI Devtools. */
|
|
36
36
|
devtools?: AIDevtoolsDisplayOptions;
|
|
37
37
|
live?: boolean;
|
|
@@ -45,7 +45,7 @@ type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema e
|
|
|
45
45
|
* Discriminated return shape: when `outputSchema` is supplied, the hook adds
|
|
46
46
|
* typed `partial` / `final` accessors; otherwise the return is unchanged.
|
|
47
47
|
*/
|
|
48
|
-
type UseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined> = BaseUseChatReturn<TTools, TSchema extends SchemaInput ? InferSchemaType<TSchema> : unknown> & (TSchema extends SchemaInput ? {
|
|
48
|
+
type UseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = BaseUseChatReturn<TTools, TSchema extends SchemaInput ? InferSchemaType<TSchema> : unknown, TInterrupts> & (TSchema extends SchemaInput ? {
|
|
49
49
|
/**
|
|
50
50
|
* Live progressively-parsed structured output. Derived from the
|
|
51
51
|
* latest assistant message's structured-output part.
|
|
@@ -57,7 +57,7 @@ type UseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema ex
|
|
|
57
57
|
*/
|
|
58
58
|
final: Accessor<InferSchemaType<TSchema> | null>;
|
|
59
59
|
} : Record<never, never>);
|
|
60
|
-
interface BaseUseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown> {
|
|
60
|
+
interface BaseUseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> {
|
|
61
61
|
/**
|
|
62
62
|
* Current messages in the conversation. When `outputSchema` is supplied,
|
|
63
63
|
* `messages()[i].parts.find(p => p.type === 'structured-output')` is typed
|
|
@@ -114,14 +114,14 @@ interface BaseUseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, T
|
|
|
114
114
|
* it, correlate a log line).
|
|
115
115
|
*/
|
|
116
116
|
runId: Accessor<string | null>;
|
|
117
|
-
interrupts: Accessor<BoundInterrupts<TTools>>;
|
|
117
|
+
interrupts: Accessor<BoundInterrupts<TTools, TInterrupts>>;
|
|
118
118
|
/** @deprecated Use `interrupts`. */
|
|
119
|
-
pendingInterrupts: Accessor<BoundInterrupts<TTools>>;
|
|
120
|
-
interruptErrors: Accessor<ChatInterruptState<TTools>['interruptErrors']>;
|
|
119
|
+
pendingInterrupts: Accessor<BoundInterrupts<TTools, TInterrupts>>;
|
|
120
|
+
interruptErrors: Accessor<ChatInterruptState<TTools, TInterrupts>['interruptErrors']>;
|
|
121
121
|
resuming: Accessor<boolean>;
|
|
122
122
|
resolveInterrupts: {
|
|
123
123
|
(approved: boolean): void;
|
|
124
|
-
(resolver: (interrupt:
|
|
124
|
+
(resolver: (interrupt: ResolvableChatInterrupt<TTools, TInterrupts>) => undefined): void;
|
|
125
125
|
};
|
|
126
126
|
cancelInterrupts: () => void;
|
|
127
127
|
retryInterrupts: () => void;
|
package/dist/use-chat.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { UseChatOptions, UseChatReturn } from "./types.js";
|
|
2
2
|
import { InferredClientContext } from "@tanstack/ai-client";
|
|
3
|
-
import { AnyClientTool, SchemaInput } from "@tanstack/ai";
|
|
3
|
+
import { AnyClientTool, InterruptDefinition, SchemaInput } from "@tanstack/ai";
|
|
4
4
|
|
|
5
5
|
//#region src/use-chat.d.ts
|
|
6
|
-
declare function useChat<const TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>>(options?: UseChatOptions<TTools, TSchema, TContext>): UseChatReturn<TTools, TSchema>;
|
|
6
|
+
declare function useChat<const TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>, const TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []>(options?: UseChatOptions<TTools, TSchema, TContext, TInterrupts>): UseChatReturn<TTools, TSchema, TInterrupts>;
|
|
7
7
|
//#endregion
|
|
8
8
|
export { useChat };
|
|
9
9
|
//# sourceMappingURL=use-chat.d.ts.map
|
package/dist/use-chat.js
CHANGED
|
@@ -32,10 +32,12 @@ function useChat(options = {}) {
|
|
|
32
32
|
devtoolsBridgeFactory: createChatDevtoolsBridge,
|
|
33
33
|
...options.connection ? { connection: options.connection } : { fetcher: options.fetcher },
|
|
34
34
|
...options.initialMessages !== void 0 && { initialMessages: options.initialMessages },
|
|
35
|
-
...options.
|
|
35
|
+
...typeof options.threadId === "string" && options.persistence ? {
|
|
36
|
+
persistence: options.persistence,
|
|
37
|
+
threadId: options.threadId
|
|
38
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } },
|
|
36
39
|
...options.initialResumeSnapshot !== void 0 && { initialResumeSnapshot: options.initialResumeSnapshot },
|
|
37
40
|
body: options.body,
|
|
38
|
-
...options.threadId !== void 0 && { threadId: options.threadId },
|
|
39
41
|
...options.forwardedProps !== void 0 && { forwardedProps: options.forwardedProps },
|
|
40
42
|
...options.context !== void 0 && { context: options.context },
|
|
41
43
|
devtools: {
|
|
@@ -55,6 +57,7 @@ function useChat(options = {}) {
|
|
|
55
57
|
options.onError?.(err);
|
|
56
58
|
},
|
|
57
59
|
tools: options.tools,
|
|
60
|
+
...options.interrupts !== void 0 && { interrupts: options.interrupts },
|
|
58
61
|
onCustomEvent: (eventType, data, context) => options.onCustomEvent?.(eventType, data, context),
|
|
59
62
|
...options.streamProcessor !== void 0 && { streamProcessor: options.streamProcessor },
|
|
60
63
|
onMessagesChange: (newMessages) => {
|
|
@@ -93,9 +96,9 @@ function useChat(options = {}) {
|
|
|
93
96
|
pendingInterrupts: nextPendingInterrupts
|
|
94
97
|
}));
|
|
95
98
|
},
|
|
96
|
-
onInterruptStateChange: (nextInterruptState) => {
|
|
99
|
+
onInterruptStateChange: (nextInterruptState, context) => {
|
|
97
100
|
setInterruptState(nextInterruptState);
|
|
98
|
-
options.onInterruptStateChange?.(nextInterruptState);
|
|
101
|
+
options.onInterruptStateChange?.(nextInterruptState, context);
|
|
99
102
|
}
|
|
100
103
|
});
|
|
101
104
|
}, [clientId]);
|
package/dist/use-chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-chat.js","names":[],"sources":["../src/use-chat.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\n\nimport { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport type {\n ChatClientState,\n ChatInterrupt,\n ChatInterruptState,\n ChatResumeState,\n ConnectionStatus,\n InferredClientContext,\n QueuedMessage,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\n\nconst EMPTY_INTERRUPTS = Object.freeze([])\nconst EMPTY_INTERRUPT_ERRORS = Object.freeze([])\n\nexport function useChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n>(\n options: UseChatOptions<TTools, TSchema, TContext> = {} as UseChatOptions<\n TTools,\n TSchema,\n TContext\n >,\n): UseChatReturn<TTools, TSchema> {\n // The hook's identity is its `threadId` — also the persistence key, so a\n // reload with the same `threadId` restores the same conversation. `hookId` is\n // only a stable fallback for client-recreation keying when no `threadId` is\n // given (an ephemeral chat), never a persistence key.\n const hookId = createUniqueId()\n const clientId = options.threadId ?? hookId\n\n const [messages, setMessages] = createSignal<Array<UIMessage<TTools>>>(\n options.initialMessages || [],\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<ChatClientState>('ready')\n const [isSubscribed, setIsSubscribed] = createSignal(false)\n const [connectionStatus, setConnectionStatus] =\n createSignal<ConnectionStatus>('disconnected')\n const [sessionGenerating, setSessionGenerating] = createSignal(false)\n const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])\n const [runId, setRunId] = createSignal<string | null>(null)\n const [interruptState, setInterruptState] = createSignal<\n ChatInterruptState<TTools>\n >({\n interrupts: EMPTY_INTERRUPTS,\n pendingInterrupts: EMPTY_INTERRUPTS,\n interruptErrors: EMPTY_INTERRUPT_ERRORS,\n resuming: false,\n })\n\n const syncResumeState = () => {\n setRunId(client().getCurrentRunId())\n setInterruptState(client().getInterruptState())\n }\n\n // Structured-output `partial` / `final` are derived from `messages` —\n // specifically from the structured-output part on the latest assistant\n // message (the one after the most recent user message). Per-turn parts\n // keep history coherent without a separate reset signal.\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n // Create ChatClient instance with callbacks to sync state.\n // Every user-provided callback is wrapped so the LATEST `options.xxx` value\n // is read at call time. Direct assignment would freeze the callback to the\n // reference we saw at creation; the wrapper lets reactive `options` or\n // in-place mutations propagate. When the user clears a callback (sets it to\n // undefined), `?.` no-ops.\n const client = createMemo(() => {\n // Build options with conditional spreads for fields whose source\n // type is `T | undefined` but the ChatClient target uses a strict\n // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects\n // assigning `undefined` to those, so we omit the key when absent.\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n return new ChatClient<TTools, TContext>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n body: options.body,\n ...(options.threadId !== undefined && { threadId: options.threadId }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n ...(options.context !== undefined && { context: options.context }),\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => {\n options.onChunk?.(chunk)\n },\n onFinish: (message) => {\n options.onFinish?.(message)\n },\n onError: (err) => {\n options.onError?.(err)\n },\n tools: options.tools,\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {\n setMessages(newMessages)\n },\n onLoadingChange: (newIsLoading: boolean) => {\n setIsLoading(newIsLoading)\n syncResumeState()\n },\n onStatusChange: (newStatus: ChatClientState) => {\n setStatus(newStatus)\n },\n onErrorChange: (newError: Error | undefined) => {\n setError(newError)\n },\n onSubscriptionChange: (nextIsSubscribed: boolean) => {\n setIsSubscribed(nextIsSubscribed)\n },\n onConnectionStatusChange: (nextStatus: ConnectionStatus) => {\n setConnectionStatus(nextStatus)\n },\n onSessionGeneratingChange: (isGenerating: boolean) => {\n setSessionGenerating(isGenerating)\n },\n ...(options.queue !== undefined && { queue: options.queue }),\n onQueueChange: (nextQueue: Array<QueuedMessage>) => {\n setQueue(nextQueue)\n },\n onRunIdChange: (nextRunId) => {\n setRunId(nextRunId)\n },\n onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {\n setInterruptState((current) => ({\n ...current,\n interrupts: nextPendingInterrupts,\n pendingInterrupts: nextPendingInterrupts,\n }))\n },\n onInterruptStateChange: (nextInterruptState) => {\n setInterruptState(nextInterruptState)\n options.onInterruptStateChange?.(nextInterruptState)\n },\n })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\n syncResumeState()\n\n // Sync body / forwardedProps changes to the client.\n // Both populate the same wire payload; `forwardedProps` is preferred\n // and `body` is deprecated but still supported.\n createEffect(() => {\n // Conditional spread: `updateOptions` declares strict-optional\n // fields and rejects explicit `undefined` under EOPT.\n client().updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n context: options.context,\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n })\n\n // Apply initial live mode immediately on hook creation.\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n\n createEffect(() => {\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n })\n\n onMount(() => {\n // START TAILING HERE, not in the constructor. A client is idle until a view\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded.\n client().attach()\n client().mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE connection\n // adapter reattaches via the browser's native Last-Event-ID on reconnect.\n // We only seed interrupt (state) resume from the client here.\n syncResumeState()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\n // Release the connection first: `detach` is the counterpart of the `attach`\n // above, and it keeps the transcript and resume pointer so a later mount can\n // pick the run back up from the durable log.\n client().detach()\n if (options.live) {\n client().unsubscribe()\n } else {\n client().stop()\n }\n client().dispose()\n })\n\n // Callback options are read through `options.xxx` at call time, so reactive\n // or mutated options propagate without recreating the client.\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n try {\n await client().sendMessage(content, undefined, sendOptions)\n } finally {\n syncResumeState()\n }\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n try {\n await client().append(message)\n } finally {\n syncResumeState()\n }\n }\n\n const reload = async () => {\n try {\n await client().reload()\n } finally {\n syncResumeState()\n }\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\n syncResumeState()\n }\n\n const setMessagesManually = (newMessages: Array<UIMessage<TTools>>) => {\n client().setMessagesManually(newMessages)\n }\n\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client().addToolResult(result)\n }\n\n const addToolApprovalResponse = async (response: {\n id: string\n approved: boolean\n }) => {\n await client().addToolApprovalResponse(response)\n syncResumeState()\n }\n\n const cancelQueued = (id: string) => client().cancelQueued(id)\n\n const resumeInterrupts = async (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => {\n const result = await client().resumeInterrupts(resumeItems, state)\n syncResumeState()\n return result\n }\n\n const resolveInterrupts = (\n resolution: boolean | ((interrupt: ChatInterrupt<TTools>) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client().resolveInterrupts(resolution)\n } else {\n client().resolveInterrupts(resolution)\n }\n }\n\n const cancelInterrupts = () => {\n client().cancelInterrupts()\n }\n\n const retryInterrupts = () => {\n client().retryInterrupts()\n }\n\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client().resumeInterruptsUnsafe(resumeItems, state)\n\n const interrupts = () => interruptState().interrupts\n const pendingInterrupts = () => interruptState().pendingInterrupts\n const interruptErrors = () => interruptState().interruptErrors\n const resuming = () => interruptState().resuming\n\n // The \"active\" structured-output part is on the assistant message after\n // the latest user message. When no user message exists yet, return null\n // rather than scanning history — otherwise a stale `final` from\n // `initialMessages` would leak into the value on first render.\n const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = createMemo<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = createMemo<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n // partial / final are runtime-tracked unconditionally; the conditional\n // return type hides them when no `outputSchema` is supplied.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields\n return {\n messages,\n queue,\n sendMessage,\n append,\n reload,\n stop,\n isLoading,\n error,\n status,\n isSubscribed,\n connectionStatus,\n sessionGenerating,\n setMessages: setMessagesManually,\n clear,\n addToolResult,\n addToolApprovalResponse,\n cancelQueued,\n runId,\n interrupts,\n pendingInterrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n resumeInterrupts,\n partial,\n final,\n } as unknown as UseChatReturn<TTools, TSchema>\n}\n"],"mappings":";;;;;AAsCA,MAAM,mBAAmB,OAAO,OAAO,EAAE,CAAC;AAC1C,MAAM,yBAAyB,OAAO,OAAO,EAAE,CAAC;AAEhD,SAAgB,QAKd,UAAqD,EAAE,EAKvB;CAKhC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,YAAY;CAErC,MAAM,CAAC,UAAU,eAAe,aAC9B,QAAQ,mBAAmB,EAAE,CAC9B;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAA8B,QAAQ;CAClE,MAAM,CAAC,cAAc,mBAAmB,aAAa,MAAM;CAC3D,MAAM,CAAC,kBAAkB,uBACvB,aAA+B,eAAe;CAChD,MAAM,CAAC,mBAAmB,wBAAwB,aAAa,MAAM;CACrE,MAAM,CAAC,OAAO,YAAY,aAAmC,EAAE,CAAC;CAChE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,gBAAgB,qBAAqB,aAE1C;EACA,YAAY;EACZ,mBAAmB;EACnB,iBAAiB;EACjB,UAAU;EACX,CAAC;CAEF,MAAM,wBAAwB;AAC5B,WAAS,QAAQ,CAAC,iBAAiB,CAAC;AACpC,oBAAkB,QAAQ,CAAC,mBAAmB,CAAC;;CAgBjD,MAAM,SAAS,iBAAiB;AAQ9B,SAAO,IAAI,WAA6B;GACtC,uBAAuB;GACvB,GALgB,QAAQ,aACtB,EAAE,YAAY,QAAQ,YAAY,GAClC,EAAE,SAAS,QAAQ,SAAS;GAI9B,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AK;GACpD,MAAM,IAAI,KAAK;AACf,OAAI,GAAG,SAAS,YAAa;GAC7B,MAAM,OAAO,EAAE,MAAM,MAClB,MAAiC,EAAE,SAAS,oBAC9C;AACD,OAAI,KAAM,QAAO;;AAEnB,SAAO;GACP;AAkBF,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SA5Cc,iBAA0B;GACxC,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,KAAM,QAAO,EAAE;AAEpB,UADU,KAAK,WAAW,KAAK,QAClB,EAAE;IACf;EAwCA,OAtCY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAmCD"}
|
|
1
|
+
{"version":3,"file":"use-chat.js","names":[],"sources":["../src/use-chat.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\n\nimport { ChatClient } from '@tanstack/ai-client'\nimport { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport type {\n ChatClientState,\n ResolvableChatInterrupt,\n ChatInterruptState,\n ChatResumeState,\n ConnectionStatus,\n InferredClientContext,\n QueuedMessage,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InterruptDefinition,\n InferSchemaType,\n ModelMessage,\n RunAgentResumeItem,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\n\nconst EMPTY_INTERRUPTS = Object.freeze([])\nconst EMPTY_INTERRUPT_ERRORS = Object.freeze([])\n\nexport function useChat<\n const TTools extends ReadonlyArray<AnyClientTool> = any,\n TSchema extends SchemaInput | undefined = undefined,\n TContext = InferredClientContext<TTools>,\n const TInterrupts extends ReadonlyArray<\n InterruptDefinition<any, any, any, any>\n > = readonly [],\n>(\n options: UseChatOptions<\n TTools,\n TSchema,\n TContext,\n TInterrupts\n > = {} as UseChatOptions<TTools, TSchema, TContext, TInterrupts>,\n): UseChatReturn<TTools, TSchema, TInterrupts> {\n // The hook's identity is its `threadId`. Reload with the same `threadId`\n // restores the same conversation. `hookId` is only a recreation key when no\n // `threadId` is given. It is never sent on the wire.\n const hookId = createUniqueId()\n const clientId = options.threadId ?? hookId\n\n const [messages, setMessages] = createSignal<Array<UIMessage<TTools>>>(\n options.initialMessages || [],\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<ChatClientState>('ready')\n const [isSubscribed, setIsSubscribed] = createSignal(false)\n const [connectionStatus, setConnectionStatus] =\n createSignal<ConnectionStatus>('disconnected')\n const [sessionGenerating, setSessionGenerating] = createSignal(false)\n const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])\n const [runId, setRunId] = createSignal<string | null>(null)\n const [interruptState, setInterruptState] = createSignal<\n ChatInterruptState<TTools, TInterrupts>\n >({\n interrupts: EMPTY_INTERRUPTS,\n pendingInterrupts: EMPTY_INTERRUPTS,\n interruptErrors: EMPTY_INTERRUPT_ERRORS,\n resuming: false,\n })\n\n const syncResumeState = () => {\n setRunId(client().getCurrentRunId())\n setInterruptState(client().getInterruptState())\n }\n\n // Structured-output `partial` / `final` are derived from `messages` —\n // specifically from the structured-output part on the latest assistant\n // message (the one after the most recent user message). Per-turn parts\n // keep history coherent without a separate reset signal.\n type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>\n type Final = InferSchemaType<NonNullable<TSchema>>\n\n // Create ChatClient instance with callbacks to sync state.\n // Every user-provided callback is wrapped so the LATEST `options.xxx` value\n // is read at call time. Direct assignment would freeze the callback to the\n // reference we saw at creation; the wrapper lets reactive `options` or\n // in-place mutations propagate. When the user clears a callback (sets it to\n // undefined), `?.` no-ops.\n const client = createMemo(() => {\n // Build options with conditional spreads for fields whose source\n // type is `T | undefined` but the ChatClient target uses a strict\n // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects\n // assigning `undefined` to those, so we omit the key when absent.\n const transport = options.connection\n ? { connection: options.connection }\n : { fetcher: options.fetcher }\n return new ChatClient<TTools, TContext, TInterrupts>({\n devtoolsBridgeFactory: createChatDevtoolsBridge,\n ...transport,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(typeof options.threadId === 'string' && options.persistence\n ? {\n persistence: options.persistence,\n threadId: options.threadId,\n }\n : {\n ...(options.threadId !== undefined && {\n threadId: options.threadId,\n }),\n }),\n ...(options.initialResumeSnapshot !== undefined && {\n initialResumeSnapshot: options.initialResumeSnapshot,\n }),\n body: options.body,\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n ...(options.context !== undefined && { context: options.context }),\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useChat',\n outputKind: options.outputSchema ? 'structured' : 'chat',\n },\n onResponse: (response) => options.onResponse?.(response),\n onChunk: (chunk: StreamChunk) => {\n options.onChunk?.(chunk)\n },\n onFinish: (message) => {\n options.onFinish?.(message)\n },\n onError: (err) => {\n options.onError?.(err)\n },\n tools: options.tools,\n ...(options.interrupts !== undefined && {\n interrupts: options.interrupts,\n }),\n onCustomEvent: (eventType, data, context) =>\n options.onCustomEvent?.(eventType, data, context),\n ...(options.streamProcessor !== undefined && {\n streamProcessor: options.streamProcessor,\n }),\n onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {\n setMessages(newMessages)\n },\n onLoadingChange: (newIsLoading: boolean) => {\n setIsLoading(newIsLoading)\n syncResumeState()\n },\n onStatusChange: (newStatus: ChatClientState) => {\n setStatus(newStatus)\n },\n onErrorChange: (newError: Error | undefined) => {\n setError(newError)\n },\n onSubscriptionChange: (nextIsSubscribed: boolean) => {\n setIsSubscribed(nextIsSubscribed)\n },\n onConnectionStatusChange: (nextStatus: ConnectionStatus) => {\n setConnectionStatus(nextStatus)\n },\n onSessionGeneratingChange: (isGenerating: boolean) => {\n setSessionGenerating(isGenerating)\n },\n ...(options.queue !== undefined && { queue: options.queue }),\n onQueueChange: (nextQueue: Array<QueuedMessage>) => {\n setQueue(nextQueue)\n },\n onRunIdChange: (nextRunId) => {\n setRunId(nextRunId)\n },\n onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {\n setInterruptState((current) => ({\n ...current,\n interrupts: nextPendingInterrupts,\n pendingInterrupts: nextPendingInterrupts,\n }))\n },\n onInterruptStateChange: (nextInterruptState, context) => {\n setInterruptState(nextInterruptState)\n options.onInterruptStateChange?.(nextInterruptState, context)\n },\n })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\n syncResumeState()\n\n // Sync body / forwardedProps changes to the client.\n // Both populate the same wire payload; `forwardedProps` is preferred\n // and `body` is deprecated but still supported.\n createEffect(() => {\n // Conditional spread: `updateOptions` declares strict-optional\n // fields and rejects explicit `undefined` under EOPT.\n client().updateOptions({\n ...(options.body !== undefined && { body: options.body }),\n ...(options.forwardedProps !== undefined && {\n forwardedProps: options.forwardedProps,\n }),\n context: options.context,\n ...(options.queue !== undefined && { queue: options.queue }),\n })\n })\n\n // Apply initial live mode immediately on hook creation.\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n\n createEffect(() => {\n if (options.live) {\n client().subscribe()\n } else {\n client().unsubscribe()\n }\n })\n\n onMount(() => {\n // START TAILING HERE, not in the constructor. A client is idle until a view\n // attaches it, so a client that gets built and thrown away never opens a\n // connection — an unreachable stream would hold one of the browser's ~6\n // connections per origin until the page reloaded.\n client().attach()\n client().mountDevtools()\n // Delivery-durability resume is transparent: the resumable SSE connection\n // adapter reattaches via the browser's native Last-Event-ID on reconnect.\n // We only seed interrupt (state) resume from the client here.\n syncResumeState()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\n // Release the connection first: `detach` is the counterpart of the `attach`\n // above, and it keeps the transcript and resume pointer so a later mount can\n // pick the run back up from the durable log.\n client().detach()\n if (options.live) {\n client().unsubscribe()\n } else {\n client().stop()\n }\n client().dispose()\n })\n\n // Callback options are read through `options.xxx` at call time, so reactive\n // or mutated options propagate without recreating the client.\n\n const sendMessage = async (\n content: string | MultimodalContent,\n sendOptions?: SendMessageOptions,\n ) => {\n try {\n await client().sendMessage(content, undefined, sendOptions)\n } finally {\n syncResumeState()\n }\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n try {\n await client().append(message)\n } finally {\n syncResumeState()\n }\n }\n\n const reload = async () => {\n try {\n await client().reload()\n } finally {\n syncResumeState()\n }\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\n syncResumeState()\n }\n\n const setMessagesManually = (newMessages: Array<UIMessage<TTools>>) => {\n client().setMessagesManually(newMessages)\n }\n\n const addToolResult = async (result: {\n toolCallId: string\n tool: string\n output: any\n state?: 'output-available' | 'output-error'\n errorText?: string\n }) => {\n await client().addToolResult(result)\n }\n\n const addToolApprovalResponse = async (response: {\n id: string\n approved: boolean\n }) => {\n await client().addToolApprovalResponse(response)\n syncResumeState()\n }\n\n const cancelQueued = (id: string) => client().cancelQueued(id)\n\n const resumeInterrupts = async (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => {\n const result = await client().resumeInterrupts(resumeItems, state)\n syncResumeState()\n return result\n }\n\n const resolveInterrupts = (\n resolution:\n | boolean\n | ((\n interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,\n ) => undefined),\n ) => {\n if (typeof resolution === 'boolean') {\n client().resolveInterrupts(resolution)\n } else {\n client().resolveInterrupts(resolution)\n }\n }\n\n const cancelInterrupts = () => {\n client().cancelInterrupts()\n }\n\n const retryInterrupts = () => {\n client().retryInterrupts()\n }\n\n const resumeInterruptsUnsafe = (\n resumeItems: Array<RunAgentResumeItem>,\n state?: ChatResumeState,\n ) => client().resumeInterruptsUnsafe(resumeItems, state)\n\n const interrupts = () => interruptState().interrupts\n const pendingInterrupts = () => interruptState().pendingInterrupts\n const interruptErrors = () => interruptState().interruptErrors\n const resuming = () => interruptState().resuming\n\n // The \"active\" structured-output part is on the assistant message after\n // the latest user message. When no user message exists yet, return null\n // rather than scanning history — otherwise a stale `final` from\n // `initialMessages` would leak into the value on first render.\n const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {\n const list = messages()\n let lastUserIndex = -1\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i]?.role === 'user') {\n lastUserIndex = i\n break\n }\n }\n if (lastUserIndex === -1) return null\n for (let i = list.length - 1; i > lastUserIndex; i--) {\n const m = list[i]\n if (m?.role !== 'assistant') continue\n const part = m.parts.find(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n if (part) return part\n }\n return null\n })\n\n const partial = createMemo<Partial>(() => {\n const part = activeStructuredPart()\n if (!part) return {} as Partial\n const v = part.partial ?? part.data\n return (v ?? {}) as Partial\n })\n\n const final = createMemo<Final | null>(() => {\n const part = activeStructuredPart()\n if (!part || part.status !== 'complete') return null\n return part.data as Final\n })\n\n // partial / final are runtime-tracked unconditionally; the conditional\n // return type hides them when no `outputSchema` is supplied.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields\n return {\n messages,\n queue,\n sendMessage,\n append,\n reload,\n stop,\n isLoading,\n error,\n status,\n isSubscribed,\n connectionStatus,\n sessionGenerating,\n setMessages: setMessagesManually,\n clear,\n addToolResult,\n addToolApprovalResponse,\n cancelQueued,\n runId,\n interrupts,\n pendingInterrupts,\n interruptErrors,\n resuming,\n resolveInterrupts,\n cancelInterrupts,\n retryInterrupts,\n resumeInterruptsUnsafe,\n resumeInterrupts,\n partial,\n final,\n } as unknown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AE,MAAM,MAClB,MAAiC,EAAE,SAAS,oBAC9C;AACD,OAAI,KAAM,QAAO;;AAEnB,SAAO;GACP;AAkBF,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SA5Cc,iBAA0B;GACxC,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,KAAM,QAAO,EAAE;AAEpB,UADU,KAAK,WAAW,KAAK,QAClB,EAAE;IACf;EAwCA,OAtCY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAmCD"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateAudioOptions<TOutput = AudioGenerationResult> extends Pick<
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for audio generation */
|
|
17
17
|
fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -79,7 +75,7 @@ interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> extends Omit<U
|
|
|
79
75
|
* }
|
|
80
76
|
* ```
|
|
81
77
|
*/
|
|
82
|
-
declare function useGenerateAudio<TTransformed = void>(options: Omit<UseGenerateAudioOptions, 'onResult' | 'persistence' | 'threadId'
|
|
78
|
+
declare function useGenerateAudio<TTransformed = void>(options: Omit<UseGenerateAudioOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
83
79
|
onResult?: (result: AudioGenerationResult) => TTransformed;
|
|
84
80
|
} & GenerationPersistenceOptions): UseGenerateAudioReturn<InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>>;
|
|
85
81
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-audio.js","names":[],"sources":["../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateAudio hook.\n *\n * @template TOutput - The transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n UseGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for audio generation */\n fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>\n
|
|
1
|
+
{"version":3,"file":"use-generate-audio.js","names":[],"sources":["../src/use-generate-audio.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructAudioResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n AudioGenerateInput,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateAudio hook.\n *\n * @template TOutput - The transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioOptions<\n TOutput = AudioGenerationResult,\n> extends Pick<\n UseGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for audio generation */\n fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>\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 audio 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: AudioGenerationResult) => 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 useGenerateAudio hook.\n *\n * @template TOutput - The transformed output type (defaults to AudioGenerationResult)\n */\nexport interface UseGenerateAudioReturn<\n TOutput = AudioGenerationResult,\n> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {\n /** Trigger audio generation */\n generate: (input: AudioGenerateInput) => Promise<void>\n /** The generation result containing audio, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating audio (music, sound effects) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateAudio } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function AudioGenerator() {\n * const { generate, result, isLoading } = useGenerateAudio({\n * connection: fetchServerSentEvents('/api/generate/audio'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'An upbeat electronic track', duration: 10 })}>\n * Generate\n * </button>\n * {result()?.audio.url && <audio src={result()!.audio.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateAudio<TTransformed = void>(\n options: Omit<\n UseGenerateAudioOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: AudioGenerationResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateAudioReturn<\n InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateAudio',\n outputKind: 'audio' as const,\n }\n const generation = useGeneration<\n AudioGenerateInput,\n AudioGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructAudioResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,SAAgB,iBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateImageOptions<TOutput = ImageGenerationResult> extends Pick<
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for image generation */
|
|
17
17
|
fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -87,7 +83,7 @@ interface UseGenerateImageReturn<TOutput = ImageGenerationResult> extends Omit<U
|
|
|
87
83
|
* }
|
|
88
84
|
* ```
|
|
89
85
|
*/
|
|
90
|
-
declare function useGenerateImage<TTransformed = void>(options: Omit<UseGenerateImageOptions, 'onResult' | 'persistence' | 'threadId'
|
|
86
|
+
declare function useGenerateImage<TTransformed = void>(options: Omit<UseGenerateImageOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
91
87
|
onResult?: (result: ImageGenerationResult) => TTransformed;
|
|
92
88
|
} & GenerationPersistenceOptions): UseGenerateImageReturn<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
|
|
93
89
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-image.js","names":[],"sources":["../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateImage hook.\n *\n * @template TOutput - The transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageOptions<\n TOutput = ImageGenerationResult,\n> extends Pick<\n UseGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for image generation */\n fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>\n
|
|
1
|
+
{"version":3,"file":"use-generate-image.js","names":[],"sources":["../src/use-generate-image.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructImageResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n ImageGenerateInput,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateImage hook.\n *\n * @template TOutput - The transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageOptions<\n TOutput = ImageGenerationResult,\n> extends Pick<\n UseGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for image generation */\n fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>\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 images are 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: ImageGenerationResult) => 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 useGenerateImage hook.\n *\n * @template TOutput - The transformed output type (defaults to ImageGenerationResult)\n */\nexport interface UseGenerateImageReturn<\n TOutput = ImageGenerationResult,\n> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {\n /** Trigger image generation */\n generate: (input: ImageGenerateInput) => Promise<void>\n /** The generation result containing images, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating images using AI models.\n *\n * Supports two transport modes:\n * - **ConnectConnectionAdapter** -- Streaming transport (SSE, HTTP stream, custom)\n * - **Fetcher** -- Direct async function call\n *\n * @example\n * ```tsx\n * import { useGenerateImage } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function ImageGenerator() {\n * const { generate, result, isLoading, error, reset } = useGenerateImage({\n * connection: fetchServerSentEvents('/api/generate/image'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>\n * Generate\n * </button>\n * {isLoading() && <p>Generating...</p>}\n * {error() && <p>Error: {error()!.message}</p>}\n * {result()?.images.map((img, i) => (\n * <img src={img.url || `data:image/png;base64,${img.b64Json}`} />\n * ))}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateImage<TTransformed = void>(\n options: Omit<\n UseGenerateImageOptions,\n 'onResult' | 'persistence' | 'threadId'\n > & {\n onResult?: (result: ImageGenerationResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateImageReturn<\n InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateImage',\n outputKind: 'image' as const,\n }\n const generation = useGeneration<\n ImageGenerateInput,\n ImageGenerationResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructImageResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,SAAgB,iBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -15,10 +15,6 @@ interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<UseGenerati
|
|
|
15
15
|
connection?: ConnectConnectionAdapter;
|
|
16
16
|
/** Direct async function for speech generation */
|
|
17
17
|
fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>;
|
|
18
|
-
/**
|
|
19
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
20
|
-
*/
|
|
21
|
-
id?: string;
|
|
22
18
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
23
19
|
body?: Record<string, any>;
|
|
24
20
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -81,7 +77,7 @@ interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<UseGeneratio
|
|
|
81
77
|
* }
|
|
82
78
|
* ```
|
|
83
79
|
*/
|
|
84
|
-
declare function useGenerateSpeech<TTransformed = void>(options: Omit<UseGenerateSpeechOptions, 'onResult' | 'persistence' | 'threadId'
|
|
80
|
+
declare function useGenerateSpeech<TTransformed = void>(options: Omit<UseGenerateSpeechOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
85
81
|
onResult?: (result: TTSResult) => TTransformed;
|
|
86
82
|
} & GenerationPersistenceOptions): UseGenerateSpeechReturn<InferGenerationOutputFromReturn<TTSResult, TTransformed>>;
|
|
87
83
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
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 {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\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'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<\n UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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 {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\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'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<\n UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\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 /** 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 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 transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<\n UseGenerationReturn<TOutput>,\n 'generate'\n> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-solid'\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'\n > & {\n onResult?: (result: TTSResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -14,10 +14,6 @@ interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
14
14
|
connection?: ConnectConnectionAdapter;
|
|
15
15
|
/** Direct async function that returns a completed video result */
|
|
16
16
|
fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
|
|
17
|
-
/**
|
|
18
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
19
|
-
*/
|
|
20
|
-
id?: string;
|
|
21
17
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
22
18
|
body?: Record<string, any>;
|
|
23
19
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -41,8 +37,8 @@ interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
41
37
|
* id on the wire, which the protocol requires.
|
|
42
38
|
*
|
|
43
39
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
44
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
45
|
-
*
|
|
40
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
41
|
+
* omitted, the client mints a wire id after mount.
|
|
46
42
|
*/
|
|
47
43
|
threadId?: string;
|
|
48
44
|
/**
|
|
@@ -141,7 +137,7 @@ interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
141
137
|
* }
|
|
142
138
|
* ```
|
|
143
139
|
*/
|
|
144
|
-
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId'
|
|
140
|
+
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId'> & {
|
|
145
141
|
onResult?: (result: VideoGenerateResult) => TTransformed;
|
|
146
142
|
} & GenerationPersistenceOptions): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
147
143
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect, createSignal,
|
|
1
|
+
import { createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { VideoGenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -35,7 +35,6 @@ import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
35
35
|
* ```
|
|
36
36
|
*/
|
|
37
37
|
function useGenerateVideo(options) {
|
|
38
|
-
const hookId = createUniqueId();
|
|
39
38
|
const [result, setResult] = createSignal(null);
|
|
40
39
|
const [jobId, setJobId] = createSignal(null);
|
|
41
40
|
const [videoStatus, setVideoStatus] = createSignal(null);
|
|
@@ -47,8 +46,10 @@ function useGenerateVideo(options) {
|
|
|
47
46
|
const client = untrack(() => {
|
|
48
47
|
const baseOptions = {
|
|
49
48
|
body: options.body,
|
|
50
|
-
...options.threadId
|
|
51
|
-
|
|
49
|
+
...typeof options.threadId === "string" && options.persistence ? {
|
|
50
|
+
persistence: options.persistence,
|
|
51
|
+
threadId: options.threadId
|
|
52
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } },
|
|
52
53
|
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
53
54
|
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
54
55
|
devtoolsBridgeFactory: createVideoDevtoolsBridge,
|
|
@@ -1 +1 @@
|
|
|
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 {\n createEffect,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\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'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\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 transformed output type (defaults to VideoGenerateResult)\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: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<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: Accessor<string | null>\n}\n\n/**\n * Solid 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-solid'\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 = createUniqueId()\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): VideoGenerationClient<TOutput> => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n body: options.body,\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n ...(options.threadId !== undefined\n ? { threadId: options.threadId }\n : { id: options.id ?? hookId }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\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) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposed) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposed) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposed) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsKA,SAAgB,iBACd,SAQA;CAKA,MAAM,SAAS,gBAAgB;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ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BAAe,EAAE;;GAElC,sBAAsB,OAAiC;AACrD,QAAI,CAAC,SAAU,UAAS,IAAI,SAAS,KAAK;;GAE7C;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,kEACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAA8B;AACpD,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
|
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 {\n createEffect,\n createSignal,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\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'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\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 /** 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. If\n * omitted, the client mints a wire id after mount.\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 transformed output type (defaults to VideoGenerateResult)\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: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<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: Accessor<string | null>\n}\n\n/**\n * Solid 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-solid'\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'\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 [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): VideoGenerationClient<TOutput> => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n body: options.body,\n ...(typeof options.threadId === 'string' && options.persistence\n ? {\n persistence: options.persistence,\n threadId: options.threadId,\n }\n : {\n ...(options.threadId !== undefined && {\n threadId: options.threadId,\n }),\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\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) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposed) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposed) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposed) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiKA,SAAgB,iBACd,SAQA;CAKA,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA8C;EAG3D,MAAM,cAAc;GAClB,MAAM,QAAQ;GACd,GAAI,OAAO,QAAQ,aAAa,YAAY,QAAQ,cAChD;IACE,aAAa,QAAQ;IACrB,UAAU,QAAQ;IACnB,GACD,EACE,GAAI,QAAQ,aAAa,UAAa,EACpC,UAAU,QAAQ,UACnB,EACF;GACL,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACV,YAAY;IACb;GAID,YAAY,MAA2B,QAAQ,WAAW,EAAE;GAG5D,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU,MAAmB;AAC3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ACD"}
|
package/dist/use-generation.d.ts
CHANGED
|
@@ -18,10 +18,6 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
18
18
|
connection?: ConnectConnectionAdapter;
|
|
19
19
|
/** Direct async function for one-shot generation (no streaming protocol needed) */
|
|
20
20
|
fetcher?: GenerationFetcher<TInput, TResult>;
|
|
21
|
-
/**
|
|
22
|
-
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
23
|
-
*/
|
|
24
|
-
id?: string;
|
|
25
21
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
26
22
|
body?: Record<string, any>;
|
|
27
23
|
/** Display options for TanStack AI Devtools. */
|
|
@@ -45,8 +41,8 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
45
41
|
* id on the wire, which the protocol requires.
|
|
46
42
|
*
|
|
47
43
|
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
48
|
-
* scope has nothing to restore to. Optional for ephemeral generations
|
|
49
|
-
*
|
|
44
|
+
* scope has nothing to restore to. Optional for ephemeral generations. If
|
|
45
|
+
* omitted, the client mints a wire id after mount.
|
|
50
46
|
*/
|
|
51
47
|
threadId?: string;
|
|
52
48
|
/**
|
|
@@ -133,7 +129,7 @@ interface UseGenerationReturn<TOutput, TInput extends Record<string, any> = Reco
|
|
|
133
129
|
* await generate({ prompt: 'Hello' })
|
|
134
130
|
* ```
|
|
135
131
|
*/
|
|
136
|
-
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId'
|
|
132
|
+
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId'> & {
|
|
137
133
|
onResult?: (result: TResult) => TTransformed;
|
|
138
134
|
} & GenerationPersistenceOptions): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>, TInput>;
|
|
139
135
|
//#endregion
|
package/dist/use-generation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect, createSignal,
|
|
1
|
+
import { createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { GenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -24,7 +24,6 @@ import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
24
24
|
* ```
|
|
25
25
|
*/
|
|
26
26
|
function useGeneration(options) {
|
|
27
|
-
const hookId = createUniqueId();
|
|
28
27
|
const [result, setResult] = createSignal(null);
|
|
29
28
|
const [isLoading, setIsLoading] = createSignal(false);
|
|
30
29
|
const [error, setError] = createSignal(void 0);
|
|
@@ -34,8 +33,6 @@ function useGeneration(options) {
|
|
|
34
33
|
const client = untrack(() => {
|
|
35
34
|
const clientOptions = {
|
|
36
35
|
body: options.body,
|
|
37
|
-
...options.threadId !== void 0 ? { threadId: options.threadId } : { id: options.id ?? hookId },
|
|
38
|
-
...options.persistence !== void 0 && { persistence: options.persistence },
|
|
39
36
|
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
40
37
|
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
41
38
|
...options.reconstructResult ? { reconstructResult: options.reconstructResult } : {},
|
|
@@ -71,12 +68,18 @@ function useGeneration(options) {
|
|
|
71
68
|
if (!disposed) setRunId(rs?.runId ?? null);
|
|
72
69
|
}
|
|
73
70
|
};
|
|
71
|
+
const persistenceProps = typeof options.threadId === "string" && options.persistence ? {
|
|
72
|
+
persistence: options.persistence,
|
|
73
|
+
threadId: options.threadId
|
|
74
|
+
} : { ...options.threadId !== void 0 && { threadId: options.threadId } };
|
|
74
75
|
if (options.connection) return new GenerationClient({
|
|
75
76
|
...clientOptions,
|
|
77
|
+
...persistenceProps,
|
|
76
78
|
connection: options.connection
|
|
77
79
|
});
|
|
78
80
|
if (options.fetcher) return new GenerationClient({
|
|
79
81
|
...clientOptions,
|
|
82
|
+
...persistenceProps,
|
|
80
83
|
fetcher: options.fetcher
|
|
81
84
|
});
|
|
82
85
|
throw new Error("useGeneration requires either a connection or fetcher option");
|