@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.
@@ -1,6 +1,6 @@
1
- import { AnyClientTool, SchemaInput, ModelMessage, InferSchemaType, StreamChunk, ImageGenerationResult, AudioGenerationResult, TTSResult, TranscriptionResult, SummarizationResult } from '@tanstack/ai';
2
- import { InferredClientContext, DistributedOmit, ChatClientOptions, AIDevtoolsDisplayOptions, ClientContextOptionFromTools, UIMessage, MultimodalContent, SendMessageOptions, QueuedMessage, ChatClientState, ConnectionStatus, ConnectConnectionAdapter, GenerationFetcher, GenerationClientState, InferGenerationOutputFromReturn, ImageGenerateInput, AudioGenerateInput, SpeechGenerateInput, TranscriptionGenerateInput, AudioRecorderOptions, AudioRecording, InferAudioRecordingOutput, SummarizeGenerateInput, VideoGenerateResult, VideoGenerateInput, VideoStatusInfo } from '@tanstack/ai-client';
3
- export { AudioGenerateInput, ChatRequestBody, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, InferChatMessages, MultimodalContent, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, RunAgentInputContext, SendMessageOptions, SpeechGenerateInput, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, UIMessage, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WhenBusy, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from '@tanstack/ai-client';
1
+ import { AnyClientTool, SchemaInput, ModelMessage, RunAgentResumeItem, InferSchemaType, StreamChunk, ImageGenerationResult, AudioGenerationResult, TTSResult, TranscriptionResult, SummarizationResult } from '@tanstack/ai';
2
+ import { InferredClientContext, DistributedOmit, ChatClientOptions, AIDevtoolsDisplayOptions, ClientContextOptionFromTools, UIMessage, MultimodalContent, SendMessageOptions, QueuedMessage, BoundInterrupts, ChatInterruptState, ChatInterrupt, ChatResumeState, ChatClientState, ConnectionStatus, ConnectConnectionAdapter, GenerationFetcher, GenerationRestoredResult, GenerationClientState, GenerationPersistenceOptions, InferGenerationOutputFromReturn, ImageGenerateInput, AudioGenerateInput, SpeechGenerateInput, TranscriptionGenerateInput, AudioRecorderOptions, AudioRecording, InferAudioRecordingOutput, SummarizeGenerateInput, VideoGenerateResult, VideoGenerateInput, VideoStatusInfo } from '@tanstack/ai-client';
3
+ export { AudioGenerateInput, ChatClientPersistence, ChatPersistedState, ChatPersistenceOption, ChatRequestBody, ChatStorageAdapter, ConnectConnectionAdapter, ConnectionAdapter, FetchConnectionOptions, GenerationClientState, ImageGenerateInput, IndexedDBPersistenceOptions, InferChatMessages, MultimodalContent, QueueConfig, QueueOption, QueueStrategy, QueuedMessage, RunAgentInputContext, SendMessageOptions, SpeechGenerateInput, StorageUnavailableError, SubscribeConnectionAdapter, SummarizeGenerateInput, TranscriptionGenerateInput, UIMessage, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo, WebStoragePersistenceOptions, WhenBusy, XhrConnectionOptions, createChatClientOptions, fetchHttpStream, fetchServerSentEvents, indexedDBPersistence, localStoragePersistence, rpcStream, sessionStoragePersistence, stream, xhrHttpStream, xhrServerSentEvents } from '@tanstack/ai-client';
4
4
  import { Signal } from '@angular/core';
5
5
 
6
6
  /**
@@ -26,7 +26,7 @@ type DeepPartial<T> = T extends ReadonlyArray<infer U> ? Array<DeepPartial<U>> :
26
26
  * - `body`, `forwardedProps`, and `live` accept a {@link ReactiveOption} so
27
27
  * they can be a static value, a `Signal`, or a getter and stay reactive.
28
28
  */
29
- type InjectChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientOptions<TTools, TContext>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'context' | 'devtools' | 'body' | 'forwardedProps'> & {
29
+ type InjectChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TSchema extends SchemaInput | undefined = undefined, TContext = InferredClientContext<TTools>> = DistributedOmit<ChatClientOptions<TTools, TContext>, 'onMessagesChange' | 'onLoadingChange' | 'onErrorChange' | 'onStatusChange' | 'onSubscriptionChange' | 'onConnectionStatusChange' | 'onSessionGeneratingChange' | 'onQueueChange' | 'onResumeStateChange' | 'onRunIdChange' | 'context' | 'devtools' | 'body' | 'forwardedProps'> & {
30
30
  /** Display options for TanStack AI Devtools. */
31
31
  devtools?: AIDevtoolsDisplayOptions;
32
32
  /** Additional request body params. Reactive. */
@@ -75,6 +75,33 @@ interface BaseInjectChatResult<TTools extends ReadonlyArray<AnyClientTool> = any
75
75
  id: string;
76
76
  approved: boolean;
77
77
  }) => Promise<void>;
78
+ /**
79
+ * The id of the run this client has in flight — one it started or rejoined —
80
+ * or `null` when there is none (including while a run sits paused on an
81
+ * interrupt, waiting on approval).
82
+ *
83
+ * A run is one turn of the conversation, so this changes from turn to turn. A
84
+ * whole tool loop stays inside one run, while resuming after an interrupt
85
+ * continues the turn under a new id — so one user message can produce several
86
+ * run ids. Use it to talk to your own server about that run (cancel it, poll
87
+ * it, correlate a log line).
88
+ */
89
+ runId: Signal<string | null>;
90
+ /** Immutable bound interrupts for the current interrupted run. */
91
+ interrupts: Signal<BoundInterrupts<TTools>>;
92
+ /** @deprecated Use `interrupts`. */
93
+ pendingInterrupts: Signal<BoundInterrupts<TTools>>;
94
+ /** Batch-level interrupt errors. */
95
+ interruptErrors: Signal<ChatInterruptState<TTools>['interruptErrors']>;
96
+ /** Whether the client is submitting an interrupt batch. */
97
+ resuming: Signal<boolean>;
98
+ resolveInterrupts: {
99
+ (approved: boolean): void;
100
+ (resolver: (interrupt: ChatInterrupt<TTools>) => undefined): void;
101
+ };
102
+ cancelInterrupts: () => void;
103
+ retryInterrupts: () => void;
104
+ resumeInterruptsUnsafe: (resume: Array<RunAgentResumeItem>, state?: ChatResumeState) => Promise<boolean>;
78
105
  /** Reload the last assistant message. */
79
106
  reload: () => Promise<void>;
80
107
  /** Stop the current response generation. */
@@ -104,12 +131,51 @@ interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
104
131
  connection?: ConnectConnectionAdapter;
105
132
  /** Direct async function for one-shot generation (no streaming protocol needed) */
106
133
  fetcher?: GenerationFetcher<TInput, TResult>;
107
- /** Unique identifier for this generation instance */
134
+ /**
135
+ * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
136
+ */
108
137
  id?: string;
109
138
  /** Additional request body params. Reactive. */
110
139
  body?: ReactiveOption<Record<string, any>>;
111
140
  /** Display options for TanStack AI Devtools. */
112
141
  devtools?: AIDevtoolsDisplayOptions;
142
+ /**
143
+ * How this generation persists across reloads.
144
+ * - Omit / `false`: ephemeral, in-memory only.
145
+ * - `true`: server-driven — on mount the client hydrates the last generation
146
+ * for its `threadId` from the server (needs a connection with a
147
+ * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
148
+ */
149
+ persistence?: boolean;
150
+ /**
151
+ * The **scope** this generation belongs to: a stable, app-chosen name for the
152
+ * slot successive runs fill — not a link to a chat conversation.
153
+ *
154
+ * The hook starts empty and produces many runs over its life; each gets its
155
+ * own `runId`, but all belong to one scope. Persistence keys on this, so
156
+ * derive it from your own domain and keep it identical across reloads (e.g.
157
+ * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
158
+ * id on the wire, which the protocol requires.
159
+ *
160
+ * **Required whenever `persistence` is set** — an app that cannot name the
161
+ * scope has nothing to restore to. Optional for ephemeral generations, where
162
+ * it falls back to `id` purely to satisfy the wire.
163
+ */
164
+ threadId?: string;
165
+ /**
166
+ * Server-driven hydration handler for `persistence: true` when the
167
+ * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
168
+ * `rpcStream()` adapter built without handlers) — typically a one-line
169
+ * server-function call. The connection's own handler takes precedence.
170
+ */
171
+ hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
172
+ /**
173
+ * Re-attach handler that replays a run still generating to completion on
174
+ * mount, when the connection doesn't carry one. Without it, a restored
175
+ * `running` snapshot surfaces as an (interrupted) error. The connection's
176
+ * own handler takes precedence.
177
+ */
178
+ joinRun?: ConnectConnectionAdapter['joinRun'];
113
179
  /**
114
180
  * Callback when a result is received. Can optionally return a transformed value.
115
181
  *
@@ -124,10 +190,22 @@ interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
124
190
  onProgress?: (progress: number, message?: string) => void;
125
191
  /** Callback for each stream chunk (connect-based adapter mode only) */
126
192
  onChunk?: (chunk: StreamChunk) => void;
193
+ /**
194
+ * @internal Rebuild a typed result from a restored snapshot, injected by each
195
+ * specialized injectable (image / speech / audio / transcription / summarize).
196
+ * Forwarded to the client so a server-hydrate restore repaints `result`.
197
+ */
198
+ reconstructResult?: (restored: GenerationRestoredResult) => TResult | null;
127
199
  }
