@tanstack/ai-angular 0.3.1 → 0.4.0

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.
@@ -18,6 +18,8 @@ import type {
18
18
  GenerationClientOptions,
19
19
  GenerationClientState,
20
20
  GenerationFetcher,
21
+ GenerationPersistenceOptions,
22
+ GenerationRestoredResult,
21
23
  InferGenerationOutputFromReturn,
22
24
  } from '@tanstack/ai-client'
23
25
  import type { ReactiveOption } from './internal/to-reactive'
@@ -29,12 +31,51 @@ export interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
29
31
  connection?: ConnectConnectionAdapter
30
32
  /** Direct async function for one-shot generation (no streaming protocol needed) */
31
33
  fetcher?: GenerationFetcher<TInput, TResult>
32
- /** Unique identifier for this generation instance */
34
+ /**
35
+ * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
36
+ */
33
37
  id?: string
34
38
  /** Additional request body params. Reactive. */
35
39
  body?: ReactiveOption<Record<string, any>>
36
40
  /** Display options for TanStack AI Devtools. */
37
41
  devtools?: AIDevtoolsDisplayOptions
42
+ /**
43
+ * How this generation persists across reloads.
44
+ * - Omit / `false`: ephemeral, in-memory only.
45
+ * - `true`: server-driven — on mount the client hydrates the last generation
46
+ * for its `threadId` from the server (needs a connection with a
47
+ * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
48
+ */
49
+ persistence?: boolean
50
+ /**
51
+ * The **scope** this generation belongs to: a stable, app-chosen name for the
52
+ * slot successive runs fill — not a link to a chat conversation.
53
+ *
54
+ * The hook starts empty and produces many runs over its life; each gets its
55
+ * own `runId`, but all belong to one scope. Persistence keys on this, so
56
+ * derive it from your own domain and keep it identical across reloads (e.g.
57
+ * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
58
+ * id on the wire, which the protocol requires.
59
+ *
60
+ * **Required whenever `persistence` is set** — an app that cannot name the
61
+ * scope has nothing to restore to. Optional for ephemeral generations, where
62
+ * it falls back to `id` purely to satisfy the wire.
63
+ */
64
+ threadId?: string
65
+ /**
66
+ * Server-driven hydration handler for `persistence: true` when the
67
+ * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
68
+ * `rpcStream()` adapter built without handlers) — typically a one-line
69
+ * server-function call. The connection's own handler takes precedence.
70
+ */
71
+ hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
72
+ /**
73
+ * Re-attach handler that replays a run still generating to completion on
74
+ * mount, when the connection doesn't carry one. Without it, a restored
75
+ * `running` snapshot surfaces as an (interrupted) error. The connection's
76
+ * own handler takes precedence.
77
+ */
78
+ joinRun?: ConnectConnectionAdapter['joinRun']
38
79
  /**
39
80
  * Callback when a result is received. Can optionally return a transformed value.
40
81
  *
@@ -49,11 +90,26 @@ export interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
49
90
  onProgress?: (progress: number, message?: string) => void
50
91
  /** Callback for each stream chunk (connect-based adapter mode only) */
51
92
  onChunk?: (chunk: StreamChunk) => void
93
+ /**
94
+ * @internal Rebuild a typed result from a restored snapshot, injected by each
95
+ * specialized injectable (image / speech / audio / transcription / summarize).
96
+ * Forwarded to the client so a server-hydrate restore repaints `result`.
97
+ */
98
+ reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
52
99
  }
53
100
 
