Open History to see the last commit
1import {
2 aiEventClient,
3 createAIDevtoolsEventEnvelope,
4} from '@tanstack/ai-event-client'
5import type { ContentPart } from '@tanstack/ai/client'
6import type { UIMessage } from './types'
7
8export interface ChatClientRunEventContext {
9 threadId: string
10 runId: string
11 toolCallId?: string
12}
13
14export interface ChatClientEventContext {
15 threadId?: string
16 runId?: string
17 toolCallId?: string
18}
19
20export interface ChatClientToolFixtureAppliedEvent {
21 hookId: string
22 threadId: string
23 toolName: string
24 input: unknown
25 output: unknown
26 execute?: boolean
27 message?: {
28 id: string
29 role: UIMessage['role']
30 parts: Array<unknown>
31 createdAt?: number | string
32 }
33 messageId: string
34 toolCallId: string
35 runId?: string
36 errorText?: string
37}
38
39export interface ChatClientStructuredOutputEvent {
40 status: 'streaming' | 'complete' | 'error'
41 raw?: string
42 partial?: unknown
43 data?: unknown
44 reasoning?: string
45 errorMessage?: string
46 delta?: string
47}
48
49export type ChatClientStructuredOutputEventName =
50 | 'structured-output:started'
51 | 'structured-output:updated'
52 | 'structured-output:completed'
53 | 'structured-output:errored'
54
55/**
56 * Abstract base class for ChatClient event emission
57 */
58export abstract class ChatClientEventEmitter {
59 protected clientId: string
60
61 constructor(clientId: string) {
62 this.clientId = clientId
63 }
64
65 /**
66 * Protected abstract method for emitting events
67 * Implementations should handle adding clientId and timestamp
68 */
69 protected abstract emitEvent(
70 eventName: string,
71 data?: Record<string, unknown>,
72 ): void
73
74 /**
75 * Emit client created event
76 */
77 clientCreated(initialMessageCount: number): void {
78 this.emitEvent('client:created', {
79 initialMessageCount,
80 })
81 }
82
83 /**
84 * Emit loading state changed event
85 */
86 loadingChanged(isLoading: boolean): void {
87 this.emitEvent('client:loading:changed', { isLoading })
88 }
89
90 /**
91 * Emit error state changed event
92 */
93 errorChanged(error: string | null): void {
94 this.emitEvent('client:error:changed', {
95 error,
96 })
97 }
98
99 /**
100 * Emit text update events (combines processor and client events)
101 */
102 textUpdated(
103 streamId: string,
104 messageId: string,
105 content: string,
106 context?: ChatClientRunEventContext,
107 ): void {
108 this.emitEvent('text:chunk:content', {
109 streamId,
110 messageId,
111 content,
112 ...context,
113 })
114 }
115
116 /**
117 * Emit tool call state change events (combines processor and client events)
118 */
119 toolCallStateChanged(
120 streamId: string,
121 messageId: string,
122 toolCallId: string,
123 toolName: string,
124 state: string,
125 args: string,
126 context?: ChatClientRunEventContext,
127 ): void {
128 this.emitEvent('tools:call:updated', {
129 streamId,
130 messageId,
131 toolCallId,
132 toolName,
133 state,
134 arguments: args,
135 ...context,
136 })
137 }
138
139 /**
140 * Emit tool result state change event
141 */
142 /**
143 * Emit thinking update event
144 */
145 thinkingUpdated(
146 streamId: string,
147 messageId: string,
148 content: string,
149 delta?: string,
150 context?: ChatClientRunEventContext,
151 ): void {
152 this.emitEvent('text:chunk:thinking', {
153 streamId,
154 messageId,
155 content,
156 delta,
157 ...context,
158 })
159 }
160
161 structuredOutputChanged(
162 eventName: ChatClientStructuredOutputEventName,
163 streamId: string,
164 messageId: string,
165 output: ChatClientStructuredOutputEvent,
166 context?: ChatClientRunEventContext,
167 ): void {
168 this.emitEvent(eventName, {
169 streamId,
170 messageId,
171 ...output,
172 ...context,
173 })
174 }
175
176 /**
177 * Emit approval requested event
178 */
179 approvalRequested(
180 streamId: string,
181 messageId: string,
182 toolCallId: string,
183 toolName: string,
184 input: unknown,
185 approvalId: string,
186 context?: ChatClientRunEventContext,
187 ): void {
188 this.emitEvent('tools:approval:requested', {
189 streamId,
190 messageId,
191 toolCallId,
192 toolName,
193 input,
194 approvalId,
195 ...context,
196 })
197 }
198
199 /**
200 * Emit message appended event
201 */
202 messageAppended(
203 uiMessage: UIMessage,
204 streamId?: string,
205 context?: ChatClientEventContext,
206 ): void {
207 const content = uiMessage.parts
208 .filter((part) => part.type === 'text')
209 .map((part) => part.content)
210 .join(' ')
211
212 this.emitEvent('text:message:created', {
213 streamId,
214 messageId: uiMessage.id,
215 role: uiMessage.role,
216 content,
217 parts: uiMessage.parts,
218 ...context,
219 })
220 }
221
222 /**
223 * Emit message sent event.
224 * Supports both simple string content and multimodal content arrays.
225 *
226 * @param messageId - The ID of the sent message
227 * @param content - The message content (string or array of ContentPart for multimodal)
228 */
229 messageSent(messageId: string, content: string | Array<ContentPart>): void {
230 // For text content, extract it; for multimodal, provide the array
231 const textContent =
232 typeof content === 'string'
233 ? content
234 : content
235 .filter((part) => part.type === 'text')
236 .map((part) => (part as { type: 'text'; content: string }).content)
237 .join('')
238
239 this.emitEvent('text:message:created', {
240 messageId,
241 role: 'user',
242 content: textContent,
243 // Include full content for multimodal messages
244 ...(Array.isArray(content) && { parts: content }),
245 })
246
247 this.emitEvent('text:message:user', {
248 messageId,
249 role: 'user',
250 content: textContent,
251 // Include full content for multimodal messages
252 ...(Array.isArray(content) && { parts: content }),
253 })
254 }
255
256 /**
257 * Emit reloaded event
258 */
259 reloaded(fromMessageIndex: number): void {
260 this.emitEvent('client:reloaded', {
261 fromMessageIndex,
262 })
263 }
264 /**
265 * Emit stopped event
266 */
267 stopped(): void {
268 this.emitEvent('client:stopped')
269 }
270
271 /**
272 * Emit messages cleared event
273 */
274 messagesCleared(): void {
275 this.emitEvent('client:messages:cleared')
276 }
277
278 /**
279 * Emit tool result added event
280 */
281 toolResultAdded(
282 toolCallId: string,
283 toolName: string,
284 output: unknown,
285 state: string,
286 context?: ChatClientEventContext,
287 ): void {
288 this.emitEvent('tools:result:added', {
289 toolCallId,
290 toolName,
291 output,
292 state,
293 ...context,
294 })
295 }
296
297 /**
298 * Emit tool approval responded event
299 */
300 toolApprovalResponded(
301 approvalId: string,
302 toolCallId: string,
303 approved: boolean,
304 context?: ChatClientRunEventContext,
305 ): void {
306 this.emitEvent('tools:approval:responded', {
307 approvalId,
308 toolCallId,
309 approved,
310 ...context,
311 })
312 }
313
314 /**
315 * Emit tool fixture applied event.
316 */
317 toolFixtureApplied(fixture: ChatClientToolFixtureAppliedEvent): void {
318 this.emitEvent('devtools:tool-fixture:applied', { ...fixture })
319 }
320}
321
322/**
323 * Default implementation of ChatClientEventEmitter
324 */
325export class DefaultChatClientEventEmitter extends ChatClientEventEmitter {
326 /**
327 * Emit an event with automatic clientId and timestamp for client/tool events
328 */
329 protected emitEvent(eventName: string, data?: Record<string, any>): void {
330 const timestamp = Date.now()
331 const isUserVisibleEvent =
332 eventName.startsWith('text:') ||
333 eventName.startsWith('tools:') ||
334 eventName.startsWith('structured-output:') ||
335 eventName === 'devtools:tool-fixture:applied'
336 const includesClientContext =
337 eventName.startsWith('client:') ||
338 eventName.startsWith('tools:') ||
339 eventName.startsWith('text:') ||
340 eventName.startsWith('structured-output:') ||
341 eventName === 'devtools:tool-fixture:applied'
342 const visibility = isUserVisibleEvent ? 'user-visible' : 'client-state'
343 const envelopeContext = {
344 hookId: this.clientId,
345 ...(typeof data?.threadId === 'string'
346 ? { threadId: data.threadId }
347 : {}),
348 ...(typeof data?.runId === 'string' ? { runId: data.runId } : {}),
349 ...(typeof data?.streamId === 'string'
350 ? { streamId: data.streamId }
351 : {}),
352 ...(typeof data?.messageId === 'string'
353 ? { messageId: data.messageId }
354 : {}),
355 ...(typeof data?.toolCallId === 'string'
356 ? { toolCallId: data.toolCallId }
357 : {}),
358 }
359
360 // For client:* and tool:* events, automatically add clientId and timestamp
361 if (includesClientContext) {
362 const envelope = createAIDevtoolsEventEnvelope({
363 eventType: eventName,
364 clientId: this.clientId,
365 ...envelopeContext,
366 source: 'client',
367 visibility,
368 timestamp,
369 })
370 aiEventClient.emit(eventName as any, {
371 ...data,
372 ...envelope,
373 })
374 } else {
375 const envelope = createAIDevtoolsEventEnvelope({
376 eventType: eventName,
377 source: 'client',
378 visibility: 'client-state',
379 timestamp,
380 })
381 // For other events, just add timestamp
382 aiEventClient.emit(eventName as any, {
383 ...data,
384 ...envelope,
385 })
386 }
387 }
388}