128
- interface InjectGenerationResult<TOutput> {
200
+ /**
201
+ * Return type for the injectGeneration function.
202
+ *
203
+ * @template TOutput - The output type (after optional transform)
204
+ * @template TInput - The input type accepted by `generate` (defaults to any object)
205
+ */
206
+ interface InjectGenerationResult<TOutput, TInput extends Record<string, any> = Record<string, any>> {
129
207
  /** Trigger a generation request */
130
- generate: (input: Record<string, any>) => Promise<void>;
208
+ generate: (input: TInput) => Promise<void>;
131
209
  /** The generation result, or null if not yet generated */
132
210
  result: Signal<TOutput | null>;
133
211
  /** Whether a generation is currently in progress */
@@ -140,38 +218,46 @@ interface InjectGenerationResult<TOutput> {
140
218
  stop: () => void;
141
219
  /** Clear result, error, and return to idle */
142
220
  reset: () => void;
221
+ /** Identity of the in-flight run while one is streaming, or null after it ends */
222
+ /**
223
+ * The id of the generation job currently running, or `null` when nothing is in
224
+ * flight. Each call to `generate` is one job with its own id. Pass it to your
225
+ * own endpoint to cancel or poll the provider job — `stop()` only aborts the
226
+ * local stream, it does not stop work already running on the provider.
227
+ */
228
+ runId: Signal<string | null>;
143
229
  }
144
- declare function injectGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {
230
+ declare function injectGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
145
231
  onResult?: (result: TResult) => TTransformed;
146
- }): InjectGenerationResult<InferGenerationOutputFromReturn<TResult, TTransformed>>;
232
+ } & GenerationPersistenceOptions): InjectGenerationResult<InferGenerationOutputFromReturn<TResult, TTransformed>, TInput>;
147
233
 
