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

inject-chat.ts

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