@tanstack/ai-solid 0.14.4 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ChatRequestBody, DeepPartial, UIMessage, UseChatOptions, UseChatReturn } from "./types.js";
1
+ import { ChatRequestBody, DeepPartial, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, SendMessageOptions, UIMessage, UseChatOptions, UseChatReturn, WhenBusy } from "./types.js";
2
2
  import { useChat } from "./use-chat.js";
3
3
  import { UseGenerationOptions, UseGenerationReturn, useGeneration } from "./use-generation.js";
4
4
  import { UseGenerateImageOptions, UseGenerateImageReturn, useGenerateImage } from "./use-generate-image.js";
@@ -9,4 +9,4 @@ import { UseSummarizeOptions, UseSummarizeReturn, useSummarize } from "./use-sum
9
9
  import { UseGenerateVideoOptions, UseGenerateVideoReturn, useGenerateVideo } from "./use-generate-video.js";
10
10
  import { UseAudioRecorderOptions, UseAudioRecorderReturn, useAudioRecorder } from "./use-audio-recorder.js";
11
11
  import { AudioGenerateInput, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, InferChatMessages, RunAgentInputContext, SpeechGenerateInput, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from "@tanstack/ai-client";
12
- export { type AudioGenerateInput, type ChatRequestBody, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type InferChatMessages, type RunAgentInputContext, type SpeechGenerateInput, 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 XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
12
+ export { type AudioGenerateInput, type ChatRequestBody, type ConnectConnectionAdapter, type ConnectionAdapter, type DeepPartial, type FetchConnectionOptions, type GenerationClientState, type ImageGenerateInput, type InferChatMessages, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type RunAgentInputContext, type SendMessageOptions, type SpeechGenerateInput, 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 WhenBusy, type XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, useAudioRecorder, useChat, useGenerateAudio, useGenerateImage, useGenerateSpeech, useGenerateVideo, useGeneration, useSummarize, useTranscription, xhrHttpStream, xhrServerSentEvents };
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Accessor } from "solid-js";
2
- import { AIDevtoolsDisplayOptions, ChatClientOptions, ChatClientState, ChatRequestBody, ClientContextOptionFromTools, ConnectionStatus, DistributedOmit, InferredClientContext, MultimodalContent, UIMessage } from "@tanstack/ai-client";
2
+ import { AIDevtoolsDisplayOptions, ChatClientOptions, ChatClientState, ChatRequestBody, ClientContextOptionFromTools, ConnectionStatus, DistributedOmit, InferredClientContext, MultimodalContent, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, SendMessageOptions, UIMessage, WhenBusy } from "@tanstack/ai-client";
3
3
  import { AnyClientTool, InferSchemaType, ModelMessage, SchemaInput } from "@tanstack/ai";
4
4
 
5
5
  //#region src/types.d.ts
@@ -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' | 'context' | 'devtools'> & {
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' | 'context' | 'devtools'> & {
35
35
  /** Display options for TanStack AI Devtools. */
36
36
  devtools?: AIDevtoolsDisplayOptions;
37
37
  live?: boolean;
@@ -64,11 +64,23 @@ interface BaseUseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, T
64
64
  * by the schema — `data: T`, `partial: DeepPartial<T>`.
65
65
  */
66
66
  messages: Accessor<Array<UIMessage<TTools, TData>>>;
67
+ /**
68
+ * Pending messages queued while the client is busy (streaming, claiming a
69
+ * send, or draining). Separate from `messages` until they drain.
70
+ */
71
+ queue: Accessor<Array<QueuedMessage>>;
72
+ /**
73
+ * Cancel a queued message before it drains. No-op if already sent.
74
+ */
75
+ cancelQueued: (id: string) => void;
67
76
  /**
68
77
  * Send a message and get a response.
69
78
  * Can be a simple string or multimodal content with images, audio, etc.
79
+ * By default, sends while busy are queued until the run settles successfully
80
+ * (`queue: 'drop'` restores the old drop-while-busy behavior).
81
+ * Pass `{ whenBusy }` to override the policy for a single send.
70
82
  */
71
- sendMessage: (content: string | MultimodalContent) => Promise<void>;
83
+ sendMessage: (content: string | MultimodalContent, options?: SendMessageOptions) => Promise<void>;
72
84
  /**
73
85
  * Append a message to the conversation
74
86
  */
@@ -135,5 +147,5 @@ interface BaseUseChatReturn<TTools extends ReadonlyArray<AnyClientTool> = any, T
135
147
  sessionGenerating: Accessor<boolean>;
136
148
  }
137
149
  //#endregion
138
- export { type ChatRequestBody, DeepPartial, type UIMessage, UseChatOptions, UseChatReturn };
150
+ export { type ChatRequestBody, DeepPartial, type QueueConfig, type QueueOption, type QueueStrategy, type QueuedMessage, type SendMessageOptions, type UIMessage, UseChatOptions, UseChatReturn, type WhenBusy };
139
151
  //# sourceMappingURL=types.d.ts.map