148
- type InjectGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<InjectGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>, 'onResult'> & {
234
+ type InjectGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<InjectGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>, 'onResult' | 'reconstructResult'> & {
149
235
  onResult?: (result: ImageGenerationResult) => TOutput | null | void;
150
236
  };
151
- interface InjectGenerateImageResult<TOutput = ImageGenerationResult> {
237
+ interface InjectGenerateImageResult<TOutput = ImageGenerationResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
152
238
  generate: (input: ImageGenerateInput) => Promise<void>;
153
239
  result: Signal<TOutput | null>;
154
240
  isLoading: Signal<boolean>;
155
241
  error: Signal<Error | undefined>;
156
242
  status: Signal<GenerationClientState>;
157
- stop: () => void;
158
- reset: () => void;
159
243
  }
160
- declare function injectGenerateImage<TTransformed = void>(options: Omit<InjectGenerateImageOptions, 'onResult'> & {
244
+ declare function injectGenerateImage<TTransformed = void>(options: Omit<InjectGenerateImageOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
161
245
  onResult?: (result: ImageGenerationResult) => TTransformed;
162
- }): InjectGenerateImageResult<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
246
+ } & GenerationPersistenceOptions): InjectGenerateImageResult<InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>>;
163
247
 
164
248
  /**
165
249
  * Options for the injectGenerateAudio injectable.
166
250
  *
167
251
  * @template TOutput - The output type after optional transform (defaults to AudioGenerationResult)
168
252
  */
