@saar-ai/web-widget 0.13.1 → 0.14.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.
Files changed (47) hide show
  1. package/dist/chunks/{chat-R7z4DtMM.js → chat-CrbRIHVN.js} +18 -5
  2. package/dist/chunks/{esm-DSxqq2-d.js → esm-D2iq2DjO.js} +6 -6
  3. package/dist/chunks/{host-widget-iQ-2t8vu.js → host-widget-DlFlAZYq.js} +561 -179
  4. package/dist/chunks/{schemas-B2B3k74u.js → schemas-DC_oWrTO.js} +51 -19
  5. package/dist/chunks/starters-pick-noq7o_W8.js +139 -0
  6. package/dist/chunks/{telemetry-3f--vvdX.js → telemetry-UHSrhVyf.js} +1 -1
  7. package/dist/concierge-shell.css +1 -1
  8. package/dist/consent/consent-prompt-dom.d.ts.map +1 -1
  9. package/dist/dock/dock-caption.d.ts.map +1 -1
  10. package/dist/dock/dock-drag.d.ts +0 -2
  11. package/dist/dock/dock-drag.d.ts.map +1 -1
  12. package/dist/dock/dock-motion.d.ts +0 -1
  13. package/dist/dock/dock-motion.d.ts.map +1 -1
  14. package/dist/dock/dock-state.d.ts +0 -52
  15. package/dist/dock/dock-state.d.ts.map +1 -1
  16. package/dist/dock/dock.d.ts +0 -18
  17. package/dist/dock/dock.d.ts.map +1 -1
  18. package/dist/generated/concierge-shell-css.d.ts.map +1 -1
  19. package/dist/generated/widget-css.d.ts.map +1 -1
  20. package/dist/host-widget.d.ts +9 -1
  21. package/dist/host-widget.d.ts.map +1 -1
  22. package/dist/index.js +4 -4
  23. package/dist/message-limit.d.ts +10 -0
  24. package/dist/message-limit.d.ts.map +1 -0
  25. package/dist/messages.d.ts +16 -0
  26. package/dist/messages.d.ts.map +1 -1
  27. package/dist/next/index.js +1 -1
  28. package/dist/starters-pick.d.ts +16 -0
  29. package/dist/starters-pick.d.ts.map +1 -0
  30. package/dist/text-direction.d.ts +11 -45
  31. package/dist/text-direction.d.ts.map +1 -1
  32. package/dist/use-chat-session.d.ts +73 -13
  33. package/dist/use-chat-session.d.ts.map +1 -1
  34. package/dist/voice-widget.d.ts +13 -1
  35. package/dist/voice-widget.d.ts.map +1 -1
  36. package/dist/widget/concierge-shell.d.ts +7 -1
  37. package/dist/widget/concierge-shell.d.ts.map +1 -1
  38. package/dist/widget/open-state.d.ts +3 -0
  39. package/dist/widget/open-state.d.ts.map +1 -0
  40. package/dist/widget/shell-renderer.d.ts +1 -1
  41. package/dist/widget/shell-renderer.d.ts.map +1 -1
  42. package/dist/widget/transcript-geometry.d.ts +12 -6
  43. package/dist/widget/transcript-geometry.d.ts.map +1 -1
  44. package/dist/widget-markdown.d.ts +8 -0
  45. package/dist/widget-markdown.d.ts.map +1 -1
  46. package/dist/widget.css +1 -1
  47. package/package.json +9 -9
@@ -4618,6 +4618,9 @@ var defaultWidgetMessages = {
4618
4618
  dock_minimise_dock: "Minimise the concierge",
4619
4619
  dock_hide_conversation: "Hide conversation",
4620
4620
  handoff_event: "Handed to a human teammate",
4621
+ handback_event: "Back with the concierge",
4622
+ capture_saved_event: "Thanks — sent.",
4623
+ capture_declined_event: "No problem — skipped.",
4621
4624
  escalated_banner: "A human teammate will pick this up shortly.",
4622
4625
  status_sending: "Sending",
4623
4626
  status_sent: "Sent",
@@ -5795,6 +5798,17 @@ function pillAnchor(dir, isDesktop, desktopAlign) {
5795
5798
  };
5796
5799
  }
5797
5800
  //#endregion
5801
+ //#region src/message-limit.ts
5802
+ /**
5803
+ * The longest message `POST /widget/chat` accepts (`MAX_MESSAGE_LENGTH` in
5804
+ * `apps/api/src/widget/widget-chat.controller.ts`; a test pins the two). Both
5805
+ * composers cap their input at it (SAA-434), so a message is never refused
5806
+ * for its length after the shopper has typed it.
5807
+ */
5808
+ var WIDGET_MESSAGE_MAX_LENGTH = 4e3;
5809
+ /** How close to the limit the composer starts showing its count. */
5810
+ var WIDGET_MESSAGE_COUNT_FROM = 3600;
5811
+ //#endregion
5798
5812
  //#region src/dock/dock-caption.tsx
