ai 7.0.166 → 7.0.168

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/src/ui/chat.ts CHANGED
@@ -159,6 +159,13 @@ export interface ChatState<UI_MESSAGE extends UIMessage> {
159
159
  popMessage: () => void;
160
160
  replaceMessage: (index: number, message: UI_MESSAGE) => void;
161
161
 
162
+ /**
163
+ * Experimental. Messages that are waiting to be sent when
164
+ * `experimental_queue` is enabled. States that don't implement it keep the
165
+ * queue in the chat, without change notifications.
166
+ */
167
+ experimental_queuedMessages?: UI_MESSAGE[];
168
+
162
169
  snapshot: <T>(thing: T) => T;
163
170
  }
164
171
 
@@ -246,6 +253,17 @@ export interface ChatInit<UI_MESSAGE extends UIMessage> {
246
253
  sendAutomaticallyWhen?: (options: {
247
254
  messages: UI_MESSAGE[];
248
255
  }) => boolean | PromiseLike<boolean>;
256
+
257
+ /**
258
+ * Experimental. Queue messages that are sent while a response is in progress
259
+ * or while the assistant waits for a tool result or approval, and send them
260
+ * one at a time after each response finishes. Stopping, an error or an
261
+ * interrupted response pauses the queue until the next message is sent.
262
+ * Editing a message or regenerating clears the queue.
263
+ *
264
+ * @default false
265
+ */
266
+ experimental_queue?: boolean;
249
267
  }
250
268
 
251
269
  export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
@@ -271,6 +289,12 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
271
289
  private onFinish?: ChatInit<UI_MESSAGE>['onFinish'];
272
290
  private onData?: ChatInit<UI_MESSAGE>['onData'];
273
291
  private sendAutomaticallyWhen?: ChatInit<UI_MESSAGE>['sendAutomaticallyWhen'];
292
+ private queueEnabled: boolean;
293
+ private queuedMessagesFallback: UI_MESSAGE[] = [];
294
+ private queuedMessageOptions = new Map<string, ChatRequestOptions>();
295
+ // a stop or an error pauses the queue. a paused response is not waiting for
296
+ // the user, so resuming the queue skips that check:
297
+ private isQueuePaused = false;
274
298
 
275
299
  private pendingMessagePreparations = new Set<AbortController>();
276
300
  private pendingApprovalMessageId: string | undefined;
@@ -298,6 +322,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
298
322
  onFinish,
299
323
  onData,
300
324
  sendAutomaticallyWhen,
325
+ experimental_queue = false,
301
326
  }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
302
327
  state: ChatState<UI_MESSAGE>;
303
328
  }) {
@@ -312,6 +337,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
312
337
  this.onFinish = onFinish;
313
338
  this.onData = onData;
314
339
  this.sendAutomaticallyWhen = sendAutomaticallyWhen;
340
+ this.queueEnabled = experimental_queue;
315
341
  }
316
342
 