package/dist/use-chat.js CHANGED
@@ -13,6 +13,7 @@ function useChat(options = {}) {
13
13
  const [isSubscribed, setIsSubscribed] = createSignal(false);
14
14
  const [connectionStatus, setConnectionStatus] = createSignal("disconnected");
15
15
  const [sessionGenerating, setSessionGenerating] = createSignal(false);
16
+ const [queue, setQueue] = createSignal([]);
16
17
  const client = createMemo(() => {
17
18
  return new ChatClient({
18
19
  devtoolsBridgeFactory: createChatDevtoolsBridge,
@@ -63,6 +64,10 @@ function useChat(options = {}) {
63
64
  },
64
65
  onSessionGeneratingChange: (isGenerating) => {
65
66
  setSessionGenerating(isGenerating);
67
+ },
68
+ ...options.queue !== void 0 && { queue: options.queue },
69
+ onQueueChange: (nextQueue) => {
70
+ setQueue(nextQueue);
66
71
  }
67
72
  });
68
73
  }, [clientId]);
@@ -71,7 +76,8 @@ function useChat(options = {}) {
71
76
  client().updateOptions({
72
77
  ...options.body !== void 0 && { body: options.body },
73
78
  ...options.forwardedProps !== void 0 && { forwardedProps: options.forwardedProps },
74
- context: options.context
79
+ context: options.context,
80
+ ...options.queue !== void 0 && { queue: options.queue }
75
81
  });
76
82
  });
77
83
  if (options.live) client().subscribe();
@@ -88,8 +94,8 @@ function useChat(options = {}) {
88
94
  else client().stop();
89
95
  client().dispose();
90
96
  });