5799
5813
  function DockCaption({ line, swapKey, draft, onDraftChange, onSubmit, placeholder, label, disabled = false, inputRef, durationMs, inputTestId, lineTestId = "widget-dock-caption" }) {
5800
5814
  const outgoing = useCrossFade(line, swapKey, durationMs);
@@ -5817,6 +5831,7 @@ function DockCaption({ line, swapKey, draft, onDraftChange, onSubmit, placeholde
5817
5831
  placeholder,
5818
5832
  "aria-label": label,
5819
5833
  autoComplete: "off",
5834
+ maxLength: WIDGET_MESSAGE_MAX_LENGTH,
5820
5835
  disabled,
5821
5836
  onChange: (event) => onDraftChange(event.target.value),
5822
5837
  onKeyDown,
@@ -8294,50 +8309,6 @@ function deriveView(state, input) {
8294
8309
  }
8295
8310
  throw new TypeError(`Unknown dock state: ${JSON.stringify(state)}`);
8296
8311
  }
8297
- /**
8298
- * §3.4 (revised 2026-09-11) — where the LATEST EXCHANGE begins.
8299
- *
8300
- * @deprecated Nothing in the dock renders a latest-exchange view any more
8301
- * (§3.4, revised 2026-09-15). Kept, and still correct, because it is
8302
- * published API.
8303
- *
8304
- * An exchange is the shopper's line and the reply to it. The latest one
8305
- * therefore starts at the LAST caller turn and runs to the end, so a reply
8306
- * that arrived as three turns (a filler, the answer, the cards) stays whole.
8307
- *
8308
- * Two cases are not that shape and both are real:
8309
- *
8310
- * - the shopper has not spoken yet. The concierge opens with a greeting of
8311
- * its own, and a proactive nudge can add a second line before anybody has
8312
- * typed; the latest exchange is then the LAST agent turn alone, because
8313
- * two unanswered agent lines are two things said, not one exchange.
8314
- * - a `speaker: 'event'` row — §3.4's handoff marker. It is something that
8315
- * happened TO an exchange rather than a turn in one, so it never starts a
8316
- * new one and never ends the search for the caller line above it.
8317
- */
8318
- function latestExchangeStart(speakers) {
8319
- for (let i = speakers.length - 1; i >= 0; i--) if (speakers[i] === "caller") return i;
8320
- return Math.max(0, speakers.length - 1);
8321
- }
8322
- /**
8323
- * How many exchanges the transcript holds — the number "Show conversation"
8324
- * was offered on (§3.4: the control existed only when there was more than one).
8325
- *
8326
- * @deprecated The control was removed with §3.4's latest-exchange view on
8327
- * 2026-09-15. Kept, and still correct, because it is published API.
8328
- *
8329
- * A caller line opens an exchange; anything said BEFORE the first one (the
8330
- * greeting, a proactive nudge) is an exchange of its own, because it is
8331
- * something the shopper can scroll back to and would otherwise be counted as
8332
- * nothing at all — leaving a dock that shows a greeting, then an answer, and
8333
- * claims there is nothing more to see.
8334
- */
8335
- function exchangeCount(speakers) {
8336
- if (speakers.length === 0) return 0;
8337
- const opened = speakers.findIndex((s) => s === "caller");
8338
- if (opened === -1) return speakers.length;
8339
- return speakers.filter((s) => s === "caller").length + (opened === 0 ? 0 : 1);
8340
- }
8341
8312
  //#endregion
8342
8313
  //#region src/dock/dock.tsx
8343
8314
  var DEFAULT_COLOR = {
@@ -9858,7 +9829,7 @@ function botStateFor(snapshot) {
9858
9829
  return "listening";
9859
9830
  }
9860
9831
  //#endregion
9861
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
9832
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
9862
9833
  /**
9863
9834
  * @license lucide-react v1.50.0 - ISC
9864
9835
  *
@@ -9867,7 +9838,7 @@ function botStateFor(snapshot) {
9867
9838
  */
9868
9839
  var toKebabCase = (string) => string?.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
9869
9840
  //#endregion
9870
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/toLucideIconData.mjs
9841
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/toLucideIconData.mjs
9871
9842
  /**
9872
9843
  * @license lucide-react v1.50.0 - ISC
9873
9844
  *
@@ -9884,7 +9855,7 @@ function toLucideIconData(iconName, iconNode, aliases = []) {
9884
9855
  };
9885
9856
  }
9886
9857
  //#endregion
9887
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
9858
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
9888
9859
  /**
9889
9860
  * @license lucide-react v1.50.0 - ISC
9890
9861
  *
@@ -9906,7 +9877,7 @@ var toCamelCase = (string) => {
9906
9877
  return out;
9907
9878
  };
9908
9879
  //#endregion
9909
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
9880
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
9910
9881
  /**
9911
9882
  * @license lucide-react v1.50.0 - ISC
9912
9883
  *
@@ -9918,7 +9889,7 @@ var toPascalCase = (string) => {
9918
9889
  return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
9919
9890
  };
9920
9891
  //#endregion
9921
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
9892
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
9922
9893
  /**
9923
9894
  * @license lucide-react v1.50.0 - ISC
9924
9895
  *
@@ -9929,7 +9900,7 @@ var mergeClasses = (...classes) => classes.filter((className, index, array) => {
9929
9900
  return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
9930
9901
  }).join(" ").trim();
9931
9902
  //#endregion
9932
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/build/defaultAttributes.mjs
9903
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/build/defaultAttributes.mjs
9933
9904
  /**
9934
9905
  * @license lucide-react v1.50.0 - ISC
9935
9906
  *
@@ -9948,7 +9919,7 @@ var defaultAttributes = {
9948
9919
  "stroke-linejoin": "round"
9949
9920
  };
9950
9921
  //#endregion
9951
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconNode.mjs
9922
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconNode.mjs
9952
9923
  /**
9953
9924
  * @license lucide-react v1.50.0 - ISC
9954
9925
  *
@@ -10003,7 +9974,7 @@ function buildLucideIconNode(icon, params = {}) {
10003
9974
  ];
10004
9975
  }
10005
9976
  //#endregion
10006
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconForReact.mjs
9977
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/build/buildLucideIconForReact.mjs
10007
9978
  /**
10008
9979
  * @license lucide-react v1.50.0 - ISC
10009
9980
  *
@@ -10024,7 +9995,7 @@ function buildLucideIconForReact(icon, params = {}) {
10024
9995
  });
10025
9996
  }
10026
9997
  //#endregion
10027
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
9998
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
10028
9999
  /**
10029
10000
  * @license lucide-react v1.50.0 - ISC
10030
10001
  *
@@ -10036,7 +10007,7 @@ var hasA11yProp = (props) => {
10036
10007
  return false;
10037
10008
  };
10038
10009
  //#endregion
10039
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/context.mjs
10010
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/context.mjs
10040
10011
  /**
10041
10012
  * @license lucide-react v1.50.0 - ISC
10042
10013
  *
@@ -10046,7 +10017,7 @@ var hasA11yProp = (props) => {
10046
10017
  var LucideContext = createContext({});
10047
10018
  var useLucideContext = () => useContext(LucideContext);
10048
10019
  //#endregion
10049
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/Icon.mjs
10020
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/Icon.mjs
10050
10021
  /**
10051
10022
  * @license lucide-react v1.50.0 - ISC
10052
10023
  *
@@ -10077,7 +10048,7 @@ var Icon = forwardRef(({ color, size, width, height, strokeWidth, absoluteStroke
10077
10048
  }, [...builtIconNode.map(([tag, attrs]) => createElement(tag, attrs)), ...Array.isArray(children) ? children : [children]]);
10078
10049
  });
10079
10050
  //#endregion
10080
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/createLucideIcon.mjs
10051
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/createLucideIcon.mjs
10081
10052
  /**
10082
10053
  * @license lucide-react v1.50.0 - ISC
10083
10054
  *
@@ -10096,7 +10067,7 @@ function createLucideIcon(iconDataOrName, iconNode = [], aliases = []) {
10096
10067
  return Component;
10097
10068
  }
10098
10069
  //#endregion
10099
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/grip-vertical.mjs
10070
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/grip-vertical.mjs
10100
10071
  /**
10101
10072
  * @license lucide-react v1.50.0 - ISC
10102
10073
  *
@@ -10148,7 +10119,7 @@ var __iconData$6 = {
10148
10119
  __iconData$6.node;
10149
10120
  var GripVertical = createLucideIcon(__iconData$6);
10150
10121
  //#endregion
10151
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/mic-off.mjs
10122
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/mic-off.mjs
10152
10123
  /**
10153
10124
  * @license lucide-react v1.50.0 - ISC
10154
10125
  *
@@ -10188,7 +10159,7 @@ var __iconData$5 = {
10188
10159
  __iconData$5.node;
10189
10160
  var MicOff = createLucideIcon(__iconData$5);
10190
10161
  //#endregion
10191
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/mic.mjs
10162
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/mic.mjs
10192
10163
  /**
10193
10164
  * @license lucide-react v1.50.0 - ISC
10194
10165
  *
@@ -10220,7 +10191,7 @@ var __iconData$4 = {
10220
10191
  __iconData$4.node;
10221
10192
  var Mic = createLucideIcon(__iconData$4);
10222
10193
  //#endregion
10223
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/phone-off.mjs
10194
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/phone-off.mjs
10224
10195
  /**
10225
10196
  * @license lucide-react v1.50.0 - ISC
10226
10197
  *
@@ -10248,7 +10219,7 @@ var __iconData$3 = {
10248
10219
  __iconData$3.node;
10249
10220
  var PhoneOff = createLucideIcon(__iconData$3);
10250
10221
  //#endregion
10251
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/send.mjs
10222
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/send.mjs
10252
10223
  /**
10253
10224
  * @license lucide-react v1.50.0 - ISC
10254
10225
  *
@@ -10269,7 +10240,7 @@ var __iconData$2 = {
10269
10240
  __iconData$2.node;
10270
10241
  var Send = createLucideIcon(__iconData$2);
10271
10242
  //#endregion
10272
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/square.mjs
10243
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/square.mjs
10273
10244
  /**
10274
10245
  * @license lucide-react v1.50.0 - ISC
10275
10246
  *
@@ -10291,7 +10262,7 @@ var __iconData$1 = {
10291
10262
  __iconData$1.node;
10292
10263
  var Square = createLucideIcon(__iconData$1);
10293
10264
  //#endregion
10294
- //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.0/node_modules/lucide-react/dist/esm/icons/x.mjs
10265
+ //#region ../../node_modules/.pnpm/lucide-react@1.50.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/x.mjs
10295
10266
  /**
10296
10267
  * @license lucide-react v1.50.0 - ISC
10297
10268
  *
@@ -10687,7 +10658,7 @@ var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 19.24cqh)";
10687
10658
  * direction.
10688
10659
  */
10689
10660
  var TRANSCRIPT_FADE_TOP_WITH_BADGE_LEN = "max(28px, 4cqh, 19.24cqh - 115px)";
10690
- var TRANSCRIPT_FADE_BOTTOM_LEN = "max(118px, 20.27cqh)";
10661
+ var TRANSCRIPT_FADE_BOTTOM_LEN = "max(136px, 23.36cqh)";
10691
10662
  /**
10692
10663
  * The transcript's horizontal inset — the width the ellipse actually costs.
10693
10664
  *
@@ -10729,7 +10700,7 @@ var TRANSCRIPT_INSET_X = "max(8px, 10.6cqw - 11px)";
10729
10700
  * `11.86cqh - 63px` is 6.03px at 582px, so a phone renders what it rendered
10730
10701
  * before to a hundredth of a pixel and only larger panels lift the composer.
10731
10702
  */
10732
- var COMPOSER_BOTTOM_LEN = "max(6px, 11.86cqh - 63px)";
10703
+ var COMPOSER_BOTTOM_LEN = "max(6px, 15cqh - 63px)";
10733
10704
  /**
10734
10705
  * The composer overlay's bottom offset when there is NO microphone.
10735
10706
  *
@@ -10746,7 +10717,7 @@ var COMPOSER_BOTTOM_LEN = "max(6px, 11.86cqh - 63px)";
10746
10717
  * for the input + microphone pair regardless of whether the pair is drawn), so
10747
10718
  * nothing above has to move to make room.
10748
10719
  */
10749
- var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 11.86cqh - 1px)";
10720
+ var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 15cqh - 1px)";
10750
10721
  /**
10751
10722
  * The composer's width cap — what the ellipse actually offers at that row.
10752
10723
  *
@@ -10771,7 +10742,7 @@ var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 11.86cqh - 1px)";
10771
10742
  * inert at every size the widget really renders (it binds only below a 248px
10772
10743
  * panel; the narrowest phone in circulation, 320px, gives 310px).
10773
10744
  */
10774
- var COMPOSER_MAX_WIDTH_LEN = "max(160px, 64.65cqw - 10px)";
10745
+ var COMPOSER_MAX_WIDTH_LEN = "max(160px, 71.41cqw - 10px)";
10775
10746
  /**
10776
10747
  * The opaque ground the composer sits on, which has to keep covering it.
10777
10748
  *
@@ -10792,7 +10763,7 @@ var COMPOSER_MAX_WIDTH_LEN = "max(160px, 64.65cqw - 10px)";
10792
10763
  * 118:132 relationship the two were tuned at), so they still meet without a
10793
10764
  * seam or a band of doubly-darkened panel.
10794
10765
  */
10795
- var COMPOSER_GROUND_LEN = "max(132px, 22.68cqh)";
10766
+ var COMPOSER_GROUND_LEN = "max(150px, 25.77cqh)";
10796
10767
  //#endregion
10797
10768
  //#region src/widget/concierge-shell.tsx
10798
10769
  /**
@@ -10811,6 +10782,10 @@ var FOLLOW_TOLERANCE_PX = 24;
10811
10782
  * last messages scroll clear of the ramp, so a ramp length that is not also
10812
10783
  * the padding leaves the newest message permanently half-dissolved.
10813
10784
  *
10785
+ * The top half of the top ramp is fully transparent (SAA-435): text beside
10786
+ * the orb read through at 20-45% under the old eased ramp, which looked like
10787
+ * no fade at all. It now clears completely before it reaches the orb's row.
10788
+ *
10814
10789
  * The top ramp's stops are scaled from `topLen` rather than hardcoded, so the
10815
10790
  * shortened badge variant keeps the same eased shape instead of becoming a
10816
10791
  * steep two-point cut. `topLen` is a CSS length EXPRESSION now (a `max(<px>,
@@ -10840,10 +10815,9 @@ function transcriptEdgeFade(topLen) {
10840
10815
  const at = (fraction) => `calc(${topLen} * ${fraction})`;
10841
10816
  const gradient = `linear-gradient(to bottom, ${[
10842
10817
  "transparent 0",
10843
- `rgba(0,0,0,0.06) ${at(.21)}`,
10844
- `rgba(0,0,0,0.20) ${at(.43)}`,
10845
- `rgba(0,0,0,0.45) ${at(.64)}`,
10846
- `rgba(0,0,0,0.75) ${at(.82)}`,
10818
+ `transparent ${at(.5)}`,
10819
+ `rgba(0,0,0,0.25) ${at(.7)}`,
10820
+ `rgba(0,0,0,0.65) ${at(.86)}`,
10847
10821
  `#000 ${topLen}`,
10848
10822
  `#000 calc(100% - ${TRANSCRIPT_FADE_BOTTOM_LEN})`,
10849
10823
  "rgba(0,0,0,0.86) calc(100% - 96px)",
@@ -10922,9 +10896,15 @@ function voiceStatePillDotColor(pillState) {
10922
10896
  case "speaking": return "var(--brand-rose)";
10923
10897
  }
10924
10898
  }
10899
+ /**
10900
+ * The footer's two controls: opaque pills in the band the column reserves
10901
+ * under the panel (SAA-435), readable over any host page. Inherited colour
10902
+ * there was the HOST's, which is how "Privacy choices" went near-invisible.
10903
+ */
10904
+ var FOOTER_PILL = "absolute bottom-[env(safe-area-inset-bottom,0px)] h-7 rounded-full bg-[var(--widget-card)] px-2.5 text-xs shadow-sm ring-1 ring-black/5 transition-opacity duration-300";
10925
10905
  /** How long the opening flourish runs. Matches `.widget-portal`'s own duration. */
10926
10906
  var PORTAL_MS = 720;
10927
- function ConciergeShell({ open, onOpenChange, state, messageArrived = false, launcher, launcherInitials, typing = false, operatorName, avatar = "orb", labels, children, badge, draft, onDraftChange, onSubmit, composerDisabled = false, voice, announcement, skin, skinStyle, idPrefix = "concierge", scrollKey, composerLeading, testIds, position = DEFAULT_CONCIERGE_POSITION, onPositionChange, attribution, privacyChoices }) {
10907
+ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, launcher, launcherInitials, typing = false, operatorName, avatar = "orb", labels, children, badge, draft, onDraftChange, onSubmit, composerDisabled = false, voice, announcement, skin, skinStyle, idPrefix = "concierge", scrollKey, composerLeading, testIds, position = DEFAULT_CONCIERGE_POSITION, onPositionChange, attribution, privacyChoices, focusOnOpen = true }) {
10928
10908
  const triggerId = `${idPrefix}-trigger`;
10929
10909
  const inputId = `${idPrefix}-input`;
10930
10910
  const [portalActive, setPortalActive] = useState(false);
@@ -11026,6 +11006,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11026
11006
  el.removeEventListener("scroll", onScroll);
11027
11007
  };
11028
11008
  }, [open]);
