@cloudflare/ai-chat 0.5.2 → 0.5.4

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
@@ -253,8 +253,25 @@ await this.saveMessages((messages) => [
253
253
  ]);
254
254
  ```
255
255
 
256
- `saveMessages()` returns `{ requestId, status }` — check `status` to detect
257
- whether the turn was skipped (e.g. because the chat was cleared while queued).
256
+ `saveMessages()` returns `{ requestId, status }`. The `status` field is
257
+ `"completed"` when the turn ran, `"skipped"` when it was invalidated mid-flight
258
+ (e.g. by a `chat-clear`), or `"aborted"` when an external `AbortSignal` cancelled
259
+ it. Pass `options.signal` to cancel a programmatic turn from outside without
260
+ knowing the internally-generated request id:
261
+
262
+ ```typescript
263
+ const controller = new AbortController();
264
+ const result = await this.saveMessages([userMsg], {
265
+ signal: controller.signal
266
+ });
267
+ if (result.status === "aborted") {
268
+ // ...
269
+ }
270
+ ```
271
+
272
+ This is the same shape `Think.saveMessages` uses — see
273
+ [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406)
274
+ for the helper-as-sub-agent pattern that motivated the API.
258
275
 
259
276
  ## Storage Management
260
277
 
@@ -337,18 +354,18 @@ async onChatMessage(onFinish, options) {
337
354
 
338
355
  Extends `Agent` from the `agents` package.
339
356
 
340
- | Property / Method | Type | Description |
341
- | ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------- |
342
- | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
343
- | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
344
- | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
345
- | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
346
- | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
347
- | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
348
- | `saveMessages(messages)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. |
349
- | `waitUntilStable()` | `Promise<boolean>` | Protected helper to wait until the conversation is fully stable |
350
- | `resetTurnState()` | `void` | Protected helper to abort the active turn and invalidate queued continuations |
351
- | `hasPendingInteraction()` | `boolean` | Protected helper to detect pending tool input or approval in assistant messages |
357
+ | Property / Method | Type | Description |
358
+ | ------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
359
+ | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
360
+ | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
361
+ | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
362
+ | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
363
+ | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
364
+ | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
365
+ | `saveMessages(messages, options?)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. `options.signal` cancels the turn externally. |
366
+ | `waitUntilStable()` | `Promise<boolean>` | Protected helper to wait until the conversation is fully stable |
367
+ | `resetTurnState()` | `void` | Protected helper to abort the active turn and invalidate queued continuations |
368
+ | `hasPendingInteraction()` | `boolean` | Protected helper to detect pending tool input or approval in assistant messages |
352
369
 
353
370
  ### `useAgentChat(options)`
354
371
 
package/dist/index.d.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  MessageConcurrency,
12
12
  MessageConcurrency as MessageConcurrency$1,
13
13
  ResumableStream,
14
+ SaveMessagesOptions,
15
+ SaveMessagesOptions as SaveMessagesOptions$1,
14
16
  SaveMessagesResult,
15
17
  SaveMessagesResult as SaveMessagesResult$1,
16
18
  createToolsFromClientSchemas
@@ -354,6 +356,34 @@ declare class AIChatAgent<
354
356
  * the built-in handler calls it automatically.
355
357
  */
356
358
  protected resetTurnState(): void;
359
+ /**
360
+ * Abort a single in-flight chat turn by request id.
361
+ *
362
+ * Equivalent to the cancel path that fires when a client sends a
363
+ * `chat-request-cancel` WebSocket message — the inference loop's
364
+ * signal aborts and the turn's `ChatResponseResult` reports
365
+ * `status: "aborted"`. No-op if no controller exists for `requestId`.
366
+ *
367
+ * Most callers don't have the request id and want
368
+ * {@link abortAllRequests} instead. Prefer
369
+ * {@link SaveMessagesOptions.signal} when driving a turn
370
+ * programmatically — it threads the abort intent in from the start
371
+ * without requiring the caller to know the id.
372
+ */
373
+ protected abortRequest(requestId: string, reason?: unknown): void;
374
+ /**
375
+ * Abort every in-flight chat turn on this agent.
376
+ *
377
+ * Aborts all controllers in the registry and clears it. Used by
378
+ * subclasses that drive single-purpose turns (e.g. an RPC-driven
379
+ * sub-agent helper that runs one turn at a time) and want a coarse
380
+ * "cancel whatever is running" handle without tracking request ids.
381
+ *
382
+ * Does NOT reset queued turns, continuation timers, or submit
383
+ * concurrency state — use {@link resetTurnState} for the full
384
+ * teardown that runs on `chat-clear`.
385
+ */
386
+ protected abortAllRequests(): void;
357
387
  private _awaitWithDeadline;
358
388
  private _messageHasPendingInteraction;
359
389
  /**
@@ -364,6 +394,12 @@ declare class AIChatAgent<
364
394
  private _enqueueAutoContinuation;
365
395
  private _awaitPendingAutoContinuationPrerequisite;
366
396
  private _queueAutoContinuation;
397
+ /**
398
+ * @returns `true` if the registry's controller for `requestId` was
399
+ * aborted during the turn (so the caller can surface
400
+ * `status: "aborted"` to the public API). Returns `false` for
401
+ * successful or errored completion.
402
+ */
367
403
  private _runProgrammaticChatTurn;
368
404
  /**
369
405
  * Handle incoming chat messages and generate a response
@@ -449,16 +485,23 @@ declare class AIChatAgent<
449
485
  * await this.saveMessages((messages) => [...messages, syntheticMessage]);
450
486
  * ```