91
- const sendMessage = async (content) => {
92
- await client().sendMessage(content);
97
+ const sendMessage = async (content, sendOptions) => {
98
+ await client().sendMessage(content, void 0, sendOptions);
93
99
  };
94
100
  const append = async (message) => {
95
101
  await client().append(message);
@@ -112,6 +118,7 @@ function useChat(options = {}) {
112
118
  const addToolApprovalResponse = async (response) => {
113
119
  await client().addToolApprovalResponse(response);
114
120
  };
121
+ const cancelQueued = (id) => client().cancelQueued(id);
115
122
  const activeStructuredPart = createMemo(() => {
116
123
  const list = messages();
117
124
  let lastUserIndex = -1;
@@ -130,6 +137,7 @@ function useChat(options = {}) {
130
137
  });
131
138
  return {
132
139
  messages,
140
+ queue,
133
141
  sendMessage,
134
142
  append,
135
143
  reload,
@@ -144,6 +152,7 @@ function useChat(options = {}) {
144
152
  clear,
145
153
  addToolResult,
146
154
  addToolApprovalResponse,
155
+ cancelQueued,
147
156
  partial: createMemo(() => {
148
157
  const part = activeStructuredPart();
149
158
  if (!part) return {};
@@ -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 ConnectionStatus,\n InferredClientContext,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InferSchemaType,\n ModelMessage,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\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 const hookId = createUniqueId()\n const clientId = options.id || 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\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 id: clientId,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\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 },\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 })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\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 })\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 client().mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\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 (content: string | MultimodalContent) => {\n await client().sendMessage(content)\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n await client().append(message)\n }\n\n const reload = async () => {\n await client().reload()\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\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 }\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 // eslint-disable-next-line 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 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 partial,\n final,\n } as unknown as UseChatReturn<TTools, TSchema>\n}\n"],"mappings":";;;;;AAgCA,SAAgB,QAKd,UAAqD,EAAE,EAKvB;CAChC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,MAAM;CAE/B,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;CAerE,MAAM,SAAS,iBAAiB;AAQ9B,SAAO,IAAI,WAA6B;GACtC,uBAAuB;GACvB,GALgB,QAAQ,aACtB,EAAE,YAAY,QAAQ,YAAY,GAClC,EAAE,SAAS,QAAQ,SAAS;GAI9B,IAAI;GACJ,GAAI,QAAQ,oBAAoB,UAAa,EAC3C,iBAAiB,Q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ClB,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,aAAa;EACb;EACA;EACA;EACA,SAhCc,iBAA0B;GACxC,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,KAAM,QAAO,EAAE;AAEpB,UADU,KAAK,WAAW,KAAK,QAClB,EAAE;IACf;EA4BA,OA1BY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAuBD"}
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 ConnectionStatus,\n InferredClientContext,\n QueuedMessage,\n SendMessageOptions,\n StructuredOutputPart,\n} from '@tanstack/ai-client'\nimport type {\n AnyClientTool,\n InferSchemaType,\n ModelMessage,\n SchemaInput,\n StreamChunk,\n} from '@tanstack/ai'\nimport type {\n DeepPartial,\n MultimodalContent,\n UIMessage,\n UseChatOptions,\n UseChatReturn,\n} from './types'\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 const hookId = createUniqueId()\n const clientId = options.id || 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\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 id: clientId,\n ...(options.initialMessages !== undefined && {\n initialMessages: options.initialMessages,\n }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\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 },\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 })\n // Only recreate when clientId changes\n // Connection and other options are captured at creation time\n }, [clientId])\n\n setMessages(client().getMessages())\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 client().mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests.\n onCleanup(() => {\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 await client().sendMessage(content, undefined, sendOptions)\n }\n\n const append = async (message: ModelMessage | UIMessage<TTools>) => {\n await client().append(message)\n }\n\n const reload = async () => {\n await client().reload()\n }\n\n const stop = () => {\n client().stop()\n }\n\n const clear = () => {\n client().clear()\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 }\n\n const cancelQueued = (id: string) => client().cancelQueued(id)\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 // eslint-disable-next-line 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 partial,\n final,\n } as unknown as UseChatReturn<TTools, TSchema>\n}\n"],"mappings":";;;;;AAkCA,SAAgB,QAKd,UAAqD,EAAE,EAKvB;CAChC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,MAAM;CAE/B,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;CAehE,MAAM,SAAS,iBAAiB;AAQ9B,SAAO,IAAI,WAA6B;GACtC,uBAAuB;GACvB,GALgB,QAAQ,aACtB,EAAE,YAAY,QAAQ,YAAY,GAClC,EAAE,SAAS,QAAQ,SAAS;GAI9B,IAAI;GACJ,GAAI,QAAQ,oBAAoB,UAAa,EAC3C,iBAAiB,QAAQ,iBAC1B;GACD,GAAI,QAAQ,gBAAgB,UAAa,EACvC,aAAa,QAAQ,aACtB;GACD,MAAM,QAAQ;GACd,GAAI,QAAQ,aAAa,UAAa,EAAE,UAAU,QAAQ,UAAU;GACpE,GAAI,QAAQ,mBAAmB,UAAa,EAC1C,gBAAgB,QAAQ,gBACzB;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,UAAU;IACR,GAAG,QAAQ;I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P;AAkBF,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb;EACA;EACA;EACA;EACA,SAlCc,iBAA0B;GACxC,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,KAAM,QAAO,EAAE;AAEpB,UADU,KAAK,WAAW,KAAK,QAClB,EAAE;IACf;EA8BA,OA5BY,iBAA+B;GAC3C,MAAM,OAAO,sBAAsB;AACnC,OAAI,CAAC,QAAQ,KAAK,WAAW,WAAY,QAAO;AAChD,UAAO,KAAK;IACZ;EAyBD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-solid",
3
- "version": "0.14.4",
3
+ "version": "0.15.0",
4
4
  "description": "Solid hooks for TanStack AI streaming chat, structured outputs, and media generation.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  "media-generation"
46
46
  ],