11009
+ const skipFocus = useRef(!focusOnOpen);
11029
11010
  const handleClose = useCallback(() => {
11030
11011
  onOpenChange(false);
11031
11012
  window.setTimeout(() => {
@@ -11055,7 +11036,8 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11055
11036
  first.focus();
11056
11037
  }
11057
11038
  };
11058
- const focusTimer = window.setTimeout(() => document.getElementById(inputId)?.focus(), 120);
11039
+ const focusTimer = skipFocus.current ? void 0 : window.setTimeout(() => document.getElementById(inputId)?.focus(), 120);
11040
+ skipFocus.current = false;
11059
11041
  window.addEventListener("keydown", onKeyDown);
11060
11042
  return () => {
11061
11043
  window.clearTimeout(focusTimer);
@@ -11112,6 +11094,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11112
11094
  * `ConciergeShellVoice.labels.unavailable`.
11113
11095
  */
11114
11096
  const micLabel = micUnusable ? voice?.labels.unavailable ?? voice?.labels.start ?? "" : connecting ? connectingLabel : inCall ? (voice?.muted === true ? voice.labels.unmute : voice.labels.mute) ?? voice.labels.start : voice?.labels.start ?? "";
11097
+ const counting = draft.length >= WIDGET_MESSAGE_COUNT_FROM;
11115
11098
  const submit = (e) => {
11116
11099
  e.preventDefault();
11117
11100
  if (!draft.trim() || composerDisabled) return;
@@ -11144,7 +11127,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11144
11127
  "aria-hidden": !open,
11145
11128
  className: cn("pointer-events-none fixed inset-x-0 z-50 flex", panelClasses(position)),
11146
11129
  children: /* @__PURE__ */ jsxs("div", {
11147
- className: "relative flex flex-col items-center",
11130
+ className: cn("relative flex flex-col items-center", open && (attribution || privacyChoices) && "pb-[calc(2.25rem+env(safe-area-inset-bottom,0px))]"),
11148
11131
  children: [
11149
11132
  /* @__PURE__ */ jsxs("div", {
11150
11133
  ref: panelRef,
@@ -11280,9 +11263,21 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11280
11263
  onChange: (e) => onDraftChange(e.target.value),
11281
11264
  placeholder: labels.composerPlaceholder,
11282
11265
  dir: "auto",
11266
+ maxLength: WIDGET_MESSAGE_MAX_LENGTH,
11267
+ ...counting ? { "aria-describedby": `${inputId}-count` } : {},
11283
11268
  disabled: composerDisabled,
11284
- className: cn("border-brand-plum/12 h-[40px] w-full rounded-3xl border bg-[var(--widget-chip)] ps-4 pe-12 text-[14px] text-[var(--widget-foreground)] placeholder:text-[var(--widget-foreground-muted)]", "focus:border-brand-plum/30 focus:ring-brand-plum/15 transition-[border-color] focus:bg-[var(--widget-bubble)] focus:ring-2 focus:outline-none disabled:opacity-50", inCall && draft === "" && "opacity-60 focus:opacity-100")
11269
+ className: cn("border-brand-plum/12 h-[40px] w-full rounded-3xl border bg-[var(--widget-chip)] ps-4 pe-12 text-[16px] [@media(min-width:640px)_and_(pointer:fine)]:text-[14px] text-[var(--widget-foreground)] placeholder:text-[var(--widget-foreground-muted)]", "focus:border-brand-plum/30 focus:ring-brand-plum/15 transition-[border-color] focus:bg-[var(--widget-bubble)] focus:ring-2 focus:outline-none disabled:opacity-50", inCall && draft === "" && "opacity-60 focus:opacity-100")
11285
11270
  }),
11271
+ counting ? /* @__PURE__ */ jsxs("span", {
11272
+ id: `${inputId}-count`,
11273
+ "data-testid": "widget-composer-count",
11274
+ className: "absolute end-4 -top-5 text-[11px] text-[var(--widget-foreground-muted)] tabular-nums",
11275
+ children: [
11276
+ draft.length,
11277
+ "/",
11278
+ WIDGET_MESSAGE_MAX_LENGTH
11279
+ ]
11280
+ }) : null,
11286
11281
  draft.trim() && /* @__PURE__ */ jsx("button", {
11287
11282
  type: "submit",
11288
11283
  "aria-label": labels.send,
@@ -11357,7 +11352,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11357
11352
  target: "_blank",
11358
11353
  rel: "noopener noreferrer",
11359
11354
  "data-testid": "widget-branding",
11360
- className: cn("absolute top-full left-1/2 mt-2 inline-flex -translate-x-1/2 items-center gap-1.5 whitespace-nowrap text-xs transition-opacity duration-300", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"),
11355
+ className: cn(FOOTER_PILL, "left-1/2 inline-flex -translate-x-1/2 items-center gap-1.5 whitespace-nowrap", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"),
11361
11356
  children: [/* @__PURE__ */ jsx("span", {
11362
11357
  "aria-hidden": true,
11363
11358
  className: "size-2.5 rounded-full bg-gradient-to-br from-brand-rose to-brand-amber"
@@ -11370,7 +11365,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11370
11365
  type: "button",
11371
11366
  onClick: privacyChoices.open,
11372
11367
  "data-testid": "widget-privacy-choices",
11373
- className: cn("absolute top-full right-0 mt-2 text-xs underline transition-opacity duration-300", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"),
11368
+ className: cn(FOOTER_PILL, "end-0 text-[var(--widget-foreground)] underline", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"),
11374
11369
  children: privacyChoices.label
11375
11370
  }) : null
11376
11371
  ]
@@ -11635,6 +11630,31 @@ function deriveWidgetView(snapshot, input) {
11635
11630
  throw new TypeError(`Unknown concierge state: ${JSON.stringify(state)}`);
11636
11631
  }
11637
11632
  //#endregion
11633
+ //#region src/widget/open-state.ts
11634
+ /**
11635
+ * Whether the widget's panel was open, for the rest of this browsing session
11636
+ * (SAA-435): an in-site navigation that remounts the widget, or a refresh,
11637
+ * reopens it instead of dropping the shopper back to the launcher.
11638
+ *
11639
+ * `sessionStorage`, so it ends with the tab. Every access is guarded: a
11640
+ * private window, blocked site data or a sandboxed frame throws, and the
11641
+ * widget then simply starts closed.
11642
+ */
11643
+ var KEY = "wgt_panel_open";
11644
+ function readOpen() {
11645
+ try {
11646
+ return sessionStorage.getItem(KEY) === "1";
11647
+ } catch {
11648
+ return false;
11649
+ }
11650
+ }
11651
+ function writeOpen(open) {
11652
+ try {
11653
+ if (open) sessionStorage.setItem(KEY, "1");
11654
+ else sessionStorage.removeItem(KEY);
11655
+ } catch {}
11656
+ }
11657
+ //#endregion
11638
11658
  //#region src/widget/shell-renderer.tsx
11639
11659
  /**
11640
11660
  * The widget — launcher and panel — as a `ConciergeRenderer`
@@ -11657,8 +11677,10 @@ function positionFor(dock) {
11657
11677
  const align = dock?.layout?.desktopAlign;
11658
11678
  return align === "left" || align === "right" ? `bottom-${align}` : DEFAULT_CONCIERGE_POSITION;
11659
11679
  }
11660
- function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndCall, statusKind, statusLine, escalated, operatorName, humanTyping, composing, channel, draft, onDraftChange, submit, attaching, onAttach, attachInput, transcript, extras, messages, skinStyle, avatar, attribution, privacyChoices, voice: derivedVoice, dock }) {
11661
- const [open, setOpen] = useState(dock?.initialMinimised === false);
11680
+ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndCall, statusKind, statusLine, escalated, operatorName, humanTyping, composing, replyStreaming, channel, draft, onDraftChange, submit, attaching, onAttach, attachInput, transcript, extras, messages, skinStyle, avatar, attribution, privacyChoices, voice: derivedVoice, dock }) {
11681
+ const [restored] = useState(readOpen);
11682
+ const [open, setOpen] = useState(dock?.initialMinimised === false || restored);
11683
+ useEffect(() => writeOpen(open), [open]);
11662
11684
  const onReady = dock?.onReady;
11663
11685
  useLayoutEffect(() => {
11664
11686
  onReady?.();
@@ -11680,6 +11702,13 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11680
11702
  const voiceUnavailable = showMic && escalated ? messages.voice_unavailable_escalated : void 0;
11681
11703
  const lastTurn = turns[turns.length - 1];
11682
11704
  /**
11705
+ * The foot row's dots — only for a composing state the transcript does NOT
11706
+ * already draw (SAA-420). A human composing has its own bubble in the
11707
+ * transcript, and an open concierge turn draws its own dots (or its text as
11708
+ * it streams); counting either here put a second indicator under the first.
11709
+ */
11710
+ const footComposing = composing && !humanTyping && !replyStreaming;
11711
+ /**
11683
11712
  * The SAME state machine the dock runs (docs/CONCIERGE_GENERATIONS.md §2:
11684
11713
  * one state, two presentations). `Dock` builds a `DockStateInput` from its
11685
11714
  * props and calls `deriveDockState`; this is that, in the widget's terms.
@@ -11722,7 +11751,7 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11722
11751
  shelfCount: dock?.shelf?.items.length ?? 0,
11723
11752
  hasTranscript: turns.length > 0,
11724
11753
  channel,
11725
- composing,
11754
+ composing: footComposing,
11726
11755
  ...operatorName !== void 0 ? { operatorLine: operatorName } : {},
11727
11756
  ...dock?.copy?.offlineMessage !== void 0 ? { offlineMessage: dock.copy.offlineMessage } : {},
11728
11757
  ...statusLine !== void 0 && statusLine !== "" ? {
@@ -11742,7 +11771,7 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11742
11771
  dock,
11743
11772
  turns.length,
11744
11773
  channel,
11745
- composing,
11774
+ footComposing,
11746
11775
  operatorName,
11747
11776
  statusLine,
11748
11777
  statusKind
@@ -11756,7 +11785,9 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11756
11785
  * `resolveCaption` makes, for the same reason — a renderer that invented
11757
11786
  * copy would need translating twice.
11758
11787
  */
11759
- const statusText = view.status === null ? void 0 : view.status.kind === "text" ? view.status.text : messages[view.status.key] ?? void 0;
11788
+ const handoffAt = turns.findLastIndex((t) => t.event === "handoff");
11789
+ const promiseKept = view.status?.kind === "message" && view.status.key === "escalated_banner" && turns.slice(handoffAt + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "");
11790
+ const statusText = view.status === null || promiseKept ? void 0 : view.status.kind === "text" ? view.status.text : messages[view.status.key] ?? void 0;
11760
11791
  const voice = showMic ? {
11761
11792
  phase: callPhase,
11762
11793
  onStart: onToggleMic,
@@ -11806,6 +11837,7 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11806
11837
  return /* @__PURE__ */ jsxs(ConciergeShell, {
11807
11838
  open,
11808
11839
  onOpenChange: setOpen,
11840
+ ...restored ? { focusOnOpen: false } : {},
11809
11841
  state: view.avatar,
11810
11842
  ...skinStyle !== void 0 ? { skinStyle } : {},
11811
11843
  ...avatar !== void 0 ? { avatar } : {},
@@ -11944,6 +11976,16 @@ function safeHref(raw) {
11944
11976
  return null;
11945
11977
  }
11946
11978
  /**
11979
+ * The bidi embedding and isolate controls (U+202A-U+202E, U+2066-U+2069),
11980
+ * removed from what a bubble shows (SAA-436). A right-to-left override typed
11981
+ * into a message reverses the rest of it on screen ("exe.txt" spoofing); the
11982
+ * bubble's own `dir="auto"` and `unicode-bidi: isolate` already order real
11983
+ * mixed-direction text, so nothing legitimate needs them.
11984
+ */
11985
+ function stripBidiControls(text) {
11986
+ return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "");
11987
+ }
11988
+ /**
11947
11989
  * Inline constructs, innermost-last.
11948
11990
  *
11949
11991
  * Code is matched FIRST and never recurses into its own body: `` `**not
@@ -11954,7 +11996,7 @@ function parseInline(src) {
11954
11996
  const out = [];
11955
11997
  let rest = src;
11956
11998
  while (rest.length > 0) {
11957
- const match = /`([^`]+)`|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|(?<!\*)\*(?!\s)([^*\n]+?)\*(?!\*)|(?<!_)_(?!\s)([^_\n]+?)_(?!_)|\[([^\]]*)\]\(([^)\s]+)\)/.exec(rest);
11999
+ const match = /`([^`]+)`|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|(?<!\*)\*(?!\s)([^*\n]+?)\*(?!\*)|(?<!_)_(?!\s)([^_\n]+?)_(?!_)|\[([^\]]*)\]\(([^)\s]+)\)|(https:\/\/[^\s<>"'`]*[^\s<>"'`.,;:!?)\]])/.exec(rest);
11958
12000
  if (!match || match.index === void 0) {
11959
12001
  out.push({
11960
12002
  kind: "text",
@@ -11966,7 +12008,7 @@ function parseInline(src) {
11966
12008
  kind: "text",
11967
12009
  text: rest.slice(0, match.index)
11968
12010
  });
11969
- const [full, code, boldStar, boldUnd, italStar, italUnd, linkText, linkHref] = match;
12011
+ const [full, code, boldStar, boldUnd, italStar, italUnd, linkText, linkHref, bare] = match;
11970
12012
  if (code !== void 0) out.push({
11971
12013
  kind: "code",
11972
12014
  text: code
@@ -11981,7 +12023,7 @@ function parseInline(src) {
11981
12023
  });
11982
12024
  else if (linkHref !== void 0) {
11983
12025
  const href = safeHref(linkHref);
11984
- const children = parseInline(linkText ?? "");
12026
+ const children = parseInline(linkText ?? "").flatMap((n) => n.kind === "link" ? n.children : [n]);
11985
12027
  out.push(href ? {
11986
12028
  kind: "link",
11987
12029
  href,
@@ -11990,11 +12032,25 @@ function parseInline(src) {
11990
12032
  kind: "text",
11991
12033
  text: linkText ?? ""
11992
12034
  });
11993
- }
12035
+ } else if (bare !== void 0) out.push({
12036
+ kind: "link",
12037
+ href: bare,
12038
+ children: [{
12039
+ kind: "text",
12040
+ text: bare
12041
+ }]
12042
+ });
11994
12043
  rest = rest.slice(match.index + full.length);
11995
12044
  }
11996
12045
  return out.filter((n) => !(n.kind === "text" && n.text === ""));
11997
12046
  }
12047
+ function sameOrigin(href) {
12048
+ try {
12049
+ return new URL(href).origin === window.location.origin;
12050
+ } catch {
12051
+ return false;
12052
+ }
12053
+ }
11998
12054
  function renderInline(nodes, keyPrefix) {
11999
12055
  return nodes.map((node, i) => {
12000
12056
  const key = `${keyPrefix}-${i}`;
@@ -12008,9 +12064,11 @@ function renderInline(nodes, keyPrefix) {
12008
12064
  }, key);
12009
12065
  case "link": return /* @__PURE__ */ jsx("a", {
12010
12066
  href: node.href,
12011
- target: "_blank",
12012
- rel: "noopener noreferrer nofollow",
12013
- className: "underline underline-offset-2",
12067
+ ...sameOrigin(node.href) ? {} : {
12068
+ target: "_blank",
12069
+ rel: "noopener noreferrer nofollow"
12070
+ },
12071
+ className: "underline underline-offset-2 [overflow-wrap:anywhere]",
12014
12072
  children: renderInline(node.children, key)
12015
12073
  }, key);
12016
12074
  }
@@ -12082,7 +12140,7 @@ function parseBlocks(markdown) {
12082
12140
  * briefly showing, and never a thrown parse error mid-stream.
12083
12141
  */
12084
12142
  function WidgetMarkdown({ text }) {
12085
- return parseBlocks(text).map((block, i) => {
12143
+ return parseBlocks(stripBidiControls(text)).map((block, i) => {
12086
12144
  if (block.kind === "list") return /* @__PURE__ */ jsx(block.ordered ? "ol" : "ul", {
12087
12145
  className: `my-1 space-y-1 ps-4 ${block.ordered ? "list-decimal" : "list-disc"}`,
12088
12146
  children: block.items.map((item, j) => /* @__PURE__ */ jsx("li", { children: renderInline(parseInline(item), `b${i}-i${j}`) }, `b${i}-i${j}`))
@@ -12531,54 +12589,58 @@ function CheckoutButton({ onCheckout, navigate, messages }) {
12531
12589
  }) : null] });
12532
12590
  }
12533
12591
  //#endregion
12534
- //#region src/text-direction.ts
12592
+ //#region ../widget-protocol/dist/text-direction.js
12535
12593
  /**
12536
12594
  * Base direction for a block of text whose language is the CONTENT's, not the
12537
- * reader's.
12538
- *
12539
- * Copied from `apps/web/src/i18n/text-direction.ts` (docs/WIDGET_EMBED_PLAN.md
12540
- * §4 Phase 3, coupling (2)) rather than imported — this package must not
12541
- * depend on `apps/web`, and the function is small, pure, and has no home in
12542
- * an existing shared package (`@wesence/i18n` / `@wesence/i18n-ui` do not own
12543
- * a direction helper today — see `packages/web-widget/AGENTS.md`'s Sharp
12544
- * edges for the duplication tradeoff, same reasoning as `cn.ts`). Keep the
12545
- * two copies in sync by hand; if a third copy is ever needed, that is the
12546
- * signal to extract a shared, framework-independent package instead.
12547
- *
12548
- * ## Why the widget's own direction is the wrong default
12549
- *
12550
- * `<html dir>` is set from the HOST PAGE's locale, and every element inherits
12551
- * it. That is right for the host's own chrome and wrong for a widget
12552
- * transcript: a shopper on an English storefront asking a question the
12553
- * concierge answers in Arabic would render that reply with an LTR base
12554
- * direction, and the Unicode bidirectional algorithm would then lay out the
12555
- * runs in the wrong order and throw trailing punctuation to the wrong end of
12556
- * the line.
12595
+ * reader's. Pure, string-only and dependency-free: a STATIC import into the
12596
+ * chat bundle a shopper downloads, shared by the console (`apps/web`) and the
12597
+ * widget (`@saar-ai/web-widget`), which used to keep a hand copy each.
12598
+ *
12599
+ * It lives here rather than in `@wesence/i18n` because the widget's published
12600
+ * bundle may resolve no `@wesence/*` module at all (`docs/PACKAGE_DISTRIBUTION.md`,
12601
+ * enforced by `scripts/check-npm-bundle-provenance.mjs`), the same reason
12602
+ * `./money` lives here.
12603
+ *
12604
+ * ## Why the console's own direction is the wrong answer
12605
+ *
12606
+ * `<html dir>` is set from the operator's UI locale, and every element inherits
12607
+ * it. That is right for the chrome and wrong for a transcript: an
12608
+ * English-speaking agent reading an Arabic conversation would render each
12609
+ * message with an LTR base direction, and the Unicode bidirectional algorithm
12610
+ * would then lay out the runs in the wrong order and throw trailing punctuation
12611
+ * to the wrong end of the line.
12612
+ *
12613
+ * The failure is invisible to the person looking at it. An agent who cannot read
12614
+ * Arabic sees Arabic-looking text and moves on; the customer is the one who gets
12615
+ * quoted back a sentence that reads incorrectly. The reverse case is just as
12616
+ * real — an Arabic-speaking agent reading English conversations under an RTL
12617
+ * base.
12557
12618
  *
12558
12619
  * ## Mixed runs are the normal case here, not an edge case
12559
12620
  *
12560
12621
  * Verified against live recognition output: Arabic comes back as
12561
12622
  * `رقم الـ order هو 4471. Please check من فضلك.` and Hindi as
12562
- * `मेरा order number 4471 है।`. Latin nouns inside a non-Latin sentence are
12563
- * what this product's transcripts actually contain, so bidirectional layout
12564
- * is exercised on ordinary traffic rather than by an unusual visitor.
12623
+ * `मेरा order number 4471 है।`. Latin nouns inside a non-Latin sentence are what
12624
+ * this product's transcripts actually contain, so bidirectional layout is
12625
+ * exercised on ordinary traffic rather than by an unusual customer.
12565
12626
  *
12566
12627
  * ## `auto` is the floor, not the goal
12567
12628
  *
12568
12629
  * With a known language this returns a definite direction. Without one it
12569
12630
  * returns `auto`, which delegates to the browser's first-strong-character
12570
- * heuristic — better than inheriting the host page, but wrong for a message
12571
- * that opens with an English word and continues in Arabic
12572
- * (`Please check من فضلك`).
12631
+ * heuristic — better than inheriting the chrome, but wrong for a message that
12632
+ * opens with an English word and continues in Arabic (`Please check من فضلك`).
12633
+ * The real fix is to persist the conversation's resolved locale and pass it in;
12634
+ * see the note in `Transcript`.
12573
12635
  */
12574
12636
  /**
12575
12637
  * Languages written right-to-left. Keyed on the language subtag, so a region
12576
12638
  * never has to be enumerated.
12577
12639
  *
12578
- * Beyond Arabic on purpose: Hebrew, Farsi, Urdu and Pashto are scripts this
12579
- * widget's conversations already produce, and getting one wrong is the same
12580
- * silent failure. Adding a language to the product must not also require
12581
- * remembering this file.
12640
+ * Beyond Arabic on purpose: Hebrew, Farsi, Urdu and Pashto are the scripts a CX
12641
+ * product in this region acquires next, and getting one wrong is the same silent
12642
+ * failure. Adding a language to the product must not also require remembering
12643
+ * this file.
12582
12644
  */
12583
12645
  var RTL_LANGUAGES = new Set([
12584
12646
  "ar",
@@ -12617,11 +12679,11 @@ var LANGUAGE_SUBTAG = /^[a-z]{2,3}$/;
12617
12679
  /**
12618
12680
  * The base direction for text in `locale`.
12619
12681
  *
12620
- * @param locale BCP-47 tag carried on a conversation turn — untyped by the
12621
- * time it reaches here, so anything malformed resolves to `auto` rather
12622
- * than to a guess.
12682
+ * @param locale BCP-47 tag from stored conversation data — untyped by the time
12683
+ * it reaches here, so anything malformed resolves to `auto` rather than to a
12684
+ * guess.
12623
12685
  */
12624
- function textDirectionFor(locale) {
12686
+ function textDirectionFor$1(locale) {
12625
12687
  if (locale === void 0 || locale === null || locale === "") return "auto";
12626
12688
  const language = locale.toLowerCase().split("-")[0] ?? "";
12627
12689
  if (!LANGUAGE_SUBTAG.test(language)) return "auto";
@@ -12630,6 +12692,9 @@ function textDirectionFor(locale) {
12630
12692
  return "auto";
12631
12693
  }
12632
12694
  //#endregion
12695
+ //#region src/text-direction.ts
12696
+ var textDirectionFor = textDirectionFor$1;
12697
+ //#endregion
12633
12698
  //#region src/voice-widget.tsx
12634
12699
  /**
12635
12700
  * The "still composing" affordance, shown in the agent's own bubble from the
@@ -12694,10 +12759,12 @@ function TypingDots({ label }) {
12694
12759
  * it twice would be worse than announcing it once.
12695
12760
  */
12696
12761
  function TranscriptEvent({ event, awaitingReply, messages }) {
12697
- if (event !== "handoff") return null;
12762
+ const key = event === void 0 ? void 0 : `${event}_event`;
12763
+ if (key === void 0 || !(key in defaultWidgetMessages)) return null;
12764
+ const handback = event !== "handoff";
12698
12765
  return /* @__PURE__ */ jsxs("div", {
12699
12766
  className: "wgt-turn-row flex flex-col items-center gap-1 py-1",
12700
- "data-testid": "widget-handoff-event",
12767
+ "data-testid": `widget-${event}-event`,
12701
12768
  "data-dock-follow": "",
12702
12769
  children: [/* @__PURE__ */ jsxs("p", {
12703
12770
  className: "flex w-full items-center gap-3 text-[11px] font-medium tracking-wide text-[var(--widget-foreground-muted)] [&:lang(ar)]:tracking-normal [&:lang(hi)]:tracking-normal",
@@ -12706,13 +12773,13 @@ function TranscriptEvent({ event, awaitingReply, messages }) {
12706
12773
  "aria-hidden": "true",
12707
12774
  className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
12708
12775
  }),
12709
- /* @__PURE__ */ jsx("span", { children: messages.handoff_event ?? defaultWidgetMessages.handoff_event }),
12776
+ /* @__PURE__ */ jsx("span", { children: messages[key] ?? defaultWidgetMessages[key] }),
12710
12777
  /* @__PURE__ */ jsx("span", {
12711
12778
  "aria-hidden": "true",
12712
12779
  className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
12713
12780
  })
12714
12781
  ]
12715
- }), awaitingReply ? /* @__PURE__ */ jsx("p", {
12782
+ }), awaitingReply && !handback ? /* @__PURE__ */ jsx("p", {
12716
12783
  role: "status",
12717
12784
  "data-testid": "widget-handoff-pending",
12718
12785
  className: "text-center text-[11px] text-[var(--widget-foreground-muted)]",
@@ -12939,7 +13006,7 @@ function VoiceWidget({ renderer, generation, ...props }) {
12939
13006
  });
12940
13007
  }
12941
13008
  /** `VoiceWidget` with the renderer decided — the component the CDN entries and `ConciergeHost` use. */
12942
- function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, status, statusKind, notice, mode = "voice", escalated = false, humanTyping = false, onTyping, onAddToCart, onChooseOptions, chooseOptionsBusy = false, curationHref, productHref, onAttachFile, cart, captureCard, messages = defaultWidgetMessages, navigate, locale = "en", skinStyle, avatar, attribution, privacyChoices, dock }) {
13009
+ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, status, statusKind, notice, mode = "voice", escalated = false, humanTyping = false, onTyping, onAddToCart, onChooseOptions, chooseOptionsBusy = false, curationHref, productHref, onAttachFile, cart, captureCard, messages = defaultWidgetMessages, suggestions, navigate, locale = "en", skinStyle, avatar, attribution, privacyChoices, dock }) {
12943
13010
  const [draft, setDraft] = useState("");
12944
13011
  const [sending, setSending] = useState(false);
12945
13012
  /** Roomy mode — see the expand control in the header. Collapses back on close, so a reopened widget starts small. */
@@ -12987,7 +13054,7 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
12987
13054
  };
12988
13055
  const submit = async () => {
12989
13056
  const text = draft.trim();
12990
- if (text === "" || sending) return;
13057
+ if (text === "") return;
12991
13058
  setSending(true);
12992
13059
  setDraft("");
12993
13060
  try {
@@ -13044,7 +13111,7 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13044
13111
  }) : shown.map((turn, i) => turn.speaker === "event" ? /* @__PURE__ */ jsx(TranscriptEvent, {
13045
13112
  event: turn.event,
13046
13113
  messages,
13047
- awaitingReply: !shown.slice(i + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "")
13114
+ awaitingReply: !shown.slice(i + 1).some((t) => t.event === "handoff" || t.event === "handback" || t.speaker === "agent" && t.text.trim() !== "")
13048
13115
  }, `event-${i}`) : /* @__PURE__ */ jsxs("div", {
13049
13116
  "data-dock-follow": "",
13050
13117
  className: turn.speaker === "caller" ? "wgt-turn-row flex flex-col items-end" : "wgt-turn-row flex flex-col items-start",
@@ -13055,17 +13122,17 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13055
13122
  className: "px-1 pb-0.5 text-[11px] font-medium text-[var(--widget-foreground-muted)]",
13056
13123
  children: turn.operatorName
13057
13124
  }) : null,
13058
- turn.text !== "" || turn.speaker === "agent" && turn.final === false ? /* @__PURE__ */ jsx("div", {
13125
+ turn.text !== "" || turn.speaker === "agent" && turn.final === false && !humanTyping ? /* @__PURE__ */ jsx("div", {
13059
13126
  dir: textDirectionFor(turn.locale),
13060
13127
  lang: turn.locale,
13061
13128
  "data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
13062
- className: `max-w-[85%] px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${turn.speaker === "caller" ? "from-brand-plum to-brand-plum/90 text-[var(--widget-accent-foreground)] rounded-2xl rounded-ee-md bg-gradient-to-br" : turn.filler === true ? "rounded-2xl rounded-es-md border border-dashed border-[var(--widget-foreground-muted)]/50 bg-transparent text-[var(--widget-foreground-muted)] shadow-none" : AGENT_BUBBLE_CLASS}`,
13129
+ className: `max-w-[85%] px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm [unicode-bidi:isolate] ${turn.speaker === "caller" ? "from-brand-plum to-brand-plum/90 text-[var(--widget-accent-foreground)] rounded-2xl rounded-ee-md bg-gradient-to-br" : turn.filler === true ? "rounded-2xl rounded-es-md border border-dashed border-[var(--widget-foreground-muted)]/50 bg-transparent text-[var(--widget-foreground-muted)] shadow-none" : AGENT_BUBBLE_CLASS}`,
13063
13130
  children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
13064
13131
  className: "flex items-center gap-2 italic",
13065
13132
  children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
13066
13133
  }) : turn.speaker === "agent" ? /* @__PURE__ */ jsx(WidgetMarkdown, { text: turn.text }) : /* @__PURE__ */ jsx("span", {
13067
13134
  className: `whitespace-pre-wrap ${turn.final === false ? "italic opacity-70" : ""}`,
13068
- children: turn.text
13135
+ children: stripBidiControls(turn.text)
13069
13136
  })
13070
13137
  }) : null,
13071
13138
  turn.attachments && turn.attachments.length > 0 ? /* @__PURE__ */ jsx("div", {
@@ -13111,14 +13178,14 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13111
13178
  "aria-label": messages.suggestions_label,
13112
13179
  "data-testid": "widget-suggestions",
13113
13180
  className: "flex flex-wrap gap-2 pt-1",
13114
- children: SUGGESTION_KEYS.map((key) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("button", {
13181
+ children: (suggestions ?? SUGGESTION_KEYS.map((key) => messages[key])).map((text) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("button", {
13115
13182
  type: "button",
13116
13183
  "data-testid": "widget-suggestion",
13117
13184
  disabled: sending,
13118
- onClick: () => void sendSuggestion(messages[key]),
13185
+ onClick: () => void sendSuggestion(text),
13119
13186
  className: "cursor-pointer rounded-full bg-[var(--widget-chip)] px-3 py-1.5 text-xs font-medium text-[var(--widget-foreground)] ring-1 ring-black/10 transition-colors hover:bg-[var(--widget-accent)] hover:text-[var(--widget-accent-foreground)] disabled:cursor-default disabled:opacity-50 focus-visible:ring-2 focus-visible:ring-[var(--widget-accent-ring)] focus-visible:outline-none",
13120
- children: messages[key]
13121
- }) }, key))
13187
+ children: text
13188
+ }) }, text))
13122
13189
  }) : null
13123
13190
  ]
13124
13191
  });
@@ -13232,6 +13299,7 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13232
13299
  lastTurn,
13233
13300
  operatorName,
13234
13301
  composing,
13302
+ replyStreaming,
13235
13303
  channel,
13236
13304
  mode,
13237
13305
  showMic,
@@ -13964,6 +14032,62 @@ new RegExp(`^${LOCALE_PREFIX}/cart(?:/.*)?$`, "i");
13964
14032
  */
13965
14033
  var DESK_TYPING_INDICATOR_TTL_MS = 6e3;
13966
14034
  //#endregion
14035
+ //#region ../widget-protocol/dist/desk-ownership.js
14036
+ /**
14037
+ * `desk:ownership` — the widget room event that tells a visitor who holds
14038
+ * their conversation now: the concierge (`'ai'`) or the human desk
14039
+ * (`'human'`).
14040
+ *
14041
+ * The api emits it into the conversation's widget room every time the desk
14042
+ * moves the conversation (`DeskAssignmentService.move` →
14043
+ * `WidgetRealtimeBridge.publishOwnership`): a claim or takeover says
14044
+ * `'human'`, a release to a queue says `'human'` too (a person, not the AI,
14045
+ * picks it up next), and a hand-back says `'ai'`. The widget
14046
+ * (`@saar-ai/web-widget`'s `useChatSession`) reacts to `'ai'` by leaving the
14047
+ * escalated state — the handoff banner clears and a "back with the
14048
+ * concierge" divider lands in the transcript — and to `'human'` by showing
14049
+ * the handoff divider if it is not already on screen.
14050
+ *
14051
+ * Before this event existed a hand-back told the visitor nothing: the
14052
+ * widget room carried only `desk:message` and `desk:typing`, so the widget
14053
+ * stayed "escalated" and kept promising a human would pick up a conversation
14054
+ * the AI was already answering again. A push can be missed (no socket yet, a
14055
+ * dropped connection), so the AI's first reply after a release also carries
14056
+ * an SSE `resumed` event (`./chat.ts`) — the fallback for the same fact.
14057
+ *
14058
+ * ## Zod-free on purpose
14059
+ *
14060
+ * `@saar-ai/web-widget` imports this subpath STATICALLY into its chat bundle,
14061
+ * which `tools/check-bundle-budget.mjs` forbids zod in — the same reason
14062
+ * `./desk-typing.ts` is schema-free. {@link parseDeskOwnershipEvent} is the
14063
+ * hand-written guard instead: the payload is two fields, and a wrong one is
14064
+ * dropped rather than repaired.
14065
+ *
14066
+ * ## Content-free
14067
+ *
14068
+ * Like `desk:typing`, the payload names no person — no user id, no name. Who
14069
+ * the operator is reaches the visitor only on a reply they wrote, through the
14070
+ * `handoff.showOperatorName` gate. A takeover must not leak a name that gate
14071
+ * would have withheld.
14072
+ */
14073
+ /** The Socket.IO event name. Both the api and the widget use exactly this string. */
14074
+ var DESK_OWNERSHIP_EVENT = "desk:ownership";
14075
+ /**
14076
+ * The payload, or `null` when it is not one. Returns a fresh object holding
14077
+ * only the two contract fields, so an extra field a newer api adds cannot
14078
+ * ride into the widget's state.
14079
+ */
14080
+ function parseDeskOwnershipEvent(value) {
14081
+ if (typeof value !== "object" || value === null) return null;
14082
+ const { to, at } = value;
14083
+ if (to !== "ai" && to !== "human") return null;
14084
+ if (typeof at !== "string" || at === "") return null;
14085
+ return {
14086
+ to,
14087
+ at
14088
+ };
14089
+ }
14090
+ //#endregion
13967
14091
  //#region src/use-chat-session.ts
13968
14092
  /**
13969
14093
  * The RUNTIME twin of `@saar-ai/widget-protocol`'s `SameOriginPathSchema`,
@@ -14037,15 +14161,30 @@ var DEFAULT_API_BASE = "";
14037
14161
  var DEFAULT_POLL_INTERVAL_MS = 4e3;
14038
14162
  /** Poll cadence once the socket is connected — a safety net, not a second primary channel. See the module doc comment. */
14039
14163
  var DEFAULT_IDLE_POLL_INTERVAL_MS = 3e4;
14164
+ /** The light poll's cadence before escalation — see `lightPollIntervalMs`. */
14165
+ var DEFAULT_LIGHT_POLL_INTERVAL_MS = 3e4;
14166
+ /**
14167
+ * How long a seq the poll skipped over is still asked for. An operator reply
14168
+ * held in its undo window has its seq from the moment it is written but is
14169
+ * hidden from the poll until the hold ends (at most 60 s,
14170
+ * `MAX_UNDO_WINDOW_SECONDS`, plus the outbound processor's lag), so a later,
14171
+ * visible seq can overtake it. See "Only a POLL result moves the poll cursor".
14172
+ */
14173
+ var SEQ_GAP_HOLD_MS = 12e4;
14040
14174
  /** `socket.io-client`'s `path` default — kept in sync with `apps/api/src/config/config.ts`'s `WIDGET_SOCKET_PATH` default. */
14041
14175
  var DEFAULT_SOCKET_PATH = "/socket.io";
14042
14176
  /**
14043
- * The `ChatTurn.id` of the handoff transcript event. A fixed literal because
14044
- * there is at most one per session (see `markHandoffToHuman`), and prefixed
14045
- * so it can never be mistaken for — or collide with — a server-minted turn
14046
- * id in the id-keyed `setTurns` passes `send`/`streamReply` run.
14177
+ * The `ChatTurn.id` of the FIRST handoff transcript event. Prefixed so it can
14178
+ * never be mistaken for — or collide with — a server-minted turn id in the
14179
+ * id-keyed `setTurns` passes `send`/`streamReply` run. A conversation handed
14180
+ * back and taken over again gets a second marker, suffixed `-2`, `-3`, … (see
14181
+ * `markHandoffToHuman`); the first keeps the bare literal it always had.
14047
14182
  */
14048
14183
  var HANDOFF_EVENT_TURN_ID = "event-handoff";
14184
+ /** Prefix of a hand-back transcript event's id, suffixed with its ordinal — see `markHandbackToAi`. */
14185
+ var HANDBACK_EVENT_TURN_ID = "event-handback";
14186
+ /** The one line a failed boot shows: plain words, never a status code (SAA-434). */
14187
+ var BOOT_FAILED = "Could not start the conversation.";
14049
14188
  /** Must equal `WIDGET_DESK_MESSAGE_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
14050
14189
  var DESK_MESSAGE_EVENT = "desk:message";
14051
14190
  /** Must equal `WIDGET_DESK_TYPING_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
@@ -14230,7 +14369,7 @@ function stripCartLineIds(cart) {
14230
14369
  };
14231
14370
  }
14232
14371
  function useChatSession(options) {
14233
- const { embedKey, attribution, apiBase = DEFAULT_API_BASE, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, idlePollIntervalMs = DEFAULT_IDLE_POLL_INTERVAL_MS, socketUrl, socketPath = DEFAULT_SOCKET_PATH, collector, hostRoutes } = options;
14372
+ const { embedKey, attribution, apiBase = DEFAULT_API_BASE, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, idlePollIntervalMs = DEFAULT_IDLE_POLL_INTERVAL_MS, lightPollIntervalMs = DEFAULT_LIGHT_POLL_INTERVAL_MS, socketUrl, socketPath = DEFAULT_SOCKET_PATH, collector, hostRoutes } = options;
14234
14373
  const fetchImpl = options.fetchImpl ?? fetch;
14235
14374
  const socketFactory = options.socketImpl;
14236
14375
  const now = useMemo(() => options.now ?? (() => Date.now()), []);
@@ -14334,6 +14473,22 @@ function useChatSession(options) {
14334
14473
  const lastSeqRef = useRef(0);
14335
14474
  /** Every `seq` already rendered, from EITHER path — the actual dedupe guard; see the module doc comment. */
14336
14475
  const seenSeqRef = useRef(/* @__PURE__ */ new Set());
14476
+ /**
14477
+ * Seqs a poll page skipped over (seq 7 arrived, seq 6 did not), with the
14478
+ * instant each was first missed. The poll keeps asking from below the
14479
+ * oldest one for `SEQ_GAP_HOLD_MS` — see that constant.
14480
+ */
14481
+ const seqGapsRef = useRef(/* @__PURE__ */ new Map());
14482
+ /**
14483
+ * The ids of the exchange whose `POST /widget/chat` reply is streaming, or
14484
+ * `null` — so a hand-back that lands mid-reply keeps `status` at
14485
+ * `'streaming'` and puts its divider above that exchange (SAA-420). See
14486
+ * `markHandbackToAi`.
14487
+ */
14488
+ const replyInFlightRef = useRef(null);
14489
+ /** Turns sent while a reply streams, posted in order after it (SAA-434). */
14490
+ const queuedTurnsRef = useRef([]);
14491
+ const captureEventCountRef = useRef(0);
14337
14492
  const pollTimerRef = useRef(void 0);
14338
14493
  const pollIntervalRef = useRef(pollIntervalMs);
14339
14494
  const mountedRef = useRef(true);
@@ -14422,6 +14577,13 @@ function useChatSession(options) {
14422
14577
  */
14423
14578
  const handoffEventAppendedRef = useRef(false);
14424
14579
  /**
14580
+ * How many handoff / hand-back markers this page load has appended — the
14581
+ * ordinals that keep each marker's id unique when a conversation goes to a
14582
+ * person, comes back, and goes again (see `markHandbackToAi`).
14583
+ */
14584
+ const handoffCountRef = useRef(0);
14585
+ const handbackCountRef = useRef(0);
14586
+ /**
14425
14587
  * The CURRENT chat token's expiry, epoch ms — `Date.parse` of whatever
14426
14588
  * `expiresAt` the last successful boot or refresh returned, `null` before
14427
14589
  * the first one (or when an api build predates the field, in which case
@@ -14492,8 +14654,10 @@ function useChatSession(options) {
14492
14654
  /**
14493
14655
  * The ONE place turns from push OR poll become `ChatTurn`s. Dedupes by
14494
14656
  * `seq` (never renders the same turn twice, whichever path delivers it
14495
- * first) and advances `lastSeqRef` to the highest seq seen so far (the
14496
- * poll's `afterSeq` query param), regardless of which path saw it.
14657
+ * first). Only a `'poll'` batch advances `lastSeqRef` (the poll's
14658
+ * `afterSeq` query param) — see the module doc comment's "Only a POLL
14659
+ * result moves the poll cursor" for the reply that was lost when a push
14660
+ * moved it too.
14497
14661
  *
14498
14662
  * ## A seen seq is still allowed to CORRECT the turn it named
14499
14663
  *
@@ -14520,15 +14684,24 @@ function useChatSession(options) {
14520
14684
  * is no case where it should, since the restrictive answer is the
14521
14685
  * socket's and the socket arrives first.
14522
14686
  */
14523
- const mergeIncoming = useCallback((incoming) => {
14687
+ const mergeIncoming = useCallback((incoming, source) => {
14524
14688
  if (!mountedRef.current || !Array.isArray(incoming) || incoming.length === 0) return;
14525
14689
  const sorted = incoming.slice().sort((a, b) => a.seq - b.seq);
14526
- const fresh = sorted.filter((t) => !seenSeqRef.current.has(t.seq));
14527
- const repeats = sorted.filter((t) => seenSeqRef.current.has(t.seq));
14690
+ if (source === "poll") {
14691
+ const returned = new Set(sorted.map((t) => t.seq));
14692
+ const top = sorted.reduce((max, t) => Math.max(max, t.seq), lastSeqRef.current);
14693
+ const now = Date.now();
14694
+ if (lastSeqRef.current > 0) {
14695
+ for (let seq = Math.max(lastSeqRef.current + 1, top - 20); seq < top; seq++) if (!returned.has(seq) && !seenSeqRef.current.has(seq)) seqGapsRef.current.set(seq, now);
14696
+ }
14697
+ for (const seq of returned) seqGapsRef.current.delete(seq);
14698
+ lastSeqRef.current = top;
14699
+ }
14700
+ const fresh = sorted.filter((t) => t.role === "event" || !seenSeqRef.current.has(t.seq));
14701
+ const repeats = sorted.filter((t) => t.role !== "event" && seenSeqRef.current.has(t.seq));
14528
14702
  if (fresh.length === 0 && repeats.length === 0) return;
14529
14703
  if (fresh.some((t) => speakerFor(t.role) === "agent")) clearDeskTyping();
14530
- for (const t of fresh) seenSeqRef.current.add(t.seq);
14531
- lastSeqRef.current = fresh.reduce((max, t) => Math.max(max, t.seq), lastSeqRef.current);
14704
+ for (const t of fresh) if (t.role !== "event") seenSeqRef.current.add(t.seq);
14532
14705
  setTurns((prev) => {
14533
14706
  const baseId = (id) => {
14534
14707
  const colon = id.indexOf(":");
@@ -14551,7 +14724,14 @@ function useChatSession(options) {
14551
14724
  });
14552
14725
  if (unseen.length === 0) return corrected ? patched : prev;
14553
14726
  const next = [...patched];
14554
- for (const turn of unseen.map((t) => ({
14727
+ for (const turn of unseen.map((t) => t.role === "event" ? {
14728
+ id: t.id,
14729
+ speaker: "event",
14730
+ event: t.event,
14731
+ text: "",
14732
+ final: true,
14733
+ seq: t.seq
14734
+ } : {
14555
14735
  id: t.id,
14556
14736
  speaker: speakerFor(t.role),
14557
14737
  text: t.text ?? "",
@@ -14560,7 +14740,7 @@ function useChatSession(options) {
14560
14740
  ...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {},
14561
14741
  ...t.cards && Array.isArray(t.cards.items) && t.cards.items.length > 0 ? { cards: t.cards } : {},
14562
14742
  ...typeof t.operatorName === "string" && t.operatorName !== "" ? { operatorName: t.operatorName } : {}
14563
- }))) insertBySeq(next, turn);
14743
+ })) insertBySeq(next, turn);
14564
14744
  return next;
14565
14745
  });
14566
14746
  }, [clearDeskTyping]);
@@ -14594,30 +14774,123 @@ function useChatSession(options) {
14594
14774
  setStatus("escalated");
14595
14775
  if (handoffEventAppendedRef.current) return;
14596
14776
  handoffEventAppendedRef.current = true;
14777
+ handoffCountRef.current += 1;
14778
+ const id = handoffCountRef.current === 1 ? HANDOFF_EVENT_TURN_ID : `${HANDOFF_EVENT_TURN_ID}-${handoffCountRef.current}`;
14597
14779
  setTurns((prev) => [...prev, {
14598
- id: HANDOFF_EVENT_TURN_ID,
14780
+ id,
14599
14781
  speaker: "event",
14600
14782
  event: "handoff",
14601
14783
  text: "",
14602
14784
  final: true
14603
14785
  }]);
14604
14786
  }, []);
14605
- const poll = useCallback(async () => {
14787
+ /**
14788
+ * The desk handed the conversation back to the concierge (SAA-420): leave
14789
+ * the escalated state and record the hand-back IN the transcript, the
14790
+ * mirror of {@link markHandoffToHuman}.
14791
+ *
14792
+ * Two transports report it — the widget room's `desk:ownership { to: 'ai' }`
14793
+ * push, and the SSE `resumed` event the AI's first reply after a release
14794
+ * carries for a visitor whose socket missed the push. Either may arrive
14795
+ * first, or both; the first one does the work and the second finds nothing
14796
+ * to undo.
14797
+ *
14798
+ * A no-op unless this page load has a handoff on screen. `resumed` is
14799
+ * computed server-side from the conversation's ownership history, which
14800
+ * can name a release this page never saw the escalation for (yesterday's
14801
+ * session, say); a "back with the concierge" divider with no handoff above
14802
+ * it would announce a return from somewhere the shopper never went.
14803
+ *
14804
+ * Resets the once-per-handoff guard, so a SECOND takeover draws its own
14805
+ * handoff marker rather than being swallowed by the first one's. Stops the
14806
+ * poll interval and (via `status` leaving `'escalated'`) closes the socket
14807
+ * — both exist only for a person-held conversation — and drops the
14808
+ * operator's typing dots, which nothing will now retire.
14809
+ *
14810
+ * @param options.before ids of turns the divider must sit ABOVE. The
14811
+ * `resumed` path passes the exchange it arrived on: the release
14812
+ * happened before the shopper's message, so the divider goes there
14813
+ * rather than under the reply it interrupts.
14814
+ * @param options.next the status to land on — `'streaming'` while a reply
14815
+ * is still arriving on the same stream, `'idle'` otherwise.
14816
+ */
14817
+ const markHandbackToAi = useCallback((options) => {
14818
+ if (!mountedRef.current || !handoffEventAppendedRef.current) return;
14819
+ handoffEventAppendedRef.current = false;
14820
+ handbackCountRef.current += 1;
14821
+ const marker = {
14822
+ id: `${HANDBACK_EVENT_TURN_ID}-${handbackCountRef.current}`,
14823
+ speaker: "event",
14824
+ event: "handback",
14825
+ text: "",
14826
+ final: true
14827
+ };
14828
+ const before = new Set(options?.before ?? replyInFlightRef.current ?? []);
14829
+ setTurns((prev) => {
14830
+ const at = prev.findIndex((t) => before.has(t.id));
14831
+ return at === -1 ? [...prev, marker] : [
14832
+ ...prev.slice(0, at),
14833
+ marker,
14834
+ ...prev.slice(at)
14835
+ ];
14836
+ });
14837
+ const next = options?.next ?? (replyInFlightRef.current !== null ? "streaming" : "idle");
14838
+ setStatus((prev) => prev === "escalated" ? next : prev);
14839
+ if (pollTimerRef.current !== void 0) {
14840
+ clearInterval(pollTimerRef.current);
14841
+ pollTimerRef.current = void 0;
14842
+ }
14843
+ clearDeskTyping();
14844
+ }, [clearDeskTyping]);
14845
+ /** See {@link UseChatSessionResult.markCaptureAnswered}. */
14846
+ const markCaptureAnswered = useCallback((outcome) => {
14847
+ if (!mountedRef.current) return;
14848
+ const id = `event-capture-${captureEventCountRef.current += 1}`;
14849
+ setTurns((prev) => [...prev, {
14850
+ id,
14851
+ speaker: "event",
14852
+ event: outcome === "saved" ? "capture_saved" : "capture_declined",
14853
+ text: "",
14854
+ final: true
14855
+ }]);
14856
+ }, []);
14857
+ const poll = useCallback(async (detectHandoff, events) => {
14606
14858
  const chatToken = chatTokenRef.current;
14607
14859
  if (chatToken === void 0) return;
14860
+ let afterSeq = lastSeqRef.current;
14861
+ const now = Date.now();
14862
+ for (const [seq, missedAt] of seqGapsRef.current) if (seenSeqRef.current.has(seq) || now - missedAt > SEQ_GAP_HOLD_MS) seqGapsRef.current.delete(seq);
14863
+ else afterSeq = Math.min(afterSeq, seq - 1);
14608
14864
  try {
14609
- const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/messages?afterSeq=${lastSeqRef.current}`, embedKey), { headers: { authorization: `Bearer ${chatToken}` } });
14865
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/messages?afterSeq=${afterSeq}${events ? "&events=1" : ""}`, embedKey), { headers: { authorization: `Bearer ${chatToken}` } });
14610
14866
  if (!res.ok) return;
14611
14867
  const body = await res.json();
14612
- mergeIncoming(body.messages ?? body.turns ?? []);
14868
+ const rows = body.messages ?? body.turns ?? [];
14869
+ if (detectHandoff && Array.isArray(rows) && rows.some((t) => t.role === "human" && !seenSeqRef.current.has(t.seq))) markHandoffToHuman();
14870
+ if (events && Array.isArray(rows)) {
14871
+ const last = rows.filter((t) => t.event === "handoff" || t.event === "handback").pop();
14872
+ if (last) handoffEventAppendedRef.current = last.event === "handoff";
14873
+ }
14874
+ mergeIncoming(rows, "poll");
14613
14875
  } catch {}
14614
14876
  }, [
14615
14877
  apiBase,
14616
14878
  embedKey,
14617
14879
  fetchImpl,
14618
- mergeIncoming
14880
+ mergeIncoming,
14881
+ markHandoffToHuman
14619
14882
  ]);
14620
14883
  /**
14884
+ * The CURRENT `poll`, for the socket's `connect` handler. A ref rather than
14885
+ * a dependency of the socket effect: that effect tears the socket down and
14886
+ * opens a new one whenever a dependency changes, and a catch-up poll is not
14887
+ * a reason to drop a live connection.
14888
+ */
14889
+ const pollRef = useRef(poll);
14890
+ useEffect(() => {
14891
+ pollRef.current = poll;
14892
+ }, [poll]);
14893
+ /**
14621
14894
  * (Re)starts the interval at `intervalMs` — called both on first
14622
14895
  * escalation and whenever `connection` flips (see the effect below), so
14623
14896
  * the cadence always reflects the CURRENT socket state, not just the one
@@ -14733,7 +15006,8 @@ function useChatSession(options) {
14733
15006
  const bootSession = useCallback(async (args) => {
14734
15007
  const isStale = args.isStale;
14735
15008
  const isMount = args.phase === "mount";
14736
- const stored = readStoredVisitor();
15009
+ const own = readStoredVisitor();
15010
+ const stored = !own.visitorId && collector?.visitorIdentity || own;
14737
15011
  const bootRequestedAt = now();
14738
15012
  const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/session`, embedKey), {
14739
15013
  method: "POST",
@@ -14747,13 +15021,14 @@ function useChatSession(options) {
14747
15021
  ...hostRoutes !== void 0 ? { hostRoutes } : {}
14748
15022
  })
14749
15023
  });
14750
- if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
15024
+ if (!res.ok) throw new Error(BOOT_FAILED);
14751
15025
  const body = await res.json();
14752
15026
  if (isStale?.() || !mountedRef.current) return;
14753
15027
  const receivedAt = now();
14754
15028
  const ttlMs = tokenTtlMs(res, body.expiresAt, receivedAt);
14755
15029
  adoptChatToken(body.chatToken);
14756
15030
  lastSeqRef.current = 0;
15031
+ seqGapsRef.current.clear();
14757
15032
  seenSeqRef.current.clear();
14758
15033
  visitorSessionIdRef.current = body.visitorSessionId;
14759
15034
  sessionOriginRef.current = bootRequestedAt;
@@ -14826,7 +15101,8 @@ function useChatSession(options) {
14826
15101
  }]);
14827
15102
  if (isMount && body.resumed === true) {
14828
15103
  lastSeqRef.current = 0;
14829
- poll();
15104
+ seqGapsRef.current.clear();
15105
+ poll(false, true);
14830
15106
  }
14831
15107
  setStatus((prev) => prev === "escalated" ? prev : "idle");
14832
15108
  scheduleRefresh(ttlMs);
@@ -14857,10 +15133,10 @@ function useChatSession(options) {
14857
15133
  phase: "mount",
14858
15134
  isStale: () => cancelled
14859
15135
  });
14860
- } catch (err) {
15136
+ } catch {
14861
15137
  if (cancelled) return;
14862
15138
  setStatus("error");
14863
- setError(err instanceof Error ? err.message : "Could not start the conversation.");
15139
+ setError(BOOT_FAILED);
14864
15140
  } finally {
14865
15141
  if (!cancelled) setReady(true);
14866
15142
  }
@@ -14882,10 +15158,10 @@ function useChatSession(options) {
14882
15158
  const rebootSession = useCallback(async () => {
14883
15159
  try {
14884
15160
  await bootSession({ phase: "recovery" });
14885
- } catch (err) {
15161
+ } catch {
14886
15162
  if (!mountedRef.current) return;
14887
15163
  setStatus("error");
14888
- setError(err instanceof Error ? err.message : "Could not start the conversation.");
15164
+ setError(BOOT_FAILED);
14889
15165
  }
14890
15166
  }, [bootSession]);
14891
15167
  /**
@@ -15050,7 +15326,7 @@ function useChatSession(options) {
15050
15326
  let cancelled = false;
15051
15327
  setConnection("connecting");
15052
15328
  (async () => {
15053
- const factory = socketFactory ?? (await import("./esm-DSxqq2-d.js")).io;
15329
+ const factory = socketFactory ?? (await import("./esm-D2iq2DjO.js")).io;
15054
15330
  if (cancelled) return;
15055
15331
  const socket = factory(`${socketUrl}${SOCKET_NAMESPACE}`, {
15056
15332
  path: socketPath,
@@ -15061,7 +15337,9 @@ function useChatSession(options) {
15061
15337
  });
15062
15338
  socketRef.current = socket;
15063
15339
  socket.on("connect", () => {
15064
- if (mountedRef.current) setConnection("connected");
15340
+ if (!mountedRef.current) return;
15341
+ setConnection("connected");
15342
+ pollRef.current();
15065
15343
  });
15066
15344
  socket.on("disconnect", () => {
15067
15345
  if (mountedRef.current) setConnection("disconnected");
@@ -15070,7 +15348,13 @@ function useChatSession(options) {
15070
15348
  if (mountedRef.current) setConnection("disconnected");
15071
15349
  });
15072
15350
  socket.on(DESK_MESSAGE_EVENT, (message) => {
15073
- mergeIncoming([message]);
15351
+ mergeIncoming([message], "push");
15352
+ });
15353
+ socket.on(DESK_OWNERSHIP_EVENT, (payload) => {
15354
+ const event = parseDeskOwnershipEvent(payload);
15355
+ if (!event || !mountedRef.current) return;
15356
+ if (event.to === "ai") markHandbackToAi();
15357
+ else markHandoffToHuman();
15074
15358
  });
15075
15359
  socket.on(DESK_TYPING_EVENT, () => {
15076
15360
  if (!mountedRef.current) return;
@@ -15093,6 +15377,8 @@ function useChatSession(options) {
15093
15377
  socketFactory,
15094
15378
  mergeIncoming,
15095
15379
  clearDeskTyping,
15380
+ markHandbackToAi,
15381
+ markHandoffToHuman,
15096
15382
  bootGeneration
15097
15383
  ]);
15098
15384
  useEffect(() => {
@@ -15105,6 +15391,33 @@ function useChatSession(options) {
15105
15391
  pollIntervalMs,
15106
15392
  idlePollIntervalMs
15107
15393
  ]);
15394
+ useEffect(() => {
15395
+ if (status !== "escalated") return;
15396
+ pollRef.current();
15397
+ }, [status]);
15398
+ const escalated = status === "escalated";
15399
+ useEffect(() => {
15400
+ if (!ready || escalated) return;
15401
+ let timer;
15402
+ const sync = () => {
15403
+ if (document.visibilityState === "hidden") {
15404
+ clearInterval(timer);
15405
+ timer = void 0;
15406
+ } else if (timer === void 0) timer = setInterval(() => {
15407
+ if (replyInFlightRef.current === null) pollRef.current(true);
15408
+ }, lightPollIntervalMs);
15409
+ };
15410
+ sync();
15411
+ document.addEventListener("visibilitychange", sync);
15412
+ return () => {
15413
+ clearInterval(timer);
15414
+ document.removeEventListener("visibilitychange", sync);
15415
+ };
15416
+ }, [
15417
+ ready,
15418
+ escalated,
15419
+ lightPollIntervalMs
15420
+ ]);
15108
15421
  /**
15109
15422
  * The ONE place a turn is posted to `POST /widget/chat`, shared by `send`
15110
15423
  * (shopper text) and `sendReport` (a typed storefront report).
@@ -15118,14 +15431,32 @@ function useChatSession(options) {
15118
15431
  */
15119
15432
  const postTurn = useCallback(async (payload, options) => {
15120
15433
  const chatToken = chatTokenRef.current;
15121
- if (chatToken === void 0 || status === "streaming") return false;
15434
+ if (chatToken === void 0) return false;
15122
15435
  const text = "message" in payload ? payload.message : "";
15123
15436
  const silent = options?.silent === true || !("message" in payload);
15124
- const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
15437
+ const callerTurnId = options?.queuedId ?? `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
15125
15438
  const agentTurnId = `agent-${callerTurnId}`;
15439
+ if (status === "streaming" || replyInFlightRef.current !== null && status !== "escalated") {
15440
+ if (options?.quietOnHttpError === true) return false;
15441
+ queuedTurnsRef.current.push({
15442
+ payload,
15443
+ options: {
15444
+ ...options,
15445
+ ...silent ? {} : { queuedId: callerTurnId }
15446
+ }
15447
+ });
15448
+ if (!silent) setTurns((prev) => [...prev, {
15449
+ id: callerTurnId,
15450
+ speaker: "caller",
15451
+ text,
15452
+ final: true,
15453
+ delivery: "sending"
15454
+ }]);
15455
+ return true;
15456
+ }
15126
15457
  setTurns((prev) => [
15127
15458
  ...prev,
15128
- ...silent ? [] : [{
15459
+ ...silent || options?.queuedId !== void 0 ? [] : [{
15129
15460
  id: callerTurnId,
15130
15461
  speaker: "caller",
15131
15462
  text,
@@ -15140,7 +15471,15 @@ function useChatSession(options) {
15140
15471
  }
15141
15472
  ]);
15142
15473
  setStatus((prev) => prev === "escalated" ? prev : "streaming");
15474
+ const inFlight = [callerTurnId, agentTurnId];
15475
+ replyInFlightRef.current = inFlight;
15476
+ const release = () => {
15477
+ if (replyInFlightRef.current !== inFlight) return false;
15478
+ replyInFlightRef.current = null;
15479
+ return true;
15480
+ };
15143
15481
  const rollBack = () => {
15482
+ release();
15144
15483
  setTurns((prev) => prev.filter((t) => t.id !== callerTurnId && t.id !== agentTurnId));
15145
15484
  };
15146
15485
  const postChat = (cart) => fetchImpl(withEmbedKeyParam(`${apiBase}/chat`, embedKey), {
@@ -15176,7 +15515,7 @@ function useChatSession(options) {
15176
15515
  if (!res.ok || res.body === null) {
15177
15516
  rollBack();
15178
15517
  setStatus("error");
15179
- setError(`The conversation could not accept that message (${res.status}).`);
15518
+ setError(res.status === 400 ? "That message could not be sent. Please shorten it and try again." : "That message could not be sent. Please try again.");
15180
15519
  return false;
15181
15520
  }
15182
15521
  if (mountedRef.current) setTurns((prev) => prev.map((t) => t.id === callerTurnId ? {
@@ -15202,7 +15541,14 @@ function useChatSession(options) {
15202
15541
  onEscalated: () => {
15203
15542
  markHandoffToHuman();
15204
15543
  },
15544
+ onResumed: () => {
15545
+ markHandbackToAi({
15546
+ before: [callerTurnId, agentTurnId],
15547
+ next: "streaming"
15548
+ });
15549
+ },
15205
15550
  onDone: (turnId) => {
15551
+ release();
15206
15552
  if (!mountedRef.current) return;
15207
15553
  setTurns((prev) => prev.filter((t) => t.id !== turnId || t.id === agentTurnId).map((t) => t.id === agentTurnId ? {
15208
15554
  ...t,
@@ -15212,6 +15558,7 @@ function useChatSession(options) {
15212
15558
  setStatus((prev) => prev === "escalated" ? prev : "idle");
15213
15559
  },
15214
15560
  onError: (message) => {
15561
+ release();
15215
15562
  if (!mountedRef.current) return;
15216
15563
  setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
15217
15564
  ...t,
@@ -15221,6 +15568,13 @@ function useChatSession(options) {
15221
15568
  setError(message);
15222
15569
  },
15223
15570
  isMounted: () => mountedRef.current
15571
+ }).finally(() => {
15572
+ if (!release() || !mountedRef.current) return;
15573
+ setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
15574
+ ...t,
15575
+ final: true
15576
+ } : t));
15577
+ setStatus((prev) => prev === "streaming" ? "idle" : prev);
15224
15578
  });
15225
15579
  return true;
15226
15580
  }, [
@@ -15228,7 +15582,23 @@ function useChatSession(options) {
15228
15582
  embedKey,
15229
15583
  fetchImpl,
15230
15584
  status,
15231
- markHandoffToHuman
15585
+ markHandoffToHuman,
15586
+ markHandbackToAi
15587
+ ]);
15588
+ useEffect(() => {
15589
+ if (status === "streaming" || replyInFlightRef.current !== null) return;
15590
+ if (status === "error") {
15591
+ const dropped = new Set(queuedTurnsRef.current.map((q) => q.options.queuedId));
15592
+ queuedTurnsRef.current = [];
15593
+ if (dropped.size > 0) setTurns((prev) => prev.filter((t) => !dropped.has(t.id)));
15594
+ return;
15595
+ }
15596
+ const next = queuedTurnsRef.current.shift();
15597
+ if (next) postTurn(next.payload, next.options);
15598
+ }, [
15599
+ status,
15600
+ turns,
15601
+ postTurn
15232
15602
  ]);
15233
15603
  const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
15234
15604
  const sendReport = useCallback(async (report, options) => postTurn({ report }, options?.quietOnHttpError === true ? { quietOnHttpError: true } : void 0), [postTurn]);
@@ -15636,7 +16006,8 @@ function useChatSession(options) {
15636
16006
  notifyTyping,
15637
16007
  checkout,
15638
16008
  sendAttachment,
15639
- markHandoffToHuman
16009
+ markHandoffToHuman,
16010
+ markCaptureAnswered
15640
16011
  };
15641
16012
  }
15642
16013
  /**
@@ -15645,7 +16016,7 @@ function useChatSession(options) {
15645
16016
  * promise and is trivially unit-testable with a synthetic `ReadableStream`.
15646
16017
  */
15647
16018
  async function streamReply(args) {
15648
- const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onActEvent, onEscalated, onDone, onError, isMounted } = args;
16019
+ const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onActEvent, onEscalated, onResumed, onDone, onError, isMounted } = args;
15649
16020
  const reader = body.getReader();
15650
16021
  const decoder = new TextDecoder();
15651
16022
  const parser = new SseFrameParser();
@@ -15788,6 +16159,9 @@ async function streamReply(args) {
15788
16159
  case "escalated":
15789
16160
  onEscalated();
15790
16161
  break;
16162
+ case "resumed":
16163
+ onResumed();
16164
+ break;
15791
16165
  case "done":
15792
16166
  onDone(evt.data?.turnId ?? agentTurnId);
15793
16167
  break;
@@ -15810,7 +16184,7 @@ async function streamReply(args) {
15810
16184
  * cache makes a second `start()` after `stop()` free).
15811
16185
  */
15812
16186
  async function loadVoiceProtocol() {
15813
- const [telemetry, chat] = await Promise.all([import("./telemetry-3f--vvdX.js"), import("./chat-R7z4DtMM.js")]);
16187
+ const [telemetry, chat] = await Promise.all([import("./telemetry-UHSrhVyf.js"), import("./chat-CrbRIHVN.js")]);
15814
16188
  return {
15815
16189
  decodeTelemetry: telemetry.decodeTelemetry,
15816
16190
  encodeCallerText: telemetry.encodeCallerText,
@@ -17649,7 +18023,7 @@ function ConciergeWidget({ renderer, ...props }) {
17649
18023
  renderer: renderer ?? rendererFor(props.generation)
17650
18024
  });
17651
18025
  }
17652
- function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bridge, siteProfile, collector, messages = defaultWidgetMessages, locale = "en", productHref, hostRoutes, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, privacyChoices, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady, cartLineIds }) {
18026
+ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bridge, siteProfile, collector, messages = defaultWidgetMessages, locale = "en", productHref, hostRoutes, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, privacyChoices, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, starters, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady, cartLineIds }) {
17653
18027
  /**
17654
18028
  * Maps the tenant's semantic config fields onto the widget's historical
17655
18029
  * CSS custom properties — this is the "one becomes the other" site
@@ -18353,6 +18727,8 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
18353
18727
  autoFocus: !inCallRef.current,
18354
18728
  submit: session.submitCapture,
18355
18729
  onAnswered: (outcome) => {
18730
+ setCaptureCard(null);
18731
+ session.markCaptureAnswered(outcome);
18356
18732
  if (!inCallRef.current) session.sendReport({
18357
18733
  kind: "capture_card",
18358
18734
  field: event.field,
@@ -19362,6 +19738,11 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
19362
19738
  };
19363
19739
  return bridge.onPageChange(read);
19364
19740
  }, [bridge]);
19741
+ const [pick, setPick] = useState();
19742
+ useEffect(() => {
19743
+ if (starters) import("./starters-pick-noq7o_W8.js").then((mod) => setPick(() => mod.startersFor), () => {});
19744
+ }, [starters]);
19745
+ const suggestions = pick ? pick(starters, location.pathname, locale) : starters ? [] : void 0;
19365
19746
  /**
19366
19747
  * The shelf (§3.4): the LATEST curation, and only the latest.
19367
19748
  *
@@ -19439,6 +19820,7 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
19439
19820
  ...productHref ? { productHref } : {},
19440
19821
  ...navigate ? { navigate } : {},
19441
19822
  messages,
19823
+ suggestions,
19442
19824
  locale,
19443
19825
  ...skinStyle !== void 0 ? { skinStyle } : {},
19444
19826
  ...avatar !== void 0 ? { avatar } : {},
@@ -19449,4 +19831,4 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
19449
19831
  });
19450
19832
  }
19451
19833
  //#endregion
19452
- export { deriveDockState as $, WIDGET_THEME_TOKENS as $t, rendererFor as A, BotFace as An, SHEET_EXPANDED_VH as At, nearestPosition as B, persistAlign as Bt, readsAsCartViewIntent as C, widgetMessagesFromCopy as Cn, MOBILE_MARGIN as Ct, WidgetCardList as D, isWidgetAvatar as Dn, RADII as Dt, WidgetCartSummary as E, WIDGET_AVATARS as En, PROACTIVE_NUDGE_MS as Et, ConciergeLauncher as F, SHORT_VIEWPORT as Ft, botStateFor as G, readStoredMinimised as Gt, positionClasses as H, pillAnchor as Ht, CONCIERGE_POSITIONS as I, Z_INDEX as It, SessionLog as J, snapAlign as Jt, SseFrameParser as K, rowWidthLen as Kt, DEFAULT_CONCIERGE_POSITION as L, bottomLen as Lt, ShellRenderer as M, cn as Mn, SHEET_PEEK_MAX as Mt, deriveWidgetView as N, SHEET_TOP_CLEARANCE as Nt, WidgetMarkdown as O, KNOT_PATH as On, ROW_H as Ot, ConciergeShell as P, SHEET_TUCK as Pt, DOCK_STATES as Q, SYSTEM_FONT_STACK as Qt, alignOf as R, containerAnchor as Rt, basketIntentFromTurns as S, resolveWidgetMessages as Sn, MARK as St, textDirectionFor as T, DEFAULT_WIDGET_AVATAR as Tn, PILL_MARK as Tt, positionForArrow as U, readStored as Ut, panelClasses as V, persistMinimised as Vt, IDLE_SNAPSHOT as W, readStoredAlign as Wt, latencyBetween as X, CARD_RADIUS_MAX_PX as Xt, formatMs as Y, writeStored as Yt, Dock as Z, SHEET_RADIUS_MAX_PX as Zt, isSameOriginPath as _, rotateHue as _n, DRAG_CLICK_WINDOW_MS as _t, MAX_REPORTED_CART_LINES as a, hexToOklab as an, deriveConciergeState as at, VoiceWidget as b, defaultWidgetMessages as bn, FLOAT_GAP as bt, deriveCallPhase as c, linearToSrgb as cn, ACTIVITY_W as ct, resolveCheckoutUrl as d, oklabToLinearRgb as dn, DESKTOP_BOTTOM as dt, deriveTheme as en, deriveDockView as et, toChatCart as f, oklabToOklch as fn, DESKTOP_BREAKPOINT as ft, CHECKOUT_CAPTURE_REQUIRED as g, relativeLuminance as gn, DOCK_MINIMISED_STORAGE_KEY as gt, useVoiceSession as h, parseHex as hn, DOCK_ALIGN_STORAGE_KEY as ht, ConciergeWidget as i, formatHex as in, CONCIERGE_STATES as it, DockRenderer as j, labelProps as jn, SHEET_GAP as jt, parseBlocks as k, RopeKnot as kn, SHEET_EXPANDED_DESKTOP_MAX as kt, mergeAddedCartLine as l, mixToward as ln, BOTTOM_FLOOR as lt, createWidgetVoiceTokenFetcher as m, oklchToOklab as mn, DESKTOP_WIDTHS as mt, CART_LINE_VARIANT_ID_SHAPE as n, themeToInlineStyle as nn, idleDockInput as nt, cartLinesFromSnapshot as o, hexToOklch as on, idleConciergeInput as ot, ROOM_EVENTS as p, oklchToHex as pn, DESKTOP_GUTTER as pt, SESSION_EVENTS as q, sheetMaxHeightLen as qt, ConciergeHost as r, contrastRatio as rn, latestExchangeStart as rt, chooseOptionsAction as s, linearRgbToOklab as sn, formatMoney as st, CART_LINE_PLATFORM_VARIANT_ID_SHAPE as t, themeToCss as tn, exchangeCount as tt, resolveAddToCartHandler as u, oklabToHex as un, CONTROL as ut, useChatSession as v, srgbToLinear as vn, DRAG_TAP_SLOP_PX as vt, readsAsCheckoutIntent as w, MorphingLoader as wn, PILL_H as wt, VoiceWidgetWithRenderer as x, formatMessage as xn, GLASS_IDLE_MS as xt, detectPage as y, withAlpha as yn, FLOAT_DUCK_DISMISS_MS as yt, edgeOf as z, geometryVars as zt };
19834
+ export { DOCK_STATES as $, WIDGET_THEME_TOKENS as $t, stripBidiControls as A, BotFace as An, SHEET_EXPANDED_VH as At, edgeOf as B, persistAlign as Bt, readsAsCartViewIntent as C, widgetMessagesFromCopy as Cn, MOBILE_MARGIN as Ct, WidgetCardList as D, isWidgetAvatar as Dn, RADII as Dt, WidgetCartSummary as E, WIDGET_AVATARS as En, PROACTIVE_NUDGE_MS as Et, ConciergeShell as F, SHORT_VIEWPORT as Ft, IDLE_SNAPSHOT as G, readStoredMinimised as Gt, panelClasses as H, pillAnchor as Ht, ConciergeLauncher as I, Z_INDEX as It, SESSION_EVENTS as J, snapAlign as Jt, botStateFor as K, rowWidthLen as Kt, CONCIERGE_POSITIONS as L, bottomLen as Lt, DockRenderer as M, cn as Mn, SHEET_PEEK_MAX as Mt, ShellRenderer as N, SHEET_TOP_CLEARANCE as Nt, WidgetMarkdown as O, KNOT_PATH as On, ROW_H as Ot, deriveWidgetView as P, SHEET_TUCK as Pt, Dock as Q, SYSTEM_FONT_STACK as Qt, DEFAULT_CONCIERGE_POSITION as R, containerAnchor as Rt, basketIntentFromTurns as S, resolveWidgetMessages as Sn, MARK as St, textDirectionFor as T, DEFAULT_WIDGET_AVATAR as Tn, PILL_MARK as Tt, positionClasses as U, readStored as Ut, nearestPosition as V, persistMinimised as Vt, positionForArrow as W, readStoredAlign as Wt, formatMs as X, CARD_RADIUS_MAX_PX as Xt, SessionLog as Y, writeStored as Yt, latencyBetween as Z, SHEET_RADIUS_MAX_PX as Zt, isSameOriginPath as _, rotateHue as _n, DRAG_CLICK_WINDOW_MS as _t, MAX_REPORTED_CART_LINES as a, hexToOklab as an, idleConciergeInput as at, VoiceWidget as b, defaultWidgetMessages as bn, FLOAT_GAP as bt, deriveCallPhase as c, linearToSrgb as cn, ACTIVITY_W as ct, resolveCheckoutUrl as d, oklabToLinearRgb as dn, DESKTOP_BOTTOM as dt, deriveTheme as en, deriveDockState as et, toChatCart as f, oklabToOklch as fn, DESKTOP_BREAKPOINT as ft, CHECKOUT_CAPTURE_REQUIRED as g, relativeLuminance as gn, DOCK_MINIMISED_STORAGE_KEY as gt, useVoiceSession as h, parseHex as hn, DOCK_ALIGN_STORAGE_KEY as ht, ConciergeWidget as i, formatHex as in, deriveConciergeState as it, rendererFor as j, labelProps as jn, SHEET_GAP as jt, parseBlocks as k, RopeKnot as kn, SHEET_EXPANDED_DESKTOP_MAX as kt, mergeAddedCartLine as l, mixToward as ln, BOTTOM_FLOOR as lt, createWidgetVoiceTokenFetcher as m, oklchToOklab as mn, DESKTOP_WIDTHS as mt, CART_LINE_VARIANT_ID_SHAPE as n, themeToInlineStyle as nn, idleDockInput as nt, cartLinesFromSnapshot as o, hexToOklch as on, formatMoney as ot, ROOM_EVENTS as p, oklchToHex as pn, DESKTOP_GUTTER as pt, SseFrameParser as q, sheetMaxHeightLen as qt, ConciergeHost as r, contrastRatio as rn, CONCIERGE_STATES as rt, chooseOptionsAction as s, linearRgbToOklab as sn, WIDGET_MESSAGE_MAX_LENGTH as st, CART_LINE_PLATFORM_VARIANT_ID_SHAPE as t, themeToCss as tn, deriveDockView as tt, resolveAddToCartHandler as u, oklabToHex as un, CONTROL as ut, useChatSession as v, srgbToLinear as vn, DRAG_TAP_SLOP_PX as vt, readsAsCheckoutIntent as w, MorphingLoader as wn, PILL_H as wt, VoiceWidgetWithRenderer as x, formatMessage as xn, GLASS_IDLE_MS as xt, detectPage as y, withAlpha as yn, FLOAT_DUCK_DISMISS_MS as yt, alignOf as z, geometryVars as zt };