317
343
  /**
@@ -356,6 +382,171 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
356
382
  return this.state.messages[this.state.messages.length - 1];
357
383
  }
358
384
 
385
+ /**
386
+ * Experimental. Messages that wait to be sent when `experimental_queue` is
387
+ * enabled, in the order they will be sent.
388
+ */
389
+ get experimental_queuedMessages(): UI_MESSAGE[] {
390
+ return (
391
+ this.state.experimental_queuedMessages ?? this.queuedMessagesFallback
392
+ );
393
+ }
394
+
395
+ private setQueuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {
396
+ if ('experimental_queuedMessages' in this.state) {
397
+ this.state.experimental_queuedMessages = experimental_queuedMessages;
398
+ } else {
399
+ this.queuedMessagesFallback = experimental_queuedMessages;
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Experimental. Removes a queued message so it is not sent.
405
+ */
406
+ experimental_removeQueuedMessage = (id: string): void => {
407
+ this.queuedMessageOptions.delete(id);
408
+ this.setQueuedMessages(
409
+ this.experimental_queuedMessages.filter(message => message.id !== id),
410
+ );
411
+ };
412
+
413
+ /**
414
+ * Experimental. Stops the response in progress and sends the queued message
415
+ * with the given id next. The rest of the queue is sent after it.
416
+ */
417
+ experimental_sendQueuedMessageNow = async (id: string): Promise<void> => {
418
+ const message = this.experimental_queuedMessages.find(
419
+ message => message.id === id,
420
+ );
421
+
422
+ if (message == null) {
423
+ return;
424
+ }
425
+
426
+ this.setQueuedMessages([
427
+ message,
428
+ ...this.experimental_queuedMessages.filter(queued => queued.id !== id),
429
+ ]);
430
+
431
+ await this.stop();
432
+ await this.resumeQueue({ skipWaitForUser: true });
433
+ };
434
+
435
+ // the user sending a message resumes a paused queue (after a stop, an error
436
+ // or an interruption). an answered approval that was not sent yet goes
437
+ // first, the queue continues when its response finishes:
438
+ private async resumeQueue({
439
+ skipWaitForUser,
440
+ }: {
441
+ skipWaitForUser: boolean;
442
+ }): Promise<void> {
443
+ this.isQueuePaused = false;
444
+
445
+ if (!this.isRequestInProgress() && this.hasUnsentApprovalResponse()) {
446
+ await this.sendMessage();
447
+ return;
448
+ }
449
+
450
+ await this.settleQueue({ skipWaitForUser });
451
+ }
452
+
453
+ // editing a message or regenerating rewrites the history that the queued
454
+ // messages were sent after, so they are dropped together with the response
455
+ // in progress:
456
+ private async clearQueueForHistoryChange(): Promise<void> {
457
+ if (!this.queueEnabled) {
458
+ return;
459
+ }
460
+
461
+ this.queuedMessageOptions.clear();
462
+ this.setQueuedMessages([]);
463
+
464
+ if (this.isRequestInProgress()) {
465
+ await this.stop();
466
+ }
467
+ }
468
+
469
+ private isRequestInProgress(): boolean {
470
+ return (
471
+ this.activeResponse != null ||
472
+ this.status === 'submitted' ||
473
+ this.status === 'streaming'
474
+ );
475
+ }
476
+
477
+ // the assistant waits for the user when the last message has a tool call
478
+ // without a result or an approval that has not been sent yet:
479
+ private isWaitingForUser(): boolean {
480
+ const lastMessage = this.lastMessage;
481
+
482
+ return (
483
+ lastMessage?.role === 'assistant' &&
484
+ lastMessage.parts.some(
485
+ part =>
486
+ isToolUIPart(part) &&
487
+ (part.state === 'approval-requested' ||
488
+ part.state === 'approval-responded' ||
489
+ (!part.providerExecuted &&
490
+ (part.state === 'input-streaming' ||
491
+ part.state === 'input-available'))),
492
+ )
493
+ );
494
+ }
495
+
496
+ // an answered approval has to reach the model before the next user message,
497
+ // otherwise its tool call is left without a result:
498
+ private hasUnsentApprovalResponse(): boolean {
499
+ const lastMessage = this.lastMessage;
500
+
501
+ return (
502
+ lastMessage?.role === 'assistant' &&
503
+ lastMessage.parts.some(
504
+ part => isToolUIPart(part) && part.state === 'approval-responded',
505
+ ) &&
506
+ !lastMessage.parts.some(
507
+ part =>
508
+ isToolUIPart(part) &&
509
+ (part.state === 'approval-requested' ||
510
+ (!part.providerExecuted &&
511
+ (part.state === 'input-streaming' ||
512
+ part.state === 'input-available'))),
513
+ )
514
+ );
515
+ }
516
+
517
+ // every path that can leave the chat idle ends here. the queue then either
518
+ // sends its next message, stays paused until the user sends again, or waits
519
+ // for the user to answer a tool call. a stop that happened after the caller
520
+ // captured `stopGeneration` cancels the send:
521
+ private async settleQueue({
522
+ stopGeneration = this.stopGeneration,
523
+ skipWaitForUser = false,
524
+ }: {
525
+ stopGeneration?: number;
526
+ skipWaitForUser?: boolean;
527
+ } = {}): Promise<void> {
528
+ const [message, ...rest] = this.experimental_queuedMessages;
529
+
530
+ if (
531
+ message == null ||
532
+ this.isQueuePaused ||
533
+ this.isRequestInProgress() ||
534
+ this.activeStopCount > 0 ||
535
+ stopGeneration !== this.stopGeneration ||
536
+ (!skipWaitForUser && this.isWaitingForUser())
537
+ ) {
538
+ return;
539
+ }
540
+
541
+ const options = this.queuedMessageOptions.get(message.id);
542
+ this.queuedMessageOptions.delete(message.id);
543
+ this.setQueuedMessages(rest);
544
+
545
+ this.state.pushMessage(message);
546
+
547
+ await this.makeRequest({ trigger: 'submit-message', ...options });
548
+ }
549
+
359
550
  set messages(messages: UI_MESSAGE[]) {
360
551
  this.state.messages = messages;
361
552
  }
@@ -456,7 +647,37 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
456
647
  uiMessage = message;
457
648
  }
458
649
 
650
+ if (
651
+ this.queueEnabled &&
652
+ message.messageId == null &&
653
+ (this.isRequestInProgress() ||
654
+ this.isWaitingForUser() ||
655
+ this.experimental_queuedMessages.length > 0)
656
+ ) {
657
+ const queuedMessage = {
658
+ ...uiMessage,
659
+ id: uiMessage.id ?? this.generateId(),
660
+ role: uiMessage.role ?? 'user',
661
+ metadata: message.metadata,
662
+ } as UI_MESSAGE;
663
+
664
+ if (options != null) {
665
+ this.queuedMessageOptions.set(queuedMessage.id, options);
666
+ }
667
+ this.setQueuedMessages([
668
+ ...this.experimental_queuedMessages,
669
+ queuedMessage,
670
+ ]);
671
+
672
+ // a stopped response is not waiting for the user anymore, so resuming a
673
+ // paused queue skips that check:
674
+ await this.resumeQueue({ skipWaitForUser: this.isQueuePaused });
675
+ return;
676
+ }
677
+
459
678
  if (message.messageId != null) {
679
+ await this.clearQueueForHistoryChange();
680
+
460
681
  const messageIndex = this.state.messages.findIndex(
461
682
  m => m.id === message.messageId,
462
683
  );
@@ -496,6 +717,9 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
496
717
  } as UI_MESSAGE);