54
- export interface InjectGenerationResult<TOutput> {
101
+ /**
102
+ * Return type for the injectGeneration function.
103
+ *
104
+ * @template TOutput - The output type (after optional transform)
105
+ * @template TInput - The input type accepted by `generate` (defaults to any object)
106
+ */
107
+ export interface InjectGenerationResult<
108
+ TOutput,
109
+ TInput extends Record<string, any> = Record<string, any>,
110
+ > {
55
111
  /** Trigger a generation request */
56
- generate: (input: Record<string, any>) => Promise<void>
112
+ generate: (input: TInput) => Promise<void>
57
113
  /** The generation result, or null if not yet generated */
58
114
  result: Signal<TOutput | null>
59
115
  /** Whether a generation is currently in progress */
@@ -66,6 +122,14 @@ export interface InjectGenerationResult<TOutput> {
66
122
  stop: () => void
67
123
  /** Clear result, error, and return to idle */
68
124
  reset: () => void
125
+ /** Identity of the in-flight run while one is streaming, or null after it ends */
126
+ /**
127
+ * The id of the generation job currently running, or `null` when nothing is in
128
+ * flight. Each call to `generate` is one job with its own id. Pass it to your
129
+ * own endpoint to cancel or poll the provider job — `stop()` only aborts the
130
+ * local stream, it does not stop work already running on the provider.
131
+ */
132
+ runId: Signal<string | null>
69
133
  }
70
134
 
71
135
  // `TTransformed` infers from the `onResult` return position (a covariant
@@ -79,11 +143,15 @@ export function injectGeneration<
79
143
  TResult,
80
144
  TTransformed = void,
81
145
  >(
82
- options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {
146
+ options: Omit<
147
+ InjectGenerationOptions<TInput, TResult>,
148
+ 'onResult' | 'persistence' | 'threadId' | 'id'
149
+ > & {
83
150
  onResult?: (result: TResult) => TTransformed
84
- },
151
+ } & GenerationPersistenceOptions,
85
152
  ): InjectGenerationResult<
86
- InferGenerationOutputFromReturn<TResult, TTransformed>
153
+ InferGenerationOutputFromReturn<TResult, TTransformed>,
154
+ TInput
87
155
  > {
88
156
  assertInInjectionContext(injectGeneration)
89
157
 
@@ -91,19 +159,33 @@ export function injectGeneration<
91
159
 
92
160
  const destroyRef = inject(DestroyRef)
93
161
  const injector = inject(Injector)
94
- const clientId = options.id || `injectGeneration-${nextId++}`
95
162
 
96
163
  const result = signal<TOutput | null>(null)
97
164
  const isLoading = signal(false)
98
165
  const error = signal<Error | undefined>(undefined)
99
166
  const status = signal<GenerationClientState>('idle')
167
+ const runId = signal<string | null>(null)
168
+ let disposed = false
100
169
 
101
170
  const bodySource =
102
171
  options.body !== undefined ? toReactive(options.body) : undefined
103
172
 
173
+ // Identity: pass `threadId` alone when set (never also pass deprecated `id`).
104
174
  const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
105
- id: clientId,
106
175
  ...(bodySource !== undefined && { body: bodySource() }),
176
+ ...(options.threadId !== undefined
177
+ ? { threadId: options.threadId }
178
+ : { id: options.id ?? `injectGeneration-${nextId++}` }),
179
+ ...(options.persistence !== undefined && {
180
+ persistence: options.persistence,
181
+ }),
182
+ ...(options.hydrateGeneration !== undefined && {
183
+ hydrateGeneration: options.hydrateGeneration,
184
+ }),
185
+ ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
186
+ ...(options.reconstructResult
187
+ ? { reconstructResult: options.reconstructResult }
188
+ : {}),
107
189
  devtoolsBridgeFactory: createGenerationDevtoolsBridge,
108
190
  devtools: {
109
191
  ...options.devtools,
@@ -116,13 +198,30 @@ export function injectGeneration<
116
198
  onResult: ((r: TResult) => options.onResult?.(r)) as (
117
199
  result: TResult,
118
200
  ) => TOutput | null | void,
119
- onError: (e: Error) => options.onError?.(e),
120
- onProgress: (p: number, m?: string) => options.onProgress?.(p, m),
121
- onChunk: (c: StreamChunk) => options.onChunk?.(c),
122
- onResultChange: (r: TOutput | null) => result.set(r),
123
- onLoadingChange: (l: boolean) => isLoading.set(l),
124
- onErrorChange: (e: Error | undefined) => error.set(e),
125
- onStatusChange: (s: GenerationClientState) => status.set(s),
201
+ onError: (e: Error) => {
202
+ if (!disposed) options.onError?.(e)
203
+ },
204
+ onProgress: (p: number, m?: string) => {
205
+ if (!disposed) options.onProgress?.(p, m)
206
+ },
207
+ onChunk: (c: StreamChunk) => {
208
+ if (!disposed) options.onChunk?.(c)
209
+ },
210
+ onResultChange: (r: TOutput | null) => {
211
+ if (!disposed) result.set(r)
212
+ },
213
+ onLoadingChange: (l: boolean) => {
214
+ if (!disposed) isLoading.set(l)
215
+ },
216
+ onErrorChange: (e: Error | undefined) => {
217
+ if (!disposed) error.set(e)
218
+ },
219
+ onStatusChange: (s: GenerationClientState) => {
220
+ if (!disposed) status.set(s)
221
+ },
222
+ onResumeStateChange: (rs) => {
223
+ if (!disposed) runId.set(rs?.runId ?? null)
224
+ },
126
225
  }
127
226
 
128
227
  let client: GenerationClient<TInput, TResult, TOutput>
@@ -145,24 +244,35 @@ export function injectGeneration<
145
244
  if (bodySource) {
146
245
  effect(
147
246
  () => {
148
- client.updateOptions({ body: bodySource() })
247
+ client.updateOptions({
248
+ body: bodySource(),
249
+ })
149
250
  },
150
251
  { injector },
151
252
  )
152
253
  }
153
254
 
154
- afterNextRender(() => client.mountDevtools(), { injector })
155
- destroyRef.onDestroy(() => client.dispose())
255
+ // Mount devtools only. Generation runs are never auto-started after render —
256
+ // persisted state is read-only for display.
257
+ afterNextRender(
258
+ () => {
259
+ client.mountDevtools()
260
+ },
261
+ { injector },
262
+ )
263
+ destroyRef.onDestroy(() => {
264
+ disposed = true
265
+ client.dispose()
266
+ })
156
267
 
157
268
  return {
158
- generate: ((input: TInput) => client.generate(input)) as (
159
- input: Record<string, any>,
160
- ) => Promise<void>,
269
+ generate: (input: TInput) => client.generate(input),
161
270
  result: result.asReadonly(),
162
271
  isLoading: isLoading.asReadonly(),
163
272
  error: error.asReadonly(),
164
273
  status: status.asReadonly(),
165
274
  stop: () => client.stop(),
166
275
  reset: () => client.reset(),
276
+ runId: runId.asReadonly(),
167
277
  }
168
278
  }
@@ -1,34 +1,42 @@
1
1
  import { injectGeneration } from './inject-generation'
2
+ import { reconstructSummarizeResult } from '@tanstack/ai-client'
2
3
  import type { Signal } from '@angular/core'
3
4
  import type { SummarizationResult } from '@tanstack/ai'
4
5
  import type {
5
6
  GenerationClientState,
7
+ GenerationPersistenceOptions,
6
8
  InferGenerationOutputFromReturn,
7
9
  SummarizeGenerateInput,
8
10
  } from '@tanstack/ai-client'
9
- import type { InjectGenerationOptions } from './inject-generation'
11
+ import type {
12
+ InjectGenerationOptions,
13
+ InjectGenerationResult,
14
+ } from './inject-generation'
10
15
 
11
16
  export type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<
12
17
  InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,
13
- 'onResult'
18
+ 'onResult' | 'reconstructResult'
14
19
  > & {
15
20
  onResult?: (result: SummarizationResult) => TOutput | null | void
16
21
  }
17
22
 
18
- export interface InjectSummarizeResult<TOutput = SummarizationResult> {
23
+ export interface InjectSummarizeResult<
24
+ TOutput = SummarizationResult,
25
+ > extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
19
26
  generate: (input: SummarizeGenerateInput) => Promise<void>
20
27
  result: Signal<TOutput | null>
21
28
  isLoading: Signal<boolean>
22
29
  error: Signal<Error | undefined>
23
30
  status: Signal<GenerationClientState>
24
- stop: () => void
25
- reset: () => void
26
31
  }
27
32
 
28
33
  export function injectSummarize<TTransformed = void>(
29
- options: Omit<InjectSummarizeOptions, 'onResult'> & {
34
+ options: Omit<
35
+ InjectSummarizeOptions,
36
+ 'onResult' | 'persistence' | 'threadId' | 'id'
37
+ > & {
30
38
  onResult?: (result: SummarizationResult) => TTransformed
31
- },
39
+ } & GenerationPersistenceOptions,
32
40
  ): InjectSummarizeResult<
33
41
  InferGenerationOutputFromReturn<SummarizationResult, TTransformed>
34
42
  > {
@@ -38,20 +46,14 @@ export function injectSummarize<TTransformed = void>(
38
46
  hookName: 'injectSummarize',
39
47
  outputKind: 'text' as const,
40
48
  }
41
- const { generate, result, isLoading, error, status, stop, reset } =
42
- injectGeneration<SummarizeGenerateInput, SummarizationResult, TTransformed>(
43
- {
44
- ...options,
45
- devtools,
46
- },
47
- )
48
- return {
49
- generate: generate as (input: SummarizeGenerateInput) => Promise<void>,
50
- result,
51
- isLoading,
52
- error,
53
- status,
54
- stop,
55
- reset,
56
- }
49
+ const generation = injectGeneration<
50
+ SummarizeGenerateInput,
51
+ SummarizationResult,
52
+ TTransformed
53
+ >({
54
+ ...options,
55
+ devtools,
56
+ reconstructResult: reconstructSummarizeResult,
57
+ })
58
+ return generation
57
59
  }
@@ -1,12 +1,17 @@
1
1
  import { injectGeneration } from './inject-generation'
2
+ import { reconstructTranscriptionResult } from '@tanstack/ai-client'
2
3
  import type { Signal } from '@angular/core'
3
4
  import type { TranscriptionResult } from '@tanstack/ai'
4
5
  import type {
5
6
  GenerationClientState,
7
+ GenerationPersistenceOptions,
6
8
  InferGenerationOutputFromReturn,
7
9
  TranscriptionGenerateInput,
8
10
  } from '@tanstack/ai-client'
9
- import type { InjectGenerationOptions } from './inject-generation'
11
+ import type {
12
+ InjectGenerationOptions,
13
+ InjectGenerationResult,
14
+ } from './inject-generation'
10
15
 
11
16
  export type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<
12
17
  InjectGenerationOptions<
@@ -14,25 +19,28 @@ export type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<
14
19
  TranscriptionResult,
15
20
  TOutput
16
21
  >,
17
- 'onResult'
22
+ 'onResult' | 'reconstructResult'
18
23
  > & {
19
24
  onResult?: (result: TranscriptionResult) => TOutput | null | void
20
25
  }
21
26
 
22
- export interface InjectTranscriptionResult<TOutput = TranscriptionResult> {
27
+ export interface InjectTranscriptionResult<
28
+ TOutput = TranscriptionResult,
29
+ > extends Omit<InjectGenerationResult<TOutput>, 'generate'> {
23
30
  generate: (input: TranscriptionGenerateInput) => Promise<void>
24
31
  result: Signal<TOutput | null>
25
32
  isLoading: Signal<boolean>
26
33
  error: Signal<Error | undefined>
27
34
  status: Signal<GenerationClientState>
28
- stop: () => void
29
- reset: () => void
30
35
  }
31
36
 
32
37
  export function injectTranscription<TTransformed = void>(
33
- options: Omit<InjectTranscriptionOptions, 'onResult'> & {
38
+ options: Omit<
39
+ InjectTranscriptionOptions,
40
+ 'onResult' | 'persistence' | 'threadId' | 'id'
41
+ > & {
34
42
  onResult?: (result: TranscriptionResult) => TTransformed
35
- },
43
+ } & GenerationPersistenceOptions,
36
44
  ): InjectTranscriptionResult<
37
45
  InferGenerationOutputFromReturn<TranscriptionResult, TTransformed>
38
46
  > {
@@ -42,22 +50,14 @@ export function injectTranscription<TTransformed = void>(
42
50
  hookName: 'injectTranscription',
43
51
  outputKind: 'text' as const,
44
52
  }
45
- const { generate, result, isLoading, error, status, stop, reset } =
46
- injectGeneration<
47
- TranscriptionGenerateInput,
48
- TranscriptionResult,
49
- TTransformed
50
- >({
51
- ...options,
52
- devtools,
53
- })
54
- return {
55
- generate: generate as (input: TranscriptionGenerateInput) => Promise<void>,
56
- result,
57
- isLoading,
58
- error,
59
- status,
60
- stop,
61
- reset,
62
- }
53
+ const generation = injectGeneration<
54
+ TranscriptionGenerateInput,
55
+ TranscriptionResult,
56
+ TTransformed
57
+ >({
58
+ ...options,
59
+ devtools,
60
+ reconstructResult: reconstructTranscriptionResult,
61
+ })
62
+ return generation
63
63
  }
package/src/types.ts CHANGED
@@ -2,13 +2,18 @@ import type {
2
2
  AnyClientTool,
3
3
  InferSchemaType,
4
4
  ModelMessage,
5
+ RunAgentResumeItem,
5
6
  SchemaInput,
6
7
  } from '@tanstack/ai'
7
8
  import type {
8
9
  AIDevtoolsDisplayOptions,
10
+ BoundInterrupts,
9
11
  ChatClientOptions,
10
12
  ChatClientState,
13
+ ChatInterrupt,
14
+ ChatInterruptState,
11
15
  ChatRequestBody,
16
+ ChatResumeState,
12
17
  ClientContextOptionFromTools,
13
18
  ConnectionStatus,
14
19
  DistributedOmit,
@@ -72,6 +77,8 @@ export type InjectChatOptions<
72
77
  | 'onConnectionStatusChange'
73
78
  | 'onSessionGeneratingChange'
74
79
  | 'onQueueChange'
80
+ | 'onResumeStateChange'
81
+ | 'onRunIdChange'
75
82
  | 'context'
76
83
  | 'devtools'
77
84
  | 'body'
@@ -142,6 +149,36 @@ interface BaseInjectChatResult<
142
149
  id: string
143
150
  approved: boolean
144
151
  }) => Promise<void>
152
+ /**
153
+ * The id of the run this client has in flight — one it started or rejoined —
154
+ * or `null` when there is none (including while a run sits paused on an
155
+ * interrupt, waiting on approval).
156
+ *
157
+ * A run is one turn of the conversation, so this changes from turn to turn. A
158
+ * whole tool loop stays inside one run, while resuming after an interrupt
159
+ * continues the turn under a new id — so one user message can produce several
160
+ * run ids. Use it to talk to your own server about that run (cancel it, poll
161
+ * it, correlate a log line).
162
+ */
163
+ runId: Signal<string | null>
164
+ /** Immutable bound interrupts for the current interrupted run. */
165
+ interrupts: Signal<BoundInterrupts<TTools>>
166
+ /** @deprecated Use `interrupts`. */
167
+ pendingInterrupts: Signal<BoundInterrupts<TTools>>
168
+ /** Batch-level interrupt errors. */
169
+ interruptErrors: Signal<ChatInterruptState<TTools>['interruptErrors']>
170
+ /** Whether the client is submitting an interrupt batch. */
171
+ resuming: Signal<boolean>
172
+ resolveInterrupts: {
173
+ (approved: boolean): void
174
+ (resolver: (interrupt: ChatInterrupt<TTools>) => undefined): void
175
+ }
176
+ cancelInterrupts: () => void
177
+ retryInterrupts: () => void
178
+ resumeInterruptsUnsafe: (
179
+ resume: Array<RunAgentResumeItem>,
180
+ state?: ChatResumeState,
181
+ ) => Promise<boolean>
145
182
  /** Reload the last assistant message. */
146
183
  reload: () => Promise<void>
147
184
  /** Stop the current response generation. */