Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

inject-chat.ts

381 lines12.4 KB

1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 DestroyRef,
5 Injector,
6 afterNextRender,
7 assertInInjectionContext,
8 computed,
9 effect,
10 inject,
11 signal,
12} from '@angular/core'
13import { toReactive } from './internal/to-reactive'
14import type {
15 AnyClientTool,
16 InterruptDefinition,
17 InferSchemaType,
18 ModelMessage,
19 RunAgentResumeItem,
20 SchemaInput,
21 StreamChunk,
22} from '@tanstack/ai'
23import type {
24 ChatClientState,
25 ResolvableChatInterrupt,
26 ChatInterruptState,
27 ChatResumeState,
28 ConnectionStatus,
29 InferredClientContext,
30 QueuedMessage,
31 SendMessageOptions,
32 StructuredOutputPart,
33} from '@tanstack/ai-client'
34import type {
35 DeepPartial,
36 InjectChatOptions,
37 InjectChatResult,
38 MultimodalContent,
39 UIMessage,
40} from './types'
41​
42const EMPTY_INTERRUPTS = Object.freeze([])
43const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
44​
45export function injectChat<
46 const TTools extends ReadonlyArray<AnyClientTool> = any,
47 TSchema extends SchemaInput | undefined = undefined,
48 TContext = InferredClientContext<TTools>,
49 const TInterrupts extends ReadonlyArray<
50 InterruptDefinition<any, any, any, any>
51 > = readonly [],
52>(
53 options: InjectChatOptions<
54 TTools,
55 TSchema,
56 TContext,
57 TInterrupts
58 > = {} as InjectChatOptions<TTools, TSchema, TContext, TInterrupts>,
59): InjectChatResult<TTools, TSchema, TInterrupts> {
60 assertInInjectionContext(injectChat)
61​
62 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
63 type Final = InferSchemaType<NonNullable<TSchema>>
64​
65 const destroyRef = inject(DestroyRef)
66 const injector = inject(Injector)
67​
68 const messages = signal<Array<UIMessage<TTools>>>(
69 options.initialMessages || [],
70 )
71 const isLoading = signal(false)
72 const hasOlderMessages = signal(false)
73 const error = signal<Error | undefined>(undefined)
74 const status = signal<ChatClientState>('ready')
75 const isSubscribed = signal(false)
76 const connectionStatus = signal<ConnectionStatus>('disconnected')
77 const sessionGenerating = signal(false)
78 const queue = signal<Array<QueuedMessage>>([])
79 const runId = signal<string | null>(null)
80 const interruptState = signal<ChatInterruptState<TTools, TInterrupts>>({
81 interrupts: EMPTY_INTERRUPTS,
82 pendingInterrupts: EMPTY_INTERRUPTS,
83 interruptErrors: EMPTY_INTERRUPT_ERRORS,
84 resuming: false,
85 })
86​
87 // Reactive option sources. Plain values become constant computeds.
88 const bodySource =
89 options.body !== undefined ? toReactive(options.body) : undefined
90 const forwardedPropsSource =
91 options.forwardedProps !== undefined
92 ? toReactive(options.forwardedProps)
93 : undefined
94 const contextSource =
95 options.context !== undefined ? toReactive(options.context) : undefined
96 const liveSource =
97 options.live !== undefined ? toReactive(options.live) : undefined
98 const toolsSource =
99 options.tools !== undefined ? toReactive(options.tools) : undefined
100​
101 const transport = options.connection
102 ? { connection: options.connection }
103 : { fetcher: options.fetcher }
104​
105 const client = new ChatClient<TTools, TContext, TInterrupts>({
106 devtoolsBridgeFactory: createChatDevtoolsBridge,
107 ...transport,
108 ...(options.initialMessages !== undefined && {
109 initialMessages: options.initialMessages,
110 }),
111 ...(typeof options.threadId === 'string' && options.persistence === true
112 ? {
113 persistence: true,
114 threadId: options.threadId,
115 ...(options.history !== undefined && {
116 history: options.history,
117 }),
118 }
119 : typeof options.threadId === 'string' && options.persistence
120 ? {
121 persistence: options.persistence,
122 threadId: options.threadId,
123 }
124 : {
125 ...(options.threadId !== undefined && {
126 threadId: options.threadId,
127 }),
128 }),
129 ...(options.initialResumeSnapshot !== undefined && {
130 initialResumeSnapshot: options.initialResumeSnapshot,
131 }),
132 ...(bodySource !== undefined && { body: bodySource() }),
133 ...(forwardedPropsSource !== undefined && {
134 forwardedProps: forwardedPropsSource(),
135 }),
136 ...(options.byok !== undefined && { byok: options.byok }),
137 byokProvider: () => options.byokProvider?.(),
138 ...(contextSource !== undefined && { context: contextSource() }),
139 devtools: {
140 ...options.devtools,
141 framework: 'angular',
142 hookName: 'injectChat',
143 outputKind: options.outputSchema ? 'structured' : 'chat',
144 },
145 onResponse: (response) => options.onResponse?.(response),
146 onChunk: (chunk: StreamChunk) => options.onChunk?.(chunk),
147 onFinish: (message) => options.onFinish?.(message),
148 onError: (err) => options.onError?.(err),
149 onRunIdChange: (nextRunId) => runId.set(nextRunId),
150 // No `onResumeStateChange`: the run identity is surfaced as the `runId`
151 // signal (via `onRunIdChange`) and pending interrupts arrive through
152 // `onInterruptStateChange`, so there is nothing left for it to do — and it
153 // is not a public option here, matching the other framework packages.
154 onInterruptStateChange: (nextInterruptState, context) => {
155 interruptState.set(nextInterruptState)
156 options.onInterruptStateChange?.(nextInterruptState, context)
157 },
158 tools: toolsSource?.(),
159 ...(options.interrupts !== undefined && {
160 interrupts: options.interrupts,
161 }),
162 onCustomEvent: (eventType, data, context) =>
163 options.onCustomEvent?.(eventType, data, context),
164 ...(options.streamProcessor !== undefined && {
165 streamProcessor: options.streamProcessor,
166 }),
167 onMessagesChange: (m: Array<UIMessage<TTools>>) => {
168 messages.set(m)
169 hasOlderMessages.set(client.getHasOlderMessages())
170 },
171 onLoadingChange: (v: boolean) => isLoading.set(v),
172 onStatusChange: (v: ChatClientState) => status.set(v),
173 onErrorChange: (v: Error | undefined) => error.set(v),
174 onSubscriptionChange: (v: boolean) => isSubscribed.set(v),
175 onConnectionStatusChange: (v: ConnectionStatus) => connectionStatus.set(v),
176 onSessionGeneratingChange: (v: boolean) => sessionGenerating.set(v),
177 ...(options.queue !== undefined && { queue: options.queue }),
178 onQueueChange: (nextQueue: Array<QueuedMessage>) => queue.set(nextQueue),
179 })
180​
181 messages.set(client.getMessages())
182 interruptState.set(client.getInterruptState())
183 hasOlderMessages.set(client.getHasOlderMessages())
184​
185 // START TAILING HERE, not in the constructor. A client is idle until something
186 // attaches it, so a client that gets built and thrown away never opens a
187 // connection — an unreachable stream would hold one of the browser's ~6
188 // connections per origin until the page reloaded. `inject*` runs in an injection
189 // context tied to the consumer's lifetime, and `destroyRef.onDestroy` below is the
190 // matching `detach`.
191 client.attach()
192​
193 // Sync reactive body / forwardedProps / context to the client.
194 if (bodySource || forwardedPropsSource || contextSource) {
195 effect(
196 () => {
197 const newBody = bodySource?.()
198 const newForwardedProps = forwardedPropsSource?.()
199 const newContext = contextSource?.()
200 client.updateOptions({
201 ...(newBody !== undefined && { body: newBody }),
202 ...(newForwardedProps !== undefined && {
203 forwardedProps: newForwardedProps,
204 }),
205 ...(newContext !== undefined && { context: newContext }),
206 })
207 },
208 { injector },
209 )
210 }
211​
212 // Sync reactive tools to the client.
213 if (toolsSource) {
214 effect(() => client.updateOptions({ tools: toolsSource() }), { injector })
215 }
216​
217 // Subscribe / unsubscribe based on reactive `live`.
218 if (liveSource) {
219 effect(
220 () => {
221 if (liveSource()) {
222 client.subscribe()
223 } else {
224 client.unsubscribe()
225 }
226 },
227 { injector },
228 )
229 }
230​
231 afterNextRender(
232 () => {
233 client.mountDevtools()
234 // Delivery-durability resume is transparent: the resumable SSE
235 // connection adapter reattaches via the browser's native Last-Event-ID
236 // on reconnect. No client-side auto-resume wiring is needed.
237 },
238 { injector },
239 )
240​
241 destroyRef.onDestroy(() => {
242 // Release the connection first: the counterpart of the `attach` above.
243 client.detach()
244 if (liveSource?.()) {
245 client.unsubscribe()
246 } else {
247 client.stop()
248 }
249 client.dispose()
250 })
251​
252 // Active structured-output part = the one on the assistant message after the
253 // latest user message. Ported from ai-vue/src/use-chat.ts.
254 const activeStructuredPart = computed<StructuredOutputPart | null>(() => {
255 const list = messages()
256 let lastUserIndex = -1
257 for (let i = list.length - 1; i >= 0; i--) {
258 if (list[i]?.role === 'user') {
259 lastUserIndex = i
260 break
261 }
262 }
263 if (lastUserIndex === -1) return null
264 for (let i = list.length - 1; i > lastUserIndex; i--) {
265 const m = list[i]
266 if (m?.role !== 'assistant') continue
267 const part = m.parts.find(
268 (p): p is StructuredOutputPart => p.type === 'structured-output',
269 )
270 if (part) return part
271 }
272 return null
273 })
274​
275 const partial = computed<Partial>(() => {
276 const part = activeStructuredPart()
277 if (!part) return {} as Partial
278 const v = part.partial ?? part.data
279 return (v ?? {}) as Partial
280 })
281​
282 const final = computed<Final | null>(() => {
283 const part = activeStructuredPart()
284 if (!part || part.status !== 'complete') return null
285 return part.data as Final
286 })
287​
288 const sendMessage = async (
289 content: string | MultimodalContent,
290 sendOptions?: SendMessageOptions,
291 ) => {
292 await client.sendMessage(content, undefined, sendOptions)
293 }
294 const cancelQueued = (id: string) => client.cancelQueued(id)
295 const append = async (message: ModelMessage | UIMessage<TTools>) => {
296 await client.append(message)
297 }
298 const reload = async () => {
299 await client.reload()
300 }
301 const loadOlderMessages = async () => {
302 await client.loadOlderMessages()
303 hasOlderMessages.set(client.getHasOlderMessages())
304 }
305 const stop = () => client.stop()
306 const clear = () => client.clear()
307 const setMessages = (m: Array<UIMessage<TTools>>) =>
308 client.setMessagesManually(m)
309 const addToolResult = async (result: {
310 toolCallId: string
311 tool: string
312 output: any
313 state?: 'output-available' | 'output-error'
314 errorText?: string
315 }) => {
316 await client.addToolResult(result)
317 }
318 const addToolApprovalResponse = async (response: {
319 id: string
320 approved: boolean
321 }) => {
322 await client.addToolApprovalResponse(response)
323 }
324 const interrupts = computed(() => interruptState().interrupts)
325 const pendingInterrupts = computed(() => interruptState().interrupts)
326 const interruptErrors = computed(() => interruptState().interruptErrors)
327 const resuming = computed(() => interruptState().resuming)
328 const resolveInterrupts = (
329 resolution:
330 | boolean
331 | ((
332 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
333 ) => undefined),
334 ) => {
335 if (typeof resolution === 'boolean') {
336 client.resolveInterrupts(resolution)
337 } else {
338 client.resolveInterrupts(resolution)
339 }
340 }
341 const cancelInterrupts = () => client.cancelInterrupts()
342 const retryInterrupts = () => client.retryInterrupts()
343 const resumeInterruptsUnsafe = (
344 resumeItems: Array<RunAgentResumeItem>,
345 state?: ChatResumeState,
346 ) => client.resumeInterruptsUnsafe(resumeItems, state)
347​
348 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- return shape diverges from conditional InjectChatResult<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final signals
349 return {
350 messages: messages.asReadonly(),
351 sendMessage,
352 queue: queue.asReadonly(),
353 cancelQueued,
354 append,
355 reload,
356 stop,
357 isLoading: isLoading.asReadonly(),
358 hasOlderMessages: hasOlderMessages.asReadonly(),
359 loadOlderMessages,
360 error: error.asReadonly(),
361 status: status.asReadonly(),
362 isSubscribed: isSubscribed.asReadonly(),
363 connectionStatus: connectionStatus.asReadonly(),
364 sessionGenerating: sessionGenerating.asReadonly(),
365 setMessages,
366 clear,
367 addToolResult,
368 addToolApprovalResponse,
369 runId: runId.asReadonly(),
370 interrupts,
371 pendingInterrupts,
372 interruptErrors,
373 resuming,
374 resolveInterrupts,
375 cancelInterrupts,
376 retryInterrupts,
377 resumeInterruptsUnsafe,
378 partial,
379 final,
380 } as unknown as InjectChatResult<TTools, TSchema, TInterrupts>