169
- interface InjectGenerateAudioOptions<TOutput = AudioGenerationResult> {
253
+ interface InjectGenerateAudioOptions<TOutput = AudioGenerationResult> extends Pick<InjectGenerationOptions<AudioGenerateInput, AudioGenerationResult, TOutput>, 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'> {
170
254
  /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
171
255
  connection?: ConnectConnectionAdapter;
172
256
  /** Direct async function for audio generation */
173
257
  fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>;
174
- /** Unique identifier for this generation instance */
258
+ /**
259
+ * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
260
+ */
175
261
  id?: string;
176
262
  /** Additional body parameters to send with connect-based adapter requests. Reactive. */
177
263
  body?: ReactiveOption<Record<string, any>>;
@@ -197,7 +283,7 @@ interface InjectGenerateAudioOptions<TOutput = AudioGenerationResult> {
197
283
  *
198
284
  * @template TOutput - The output type (after optional transform)
199
285
  */
200
- interface InjectGenerateAudioResult<TOutput = AudioGenerationResult> {
286
+ interface InjectGenerateAudioResult<TOutput = AudioGenerationResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
201
287
  /** Trigger audio generation */
202
288
  generate: (input: AudioGenerateInput) => Promise<void>;
203
289
  /** The generation result containing audio, or null */
@@ -208,10 +294,6 @@ interface InjectGenerateAudioResult<TOutput = AudioGenerationResult> {
208
294
  error: Signal<Error | undefined>;
209
295
  /** Current state of the generation */
210
296
  status: Signal<GenerationClientState>;
211
- /** Abort the current generation */
212
- stop: () => void;
213
- /** Clear result, error, and return to idle */
214
- reset: () => void;
215
297
  }
216
298
  /**
217
299
  * Angular injectable for generating audio (music, sound effects) using AI models.
@@ -244,41 +326,37 @@ interface InjectGenerateAudioResult<TOutput = AudioGenerationResult> {
244
326
  * }
245
327
  * ```
246
328
  */
247
- declare function injectGenerateAudio<TTransformed = void>(options: Omit<InjectGenerateAudioOptions, 'onResult'> & {
329
+ declare function injectGenerateAudio<TTransformed = void>(options: Omit<InjectGenerateAudioOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
248
330
  onResult?: (result: AudioGenerationResult) => TTransformed;
249
- }): InjectGenerateAudioResult<InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>>;
331
+ } & GenerationPersistenceOptions): InjectGenerateAudioResult<InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>>;
250
332
 
251
- type InjectGenerateSpeechOptions<TOutput = TTSResult> = Omit<InjectGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>, 'onResult'> & {
333
+ type InjectGenerateSpeechOptions<TOutput = TTSResult> = Omit<InjectGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>, 'onResult' | 'reconstructResult'> & {
252
334
  onResult?: (result: TTSResult) => TOutput | null | void;
253
335
  };
254
- interface InjectGenerateSpeechResult<TOutput = TTSResult> {
336
+ interface InjectGenerateSpeechResult<TOutput = TTSResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
255
337
  generate: (input: SpeechGenerateInput) => Promise<void>;
256
338
  result: Signal<TOutput | null>;
257
339
  isLoading: Signal<boolean>;
258
340
  error: Signal<Error | undefined>;
259
341
  status: Signal<GenerationClientState>;
260
- stop: () => void;
261
- reset: () => void;
262
342
  }
263
- declare function injectGenerateSpeech<TTransformed = void>(options: Omit<InjectGenerateSpeechOptions, 'onResult'> & {
343
+ declare function injectGenerateSpeech<TTransformed = void>(options: Omit<InjectGenerateSpeechOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
264
344
  onResult?: (result: TTSResult) => TTransformed;
265
- }): InjectGenerateSpeechResult<InferGenerationOutputFromReturn<TTSResult, TTransformed>>;
345
+ } & GenerationPersistenceOptions): InjectGenerateSpeechResult<InferGenerationOutputFromReturn<TTSResult, TTransformed>>;
266
346
 
267
- type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<InjectGenerationOptions<TranscriptionGenerateInput, TranscriptionResult, TOutput>, 'onResult'> & {
347
+ type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<InjectGenerationOptions<TranscriptionGenerateInput, TranscriptionResult, TOutput>, 'onResult' | 'reconstructResult'> & {
268
348
  onResult?: (result: TranscriptionResult) => TOutput | null | void;
269
349
  };
270
- interface InjectTranscriptionResult<TOutput = TranscriptionResult> {
350
+ interface InjectTranscriptionResult<TOutput = TranscriptionResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
271
351
  generate: (input: TranscriptionGenerateInput) => Promise<void>;
272
352
  result: Signal<TOutput | null>;
273
353
  isLoading: Signal<boolean>;
274
354
  error: Signal<Error | undefined>;
275
355
  status: Signal<GenerationClientState>;
276
- stop: () => void;
277
- reset: () => void;
278
356
  }
279
- declare function injectTranscription<TTransformed = void>(options: Omit<InjectTranscriptionOptions, 'onResult'> & {
357
+ declare function injectTranscription<TTransformed = void>(options: Omit<InjectTranscriptionOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
280
358
  onResult?: (result: TranscriptionResult) => TTransformed;
281
- }): InjectTranscriptionResult<InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>>;
359
+ } & GenerationPersistenceOptions): InjectTranscriptionResult<InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>>;
282
360
 
283
361
  type InjectAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {
284
362
  /**
@@ -313,21 +391,19 @@ interface InjectAudioRecorderResult<TOutput> {
313
391
  declare function injectAudioRecorder<TOnComplete extends (recording: AudioRecording) => unknown>(options: InjectAudioRecorderOptions<TOnComplete>): InjectAudioRecorderResult<InferAudioRecordingOutput<TOnComplete>>;
314
392
  declare function injectAudioRecorder(options?: InjectAudioRecorderOptions<undefined>): InjectAudioRecorderResult<AudioRecording>;
315
393
 
316
- type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>, 'onResult'> & {
394
+ type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>, 'onResult' | 'reconstructResult'> & {
317
395
  onResult?: (result: SummarizationResult) => TOutput | null | void;
318
396
  };
319
- interface InjectSummarizeResult<TOutput = SummarizationResult> {
397
+ interface InjectSummarizeResult<TOutput = SummarizationResult> extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
320
398
  generate: (input: SummarizeGenerateInput) => Promise<void>;
321
399
  result: Signal<TOutput | null>;
322
400
  isLoading: Signal<boolean>;
323
401
  error: Signal<Error | undefined>;
324
402
  status: Signal<GenerationClientState>;
325
- stop: () => void;
326
- reset: () => void;
327
403
  }
328
- declare function injectSummarize<TTransformed = void>(options: Omit<InjectSummarizeOptions, 'onResult'> & {
404
+ declare function injectSummarize<TTransformed = void>(options: Omit<InjectSummarizeOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
329
405
  onResult?: (result: SummarizationResult) => TTransformed;
330
- }): InjectSummarizeResult<InferGenerationOutputFromReturn<SummarizationResult, TTransformed>>;
406
+ } & GenerationPersistenceOptions): InjectSummarizeResult<InferGenerationOutputFromReturn<SummarizationResult, TTransformed>>;
331
407
 
332
408
  interface InjectGenerateVideoOptions<TOutput = VideoGenerateResult> {
333
409
  connection?: ConnectConnectionAdapter;
@@ -335,6 +411,43 @@ interface InjectGenerateVideoOptions<TOutput = VideoGenerateResult> {
335
411
  id?: string;
336
412
  body?: ReactiveOption<Record<string, any>>;
337
413
  devtools?: AIDevtoolsDisplayOptions;
414
+ /**
415
+ * How this generation persists across reloads.
416
+ * - Omit / `false`: ephemeral, in-memory only.
417
+ * - `true`: server-driven — on mount the client hydrates the last generation
418
+ * for its `threadId` from the server (needs a connection with a
419
+ * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
420
+ */
421
+ persistence?: boolean;
422
+ /**
423
+ * The **scope** this generation belongs to: a stable, app-chosen name for the
424
+ * slot successive runs fill — not a link to a chat conversation.
425
+ *
426
+ * The hook starts empty and produces many runs over its life; each gets its
427
+ * own `runId`, but all belong to one scope. Persistence keys on this, so
428
+ * derive it from your own domain and keep it identical across reloads (e.g.
429
+ * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
430
+ * id on the wire, which the protocol requires.
431
+ *
432
+ * **Required whenever `persistence` is set** — an app that cannot name the
433
+ * scope has nothing to restore to. Optional for ephemeral generations, where
434
+ * it falls back to `id` purely to satisfy the wire.
435
+ */
436
+ threadId?: string;
437
+ /**
438
+ * Server-driven hydration handler for `persistence: true` when the
439
+ * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
440
+ * `rpcStream()` adapter built without handlers) — typically a one-line
441
+ * server-function call. The connection's own handler takes precedence.
442
+ */
443
+ hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
444
+ /**
445
+ * Re-attach handler that replays a run still generating to completion on
446
+ * mount, when the connection doesn't carry one. Without it, a restored
447
+ * `running` snapshot surfaces as an (interrupted) error. The connection's
448
+ * own handler takes precedence.
449
+ */
450
+ joinRun?: ConnectConnectionAdapter['joinRun'];
338
451
  onResult?: (result: VideoGenerateResult) => TOutput | null | void;
339
452
  onError?: (error: Error) => void;
340
453
  onProgress?: (progress: number, message?: string) => void;
@@ -352,10 +465,17 @@ interface InjectGenerateVideoResult<TOutput = VideoGenerateResult> {
352
465
  status: Signal<GenerationClientState>;
353
466
  stop: () => void;
354
467
  reset: () => void;
468
+ /**
469
+ * The id of the generation job currently running, or `null` when nothing is in
470
+ * flight. Each call to `generate` is one job with its own id. Pass it to your
471
+ * own endpoint to cancel or poll the provider job — `stop()` only aborts the
472
+ * local stream, it does not stop work already running on the provider.
473
+ */
474
+ runId: Signal<string | null>;
355
475
  }
356
- declare function injectGenerateVideo<TTransformed = void>(options: Omit<InjectGenerateVideoOptions, 'onResult'> & {
476
+ declare function injectGenerateVideo<TTransformed = void>(options: Omit<InjectGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
357
477
  onResult?: (result: VideoGenerateResult) => TTransformed;
358
- }): InjectGenerateVideoResult<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
478
+ } & GenerationPersistenceOptions): InjectGenerateVideoResult<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
359
479
 
360
480
  export { injectAudioRecorder, injectChat, injectGenerateAudio, injectGenerateImage, injectGenerateSpeech, injectGenerateVideo, injectGeneration, injectSummarize, injectTranscription };
361
481
  export type { DeepPartial, InjectAudioRecorderOptions, InjectAudioRecorderResult, InjectChatOptions, InjectChatResult, InjectGenerateAudioOptions, InjectGenerateAudioResult, InjectGenerateImageOptions, InjectGenerateImageResult, InjectGenerateSpeechOptions, InjectGenerateSpeechResult, InjectGenerateVideoOptions, InjectGenerateVideoResult, InjectGenerationOptions, InjectGenerationResult, InjectSummarizeOptions, InjectSummarizeResult, InjectTranscriptionOptions, InjectTranscriptionResult, ReactiveOption };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-angular",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Angular signals integration for TanStack AI streaming chat, structured outputs, and media generation.",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -45,11 +45,11 @@
45
45
  ],
46
46
  "dependencies": {
47
47
  "tslib": "^2.8.1",
48
- "@tanstack/ai-client": "0.22.1"
48
+ "@tanstack/ai-client": "0.23.1"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@angular/core": ">=21.0.0",
52
- "@tanstack/ai": "^0.42.0"
52
+ "@tanstack/ai": "^0.43.1"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@analogjs/vite-plugin-angular": "^2.6.2",
@@ -63,18 +63,18 @@
63
63
  "jsdom": "^27.2.0",
64
64
  "ng-packagr": "^21.2.0",
65
65
  "typescript": "5.9.3",
66
- "vitest": "^4.0.14",
66
+ "vitest": "^4.1.10",
67
67
  "zod": "^4.2.0",
68
68
  "zone.js": "^0.15.0",
69
- "@tanstack/ai": "0.42.0"
69
+ "@tanstack/ai": "0.43.1"
70
70
  },
71
71
  "scripts": {
72
72
  "clean": "premove ./build ./dist",
73
- "test:eslint": "eslint ./src",
73
+ "test:oxlint": "oxlint src --type-aware",
74
74
  "test:lib": "vitest run",
75
75
  "test:lib:dev": "vitest",
76
76
  "test:types": "tsc",
77
77
  "test:build": "publint --strict",
78
- "build": "ng-packagr -p ng-package.json -c tsconfig.build.json && rm -rf ./dist/package.json"
78
+ "build": "ng-packagr -p ng-package.json -c tsconfig.build.json && premove ./dist/package.json"
79
79
  }
80
80
  }