451
487
  *
452
- * Returns `{ requestId, status }` so callers can detect whether the turn
453
- * ran (`"completed"`) or was skipped because the chat was cleared
454
- * (`"skipped"`).
488
+ * Pass `options.signal` to cancel the turn from outside without knowing
489
+ * the internally-generated request id. The signal is linked to the
490
+ * registry's controller for this turn — when it aborts, the inference
491
+ * loop's signal aborts and the result reports `status: "aborted"`.
492
+ * Pre-aborted signals short-circuit before any model work runs.
493
+ *
494
+ * Returns `{ requestId, status }` where `status` is `"completed"` when
495
+ * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
496
+ * when an external signal cancelled it mid-stream.
455
497
  */
456
498
  saveMessages(
457
499
  messages:
458
500
  | UIMessage[]
459
501
  | ((
460
502
  currentMessages: readonly UIMessage[]
461
- ) => UIMessage[] | Promise<UIMessage[]>)
503
+ ) => UIMessage[] | Promise<UIMessage[]>),
504
+ options?: SaveMessagesOptions$1
462
505
  ): Promise<SaveMessagesResult$1>;
463
506
  /**
464
507
  * Trigger a continuation of the last assistant message without inserting
@@ -471,9 +514,13 @@ declare class AIChatAgent<
471
514
  * used by tool auto-continuation.
472
515
  *
473
516
  * Returns early if there is no assistant message to continue from.
517
+ *
518
+ * Pass `options.signal` to cancel the continuation from outside —
519
+ * matches the {@link saveMessages} contract.
474
520
  */
475
521
  protected continueLastTurn(
476
- body?: Record<string, unknown>
522
+ body?: Record<string, unknown>,
523
+ options?: SaveMessagesOptions$1
477
524
  ): Promise<SaveMessagesResult$1>;
478
525
  /**
479
526
  * Context passed to `onChatRecovery` when an interrupted chat stream
@@ -612,19 +659,41 @@ declare class AIChatAgent<
612
659
  * the AI is still streaming), then retries persisted messages with backoff
613
660
  * in case streaming completes between attempts.
614
661
  *
662
+ * `applyUpdate` may return its argument by reference (or `{ ...part }`
663
+ * with no semantic changes) to signal an idempotent no-op — this is
664
+ * detected via `_isToolPartUnchanged` and short-circuits the SQLite
665
+ * write and `MESSAGE_UPDATED` broadcast.
666
+ *
615
667
  * @param toolCallId - The tool call ID to find
616
668
  * @param callerName - Name for log messages (e.g. "_applyToolResult")
617
669
  * @param matchStates - Which tool part states to match
618
670
  * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
619
- * @returns true if the update was applied, false if not found or state didn't match
671
+ * @returns true if the update was applied (or matched as an idempotent
672
+ * no-op), false if no matching part was found
620
673
  */
621
674
  private _findAndUpdateToolPart;
