@tanstack/ai-angular 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,19 @@
1
1
  <div align="center">
2
- <img src="https://raw.githubusercontent.com/TanStack/ai/main/media/header_ai.png" alt="TanStack AI" />
2
+ <picture>
3
+ <source
4
+ media="(prefers-color-scheme: dark)"
5
+ srcset="https://tanstack.com/api/readme/ai.png?framework=angular&theme=dark"
6
+ />
7
+ <source
8
+ media="(prefers-color-scheme: light)"
9
+ srcset="https://tanstack.com/api/readme/ai.png?framework=angular"
10
+ />
11
+ <img
12
+ src="https://tanstack.com/api/readme/ai.png?framework=angular"
13
+ alt="TanStack Angular AI"
14
+ width="900"
15
+ />
16
+ </picture>
3
17
  </div>
4
18
 
5
19
  <br />
package/dist/README.md CHANGED
@@ -1,5 +1,19 @@
1
1
  <div align="center">
2
- <img src="https://raw.githubusercontent.com/TanStack/ai/main/media/header_ai.png" alt="TanStack AI" />
2
+ <picture>
3
+ <source
4
+ media="(prefers-color-scheme: dark)"
5
+ srcset="https://tanstack.com/api/readme/ai.png?framework=angular&theme=dark"
6
+ />
7
+ <source
8
+ media="(prefers-color-scheme: light)"
9
+ srcset="https://tanstack.com/api/readme/ai.png?framework=angular"
10
+ />
11
+ <img
12
+ src="https://tanstack.com/api/readme/ai.png?framework=angular"
13
+ alt="TanStack Angular AI"
14
+ width="900"
15
+ />
16
+ </picture>
3
17
  </div>
4
18
 
5
19
  <br />