package/src/index.ts CHANGED
@@ -77,6 +77,16 @@ export type {
77
77
  // Re-export from @tanstack/ai-client for convenience
78
78
  export {
79
79
  fetchServerSentEvents,
80
+ localStoragePersistence,
81
+ sessionStoragePersistence,
82
+ indexedDBPersistence,
83
+ StorageUnavailableError,
84
+ type ChatClientPersistence,
85
+ type ChatPersistedState,
86
+ type ChatPersistenceOption,
87
+ type ChatStorageAdapter,
88
+ type WebStoragePersistenceOptions,
89
+ type IndexedDBPersistenceOptions,
80
90
  fetchHttpStream,
81
91
  xhrServerSentEvents,
82
92
  xhrHttpStream,
@@ -15,11 +15,15 @@ import type {
15
15
  AnyClientTool,
16
16
  InferSchemaType,
17
17
  ModelMessage,
18
+ RunAgentResumeItem,
18
19
  SchemaInput,
19
20
  StreamChunk,
20
21
  } from '@tanstack/ai'
21
22
  import type {
22
23
  ChatClientState,
24
+ ChatInterrupt,
25
+ ChatInterruptState,
26
+ ChatResumeState,
23
27
  ConnectionStatus,
24
28
  InferredClientContext,
25
29
  QueuedMessage,
@@ -34,6 +38,9 @@ import type {
34
38
  UIMessage,
35
39
  } from './types'
36
40
 
41
+ const EMPTY_INTERRUPTS = Object.freeze([])
42
+ const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
43
+
37
44
  let nextId = 0
38
45
 
39
46
  export function injectChat<
@@ -66,6 +73,13 @@ export function injectChat<
66
73
  const connectionStatus = signal<ConnectionStatus>('disconnected')
67
74
  const sessionGenerating = signal(false)
68
75
  const queue = signal<Array<QueuedMessage>>([])
76
+ const runId = signal<string | null>(null)
77
+ const interruptState = signal<ChatInterruptState<TTools>>({
78
+ interrupts: EMPTY_INTERRUPTS,
79
+ pendingInterrupts: EMPTY_INTERRUPTS,
80
+ interruptErrors: EMPTY_INTERRUPT_ERRORS,
81
+ resuming: false,
82
+ })
69
83
 
70
84
  // Reactive option sources. Plain values become constant computeds.
71
85
  const bodySource =
@@ -93,6 +107,9 @@ export function injectChat<
93
107
  ...(options.persistence !== undefined && {
94
108
  persistence: options.persistence,
95
109
  }),
110
+ ...(options.initialResumeSnapshot !== undefined && {
111
+ initialResumeSnapshot: options.initialResumeSnapshot,
112
+ }),
96
113
  ...(bodySource !== undefined && { body: bodySource() }),
97
114
  ...(options.threadId !== undefined && { threadId: options.threadId }),
98
115
  ...(forwardedPropsSource !== undefined && {
@@ -109,6 +126,15 @@ export function injectChat<
109
126
  onChunk: (chunk: StreamChunk) => options.onChunk?.(chunk),
110
127
  onFinish: (message) => options.onFinish?.(message),
111
128
  onError: (err) => options.onError?.(err),
129
+ onRunIdChange: (nextRunId) => runId.set(nextRunId),
130
+ // No `onResumeStateChange`: the run identity is surfaced as the `runId`
131
+ // signal (via `onRunIdChange`) and pending interrupts arrive through
132
+ // `onInterruptStateChange`, so there is nothing left for it to do — and it
133
+ // is not a public option here, matching the other framework packages.
134
+ onInterruptStateChange: (nextInterruptState) => {
135
+ interruptState.set(nextInterruptState)
136
+ options.onInterruptStateChange?.(nextInterruptState)
137
+ },
112
138
  tools: options.tools,
113
139
  onCustomEvent: (eventType, data, context) =>
114
140
  options.onCustomEvent?.(eventType, data, context),
@@ -127,6 +153,15 @@ export function injectChat<
127
153
  })
128
154
 
129
155
  messages.set(client.getMessages())
156
+ interruptState.set(client.getInterruptState())
157
+
158
+ // START TAILING HERE, not in the constructor. A client is idle until something
159
+ // attaches it, so a client that gets built and thrown away never opens a
160
+ // connection — an unreachable stream would hold one of the browser's ~6
161
+ // connections per origin until the page reloaded. `inject*` runs in an injection
162
+ // context tied to the consumer's lifetime, and `destroyRef.onDestroy` below is the
163
+ // matching `detach`.
164
+ client.attach()
130
165
 
131
166
  // Sync reactive body / forwardedProps / context to the client.
132
167
  if (bodySource || forwardedPropsSource || contextSource) {
@@ -161,9 +196,19 @@ export function injectChat<
161
196
  )
162
197
  }
163
198
 
164
- afterNextRender(() => client.mountDevtools(), { injector })
199
+ afterNextRender(
200
+ () => {
201
+ client.mountDevtools()
202
+ // Delivery-durability resume is transparent: the resumable SSE
203
+ // connection adapter reattaches via the browser's native Last-Event-ID
204
+ // on reconnect. No client-side auto-resume wiring is needed.
205
+ },
206
+ { injector },
207
+ )
165
208
 
166
209
  destroyRef.onDestroy(() => {
210
+ // Release the connection first: the counterpart of the `attach` above.
211
+ client.detach()
167
212
  if (liveSource?.()) {
168
213
  client.unsubscribe()
169
214
  } else {
@@ -240,8 +285,27 @@ export function injectChat<
240
285
  }) => {
241
286
  await client.addToolApprovalResponse(response)
242
287
  }
288
+ const interrupts = computed(() => interruptState().interrupts)
289
+ const pendingInterrupts = computed(() => interruptState().interrupts)
290
+ const interruptErrors = computed(() => interruptState().interruptErrors)
291
+ const resuming = computed(() => interruptState().resuming)
292
+ const resolveInterrupts = (
293
+ resolution: boolean | ((interrupt: ChatInterrupt<TTools>) => 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)
243
307
 
244
- // 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
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
245
309
  return {
246
310
  messages: messages.asReadonly(),
247
311
  sendMessage,
@@ -260,6 +324,15 @@ export function injectChat<
260
324
  clear,
261
325
  addToolResult,
262
326
  addToolApprovalResponse,
327
+ runId: runId.asReadonly(),
328
+ interrupts,
329
+ pendingInterrupts,
330
+ interruptErrors,
331
+ resuming,
332
+ resolveInterrupts,
333
+ cancelInterrupts,
334
+ retryInterrupts,
335
+ resumeInterruptsUnsafe,
263
336
  partial,
264
337
  final,
265
338
  } as unknown as InjectChatResult<TTools, TSchema>