675
+ /**
676
+ * Returns true if `applied` is the same reference as `original`, or if
677
+ * the two have identical state-relevant fields. Used by
678
+ * `_findAndUpdateToolPart` to detect idempotent re-applies and skip
679
+ * SQLite writes plus `MESSAGE_UPDATED` broadcasts.
680
+ */
681
+ private static _isToolPartUnchanged;
622
682
  /**
623
683
  * Applies a tool result to an existing assistant message.
624
684
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
625
685
  * The server is the source of truth, so we update the message here and broadcast
626
686
  * the update to all clients.
627
687
  *
688
+ * `output-available` and `output-error` are accepted as valid starting
689
+ * states for *idempotent* re-application — duplicate WS frames, second
690
+ * tabs re-running the same tool, and provider-replay round-trips all
691
+ * become silent no-ops rather than a warn + skipped update. The first
692
+ * applied terminal result wins; subsequent results carrying *different*
693
+ * data are also dropped (preserving the existing "first write wins"
694
+ * contract — see `client-tool-duplicate-message.test.ts`). See issue
695
+ * #1404.
696
+ *
628
697
  * @param toolCallId - The tool call ID this result is for
629
698
  * @param _toolName - The name of the tool (unused, kept for API compat)
630
699
  * @param output - The output from the tool execution
@@ -664,6 +733,7 @@ export {
664
733
  type ClientToolSchema,
665
734
  type MessageConcurrency,
666
735
  OnChatMessageOptions,
736
+ type SaveMessagesOptions,
667
737
  type SaveMessagesResult,
668
738
  createToolsFromClientSchemas
669
739
  };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
4
+ import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/index.ts
7
7
  const TIMED_OUT = Symbol("timed-out");
@@ -690,6 +690,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
690
690
  this._continuation.clearAll();
691
691
  this._pendingChatResponseResults.length = 0;
692
692
  }
693
+ /**
694
+ * Abort a single in-flight chat turn by request id.
695
+ *
696
+ * Equivalent to the cancel path that fires when a client sends a
697
+ * `chat-request-cancel` WebSocket message — the inference loop's
698
+ * signal aborts and the turn's `ChatResponseResult` reports
699
+ * `status: "aborted"`. No-op if no controller exists for `requestId`.
700
+ *
701
+ * Most callers don't have the request id and want
702
+ * {@link abortAllRequests} instead. Prefer
703
+ * {@link SaveMessagesOptions.signal} when driving a turn
704
+ * programmatically — it threads the abort intent in from the start
705
+ * without requiring the caller to know the id.
706
+ */
707
+ abortRequest(requestId, reason) {
708
+ this._abortRegistry.cancel(requestId, reason);
709
+ }
710
+ /**
711
+ * Abort every in-flight chat turn on this agent.
712
+ *
713
+ * Aborts all controllers in the registry and clears it. Used by
714
+ * subclasses that drive single-purpose turns (e.g. an RPC-driven
715
+ * sub-agent helper that runs one turn at a time) and want a coarse
716
+ * "cancel whatever is running" handle without tracking request ids.
717
+ *
718
+ * Does NOT reset queued turns, continuation timers, or submit
719
+ * concurrency state — use {@link resetTurnState} for the full
720
+ * teardown that runs on `chat-clear`.
721
+ */
722
+ abortAllRequests() {
723
+ this._abortRegistry.destroyAll();
724
+ }
693
725
  async _awaitWithDeadline(promise, deadline) {
694
726
  if (deadline == null) return promise;
695
727
  const remainingMs = Math.max(0, deadline - Date.now());
@@ -843,8 +875,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
843
875
  console.error(errorPrefix, error);
844
876
  });
845
877
  }