497
718
  }
498
719
 
720
+ // sending a new message is the user taking over after a stop or an error:
721
+ this.isQueuePaused = false;
722
+
499
723
  await this.makeRequest({
500
724
  trigger: 'submit-message',
501
725
  messageId: message.messageId,
@@ -513,6 +737,8 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
513
737
  }: {
514
738
  messageId?: string;
515
739
  } & ChatRequestOptions = {}): Promise<void> => {
740
+ await this.clearQueueForHistoryChange();
741
+
516
742
  const messageIndex =
517
743
  messageId == null
518
744
  ? this.state.messages.length - 1
@@ -593,6 +819,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
593
819
  options,
594
820
  }) =>
595
821
  this.jobExecutor.run(async () => {
822
+ const stopGeneration = this.stopGeneration;
596
823
  const messages = this.state.messages;
597
824
 
598
825
  const updatePart = (
@@ -659,8 +886,12 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
659
886
  ...options,
660
887
  });
661
888
  }, shouldSend);
889
+ return;
662
890
  }
663
891
  }
892
+
893
+ // no await to avoid deadlocking
894
+ void this.settleQueue({ stopGeneration });
664
895
  });
665
896
 
666
897
  addToolOutput: ChatAddToolOutputFunction<UI_MESSAGE> = async ({
@@ -671,6 +902,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
671
902
  options,
672
903
  }) =>
673
904
  this.jobExecutor.run(async () => {
905
+ const stopGeneration = this.stopGeneration;
674
906
  const messages = this.state.messages;
675
907
 
676
908
  const updatePart = (
@@ -755,8 +987,13 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
755
987
  }),
756
988
  shouldSend,
757
989
  );
990
+ return;
758
991
  }
759
992
  }
993
+
994
+ // the tool result can be what the queue was waiting for. no await to
995
+ // avoid deadlocking:
996
+ void this.settleQueue({ stopGeneration });
760
997
  });
761
998
 
762
999
  /** @deprecated Use addToolOutput */
@@ -788,6 +1025,10 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
788
1025
  // Stream cancellation can complete while a processing job is still
789
1026
  // blocked in onToolCall. Drain that job and any message update it queued.
790
1027
  await this.jobExecutor.waitForIdle();
1028
+
1029
+ // a stop pauses the queue even when no response was running, e.g. while
1030
+ // the assistant waits for a tool approval:
1031
+ this.isQueuePaused = true;
791
1032
  } finally {
792
1033
  this.activeStopCount--;
793
1034
  }
@@ -829,12 +1070,12 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
829
1070
  private async runAutomaticRequest(
830
1071
  request: () => Promise<void>,
831
1072
  shouldSend?: boolean,
832
- ): Promise<void> {
1073
+ ): Promise<boolean> {
833
1074
  const stopGeneration = this.stopGeneration;
834
1075
  const startedWhileStopping = this.activeStopCount > 0;
835
1076
 
836
1077
  if (!(shouldSend ?? (await this.shouldSendAutomatically()))) {
837
- return;
1078
+ return false;
838
1079
  }
839
1080
 
840
1081
  // A stop invalidates automatic requests that were pending when it started,
@@ -844,10 +1085,11 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
844
1085
  stopGeneration !== this.stopGeneration ||
845
1086
  this.activeStopCount > 0
846
1087
  ) {
847
- return;
1088
+ return false;
848
1089
  }
