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

inject-chat.ts

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