846
- async _runProgrammaticChatTurn(requestId, clientTools, body) {
878
+ /**
879
+ * @returns `true` if the registry's controller for `requestId` was
880
+ * aborted during the turn (so the caller can surface
881
+ * `status: "aborted"` to the public API). Returns `false` for
882
+ * successful or errored completion.
883
+ */
884
+ async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
847
885
  this._setRequestContext(clientTools, body);
886
+ let wasAborted = false;
848
887
  await this._tryCatchChat(async () => {
849
888
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
850
889
  agent: this,
@@ -853,8 +892,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
853
892
  email: void 0
854
893
  }, async () => {
855
894
  const abortSignal = this._abortRegistry.getSignal(requestId);
856
- const programmaticBody = async () => {
857
- try {
895
+ const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
896
+ try {
897
+ const programmaticBody = async () => {
858
898
  const response = await this.onChatMessage(() => {}, {
859
899
  requestId,
860
900
  abortSignal,
@@ -863,16 +903,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
863
903
  continuation: false
864
904
  });
865
905
  if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
866
- } finally {
867
- this._abortRegistry.remove(requestId);
868
- }
869
- };
870
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
871
- await programmaticBody();
872
- });
873
- else await programmaticBody();
906
+ };
907
+ if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
908
+ await programmaticBody();
909
+ });
910
+ else await programmaticBody();
911
+ } finally {
912
+ if (abortSignal?.aborted) wasAborted = true;
913
+ detachExternal();
914
+ this._abortRegistry.remove(requestId);
915
+ }
874
916
  });
875
917
  });
918
+ return wasAborted;
876
919
  }
877
920
  /**
878
921
  * Handle incoming chat messages and generate a response
@@ -959,16 +1002,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
959
1002
  * await this.saveMessages((messages) => [...messages, syntheticMessage]);
960
1003
  * ```
961
1004
  *
962
- * Returns `{ requestId, status }` so callers can detect whether the turn
963
- * ran (`"completed"`) or was skipped because the chat was cleared
964
- * (`"skipped"`).
1005
+ * Pass `options.signal` to cancel the turn from outside without knowing
1006
+ * the internally-generated request id. The signal is linked to the
1007
+ * registry's controller for this turn — when it aborts, the inference
1008
+ * loop's signal aborts and the result reports `status: "aborted"`.
1009
+ * Pre-aborted signals short-circuit before any model work runs.
1010
+ *
1011
+ * Returns `{ requestId, status }` where `status` is `"completed"` when
1012
+ * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
1013
+ * when an external signal cancelled it mid-stream.
965
1014
  */