849
1090
 
850
1091
  await request();
1092
+ return true;
851
1093
  }
852
1094
 
853
1095
  private async makeRequestForToolApproval({
@@ -1216,6 +1458,17 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1216
1458
  });
1217
1459
  }
1218
1460
  } finally {
1461
+ // a response that did not finish (stopped, failed or interrupted)
1462
+ // pauses the queue until the user sends again. a response that finishes
1463
+ // on its own (e.g. an automatic resume) never clears the pause:
1464
+ if (
1465
+ isAbort ||
1466
+ isError ||
1467
+ activeResponse?.state.finishReason === 'interrupted'
1468
+ ) {
1469
+ this.isQueuePaused = true;
1470
+ }
1471
+
1219
1472
  if (this.activeResponse === activeResponse) {
1220
1473
  this.activeResponse = undefined;
1221
1474
  }
@@ -1230,7 +1483,8 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1230
1483
  !isError &&
1231
1484
  activeResponse?.state.finishReason !== 'interrupted'
1232
1485
  ) {
1233
- await this.runAutomaticRequest(() =>
1486
+ const stopGeneration = this.stopGeneration;
1487
+ const sentAutomatically = await this.runAutomaticRequest(() =>
1234
1488
  this.makeRequest({
1235
1489
  trigger: 'submit-message',
1236
1490
  messageId: this.lastMessage?.id,
@@ -1239,6 +1493,13 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1239
1493
  body,
1240
1494
  }),
1241
1495
  );
1496
+
1497
+ // the automatic request settles the queue when it finishes. a stop while
1498
+ // sendAutomaticallyWhen was pending cancels the send too, so a stopped or
1499
+ // replaced chat never sends queued messages on its own:
1500
+ if (!sentAutomatically) {
1501
+ await this.settleQueue({ stopGeneration });
1502
+ }
1242
1503
  }
1243
1504
  }
1244
1505
  }
@@ -43,6 +43,12 @@ export function toUIMessageStream<
43
43
  let outcome: UIMessageStreamOutcome = { status: 'unknown' };
44
44
  let hasFatalFailure = false;
45
45
 
46
+ // streamText follows each invalid tool call with a tool-error part so the
47
+ // model receives a tool result. The tool-input-error chunk already reports
48
+ // the failure, so the tool-error is skipped to avoid a second onError call.
49
+ // TODO AI SDK 8: remove once invalid tool calls no longer inject tool-error parts
50
+ const invalidToolCallIds = new Set<string>();
51
+
46
52
  const setSourceOutcome = (newOutcome: UIMessageStreamOutcome) => {
47
53
  if (
48
54
  !hasFatalFailure &&
@@ -119,18 +125,29 @@ export function toUIMessageStream<
119
125
  new TransformStream({
120
126
  transform: async (part, controller) => {
121
127
  try {
128
+ if (part.type === 'tool-call' && part.invalid) {
129
+ invalidToolCallIds.add(part.toolCallId);
130
+ }
131
+
132
+ const isInvalidToolCallError =
133
+ part.type === 'tool-error' &&
134
+ !part.providerExecuted &&
135
+ invalidToolCallIds.delete(part.toolCallId);
136
+
122
137
  const messageMetadataValue = messageMetadata?.({ part });
123
138
 
124
- const uiMessageChunk = toUIMessageChunk(part, {
125
- tools,
126
- sendReasoning,
127
- sendSources,
128
- sendStart,
129
- sendFinish,
130
- onError,
131
- messageMetadata: messageMetadataValue,
132
- responseMessageId,
133
- });
139
+ const uiMessageChunk = isInvalidToolCallError
140
+ ? undefined
141
+ : toUIMessageChunk(part, {
142
+ tools,
143
+ sendReasoning,
144
+ sendSources,
145
+ sendStart,
146
+ sendFinish,
147
+ onError,
148
+ messageMetadata: messageMetadataValue,
149
+ responseMessageId,
150
+ });
134
151
 
135
152
  if (uiMessageChunk != null && part.type !== 'finish-step') {
136
153
  controller.enqueue(uiMessageChunk);