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

create-ui.ts

516 lines13.2 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 Injector,
5 computed,
6 effect,
7 inject,
8 input,
9 untracked,
10} from '@angular/core'
11import { NgComponentOutlet } from '@angular/common'
12import type { Type } from '@angular/core'
13import {
14 automaticPartsForMessage,
15 collectInlineToolNames,
16 resolveInterruptComponent,
17 selectChatUI,
18 selectMessageUI,
19} from '@tanstack/ai-client/ui'
20import type {
21 ChatUIHasNamedInterrupts,
22 ChatUIHasNamedTools,
23 ChatUIInterrupt,
24 ChatUIInterruptName,
25 ChatUIInterruptOf,
26 ChatUIInterruptsOf,
27 ChatUIMessages,
28 ChatUINamedInterruptId,
29 ChatUIPartKey,
30 ChatUIPartOf,
31 ChatUISchemaOf,
32 ChatUISelectedPart,
33 ChatUIToolApproval,
34 ChatUIToolName,
35 ChatUIToolsOf,
36} from '@tanstack/ai-client/ui'
37import type {
38 QueuedMessage,
39 ToolCallPart,
40 ToolResultPart,
41} from '@tanstack/ai-client'
42import type { InjectChatResult } from '@tanstack/ai-angular'
43import { ChatHostRef, defaultChatUITokens } from './tokens'
44import type { ChatUITokens } from './tokens'
45​
46export type ChatUIHost<TOptions = unknown> = InjectChatResult<
47 ChatUIToolsOf<TOptions>,
48 ChatUISchemaOf<TOptions>,
49 ChatUIInterruptsOf<TOptions>
51​
52export type ChatUIQueueItem = QueuedMessage & {
53 cancelQueued: () => void
55​
56export type LayoutProps<
57 TOptions,
58 TInput extends Type<unknown> | undefined = Type<unknown>,
59> = {
60 Messages: Type<unknown>
61 Interrupts: Type<unknown>
62 Queue: Type<unknown>
63 readonly __ui?: TOptions
64} & (TInput extends Type<unknown> ? { Input: Type<unknown> } : {})
65​
66export type MessageProps<TOptions> = {
67 message: ChatUIMessages<TOptions>[number]
68 Parts: Type<unknown>
70​
71export type InputProps<TOptions> = {
72 readonly __ui?: TOptions
74​
75export type QueueProps<TOptions> = {
76 item: ChatUIQueueItem
77 readonly __ui?: TOptions
79​
80export type PartProps<TOptions, TKey extends ChatUIPartKey = ChatUIPartKey> = {
81 part: ChatUIPartOf<TOptions, TKey>
83​
84export type ToolProps<
85 TOptions,
86 TName extends ChatUIToolName<TOptions> = ChatUIToolName<TOptions>,
87> = {
88 part: Extract<ToolCallPart<ChatUIToolsOf<TOptions>>, { name: TName }>
89 result?: ToolResultPart
90 interrupt?: ChatUIToolApproval<TOptions, TName>
92​
93export type InterruptProps<
94 TOptions,
95 TName extends ChatUIInterruptName<TOptions> = never,
96> = {
97 interrupt: ChatUIInterruptOf<TOptions, TName>
98 readonly __ui?: TOptions
100​
101type GenericInterruptComponents<TOptions> =
102 ChatUIHasNamedInterrupts<TOptions> extends true
103 ? {
104 [K in ChatUINamedInterruptId<TOptions>]: Type<unknown>
105 } & {
106 fallback?: Type<unknown>
107 }
108 : {
109 fallback?: Type<unknown>
110 }
111​
112type ToolApprovalMap<TOptions> = {
113 [K in ChatUIToolName<TOptions>]?: Type<unknown>
115​
116export type ChatUIChromeComponents<
117 TOptions,
118 TInput extends Type<unknown> | undefined = Type<unknown>,
119> = {
120 layout: Type<unknown>
121 message: Type<unknown>
122 input?: TInput
123 queue?: Type<unknown>
124 readonly __ui?: TOptions
126​
127export type ChatUIPartsComponents<TOptions> = {
128 [K in ChatUIPartKey]?: Type<unknown>
129} & {
130 fallback?: Type<unknown>
131 readonly __ui?: TOptions
133​
134export type ChatUIInterruptsComponents<TOptions> = {
135 tools?: ToolApprovalMap<TOptions>
136 generic: GenericInterruptComponents<TOptions>
138​
139export type ChatUIComponents<
140 TOptions,
141 TInput extends Type<unknown> | undefined = Type<unknown>,
142> = {
143 components: ChatUIChromeComponents<TOptions, TInput>
144 partsComponents: ChatUIPartsComponents<TOptions>
145} & (ChatUIHasNamedTools<TOptions> extends true
146 ? {
147 toolsComponents: {
148 [K in ChatUIToolName<TOptions>]: Type<unknown>
149 }
150 }
151 : {
152 toolsComponents?: {
153 [K in ChatUIToolName<TOptions>]?: Type<unknown>
154 }
155 }) &
156 (ChatUIHasNamedInterrupts<TOptions> extends true
157 ? { interruptsComponents: ChatUIInterruptsComponents<TOptions> }
158 : {
159 interruptsComponents?: {
160 tools?: ToolApprovalMap<TOptions>
161 generic?: GenericInterruptComponents<TOptions>
162 }
163 })
164​
165export type ChatUIContextConfig = {
166 chatRef?: ChatUITokens['chatRef']
167 part?: ChatUITokens['part']
168 interrupt?: ChatUITokens['interrupt']
170​
171export type ChatUIFactoryConfig<
172 TOptions,
173 TInput extends Type<unknown> | undefined = Type<unknown>,
174> = ChatUIComponents<TOptions, TInput> & {
175 context?: ChatUIContextConfig
177​
178function createWarnOnce() {
179 const seen = new Set<string>()
180 return (key: string, message: string) => {
181 if (process.env.NODE_ENV === 'production') return
182 if (seen.has(key)) return
183 seen.add(key)
184 console.warn(message)
185 }
187​
188/**
189 * Bind chat options and Angular widgets once at module scope.
190 *
191 * Layout, message, input, queue, parts, tools, and interrupts are
192 * standalone component classes. The factory builds `Chat`, `Messages`,
193 * `Interrupts`, and `Queue` as Angular components that inject the active
194 * chat through DI.
195 */
196export function createChatUI<
197 const TOptions,
198 TInput extends Type<unknown> | undefined = Type<unknown> | undefined,
199>(options: TOptions, config: ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
200 void options
201 const {
202 context: contextOption,
203 components,
204 partsComponents: parts,
205 toolsComponents: tools,
206 interruptsComponents: interrupts,
207 } = config as ChatUIFactoryConfig<TOptions, TInput> & {
208 toolsComponents?: Record<string, Type<unknown> | undefined>
209 interruptsComponents?: {
210 tools?: Record<string, Type<unknown> | undefined>
211 generic?: Record<string, Type<unknown> | undefined>
212 }
213 }
214 const {
215 layout: Layout,
216 message: MessageComponent,
217 input: InputComponent,
218 queue: QueueItemComponent,
219 } = components
220 const warn = createWarnOnce()
221 const tokens = {
222 chatRef: contextOption?.chatRef ?? defaultChatUITokens.chatRef,
223 part: contextOption?.part ?? defaultChatUITokens.part,
224 interrupt: contextOption?.interrupt ?? defaultChatUITokens.interrupt,
225 }
226 const inlineToolNames = collectInlineToolNames(
227 interrupts?.tools as Record<string, unknown> | undefined,
228 Object.keys(tools ?? {}),
229 )
230​
231 function injectChatContext() {
232 const ref = inject(tokens.chatRef)
233 const chat = ref.host()
234 if (!chat) {
235 throw new Error(
236 '`injectChatContext` must be used within `Chat` or `ChatProvider`.',
237 )
238 }
239 return chat as ChatUIHost<TOptions>
240 }
241​
242 @Component({
243 selector: 'ai-chat-missing-input',
244 changeDetection: ChangeDetectionStrategy.OnPush,
245 template: '',
246 })
247 class MissingInput {
248 constructor() {
249 warn(
250 'input',
251 '[tanstack-ai-ui] Rendered Input but no `input` component is registered.',
252 )
253 }
254 }
255​
256 @Component({
257 selector: 'ai-chat-queue',
258 changeDetection: ChangeDetectionStrategy.OnPush,
259 imports: [NgComponentOutlet],
260 template: `
261 @if (itemComponent) {
262 @for (row of rows(); track row.item.id) {
263 <ng-container
264 [ngComponentOutlet]="itemComponent"
265 [ngComponentOutletInputs]="{ item: row.item }"
266 />
267 }
268 }
269 `,
270 })
271 class Queue {
272 readonly ref = inject(tokens.chatRef)
273 readonly itemComponent = QueueItemComponent
274 readonly rows = computed(() => {
275 const chat = this.ref.host()
276 if (!chat || !QueueItemComponent) return []
277 const items = chat.queue()
278 return items.map((item) => ({
279 item: {
280 ...item,
281 cancelQueued: () => {
282 chat.cancelQueued(item.id)
283 },
284 },
285 }))
286 })
287 }
288​
289 @Component({
290 selector: 'ai-chat-parts',
291 changeDetection: ChangeDetectionStrategy.OnPush,
292 imports: [NgComponentOutlet],
293 template: `
294 @for (selected of selectedParts(); track $index) {
295 <ng-container
296 [ngComponentOutlet]="outletFor(selected)"
297 [ngComponentOutletInputs]="inputsFor(selected)"
298 [ngComponentOutletInjector]="injectorFor(selected)"
299 />
300 }
301 `,
302 })
303 class Parts {
304 readonly injector = inject(Injector)
305 readonly ref = inject(tokens.chatRef)
306 message = input.required<ChatUIMessages<TOptions>[number]>()
307​
308 readonly selectedParts = computed(() => {
309 const chat = this.ref.host()
310 return automaticPartsForMessage(
311 selectMessageUI(this.message(), {
312 interrupts: (chat?.interrupts() ??
313 []) as ReadonlyArray<ChatUIInterrupt>,
314 inlineToolNames,
315 }),
316 )
317 })
318​
319 outletFor(selected: ChatUISelectedPart) {
320 if (selected.key === 'toolCall') {
321 const name = selected.part.name
322 const Tool = tools?.[name as ChatUIToolName<TOptions>]
323 if (!Tool) {
324 warn(
325 `tool:${name}`,
326 `[tanstack-ai-ui] Missing tools.${name} component`,
327 )
328 return null
329 }
330 return Tool
331 }
332 const PartComponent = (parts[selected.key] ?? parts.fallback) as
333 | Type<unknown>
334 | undefined
335 if (!PartComponent) {
336 warn(
337 `part:${selected.key}`,
338 `[tanstack-ai-ui] Missing parts.${selected.key} component`,
339 )
340 return null
341 }
342 return PartComponent
343 }
344​
345 inputsFor(selected: ChatUISelectedPart) {
346 if (selected.key === 'toolCall') {
347 return {
348 part: selected.part,
349 result: selected.result,
350 interrupt: selected.interrupt,
351 }
352 }
353 return { part: selected.part }
354 }
355​
356 injectorFor(selected: ChatUISelectedPart) {
357 return Injector.create({
358 parent: this.injector,
359 providers: [{ provide: tokens.part, useValue: selected }],
360 })
361 }
362 }
363​
364 @Component({
365 selector: 'ai-chat-messages',
366 changeDetection: ChangeDetectionStrategy.OnPush,
367 imports: [NgComponentOutlet],
368 template: `
369 @for (message of messages(); track message.id) {
370 <ng-container
371 [ngComponentOutlet]="messageComponent"
372 [ngComponentOutletInputs]="{
373 message,
374 Parts,
375 }"
376 />
377 }
378 `,
379 })
380 class Messages {
381 readonly ref = inject(tokens.chatRef)
382 readonly messageComponent = MessageComponent
383 readonly Parts = Parts
384 readonly messages = computed(() => {
385 const chat = this.ref.host()
386 return (chat?.messages() ?? []) as ChatUIMessages<TOptions>
387 })
388 }
389​
390 @Component({
391 selector: 'ai-chat-interrupts',
392 changeDetection: ChangeDetectionStrategy.OnPush,
393 imports: [NgComponentOutlet],
394 template: `
395 @for (interrupt of interrupts(); track interrupt.id) {
396 <ng-container
397 [ngComponentOutlet]="outletFor(interrupt)"
398 [ngComponentOutletInputs]="{ interrupt }"
399 [ngComponentOutletInjector]="injectorFor(interrupt)"
400 />
401 }
402 `,
403 })
404 class Interrupts {
405 readonly injector = inject(Injector)
406 readonly ref = inject(tokens.chatRef)
407 readonly interrupts = computed(() => {
408 const chat = this.ref.host()
409 const selected = selectChatUI({
410 messages: (chat?.messages() ?? []) as ChatUIMessages<TOptions>,
411 interrupts: (chat?.interrupts() ??
412 []) as ReadonlyArray<ChatUIInterrupt>,
413 inlineToolNames,
414 })
415 return selected.interrupts
416 })
417​
418 outletFor(interrupt: ChatUIInterrupt) {
419 const InterruptComponent = resolveInterruptComponent(
420 interrupt,
421 interrupts,
422 ) as Type<unknown> | undefined
423 if (!InterruptComponent) {
424 warn(
425 `interrupt:${interrupt.id}`,
426 `[tanstack-ai-ui] Missing interrupt component for ${interrupt.kind}`,
427 )
428 return null
429 }
430 return InterruptComponent
431 }
432​
433 injectorFor(interrupt: ChatUIInterrupt) {
434 return Injector.create({
435 parent: this.injector,
436 providers: [{ provide: tokens.interrupt, useValue: interrupt }],
437 })
438 }
439 }
440​
441 const layoutInputs = {
442 Messages,
443 Interrupts,
444 Queue,
445 Input: (InputComponent ?? MissingInput) as Type<unknown>,
446 }
447​
448 @Component({
449 selector: 'ai-chat',
450 changeDetection: ChangeDetectionStrategy.OnPush,
451 imports: [NgComponentOutlet],
452 providers: [{ provide: tokens.chatRef, useClass: ChatHostRef }],
453 template: `
454 <ng-container
455 [ngComponentOutlet]="layout"
456 [ngComponentOutletInputs]="layoutInputs"
457 />
458 `,
459 })
460 class Chat {
461 chat = input.required<ChatUIHost<TOptions>>()
462 readonly layout = Layout
463 readonly layoutInputs = layoutInputs
464 readonly ref = inject(tokens.chatRef)
465​
466 constructor() {
467 effect(() => {
468 const next = this.chat()
469 untracked(() => this.ref.host.set(next as InjectChatResult))
470 })
471 }
472 }
473​
474 @Component({
475 selector: 'ai-chat-provider',
476 changeDetection: ChangeDetectionStrategy.OnPush,
477 providers: [{ provide: tokens.chatRef, useClass: ChatHostRef }],
478 template: `<ng-content />`,
479 })
480 class ChatProvider {
481 chat = input.required<ChatUIHost<TOptions>>()
482 readonly ref = inject(tokens.chatRef)
483​
484 constructor() {
485 effect(() => {
486 const next = this.chat()
487 untracked(() => this.ref.host.set(next as InjectChatResult))
488 })
489 }
490 }
491​
492 return {
493 Chat,
494 ChatProvider,
495 Messages,
496 Interrupts,
497 Queue,
498 Parts,
499 injectChatContext,
500 Input: InputComponent,
501 } as ChatUIKit<TOptions, TInput>
503​
504export type ChatUIKit<
505 TOptions,
506 TInput extends Type<unknown> | undefined = Type<unknown>,
507> = {
508 Chat: Type<unknown>
509 ChatProvider: Type<unknown>
510 Messages: Type<unknown>
511 Interrupts: Type<unknown>
512 Queue: Type<unknown>
513 Parts: Type<unknown>
514 injectChatContext: () => ChatUIHost<TOptions>
515 Input: TInput