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 ChatClientState,
6 ResolvableChatInterrupt,
7 ChatInterruptState,
8 ChatResumeState,
9 ConnectionStatus,
10 InferredClientContext,
11 QueuedMessage,
12 SendMessageOptions,
13 StructuredOutputPart,
14} from '@tanstack/ai-client'
15import type {
16 AnyClientTool,
17 InterruptDefinition,
18 InferSchemaType,
19 ModelMessage,
20 RunAgentResumeItem,
21 SchemaInput,
22 StreamChunk,
23} from '@tanstack/ai/client'
24import type {
25 CreateChatOptions,
26 CreateChatReturn,
27 DeepPartial,
28 MultimodalContent,
29 UIMessage,
30} from './types.ts'
31
32const EMPTY_INTERRUPTS = Object.freeze([])
33const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
34
35/**
36 * Create a chat helper for a Remix component.
37 *
38 * Call this in setup with the component Handle from `remix/ui`. The helper
39 * wraps ChatClient and stores chat state in local variables. ChatClient state
40 * callbacks write those variables and then call `handle.update()`, so render
41 * reads the latest snapshot through getters.
42 *
43 * The default thread id is `options.threadId ?? handle.id`. Cleanup runs when
44 * `handle.signal` aborts. Do not pass identification in `options.devtools`;
45 * the helper sets `framework: 'remix'` and `hookName: 'createChat'`.
46 *
47 * @param handle Remix component handle from setup.
48 * @param options Chat client options. Pass `connection` or `fetcher`.
49 *
50 * @example
51 * ```tsx
52 * import { createChat } from '@tanstack/ai-remix'
53 * import { fetchServerSentEvents } from '@tanstack/ai-client'
54 * import type { Handle } from 'remix/ui'
55 *
56 * function Chat(handle: Handle) {
57 * const chat = createChat(handle, {
58 * connection: fetchServerSentEvents('/api/chat'),
59 * })
60 * return () => (
61 * <div>
62 * {chat.messages.map((message) => (
63 * <div>{message.role}</div>
64 * ))}
65 * <button on={{ click: () => chat.sendMessage('Hello') }}>Send</button>
66 * </div>
67 * )
68 * }
69 * ```
70 *
71 * @see {@link CreateChatReturn}
72 */
73export function createChat<
74 const TTools extends ReadonlyArray<AnyClientTool> = any,
75 TSchema extends SchemaInput | undefined = undefined,
76 TContext = InferredClientContext<TTools>,
77 const TInterrupts extends ReadonlyArray<
78 InterruptDefinition<any, any, any, any>
79 > = readonly [],
80>(
81 handle: Pick<Handle, 'id' | 'update' | 'signal'>,
82 options: CreateChatOptions<TTools, TSchema, TContext, TInterrupts>,
83) {
84 let messages = options.initialMessages || []
85 let isLoading = false
86 let hasOlderMessages = false
87 let error: Error | undefined
88 let status: ChatClientState = 'ready'
89 let isSubscribed = false
90 let connectionStatus: ConnectionStatus = 'disconnected'
91 let sessionGenerating = false
92 let queue: Array<QueuedMessage> = []
93 let runId: string | null = null
94 let interruptState: ChatInterruptState<TTools, TInterrupts> = {
95 interrupts: EMPTY_INTERRUPTS,
96 pendingInterrupts: EMPTY_INTERRUPTS,
97 interruptErrors: EMPTY_INTERRUPT_ERRORS,
98 resuming: false,
99 }
100 let closed = false
101
102 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
103 type Final = InferSchemaType<NonNullable<TSchema>>
104
105 const threadId = options.threadId ?? handle.id
106 const transport = options.connection
107 ? { connection: options.connection }
108 : { fetcher: options.fetcher }
109
110 function commit() {
111 if (closed) return
112 void handle.update()
113 }
114
115 const client = new ChatClient<TTools, TContext, TInterrupts>({
116 devtoolsBridgeFactory: createChatDevtoolsBridge,
117 ...transport,
118 ...(options.initialMessages !== undefined && {
119 initialMessages: options.initialMessages,
120 }),
121 ...(options.persistence === true
122 ? {
123 persistence: true,
124 threadId,
125 ...(options.history !== undefined && {
126 history: options.history,
127 }),
128 }
129 : options.persistence
130 ? {
131 persistence: options.persistence,
132 threadId,
133 }
134 : { threadId }),
135 ...(options.initialResumeSnapshot !== undefined && {
136 initialResumeSnapshot: options.initialResumeSnapshot,
137 }),
138 ...(options.body !== undefined && { body: options.body }),
139 ...(options.forwardedProps !== undefined && {
140 forwardedProps: options.forwardedProps,
141 }),
142 ...(options.byok !== undefined && { byok: options.byok }),
143 byokProvider: () => options.byokProvider?.(),
144 ...(options.context !== undefined && { context: options.context }),
145 devtools: {
146 ...options.devtools,
147 framework: 'remix',
148 hookName: 'createChat',
149 outputKind: options.outputSchema ? 'structured' : 'chat',
150 },
151 onResponse: (response) => options.onResponse?.(response),
152 onChunk: (chunk: StreamChunk) => {
153 options.onChunk?.(chunk)
154 },
155 onFinish: (message) => {
156 options.onFinish?.(message)
157 },
158 onError: (err) => {
159 options.onError?.(err)
160 },
161 ...(options.tools !== undefined && { tools: options.tools }),
162 ...(options.interrupts !== undefined && {
163 interrupts: options.interrupts,
164 }),
165 onCustomEvent: (eventType, data, context) =>
166 options.onCustomEvent?.(eventType, data, context),
167 ...(options.streamProcessor !== undefined && {
168 streamProcessor: options.streamProcessor,
169 }),
170 onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
171 messages = newMessages
172 hasOlderMessages = client.getHasOlderMessages()
173 commit()
174 },
175 onLoadingChange: (newIsLoading: boolean) => {
176 isLoading = newIsLoading
177 syncResumeState()
178 commit()
179 },
180 onStatusChange: (newStatus: ChatClientState) => {
181 status = newStatus
182 commit()
183 },
184 onErrorChange: (newError: Error | undefined) => {
185 error = newError
186 commit()
187 },
188 onSubscriptionChange: (nextIsSubscribed: boolean) => {
189 isSubscribed = nextIsSubscribed
190 commit()
191 },
192 onConnectionStatusChange: (nextStatus: ConnectionStatus) => {
193 connectionStatus = nextStatus
194 commit()
195 },
196 onSessionGeneratingChange: (isGenerating: boolean) => {
197 sessionGenerating = isGenerating
198 commit()
199 },
200 ...(options.queue !== undefined && { queue: options.queue }),
201 onQueueChange: (nextQueue: Array<QueuedMessage>) => {
202 queue = nextQueue
203 commit()
204 },
205 onRunIdChange: (nextRunId) => {
206 runId = nextRunId
207 commit()
208 },
209 onInterruptStateChange: (nextInterruptState, context) => {
210 interruptState = nextInterruptState
211 options.onInterruptStateChange?.(nextInterruptState, context)
212 commit()
213 },
214 })
215
216 function syncResumeState() {
217 runId = client.getCurrentRunId()
218 interruptState = client.getInterruptState()
219 }
220
221 messages = client.getMessages()
222 interruptState = client.getInterruptState()
223 runId = client.getCurrentRunId()
224
225 function close() {
226 if (closed) return
227 closed = true
228 client.detach()
229 if (options.live) {
230 client.unsubscribe()
231 } else {
232 client.stop()
233 }
234 client.dispose()
235 }
236
237 if (handle.signal.aborted) {
238 close()
239 } else {
240 handle.signal.addEventListener('abort', close, { once: true })
241 if (options.live) {
242 client.subscribe()
243 }
244 client.attach()
245 client.mountDevtools()
246 }
247
248 // Remix has no effects, so read `options.tools` before each call that can
249 // start a run. A getter such as `get tools() { return page.tools }` then
250 // sends the current tools.
251 const syncTools = () => {
252 if (options.tools !== undefined) {
253 client.updateOptions({ tools: options.tools })
254 }
255 }
256
257 const sendMessage = async (
258 content: string | MultimodalContent,
259 sendOptions?: SendMessageOptions,
260 ) => {
261 syncTools()
262 try {
263 await client.sendMessage(content, undefined, sendOptions)
264 } finally {
265 syncResumeState()
266 }
267 }
268
269 const cancelQueued = (id: string) => client.cancelQueued(id)
270
271 const append = async (message: ModelMessage | UIMessage<TTools>) => {
272 syncTools()
273 try {
274 await client.append(message)
275 } finally {
276 syncResumeState()
277 }
278 }
279
280 const reload = async () => {
281 syncTools()
282 try {
283 await client.reload()
284 } finally {
285 syncResumeState()
286 }
287 }
288
289 const loadOlderMessages = async () => {
290 await client.loadOlderMessages()
291 hasOlderMessages = client.getHasOlderMessages()
292 commit()
293 }
294
295 const stop = () => {
296 client.stop()
297 }
298
299 const clear = () => {
300 client.clear()
301 syncResumeState()
302 }
303
304 const setMessages = (newMessages: Array<UIMessage<TTools>>) => {
305 client.setMessagesManually(newMessages)
306 }
307
308 const addToolResult = async (result: {
309 toolCallId: string
310 tool: string
311 output: any
312 state?: 'output-available' | 'output-error'
313 errorText?: string
314 }) => {
315 syncTools()
316 await client.addToolResult(result)
317 }
318
319 /** @deprecated Use a bound `tool-approval` interrupt and `interrupt.resolveInterrupt`. */
320 const addToolApprovalResponse = async (response: {
321 id: string
322 approved: boolean
323 }) => {
324 syncTools()
325 await client.addToolApprovalResponse(response)
326 syncResumeState()
327 }
328
329 const resumeInterrupts = async (
330 resumeItems: Array<RunAgentResumeItem>,
331 state?: ChatResumeState,
332 ) => {
333 syncTools()
334 const result = await client.resumeInterrupts(resumeItems, state)
335 syncResumeState()
336 return result
337 }
338
339 const resolveInterrupts = (
340 resolution:
341 | boolean
342 | ((
343 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
344 ) => undefined),
345 ) => {
346 syncTools()
347 if (typeof resolution === 'boolean') {
348 client.resolveInterrupts(resolution)
349 } else {
350 client.resolveInterrupts(resolution)
351 }
352 }
353
354 const cancelInterrupts = () => {
355 client.cancelInterrupts()
356 }
357
358 const retryInterrupts = () => {
359 syncTools()
360 client.retryInterrupts()
361 }
362
363 const resumeInterruptsUnsafe = (
364 resumeItems: Array<RunAgentResumeItem>,
365 state?: ChatResumeState,
366 ) => {
367 syncTools()
368 return client.resumeInterruptsUnsafe(resumeItems, state)
369 }
370
371 function activeStructuredPart(): StructuredOutputPart | null {
372 let lastUserIndex = -1
373 for (let i = messages.length - 1; i >= 0; i--) {
374 if (messages[i]?.role === 'user') {
375 lastUserIndex = i
376 break
377 }
378 }
379 if (lastUserIndex === -1) return null
380 for (let i = messages.length - 1; i > lastUserIndex; i--) {
381 const m = messages[i]
382 if (m?.role !== 'assistant') continue
383 const part = m.parts.find(
384 (p): p is StructuredOutputPart => p.type === 'structured-output',
385 )
386 if (part) return part
387 }
388 return null
389 }
390
391 return {
392 get messages() {
393 return messages
394 },
395 get isLoading() {
396 return isLoading
397 },
398 get hasOlderMessages() {
399 return hasOlderMessages
400 },
401 get error() {
402 return error
403 },
404 get status() {
405 return status
406 },
407 get isSubscribed() {
408 return isSubscribed
409 },
410 get connectionStatus() {
411 return connectionStatus
412 },
413 get sessionGenerating() {
414 return sessionGenerating
415 },
416 get queue() {
417 return queue
418 },
419 get runId() {
420 return runId
421 },
422 get interrupts() {
423 return interruptState.interrupts
424 },
425 get pendingInterrupts() {
426 return interruptState.interrupts
427 },
428 get interruptErrors() {
429 return interruptState.interruptErrors
430 },
431 get resuming() {
432 return interruptState.resuming
433 },
434 get partial() {
435 const part = activeStructuredPart()
436 if (!part) return {} as Partial
437 const v = part.partial ?? part.data
438 return (v ?? {}) as Partial
439 },
440 get final() {
441 const part = activeStructuredPart()
442 if (!part || part.status !== 'complete') return null
443 return part.data as Final
444 },
445 sendMessage,
446 cancelQueued,
447 append,
448 reload,
449 loadOlderMessages,
450 stop,
451 setMessages,
452 clear,
453 addToolResult,
454 addToolApprovalResponse,
455 resolveInterrupts,
456 cancelInterrupts,
457 retryInterrupts,
458 resumeInterruptsUnsafe,
459 resumeInterrupts,
460 }
461}