@@ -1,5 +1,5 @@
1
- import { ChatClient, GenerationClient, AudioRecorder, VideoGenerationClient } from '@tanstack/ai-client';
2
- export { createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from '@tanstack/ai-client';
1
+ import { ChatClient, GenerationClient, reconstructImageResult, reconstructAudioResult, reconstructSpeechResult, reconstructTranscriptionResult, AudioRecorder, reconstructSummarizeResult, VideoGenerationClient } from '@tanstack/ai-client';
2
+ export { StorageUnavailableError, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from '@tanstack/ai-client';
3
3
  import { createChatDevtoolsBridge, createGenerationDevtoolsBridge, createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools';
4
4
  import { isSignal, computed, assertInInjectionContext, inject, DestroyRef, Injector, signal, effect, afterNextRender } from '@angular/core';
5
5
 
@@ -20,6 +20,8 @@ function toReactive(value) {
20
20
  return () => value;
21
21
  }
22
22
 
23
+ const EMPTY_INTERRUPTS = Object.freeze([]);
24
+ const EMPTY_INTERRUPT_ERRORS = Object.freeze([]);
23
25
  let nextId$2 = 0;
24
26
  function injectChat(options = {}) {
25
27
  assertInInjectionContext(injectChat);
@@ -34,6 +36,13 @@ function injectChat(options = {}) {
34
36
  const connectionStatus = signal('disconnected', ...(ngDevMode ? [{ debugName: "connectionStatus" }] : /* istanbul ignore next */ []));
35
37
  const sessionGenerating = signal(false, ...(ngDevMode ? [{ debugName: "sessionGenerating" }] : /* istanbul ignore next */ []));
36
38
  const queue = signal([], ...(ngDevMode ? [{ debugName: "queue" }] : /* istanbul ignore next */ []));
39
+ const runId = signal(null, ...(ngDevMode ? [{ debugName: "runId" }] : /* istanbul ignore next */ []));
40
+ const interruptState = signal({
41
+ interrupts: EMPTY_INTERRUPTS,
42
+ pendingInterrupts: EMPTY_INTERRUPTS,
43
+ interruptErrors: EMPTY_INTERRUPT_ERRORS,
44
+ resuming: false,
45
+ }, ...(ngDevMode ? [{ debugName: "interruptState" }] : /* istanbul ignore next */ []));
37
46
  // Reactive option sources. Plain values become constant computeds.
38
47
  const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
39
48
  const forwardedPropsSource = options.forwardedProps !== undefined
@@ -54,6 +63,9 @@ function injectChat(options = {}) {
54
63
  ...(options.persistence !== undefined && {
55
64
  persistence: options.persistence,
56
65
  }),
66
+ ...(options.initialResumeSnapshot !== undefined && {
67
+ initialResumeSnapshot: options.initialResumeSnapshot,
68
+ }),
57
69
  ...(bodySource !== undefined && { body: bodySource() }),
58
70
  ...(options.threadId !== undefined && { threadId: options.threadId }),
59
71
  ...(forwardedPropsSource !== undefined && {
@@ -70,6 +82,15 @@ function injectChat(options = {}) {
70
82
  onChunk: (chunk) => options.onChunk?.(chunk),
71
83
  onFinish: (message) => options.onFinish?.(message),
72
84
  onError: (err) => options.onError?.(err),
85
+ onRunIdChange: (nextRunId) => runId.set(nextRunId),
86
+ // No `onResumeStateChange`: the run identity is surfaced as the `runId`
87
+ // signal (via `onRunIdChange`) and pending interrupts arrive through
88
+ // `onInterruptStateChange`, so there is nothing left for it to do — and it
89
+ // is not a public option here, matching the other framework packages.
90
+ onInterruptStateChange: (nextInterruptState) => {
91
+ interruptState.set(nextInterruptState);
92
+ options.onInterruptStateChange?.(nextInterruptState);
93
+ },
73
94
  tools: options.tools,
74
95
  onCustomEvent: (eventType, data, context) => options.onCustomEvent?.(eventType, data, context),
75
96
  ...(options.streamProcessor !== undefined && {
@@ -86,6 +107,14 @@ function injectChat(options = {}) {
86
107
  onQueueChange: (nextQueue) => queue.set(nextQueue),
87
108
  });
88
109
  messages.set(client.getMessages());
110
+ interruptState.set(client.getInterruptState());
111
+ // START TAILING HERE, not in the constructor. A client is idle until something
112
+ // attaches it, so a client that gets built and thrown away never opens a
113
+ // connection — an unreachable stream would hold one of the browser's ~6
114
+ // connections per origin until the page reloaded. `inject*` runs in an injection
115
+ // context tied to the consumer's lifetime, and `destroyRef.onDestroy` below is the
116
+ // matching `detach`.
117
+ client.attach();
89
118
  // Sync reactive body / forwardedProps / context to the client.
90
119
  if (bodySource || forwardedPropsSource || contextSource) {
91
120
  effect(() => {
@@ -112,8 +141,15 @@ function injectChat(options = {}) {
112
141
  }
113
142
  }, { injector });
114
143
  }
115
- afterNextRender(() => client.mountDevtools(), { injector });
144
+ afterNextRender(() => {
145
+ client.mountDevtools();
146
+ // Delivery-durability resume is transparent: the resumable SSE
147
+ // connection adapter reattaches via the browser's native Last-Event-ID
148
+ // on reconnect. No client-side auto-resume wiring is needed.
149
+ }, { injector });
116
150
  destroyRef.onDestroy(() => {
151
+ // Release the connection first: the counterpart of the `attach` above.
152
+ client.detach();
117
153
  if (liveSource?.()) {
118
154
  client.unsubscribe();
119
155
  }
@@ -177,7 +213,22 @@ function injectChat(options = {}) {
177
213
  const addToolApprovalResponse = async (response) => {
178
214
  await client.addToolApprovalResponse(response);
179
215
  };
180
- // eslint-disable-next-line no-restricted-syntax -- return shape diverges from conditional InjectChatResult<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final signals
216
+ const interrupts = computed(() => interruptState().interrupts, ...(ngDevMode ? [{ debugName: "interrupts" }] : /* istanbul ignore next */ []));
217
+ const pendingInterrupts = computed(() => interruptState().interrupts, ...(ngDevMode ? [{ debugName: "pendingInterrupts" }] : /* istanbul ignore next */ []));
218
+ const interruptErrors = computed(() => interruptState().interruptErrors, ...(ngDevMode ? [{ debugName: "interruptErrors" }] : /* istanbul ignore next */ []));
219
+ const resuming = computed(() => interruptState().resuming, ...(ngDevMode ? [{ debugName: "resuming" }] : /* istanbul ignore next */ []));
220
+ const resolveInterrupts = (resolution) => {
221
+ if (typeof resolution === 'boolean') {
222
+ client.resolveInterrupts(resolution);
223
+ }
224
+ else {
225
+ client.resolveInterrupts(resolution);
226
+ }
227
+ };
228
+ const cancelInterrupts = () => client.cancelInterrupts();
229
+ const retryInterrupts = () => client.retryInterrupts();
230
+ const resumeInterruptsUnsafe = (resumeItems, state) => client.resumeInterruptsUnsafe(resumeItems, state);
231
+ // 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
181
232
  return {
182
233
  messages: messages.asReadonly(),
183
234
  sendMessage,
@@ -196,6 +247,15 @@ function injectChat(options = {}) {
196
247
  clear,
197
248
  addToolResult,
198
249
  addToolApprovalResponse,
250
+ runId: runId.asReadonly(),
251
+ interrupts,
252
+ pendingInterrupts,
253
+ interruptErrors,
254
+ resuming,
255
+ resolveInterrupts,
256
+ cancelInterrupts,
257
+ retryInterrupts,
258
+ resumeInterruptsUnsafe,
199
259
  partial,
200
260
  final,
201
261
  };
@@ -212,15 +272,29 @@ function injectGeneration(options) {
212
272
  assertInInjectionContext(injectGeneration);
213
273
  const destroyRef = inject(DestroyRef);
214
274
  const injector = inject(Injector);
215
- const clientId = options.id || `injectGeneration-${nextId$1++}`;
216
275
  const result = signal(null, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
217
276
  const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
218
277
  const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
219
278
  const status = signal('idle', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
279
+ const runId = signal(null, ...(ngDevMode ? [{ debugName: "runId" }] : /* istanbul ignore next */ []));
280
+ let disposed = false;
220
281
  const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
282
+ // Identity: pass `threadId` alone when set (never also pass deprecated `id`).
221
283
  const clientOptions = {
222
- id: clientId,
223
284
  ...(bodySource !== undefined && { body: bodySource() }),
285
+ ...(options.threadId !== undefined
286
+ ? { threadId: options.threadId }
287
+ : { id: options.id ?? `injectGeneration-${nextId$1++}` }),
288
+ ...(options.persistence !== undefined && {
289
+ persistence: options.persistence,
290
+ }),
291
+ ...(options.hydrateGeneration !== undefined && {
292
+ hydrateGeneration: options.hydrateGeneration,
293
+ }),
294
+ ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
295
+ ...(options.reconstructResult
296
+ ? { reconstructResult: options.reconstructResult }
297
+ : {}),
224
298
  devtoolsBridgeFactory: createGenerationDevtoolsBridge,
225
299
  devtools: {
226
300
  ...options.devtools,
@@ -231,13 +305,38 @@ function injectGeneration(options) {
231
305
  // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
232
306
  // the cast bridges the relationship that the conditional type hides.
233
307
  onResult: ((r) => options.onResult?.(r)),
234
- onError: (e) => options.onError?.(e),
235
- onProgress: (p, m) => options.onProgress?.(p, m),
236
- onChunk: (c) => options.onChunk?.(c),
237
- onResultChange: (r) => result.set(r),
238
- onLoadingChange: (l) => isLoading.set(l),
239
- onErrorChange: (e) => error.set(e),
240
- onStatusChange: (s) => status.set(s),
308
+ onError: (e) => {
309
+ if (!disposed)
310
+ options.onError?.(e);
311
+ },
312
+ onProgress: (p, m) => {
313
+ if (!disposed)
314
+ options.onProgress?.(p, m);
315
+ },
316
+ onChunk: (c) => {
317
+ if (!disposed)
318
+ options.onChunk?.(c);
319
+ },
320
+ onResultChange: (r) => {
321
+ if (!disposed)
322
+ result.set(r);
323
+ },
324
+ onLoadingChange: (l) => {
325
+ if (!disposed)
326
+ isLoading.set(l);
327
+ },
328
+ onErrorChange: (e) => {
329
+ if (!disposed)
330
+ error.set(e);
331
+ },
332
+ onStatusChange: (s) => {
333
+ if (!disposed)
334
+ status.set(s);
335
+ },
336
+ onResumeStateChange: (rs) => {
337
+ if (!disposed)
338
+ runId.set(rs?.runId ?? null);
339
+ },
241
340
  };
242
341
  let client;
243
342
  if (options.connection) {
@@ -257,19 +356,29 @@ function injectGeneration(options) {
257
356
  }
258
357
  if (bodySource) {
259
358
  effect(() => {
260
- client.updateOptions({ body: bodySource() });
359
+ client.updateOptions({
360
+ body: bodySource(),
361
+ });
261
362
  }, { injector });
262
363
  }
263
- afterNextRender(() => client.mountDevtools(), { injector });
264
- destroyRef.onDestroy(() => client.dispose());
364
+ // Mount devtools only. Generation runs are never auto-started after render —
365
+ // persisted state is read-only for display.
366
+ afterNextRender(() => {
367
+ client.mountDevtools();
368
+ }, { injector });
369
+ destroyRef.onDestroy(() => {
370
+ disposed = true;
371
+ client.dispose();
372
+ });
265
373
  return {
266
- generate: ((input) => client.generate(input)),
374
+ generate: (input) => client.generate(input),
267
375
  result: result.asReadonly(),
268
376
  isLoading: isLoading.asReadonly(),
269
377
  error: error.asReadonly(),
270
378
  status: status.asReadonly(),
271
379
  stop: () => client.stop(),
272
380
  reset: () => client.reset(),
381
+ runId: runId.asReadonly(),
273
382
  };
274
383
  }
275
384
 
@@ -280,19 +389,12 @@ function injectGenerateImage(options) {
280
389
  hookName: 'injectGenerateImage',
281
390
  outputKind: 'image',
282
391
  };
283
- const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
392
+ const generation = injectGeneration({
284
393
  ...options,
285
394
  devtools,
395
+ reconstructResult: reconstructImageResult,
286
396
  });
287
- return {
288
- generate: generate,
289
- result,
290
- isLoading,
291
- error,
292
- status,
293
- stop,
294
- reset,
295
- };
397
+ return generation;
296
398
  }
297
399
 
298
400
  /**
@@ -333,19 +435,12 @@ function injectGenerateAudio(options) {
333
435
  hookName: 'injectGenerateAudio',
334
436
  outputKind: 'audio',
335
437
  };
336
- const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
438
+ const generation = injectGeneration({
337
439
  ...options,
338
440
  devtools,
441
+ reconstructResult: reconstructAudioResult,
339
442
  });
340
- return {
341
- generate: generate,
342
- result,
343
- isLoading,
344
- error,
345
- status,
346
- stop,
347
- reset,
348
- };
443
+ return generation;
349
444
  }
350
445
 
351
446
  function injectGenerateSpeech(options) {
@@ -355,19 +450,12 @@ function injectGenerateSpeech(options) {
355
450
  hookName: 'injectGenerateSpeech',
356
451
  outputKind: 'audio',
357
452
  };
358
- const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
453
+ const generation = injectGeneration({
359
454
  ...options,
360
455
  devtools,
456
+ reconstructResult: reconstructSpeechResult,
361
457
  });
362
- return {
363
- generate: generate,
364
- result,
365
- isLoading,
366
- error,
367
- status,
368
- stop,
369
- reset,
370
- };
458
+ return generation;
371
459
  }
372
460
 
373
461
  function injectTranscription(options) {
@@ -377,19 +465,12 @@ function injectTranscription(options) {
377
465
  hookName: 'injectTranscription',
378
466
  outputKind: 'text',
379
467
  };
380
- const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
468
+ const generation = injectGeneration({
381
469
  ...options,
382
470
  devtools,
471
+ reconstructResult: reconstructTranscriptionResult,
383
472
  });
384
- return {
385
- generate: generate,
386
- result,
387
- isLoading,
388
- error,
389
- status,
390
- stop,
391
- reset,
392
- };
473
+ return generation;
393
474
  }
394
475
 
395
476
  function injectAudioRecorder(options = {}) {
@@ -435,19 +516,12 @@ function injectSummarize(options) {
435
516
  hookName: 'injectSummarize',
436
517
  outputKind: 'text',
437
518
  };
438
- const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
519
+ const generation = injectGeneration({
439
520
  ...options,
440
521
  devtools,
522
+ reconstructResult: reconstructSummarizeResult,
441
523
  });
442
- return {
443
- generate: generate,
444
- result,
445
- isLoading,
446
- error,
447
- status,
448
- stop,
449
- reset,
450
- };
524
+ return generation;
451
525
  }
452
526
 
453
527
  let nextId = 0;
@@ -458,17 +532,28 @@ function injectGenerateVideo(options) {
458
532
  assertInInjectionContext(injectGenerateVideo);
459
533
  const destroyRef = inject(DestroyRef);
460
534
  const injector = inject(Injector);
461
- const clientId = options.id || `injectGenerateVideo-${nextId++}`;
462
535
  const result = signal(null, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
463
536
  const jobId = signal(null, ...(ngDevMode ? [{ debugName: "jobId" }] : /* istanbul ignore next */ []));
464
537
  const videoStatus = signal(null, ...(ngDevMode ? [{ debugName: "videoStatus" }] : /* istanbul ignore next */ []));
465
538
  const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
466
539
  const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
467
540
  const status = signal('idle', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
541
+ const runId = signal(null, ...(ngDevMode ? [{ debugName: "runId" }] : /* istanbul ignore next */ []));
542
+ let disposed = false;
468
543
  const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
544
+ // Identity: pass `threadId` alone when set (never also pass deprecated `id`).
469
545
  const baseOptions = {
470
- id: clientId,
471
546
  ...(bodySource !== undefined && { body: bodySource() }),
547
+ ...(options.threadId !== undefined
548
+ ? { threadId: options.threadId }
549
+ : { id: options.id ?? `injectGenerateVideo-${nextId++}` }),
550
+ ...(options.persistence !== undefined && {
551
+ persistence: options.persistence,
552
+ }),
553
+ ...(options.hydrateGeneration !== undefined && {
554
+ hydrateGeneration: options.hydrateGeneration,
555
+ }),
556
+ ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
472
557
  devtoolsBridgeFactory: createVideoDevtoolsBridge,
473
558
  devtools: {
474
559
  ...options.devtools,
@@ -480,17 +565,54 @@ function injectGenerateVideo(options) {
480
565
  // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
481
566
  // the cast bridges the relationship that the conditional type hides.
482
567
  onResult: ((r) => options.onResult?.(r)),
483
- onError: (e) => options.onError?.(e),
484
- onProgress: (p, m) => options.onProgress?.(p, m),
485
- onChunk: (c) => options.onChunk?.(c),
486
- onJobCreated: (id) => options.onJobCreated?.(id),
487
- onStatusUpdate: (s) => options.onStatusUpdate?.(s),
488
- onResultChange: (r) => result.set(r),
489
- onLoadingChange: (l) => isLoading.set(l),
490
- onErrorChange: (e) => error.set(e),
491
- onStatusChange: (s) => status.set(s),
492
- onJobIdChange: (id) => jobId.set(id),
493
- onVideoStatusChange: (s) => videoStatus.set(s),
568
+ onError: (e) => {
569
+ if (!disposed)
570
+ options.onError?.(e);
571
+ },
572
+ onProgress: (p, m) => {
573
+ if (!disposed)
574
+ options.onProgress?.(p, m);
575
+ },
576
+ onChunk: (c) => {
577
+ if (!disposed)
578
+ options.onChunk?.(c);
579
+ },
580
+ onJobCreated: (id) => {
581
+ if (!disposed)
582
+ options.onJobCreated?.(id);
583
+ },
584
+ onStatusUpdate: (s) => {
585
+ if (!disposed)
586
+ options.onStatusUpdate?.(s);
587
+ },
588
+ onResultChange: (r) => {
589
+ if (!disposed)
590
+ result.set(r);
591
+ },
592
+ onLoadingChange: (l) => {
593
+ if (!disposed)
594
+ isLoading.set(l);
595
+ },
596
+ onErrorChange: (e) => {
597
+ if (!disposed)
598
+ error.set(e);
599
+ },
600
+ onStatusChange: (s) => {
601
+ if (!disposed)
602
+ status.set(s);
603
+ },
604
+ onJobIdChange: (id) => {
605
+ if (!disposed)
606
+ jobId.set(id);
607
+ },
608
+ onVideoStatusChange: (s) => {
609
+ if (!disposed)
610
+ videoStatus.set(s);
611
+ },
612
+ onResumeStateChange: (rs) => {
613
+ if (!disposed)
614
+ runId.set(rs?.runId ?? null);
615
+ },
494
616
  };
495
617
  let client;
496
618
  if (options.connection) {
@@ -510,11 +632,20 @@ function injectGenerateVideo(options) {
510
632
  }
511
633
  if (bodySource) {
512
634
  effect(() => {
513
- client.updateOptions({ body: bodySource() });
635
+ client.updateOptions({
636
+ body: bodySource(),
637
+ });
514
638
  }, { injector });
515
639
  }
516
- afterNextRender(() => client.mountDevtools(), { injector });
517
- destroyRef.onDestroy(() => client.dispose());
640
+ // Mount devtools only. Generation runs are never auto-started after render —
641
+ // persisted state is read-only for display.
642
+ afterNextRender(() => {
643
+ client.mountDevtools();
644
+ }, { injector });
645
+ destroyRef.onDestroy(() => {
646
+ disposed = true;
647
+ client.dispose();
648
+ });
518
649
  return {
519
650
  generate: (input) => client.generate(input),
520
651
  result: result.asReadonly(),
@@ -525,6 +656,7 @@ function injectGenerateVideo(options) {
525
656
  status: status.asReadonly(),
526
657
  stop: () => client.stop(),
527
658
  reset: () => client.reset(),
659
+ runId: runId.asReadonly(),
528
660
  };
529
661
  }
530
662