Open History to see the last commit
1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import type { Handle } from 'remix/ui'
4import type {
5 ResolvableChatInterrupt,
6 ChatResumeState,
7 InferredClientContext,
8 SendMessageOptions,
9 StructuredOutputPart,
10} from '@tanstack/ai-client'
11import type {
12 AnyClientTool,
13 InterruptDefinition,
14 InferSchemaType,
15 ModelMessage,
16 RunAgentResumeItem,
17 SchemaInput,
18 StreamChunk,
19} from '@tanstack/ai/client'
20import type {
21 CreateChatOptions,
22 CreateChatReturn,
23 DeepPartial,
24 MultimodalContent,
25 UIMessage,
26} from './types.ts'
27
28/**
29 * Create a chat helper for a Remix component.
30 *
31 * Call this in setup with the component Handle from `remix/ui`. The helper
32 * wraps ChatClient and calls `handle.update()` when the client snapshot
33 * changes, so render reads the latest frozen snapshot through getters.
34 *
35 * `options.threadId` is required. Cleanup runs when `handle.signal` aborts. Do not pass identification in `options.devtools`;
36 * the helper sets `framework: 'remix'` and `hookName: 'createChat'`.
37 *
38 * @param handle Remix component handle from setup.
39 * @param options Chat client options. Pass `connection` or `fetcher`.
40 *
41 * @example
42 * ```tsx
43 * import { createChat } from '@tanstack/ai-remix'
44 * import { fetchServerSentEvents } from '@tanstack/ai-client'
45 * import type { Handle } from 'remix/ui'
46 *
47 * function Chat(handle: Handle) {
48 * const chat = createChat(handle, {
49 * connection: fetchServerSentEvents('/api/chat'),
50 * threadId: 'support-1',
51 * })
52 * return () => (
53 * <div>
54 * {chat.messages.map((message) => (
55 * <div>{message.role}</div>
56 * ))}
57 * <button on={{ click: () => chat.sendMessage('Hello') }}>Send</button>
58 * </div>
59 * )
60 * }
61 * ```
62 *
63 * @see {@link CreateChatReturn}
64 */
65export function createChat<
66 const TTools extends ReadonlyArray<AnyClientTool> = any,
67 TSchema extends SchemaInput | undefined = undefined,
68 TContext = InferredClientContext<TTools>,
69 const TInterrupts extends ReadonlyArray<
70 InterruptDefinition<any, any, any, any>
71 > = readonly [],
72>(
73 handle: Pick<Handle, 'update' | 'signal'>,
74 options: CreateChatOptions<TTools, TSchema, TContext, TInterrupts>,
75) {
76 let closed = false
77
78 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
79 type Final = InferSchemaType<NonNullable<TSchema>>
80
81 const transport = options.connection
82 ? { connection: options.connection }
83 : { fetcher: options.fetcher }
84
85 function commit() {
86 if (closed) return
87 void handle.update()
88 }
89
90 const client = new ChatClient<TTools, TContext, TInterrupts>({
91 devtoolsBridgeFactory: createChatDevtoolsBridge,
92 ...transport,
93 ...(options.initialMessages !== undefined && {
94 initialMessages: options.initialMessages,
95 }),
96 threadId: options.threadId,
97 ...(options.persistence === true
98 ? {
99 persistence: true,
100 ...(options.history !== undefined && {
101 history: options.history,
102 }),
103 }
104 : { persistence: options.persistence }),
105 ...(options.initialResumeSnapshot !== undefined && {
106 initialResumeSnapshot: options.initialResumeSnapshot,
107 }),
108 ...(options.forwardedProps !== undefined && {
109 forwardedProps: options.forwardedProps,
110 }),
111 ...(options.byok !== undefined && { byok: options.byok }),
112 byokProvider: () => options.byokProvider?.(),
113 ...(options.context !== undefined && { context: options.context }),
114 devtools: {
115 ...options.devtools,
116 framework: 'remix',
117 hookName: 'createChat',
118 outputKind: options.outputSchema ? 'structured' : 'chat',
119 },
120 onResponse: (response) => options.onResponse?.(response),
121 onChunk: (chunk: StreamChunk) => {
122 options.onChunk?.(chunk)
123 },
124 onFinish: (message) => {
125 options.onFinish?.(message)
126 },
127 onError: (err) => {
128 options.onError?.(err)
129 },
130 ...(options.tools !== undefined && { tools: options.tools }),
131 ...(options.interrupts !== undefined && {
132 interrupts: options.interrupts,
133 }),
134 onCustomEvent: (eventType, data, context) =>
135 options.onCustomEvent?.(eventType, data, context),
136 ...(options.streamProcessor !== undefined && {
137 streamProcessor: options.streamProcessor,
138 }),
139 ...(options.queue !== undefined && { queue: options.queue }),
140 onInterruptStateChange: (nextInterruptState, context) => {
141 options.onInterruptStateChange?.(nextInterruptState, context)
142 },
143 })
144
145 // Render reads the frozen client snapshot through the getters below.
146 const unsubscribeSnapshot = client.subscribeSnapshot(commit)
147
148 function close() {
149 if (closed) return
150 closed = true
151 unsubscribeSnapshot()
152 client.detach()
153 if (options.live) {
154 client.unsubscribe()
155 } else {
156 client.stop()
157 }
158 client.dispose()
159 }
160
161 if (handle.signal.aborted) {
162 close()
163 } else {
164 handle.signal.addEventListener('abort', close, { once: true })
165 if (options.live) {
166 client.subscribe()
167 }
168 client.attach()
169 client.mountDevtools()
170 }
171
172 // Remix has no effects, so read `options.tools` before each call that can
173 // start a run. A getter such as `get tools() { return page.tools }` then
174 // sends the current tools.
175 const syncTools = () => {
176 if (options.tools !== undefined) {
177 client.updateOptions({ tools: options.tools })
178 }
179 }
180
181 const sendMessage = async (
182 content: string | MultimodalContent,
183 sendOptions?: SendMessageOptions,
184 ) => {
185 syncTools()
186 await client.sendMessage(content, undefined, sendOptions)
187 }
188
189 const cancelQueued = (id: string) => client.cancelQueued(id)
190
191 const append = async (message: ModelMessage | UIMessage<TTools>) => {
192 syncTools()
193 await client.append(message)
194 }
195
196 const reload = async () => {
197 syncTools()
198 await client.reload()
199 }
200
201 const loadOlderMessages = async () => {
202 await client.loadOlderMessages()
203 }
204
205 const stop = () => {
206 client.stop()
207 }
208
209 const clear = () => {
210 client.clear()
211 }
212
213 const setMessages = (newMessages: ReadonlyArray<UIMessage<TTools>>) => {
214 client.setMessagesManually(newMessages)
215 }
216
217 const addToolResult = async (result: {
218 toolCallId: string
219 tool: string
220 output: any
221 state?: 'output-available' | 'output-error'
222 errorText?: string
223 }) => {
224 syncTools()
225 await client.addToolResult(result)
226 }
227
228 const resolveInterrupts = (
229 resolution:
230 | boolean
231 | ((
232 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
233 ) => undefined),
234 ) => {
235 syncTools()
236 if (typeof resolution === 'boolean') {
237 client.resolveInterrupts(resolution)
238 } else {
239 client.resolveInterrupts(resolution)
240 }
241 }
242
243 const cancelInterrupts = () => {
244 client.cancelInterrupts()
245 }
246
247 const retryInterrupts = () => {
248 syncTools()
249 client.retryInterrupts()
250 }
251
252 const resumeInterruptsUnsafe = (
253 resumeItems: Array<RunAgentResumeItem>,
254 state?: ChatResumeState,
255 ) => {
256 syncTools()
257 return client.resumeInterruptsUnsafe(resumeItems, state)
258 }
259
260 function activeStructuredPart(): StructuredOutputPart | null {
261 const { messages } = client.getSnapshot()
262 let lastUserIndex = -1
263 for (let i = messages.length - 1; i >= 0; i--) {
264 if (messages[i]?.role === 'user') {
265 lastUserIndex = i
266 break
267 }
268 }
269 if (lastUserIndex === -1) return null
270 for (let i = messages.length - 1; i > lastUserIndex; i--) {
271 const m = messages[i]
272 if (m?.role !== 'assistant') continue
273 const part = m.parts.find(
274 (p): p is StructuredOutputPart => p.type === 'structured-output',
275 )
276 if (part) return part
277 }
278 return null
279 }
280
281 return {
282 get messages() {
283 return client.getSnapshot().messages
284 },
285 get isLoading() {
286 return client.getSnapshot().isLoading
287 },
288 get hasOlderMessages() {
289 return client.getSnapshot().hasOlderMessages
290 },
291 get error() {
292 return client.getSnapshot().error
293 },
294 get status() {
295 return client.getSnapshot().status
296 },
297 get isSubscribed() {
298 return client.getSnapshot().isSubscribed
299 },
300 get connectionStatus() {
301 return client.getSnapshot().connectionStatus
302 },
303 get sessionGenerating() {
304 return client.getSnapshot().sessionGenerating
305 },
306 get isHydrating() {
307 return client.getSnapshot().isHydrating
308 },
309 get queue() {
310 return client.getSnapshot().queue
311 },
312 get runId() {
313 return client.getSnapshot().runId
314 },
315 get interrupts() {
316 return client.getSnapshot().interruptState.interrupts
317 },
318 get interruptErrors() {
319 return client.getSnapshot().interruptState.interruptErrors
320 },
321 get resuming() {
322 return client.getSnapshot().interruptState.resuming
323 },
324 get partial() {
325 const part = activeStructuredPart()
326 if (!part) return {} as Partial
327 const v = part.partial ?? part.data
328 return (v ?? {}) as Partial
329 },
330 get final() {
331 const part = activeStructuredPart()
332 if (!part || part.status !== 'complete') return null
333 return part.data as Final
334 },
335 sendMessage,
336 cancelQueued,
337 append,
338 reload,
339 loadOlderMessages,
340 stop,
341 setMessages,
342 clear,
343 addToolResult,
344 resolveInterrupts,
345 cancelInterrupts,
346 retryInterrupts,
347 resumeInterruptsUnsafe,
348 }
349}