47
47
  "dependencies": {
48
- "@tanstack/ai-client": "0.21.0"
48
+ "@tanstack/ai-client": "0.22.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "solid-js": ">=1.9.10",
package/src/index.ts CHANGED
@@ -5,6 +5,12 @@ export type {
5
5
  UseChatReturn,
6
6
  UIMessage,
7
7
  ChatRequestBody,
8
+ QueuedMessage,
9
+ SendMessageOptions,
10
+ WhenBusy,
11
+ QueueConfig,
12
+ QueueStrategy,
13
+ QueueOption,
8
14
  } from './types'
9
15
 
10
16
  // Generation hooks
package/src/types.ts CHANGED
@@ -14,12 +14,28 @@ import type {
14
14
  DistributedOmit,
15
15
  InferredClientContext,
16
16
  MultimodalContent,
17
+ QueueConfig,
18
+ QueueOption,
19
+ QueueStrategy,
20
+ QueuedMessage,
21
+ SendMessageOptions,
17
22
  UIMessage,
23
+ WhenBusy,
18
24
  } from '@tanstack/ai-client'
19
25
  import type { Accessor } from 'solid-js'
20
26
 
21
27
  // Re-export types from ai-client
22
- export type { ChatRequestBody, MultimodalContent, UIMessage }
28
+ export type {
29
+ ChatRequestBody,
30
+ MultimodalContent,
31
+ QueueConfig,
32
+ QueuedMessage,
33
+ QueueOption,
34
+ QueueStrategy,
35
+ SendMessageOptions,
36
+ UIMessage,
37
+ WhenBusy,
38
+ }
23
39
 
24
40
  /**
25
41
  * Recursive partial — every property and every nested array element is optional.
@@ -67,6 +83,7 @@ export type UseChatOptions<
67
83
  | 'onSubscriptionChange'
68
84
  | 'onConnectionStatusChange'
69
85
  | 'onSessionGeneratingChange'
86
+ | 'onQueueChange'
70
87
  | 'context'
71
88
  | 'devtools'
72
89
  > & {
@@ -117,11 +134,28 @@ interface BaseUseChatReturn<
117
134
  */
118
135
  messages: Accessor<Array<UIMessage<TTools, TData>>>
119
136
 
137
+ /**
138
+ * Pending messages queued while the client is busy (streaming, claiming a
139
+ * send, or draining). Separate from `messages` until they drain.
140
+ */
141
+ queue: Accessor<Array<QueuedMessage>>
142
+
143
+ /**
144
+ * Cancel a queued message before it drains. No-op if already sent.
145
+ */
146
+ cancelQueued: (id: string) => void
147
+
120
148
  /**
121
149
  * Send a message and get a response.
122
150
  * Can be a simple string or multimodal content with images, audio, etc.
123
- */
124
- sendMessage: (content: string | MultimodalContent) => Promise<void>
151
+ * By default, sends while busy are queued until the run settles successfully
152
+ * (`queue: 'drop'` restores the old drop-while-busy behavior).
153
+ * Pass `{ whenBusy }` to override the policy for a single send.
154
+ */
155
+ sendMessage: (
156
+ content: string | MultimodalContent,
157
+ options?: SendMessageOptions,
158
+ ) => Promise<void>
125
159
 
126
160
  /**
127
161
  * Append a message to the conversation
package/src/use-chat.ts CHANGED
@@ -13,6 +13,8 @@ import type {
13
13
  ChatClientState,
14
14
  ConnectionStatus,
15
15
  InferredClientContext,
16
+ QueuedMessage,
17
+ SendMessageOptions,
16
18
  StructuredOutputPart,
17
19
  } from '@tanstack/ai-client'
18
20
  import type {
@@ -54,6 +56,7 @@ export function useChat<
54
56
  const [connectionStatus, setConnectionStatus] =
55
57
  createSignal<ConnectionStatus>('disconnected')
56
58
  const [sessionGenerating, setSessionGenerating] = createSignal(false)
59
+ const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])
57
60
 
58
61
  // Structured-output `partial` / `final` are derived from `messages` —
59
62
  // specifically from the structured-output part on the latest assistant
@@ -135,6 +138,10 @@ export function useChat<
135
138
  onSessionGeneratingChange: (isGenerating: boolean) => {
136
139
  setSessionGenerating(isGenerating)
137
140
  },
141
+ ...(options.queue !== undefined && { queue: options.queue }),
142
+ onQueueChange: (nextQueue: Array<QueuedMessage>) => {
143
+ setQueue(nextQueue)
144
+ },
138
145
  })
139
146
  // Only recreate when clientId changes
140
147
  // Connection and other options are captured at creation time
@@ -154,6 +161,7 @@ export function useChat<
154
161
  forwardedProps: options.forwardedProps,
155
162
  }),
156
163
  context: options.context,
164
+ ...(options.queue !== undefined && { queue: options.queue }),
157
165
  })
158
166
  })
159
167
 
@@ -189,8 +197,11 @@ export function useChat<
189
197
  // Callback options are read through `options.xxx` at call time, so reactive
190
198
  // or mutated options propagate without recreating the client.
191
199
 
192
- const sendMessage = async (content: string | MultimodalContent) => {
193
- await client().sendMessage(content)
200
+ const sendMessage = async (
201
+ content: string | MultimodalContent,
202
+ sendOptions?: SendMessageOptions,
203
+ ) => {
204
+ await client().sendMessage(content, undefined, sendOptions)
194
205
  }
195
206
 
196
207
  const append = async (message: ModelMessage | UIMessage<TTools>) => {
@@ -230,6 +241,8 @@ export function useChat<
230
241
  await client().addToolApprovalResponse(response)
231
242
  }
232
243
 
244
+ const cancelQueued = (id: string) => client().cancelQueued(id)
245
+
233
246
  // The "active" structured-output part is on the assistant message after
234
247
  // the latest user message. When no user message exists yet, return null
235
248
  // rather than scanning history — otherwise a stale `final` from
@@ -273,6 +286,7 @@ export function useChat<
273
286
  // eslint-disable-next-line no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields
274
287
  return {
275
288
  messages,
289
+ queue,
276
290
  sendMessage,
277
291
  append,
278
292
  reload,
@@ -287,6 +301,7 @@ export function useChat<
287
301
  clear,
288
302
  addToolResult,
289
303
  addToolApprovalResponse,
304
+ cancelQueued,
290
305
  partial,
291
306
  final,
292
307
  } as unknown as UseChatReturn<TTools, TSchema>