966
- async saveMessages(messages) {
1015
+ async saveMessages(messages, options) {
967
1016
  const requestId = nanoid();
968
1017
  const clientTools = this._lastClientTools;
969
1018
  const body = this._lastBody;
970
1019
  const epoch = this._turnQueue.generation;
971
1020
  let status = "completed";
1021
+ let wasAborted = false;
972
1022
  await this._runExclusiveChatTurn(requestId, async () => {
973
1023
  const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
974
1024
  if (this._turnQueue.generation !== epoch) {
@@ -980,9 +1030,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
980
1030
  status = "skipped";
981
1031
  return;
982
1032
  }
983
- await this._runProgrammaticChatTurn(requestId, clientTools, body);
1033
+ wasAborted = await this._runProgrammaticChatTurn(requestId, clientTools, body, options?.signal);
984
1034
  }, { epoch });
985
1035
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1036
+ else if (wasAborted && status === "completed") status = "aborted";
986
1037
  return {
987
1038
  requestId,
988
1039
  status
@@ -999,8 +1050,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
999
1050
  * used by tool auto-continuation.
1000
1051
  *
1001
1052
  * Returns early if there is no assistant message to continue from.
1053
+ *
1054
+ * Pass `options.signal` to cancel the continuation from outside —
1055
+ * matches the {@link saveMessages} contract.
1002
1056
  */
1003
- async continueLastTurn(body) {
1057
+ async continueLastTurn(body, options) {
1004
1058
  if (!this._findLastAssistantMessage()) return {
1005
1059
  requestId: "",
1006
1060
  status: "skipped"
@@ -1010,6 +1064,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1010
1064
  const resolvedBody = body ?? this._lastBody;
1011
1065
  const epoch = this._turnQueue.generation;
1012
1066
  let status = "completed";
1067
+ let wasAborted = false;
1013
1068
  await this._runExclusiveChatTurn(requestId, async () => {
1014
1069
  if (this._turnQueue.generation !== epoch) {
1015
1070
  status = "skipped";
@@ -1025,6 +1080,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1025
1080
  email: void 0
1026
1081
  }, async () => {
1027
1082
  const abortSignal = this._abortRegistry.getSignal(requestId);
1083
+ const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
1028
1084
  try {
1029
1085
  const response = await this.onChatMessage(() => {}, {
1030
1086
  requestId,
@@ -1038,6 +1094,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1038
1094
  chatMessageId: requestId
1039
1095
  });
1040
1096
  } finally {
1097
+ if (abortSignal?.aborted) wasAborted = true;
1098
+ detachExternal();
1041
1099
  this._abortRegistry.remove(requestId);
1042
1100
  }
1043
1101
  });
@@ -1049,6 +1107,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1049
1107
  else await turnBody();
1050
1108
  }, { epoch });
1051
1109
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1110
+ else if (wasAborted && status === "completed") status = "aborted";
1052
1111
  return {
1053
1112
  requestId,
1054
1113
  status
@@ -1411,11 +1470,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
1411
1470
  * the AI is still streaming), then retries persisted messages with backoff
1412
1471
  * in case streaming completes between attempts.
1413
1472
  *
1473
+ * `applyUpdate` may return its argument by reference (or `{ ...part }`
1474
+ * with no semantic changes) to signal an idempotent no-op — this is
1475
+ * detected via `_isToolPartUnchanged` and short-circuits the SQLite
1476
+ * write and `MESSAGE_UPDATED` broadcast.
1477
+ *
1414
1478
  * @param toolCallId - The tool call ID to find
1415
1479
  * @param callerName - Name for log messages (e.g. "_applyToolResult")
1416
1480
  * @param matchStates - Which tool part states to match
1417
1481
  * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
1418
- * @returns true if the update was applied, false if not found or state didn't match
1482
+ * @returns true if the update was applied (or matched as an idempotent
1483
+ * no-op), false if no matching part was found
1419
1484
  */
1420
1485
  async _findAndUpdateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
1421
1486
  let message;
@@ -1435,23 +1500,30 @@ var AIChatAgent = class AIChatAgent extends Agent {
1435
1500
  return false;
1436
1501
  }
1437
1502
  const isStreamingMessage = message === this._streamingMessage;
1438
- let updated = false;
1503
+ let wasFound = false;
1504
+ let hasRealChange = false;
1439
1505
  if (isStreamingMessage) {
1440
1506
  for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
1507
+ wasFound = true;
1441
1508
  const applied = applyUpdate(part);
1442
- Object.assign(part, applied);
1443
- updated = true;
1509
+ if (!AIChatAgent._isToolPartUnchanged(part, applied)) {
1510
+ Object.assign(part, applied);
1511
+ hasRealChange = true;
1512
+ }
1444
1513
  break;
1445
1514
  }
1446
1515
  } else {
1447
1516
  const updatedParts = message.parts.map((part) => {
1448
1517
  if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
1449
- updated = true;
1450
- return applyUpdate(part);
1518
+ wasFound = true;
1519
+ const applied = applyUpdate(part);
1520
+ if (AIChatAgent._isToolPartUnchanged(part, applied)) return part;
1521
+ hasRealChange = true;
1522
+ return applied;
1451
1523
  }
1452
1524
  return part;
1453
1525
  });
1454
- if (updated) {
1526
+ if (hasRealChange) {
1455
1527
  const updatedMessage = this._sanitizeMessageForPersistence({
1456
1528
  ...message,
1457
1529
  parts: updatedParts
@@ -1468,10 +1540,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1468
1540
  this.messages = autoTransformMessages(persisted);
1469
1541
  }
1470
1542
  }
1471
- if (!updated) {
1543
+ if (!wasFound) {
1472
1544
  console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
1473
1545
  return false;
1474
1546
  }
1547
+ if (!hasRealChange) return true;
1475
1548
  if (isStreamingMessage) this._broadcastChatMessage({
1476
1549
  type: "cf_agent_message_updated",
1477
1550
  message
@@ -1486,11 +1559,34 @@ var AIChatAgent = class AIChatAgent extends Agent {
1486
1559
  return true;
1487
1560
  }
1488
1561
  /**
1562
+ * Returns true if `applied` is the same reference as `original`, or if
1563
+ * the two have identical state-relevant fields. Used by
1564
+ * `_findAndUpdateToolPart` to detect idempotent re-applies and skip
1565
+ * SQLite writes plus `MESSAGE_UPDATED` broadcasts.
1566
+ */
1567
+ static _isToolPartUnchanged(original, applied) {
1568
+ if (applied === original) return true;
1569
+ if (applied.state !== original.state) return false;
1570
+ if (applied.state === "output-available" || applied.state === "output-error") return JSON.stringify(applied.output) === JSON.stringify(original.output) && applied.errorText === original.errorText && applied.preliminary === original.preliminary;
1571
+ if (applied.state === "output-denied") return true;
1572
+ if (applied.state === "approval-responded" || applied.state === "approval-requested") return JSON.stringify(applied.approval) === JSON.stringify(original.approval);
1573
+ return false;
1574
+ }
1575
+ /**
1489
1576
  * Applies a tool result to an existing assistant message.
1490
1577
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1491
1578
  * The server is the source of truth, so we update the message here and broadcast
1492
1579
  * the update to all clients.
1493
1580
  *
1581
+ * `output-available` and `output-error` are accepted as valid starting
1582
+ * states for *idempotent* re-application — duplicate WS frames, second
1583
+ * tabs re-running the same tool, and provider-replay round-trips all
1584
+ * become silent no-ops rather than a warn + skipped update. The first
1585
+ * applied terminal result wins; subsequent results carrying *different*
1586
+ * data are also dropped (preserving the existing "first write wins"
1587
+ * contract — see `client-tool-duplicate-message.test.ts`). See issue
1588
+ * #1404.
1589
+ *
1494
1590
  * @param toolCallId - The tool call ID this result is for
1495
1591
  * @param _toolName - The name of the tool (unused, kept for API compat)
1496
1592
  * @param output - The output from the tool execution
@@ -1502,18 +1598,24 @@ var AIChatAgent = class AIChatAgent extends Agent {
1502
1598
  return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", [
1503
1599
  "input-available",
1504
1600
  "approval-requested",
1505
- "approval-responded"
1506
- ], (part) => ({
1507
- ...part,
1508
- ...overrideState === "output-error" ? {
1601
+ "approval-responded",
1602
+ "output-available",
1603
+ "output-error",
1604
+ "output-denied"
1605
+ ], (part) => {
1606
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
1607
+ if (overrideState === "output-error") return {
1608
+ ...part,
1509
1609
  state: "output-error",
1510
1610
  errorText: errorText ?? "Tool execution denied by user"
1511
- } : {
1611
+ };
1612
+ return {
1613
+ ...part,
1512
1614
  state: "output-available",
1513
1615
  output,
1514
1616
  preliminary: false
1515
- }
1516
- }));
1617
+ };
1618
+ });
1517
1619
  }
1518
1620
  async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1519
1621
  streamCompleted.value = false;
@@ -1567,6 +1669,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1567
1669
  if (continuationReasoningResumed) continue;
1568
1670
  }
1569
1671
  }
1672
+ if (isReplayChunk(message.parts, data)) continue;
1570
1673
  const handled = applyChunkToParts(message.parts, data);
1571
1674
  if (data.type === "tool-approval-request" && this._streamingMessage) {
1572
1675
  const snapshot = {
@@ -1587,23 +1690,35 @@ var AIChatAgent = class AIChatAgent extends Agent {
1587
1690
  "input-available",
1588
1691
  "input-streaming",
1589
1692
  "approval-responded",
1590
- "approval-requested"
1591
- ], (part) => ({
1592
- ...part,
1593
- state: "output-available",
1594
- output: data.output,
1595
- ...data.preliminary !== void 0 && { preliminary: data.preliminary }
1596
- }));
1693
+ "approval-requested",
1694
+ "output-available",
1695
+ "output-error",
1696
+ "output-denied"
1697
+ ], (part) => {
1698
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
1699
+ return {
1700
+ ...part,
1701
+ state: "output-available",
1702
+ output: data.output,
1703
+ ...data.preliminary !== void 0 && { preliminary: data.preliminary }
1704
+ };
1705
+ });
1597
1706
  else this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
1598
1707
  "input-available",
1599
1708
  "input-streaming",
1600
1709
  "approval-responded",
1601
- "approval-requested"
1602
- ], (part) => ({
1603
- ...part,
1604
- state: "output-error",
1605
- errorText: data.errorText
1606
- }));
1710
+ "approval-requested",
1711
+ "output-available",
1712
+ "output-error",
1713
+ "output-denied"
1714
+ ], (part) => {
1715
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
1716
+ return {
1717
+ ...part,
1718
+ state: "output-error",
1719
+ errorText: data.errorText
1720
+ };
1721
+ });
1607
1722
  }
1608
1723
  if (!handled) switch (data.type) {
1609
1724
  case "start":