@saar-ai/web-widget 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/chunks/{host-widget-BJrw-B0B.js → host-widget-CppBkOCF.js} +283 -84
  2. package/dist/concierge-shell.css +1 -1
  3. package/dist/consent/consent-prompt-dom.d.ts +7 -6
  4. package/dist/consent/consent-prompt-dom.d.ts.map +1 -1
  5. package/dist/dock/dock-caption.d.ts.map +1 -1
  6. package/dist/dock/dock.d.ts +6 -0
  7. package/dist/dock/dock.d.ts.map +1 -1
  8. package/dist/generated/concierge-shell-css.d.ts.map +1 -1
  9. package/dist/generated/widget-css.d.ts.map +1 -1
  10. package/dist/host-widget.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +147 -11
  14. package/dist/message-limit.d.ts +10 -0
  15. package/dist/message-limit.d.ts.map +1 -0
  16. package/dist/messages.d.ts +7 -0
  17. package/dist/messages.d.ts.map +1 -1
  18. package/dist/next/index.js +1 -1
  19. package/dist/theme/derive.d.ts +15 -0
  20. package/dist/theme/derive.d.ts.map +1 -1
  21. package/dist/theme/host-tone.d.ts +35 -0
  22. package/dist/theme/host-tone.d.ts.map +1 -0
  23. package/dist/use-chat-session.d.ts +11 -1
  24. package/dist/use-chat-session.d.ts.map +1 -1
  25. package/dist/voice-widget.d.ts.map +1 -1
  26. package/dist/widget/concierge-shell.d.ts +7 -1
  27. package/dist/widget/concierge-shell.d.ts.map +1 -1
  28. package/dist/widget/open-state.d.ts +3 -0
  29. package/dist/widget/open-state.d.ts.map +1 -0
  30. package/dist/widget/shell-renderer.d.ts.map +1 -1
  31. package/dist/widget/transcript-geometry.d.ts +12 -6
  32. package/dist/widget/transcript-geometry.d.ts.map +1 -1
  33. package/dist/widget-markdown.d.ts +8 -0
  34. package/dist/widget-markdown.d.ts.map +1 -1
  35. package/dist/widget.css +1 -1
  36. package/package.json +1 -1
  37. package/src/styles/tokens.css +12 -10
@@ -4619,6 +4619,8 @@ var defaultWidgetMessages = {
4619
4619
  dock_hide_conversation: "Hide conversation",
4620
4620
  handoff_event: "Handed to a human teammate",
4621
4621
  handback_event: "Back with the concierge",
4622
+ capture_saved_event: "Thanks — sent.",
4623
+ capture_declined_event: "No problem — skipped.",
4622
4624
  escalated_banner: "A human teammate will pick this up shortly.",
4623
4625
  status_sending: "Sending",
4624
4626
  status_sent: "Sent",
@@ -5099,12 +5101,13 @@ var SURFACE_GLASS_BLURRED_ALPHA = .25;
5099
5101
  *
5100
5102
  * WHY THIS IS DERIVED and not two static blocks in `styles/tokens.css`.
5101
5103
  * That was the cheaper plan and it does not work: nothing sets `.dark` on the
5102
- * shadow host. `cdn/dock-dom.ts` resolves the tone in JAVASCRIPT — it reads
5103
- * `prefers-color-scheme` once and writes the matching block as an inline
5104
- * `style` attribute — so `tokens.css`'s `.dark` rules never match the shipped
5105
- * widget, and a `@media` query there would be right only for `tone: 'auto'`
5106
- * and inverted for a tenant who pinned `light` or `dark`. The tune has to
5107
- * arrive through the same channel as the surface it is tuned for.
5104
+ * shadow host (`core`'s SAA-441 mark is `data-wgt-tone`, which that block
5105
+ * deliberately does not match). `cdn/dock-dom.ts` resolves the tone in
5106
+ * JAVASCRIPT and writes the matching block as an inline `style` attribute —
5107
+ * so `tokens.css`'s `.dark` rules never match the shipped widget, and a
5108
+ * `@media` query there would be right only for `tone: 'auto'` and inverted
5109
+ * for a tenant who pinned `light` or `dark`. The tune has to arrive through
5110
+ * the same channel as the surface it is tuned for.
5108
5111
  *
5109
5112
  * It is chosen from the SURFACE's own lightness rather than from `color.tone`
5110
5113
  * for the same reason {@link deriveText} is: the tone enum says which block
@@ -5389,14 +5392,37 @@ function block(vars, selector, indent) {
5389
5392
  * `tone: 'auto'` — a `prefers-color-scheme: dark` override on the same
5390
5393
  * selector, exactly as §9.2 requires ("both defined on `:host`").
5391
5394
  *
5395
+ * On `:host` the dark block also follows the host page (SAA-441): `core`
5396
+ * marks its shadow host `data-wgt-tone="dark"` or `"light"` from
5397
+ * `theme/host-tone.ts`, so the media query yields to a light mark and the
5398
+ * dark mark applies on a light system. A host nobody marks (the npm mount)
5399
+ * keeps the media query alone. A namespaced attribute, not a `.dark` class:
5400
+ * the host sits in the merchant's DOM, where their own `.dark` rules would
5401
+ * reach it.
5402
+ *
5392
5403
  * `:host` is the default because the dock lives in a shadow root; pass a class
5393
5404
  * or `:root` for the console preview, which renders in light DOM.
5394
5405
  */
5395
5406
  function themeToCss(theme, selector = ":host") {
5396
5407
  let css = `${block(theme.light, selector, "")}\n`;
5397
- if (theme.dark) css += `\n@media (prefers-color-scheme: dark) {\n${block(theme.dark, selector, " ")}\n}\n`;
5408
+ if (theme.dark) {
5409
+ const host = selector === ":host";
5410
+ css += `\n@media (prefers-color-scheme: dark) {\n${block(theme.dark, host ? `:host(:not(${TONE_MARK}"light"]))` : selector, " ")}\n}\n`;
5411
+ if (host) css += `\n${block(theme.dark, `:host(${TONE_MARK}"dark"])`, "")}\n`;
5412
+ }
5398
5413
  return css;
5399
5414
  }
5415
+ var TONE_MARK = "[data-wgt-tone=";
5416
+ /**
5417
+ * For an element that carries its own token block inside the shadow root
5418
+ * (the React dock's `[data-wgt-scope]`): the same marks, one level up, so the
5419
+ * host page's tone beats the media query on that element too. Matches
5420
+ * nothing in light DOM. Empty unless the tone is `auto`.
5421
+ */
5422
+ function themeToMarkedHostCss(theme, selector) {
5423
+ if (!theme.dark) return "";
5424
+ return `${block(theme.light, `:host(${TONE_MARK}"light"]) ${selector}`, "")}\n\n${block(theme.dark, `:host(${TONE_MARK}"dark"]) ${selector}`, "")}\n`;
5425
+ }
5400
5426
  /**
5401
5427
  * The theme as a `style` attribute value, for the `core` stage — which paints
5402
5428
  * the resting row before any stylesheet, adopted or otherwise, exists.
@@ -5796,6 +5822,17 @@ function pillAnchor(dir, isDesktop, desktopAlign) {
5796
5822
  };
5797
5823
  }
5798
5824
  //#endregion
5825
+ //#region src/message-limit.ts
5826
+ /**
5827
+ * The longest message `POST /widget/chat` accepts (`MAX_MESSAGE_LENGTH` in
5828
+ * `apps/api/src/widget/widget-chat.controller.ts`; a test pins the two). Both
5829
+ * composers cap their input at it (SAA-434), so a message is never refused
5830
+ * for its length after the shopper has typed it.
5831
+ */
5832
+ var WIDGET_MESSAGE_MAX_LENGTH = 4e3;
5833
+ /** How close to the limit the composer starts showing its count. */
5834
+ var WIDGET_MESSAGE_COUNT_FROM = 3600;
5835
+ //#endregion
5799
5836
  //#region src/dock/dock-caption.tsx
5800
5837
  function DockCaption({ line, swapKey, draft, onDraftChange, onSubmit, placeholder, label, disabled = false, inputRef, durationMs, inputTestId, lineTestId = "widget-dock-caption" }) {
5801
5838
  const outgoing = useCrossFade(line, swapKey, durationMs);
@@ -5818,6 +5855,7 @@ function DockCaption({ line, swapKey, draft, onDraftChange, onSubmit, placeholde
5818
5855
  placeholder,
5819
5856
  "aria-label": label,
5820
5857
  autoComplete: "off",
5858
+ maxLength: WIDGET_MESSAGE_MAX_LENGTH,
5821
5859
  disabled,
5822
5860
  onChange: (event) => onDraftChange(event.target.value),
5823
5861
  onKeyDown,
@@ -9206,7 +9244,8 @@ function Dock(props) {
9206
9244
  */
9207
9245
  const themeCss = useMemo(() => {
9208
9246
  const theme = deriveTheme(color, type);
9209
- return `${themeToCss(theme, ":host")}\n${themeToCss(theme, `[data-wgt-scope="${scopeId}"]`)}`;
9247
+ const scope = `[data-wgt-scope="${scopeId}"]`;
9248
+ return `${themeToCss(theme, ":host")}\n${themeToCss(theme, scope)}\n${themeToMarkedHostCss(theme, scope)}`;
9210
9249
  }, [
9211
9250
  color,
9212
9251
  type,
@@ -10644,7 +10683,7 @@ var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 19.24cqh)";
10644
10683
  * direction.
10645
10684
  */
10646
10685
  var TRANSCRIPT_FADE_TOP_WITH_BADGE_LEN = "max(28px, 4cqh, 19.24cqh - 115px)";
10647
- var TRANSCRIPT_FADE_BOTTOM_LEN = "max(118px, 20.27cqh)";
10686
+ var TRANSCRIPT_FADE_BOTTOM_LEN = "max(136px, 23.36cqh)";
10648
10687
  /**
10649
10688
  * The transcript's horizontal inset — the width the ellipse actually costs.
10650
10689
  *
@@ -10686,7 +10725,7 @@ var TRANSCRIPT_INSET_X = "max(8px, 10.6cqw - 11px)";
10686
10725
  * `11.86cqh - 63px` is 6.03px at 582px, so a phone renders what it rendered
10687
10726
  * before to a hundredth of a pixel and only larger panels lift the composer.
10688
10727
  */
10689
- var COMPOSER_BOTTOM_LEN = "max(6px, 11.86cqh - 63px)";
10728
+ var COMPOSER_BOTTOM_LEN = "max(6px, 15cqh - 63px)";
10690
10729
  /**
10691
10730
  * The composer overlay's bottom offset when there is NO microphone.
10692
10731
  *
@@ -10703,7 +10742,7 @@ var COMPOSER_BOTTOM_LEN = "max(6px, 11.86cqh - 63px)";
10703
10742
  * for the input + microphone pair regardless of whether the pair is drawn), so
10704
10743
  * nothing above has to move to make room.
10705
10744
  */
10706
- var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 11.86cqh - 1px)";
10745
+ var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 15cqh - 1px)";
10707
10746
  /**
10708
10747
  * The composer's width cap — what the ellipse actually offers at that row.
10709
10748
  *
@@ -10728,7 +10767,7 @@ var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 11.86cqh - 1px)";
10728
10767
  * inert at every size the widget really renders (it binds only below a 248px
10729
10768
  * panel; the narrowest phone in circulation, 320px, gives 310px).
10730
10769
  */
10731
- var COMPOSER_MAX_WIDTH_LEN = "max(160px, 64.65cqw - 10px)";
10770
+ var COMPOSER_MAX_WIDTH_LEN = "max(160px, 71.41cqw - 10px)";
10732
10771
  /**
10733
10772
  * The opaque ground the composer sits on, which has to keep covering it.
10734
10773
  *
@@ -10749,7 +10788,7 @@ var COMPOSER_MAX_WIDTH_LEN = "max(160px, 64.65cqw - 10px)";
10749
10788
  * 118:132 relationship the two were tuned at), so they still meet without a
10750
10789
  * seam or a band of doubly-darkened panel.
10751
10790
  */
10752
- var COMPOSER_GROUND_LEN = "max(132px, 22.68cqh)";
10791
+ var COMPOSER_GROUND_LEN = "max(150px, 25.77cqh)";
10753
10792
  //#endregion
10754
10793
  //#region src/widget/concierge-shell.tsx
10755
10794
  /**
@@ -10768,6 +10807,10 @@ var FOLLOW_TOLERANCE_PX = 24;
10768
10807
  * last messages scroll clear of the ramp, so a ramp length that is not also
10769
10808
  * the padding leaves the newest message permanently half-dissolved.
10770
10809
  *
10810
+ * The top half of the top ramp is fully transparent (SAA-435): text beside
10811
+ * the orb read through at 20-45% under the old eased ramp, which looked like
10812
+ * no fade at all. It now clears completely before it reaches the orb's row.
10813
+ *
10771
10814
  * The top ramp's stops are scaled from `topLen` rather than hardcoded, so the
10772
10815
  * shortened badge variant keeps the same eased shape instead of becoming a
10773
10816
  * steep two-point cut. `topLen` is a CSS length EXPRESSION now (a `max(<px>,
@@ -10797,10 +10840,9 @@ function transcriptEdgeFade(topLen) {
10797
10840
  const at = (fraction) => `calc(${topLen} * ${fraction})`;
10798
10841
  const gradient = `linear-gradient(to bottom, ${[
10799
10842
  "transparent 0",
10800
- `rgba(0,0,0,0.06) ${at(.21)}`,
10801
- `rgba(0,0,0,0.20) ${at(.43)}`,
10802
- `rgba(0,0,0,0.45) ${at(.64)}`,
10803
- `rgba(0,0,0,0.75) ${at(.82)}`,
10843
+ `transparent ${at(.5)}`,
10844
+ `rgba(0,0,0,0.25) ${at(.7)}`,
10845
+ `rgba(0,0,0,0.65) ${at(.86)}`,
10804
10846
  `#000 ${topLen}`,
10805
10847
  `#000 calc(100% - ${TRANSCRIPT_FADE_BOTTOM_LEN})`,
10806
10848
  "rgba(0,0,0,0.86) calc(100% - 96px)",
@@ -10879,9 +10921,15 @@ function voiceStatePillDotColor(pillState) {
10879
10921
  case "speaking": return "var(--brand-rose)";
10880
10922
  }
10881
10923
  }
10924
+ /**
10925
+ * The footer's two controls: opaque pills in the band the column reserves
10926
+ * under the panel (SAA-435), readable over any host page. Inherited colour
10927
+ * there was the HOST's, which is how "Privacy choices" went near-invisible.
10928
+ */
10929
+ 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";
10882
10930
  /** How long the opening flourish runs. Matches `.widget-portal`'s own duration. */
10883
10931
  var PORTAL_MS = 720;
10884
- 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 }) {
10932
+ 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 }) {
10885
10933
  const triggerId = `${idPrefix}-trigger`;
10886
10934
  const inputId = `${idPrefix}-input`;
10887
10935
  const [portalActive, setPortalActive] = useState(false);
@@ -10983,6 +11031,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
10983
11031
  el.removeEventListener("scroll", onScroll);
10984
11032
  };
10985
11033
  }, [open]);
11034
+ const skipFocus = useRef(!focusOnOpen);
10986
11035
  const handleClose = useCallback(() => {
10987
11036
  onOpenChange(false);
10988
11037
  window.setTimeout(() => {
@@ -11012,7 +11061,8 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11012
11061
  first.focus();
11013
11062
  }
11014
11063
  };
11015
- const focusTimer = window.setTimeout(() => document.getElementById(inputId)?.focus(), 120);
11064
+ const focusTimer = skipFocus.current ? void 0 : window.setTimeout(() => document.getElementById(inputId)?.focus(), 120);
11065
+ skipFocus.current = false;
11016
11066
  window.addEventListener("keydown", onKeyDown);
11017
11067
  return () => {
11018
11068
  window.clearTimeout(focusTimer);
@@ -11069,6 +11119,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11069
11119
  * `ConciergeShellVoice.labels.unavailable`.
11070
11120
  */
11071
11121
  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 ?? "";
11122
+ const counting = draft.length >= WIDGET_MESSAGE_COUNT_FROM;
11072
11123
  const submit = (e) => {
11073
11124
  e.preventDefault();
11074
11125
  if (!draft.trim() || composerDisabled) return;
@@ -11101,7 +11152,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11101
11152
  "aria-hidden": !open,
11102
11153
  className: cn("pointer-events-none fixed inset-x-0 z-50 flex", panelClasses(position)),
11103
11154
  children: /* @__PURE__ */ jsxs("div", {
11104
- className: "relative flex flex-col items-center",
11155
+ className: cn("relative flex flex-col items-center", open && (attribution || privacyChoices) && "pb-[calc(2.25rem+env(safe-area-inset-bottom,0px))]"),
11105
11156
  children: [
11106
11157
  /* @__PURE__ */ jsxs("div", {
11107
11158
  ref: panelRef,
@@ -11187,25 +11238,29 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11187
11238
  style: badge == null ? TRANSCRIPT_EDGE_FADE : TRANSCRIPT_EDGE_FADE_WITH_BADGE,
11188
11239
  children: /* @__PURE__ */ jsxs("div", {
11189
11240
  ref: transcriptContentRef,
11190
- children: [children, typing ? /* @__PURE__ */ jsxs("p", {
11191
- "data-testid": "widget-typing-indicator",
11192
- className: "flex items-center gap-1 px-1 py-1 text-[var(--widget-foreground-muted)]",
11193
- children: [/* @__PURE__ */ jsx("span", {
11194
- className: "sr-only",
11195
- children: defaultWidgetMessages.typing
11196
- }), [
11197
- 0,
11198
- 1,
11199
- 2
11200
- ].map((i) => /* @__PURE__ */ jsx("span", {
11201
- "aria-hidden": "true",
11202
- className: "h-1.5 w-1.5 animate-bounce rounded-full bg-current motion-reduce:animate-none",
11203
- style: {
11204
- animationDelay: `${i * 140}ms`,
11205
- animationDuration: "1s"
11206
- }
11207
- }, i))]
11208
- }) : null]
11241
+ children: [
11242
+ children,
11243
+ privacyChoices?.slot ? /* @__PURE__ */ jsx("div", { ref: privacyChoices.slot }) : null,
11244
+ typing ? /* @__PURE__ */ jsxs("p", {
11245
+ "data-testid": "widget-typing-indicator",
11246
+ className: "flex items-center gap-1 px-1 py-1 text-[var(--widget-foreground-muted)]",
11247
+ children: [/* @__PURE__ */ jsx("span", {
11248
+ className: "sr-only",
11249
+ children: defaultWidgetMessages.typing
11250
+ }), [
11251
+ 0,
11252
+ 1,
11253
+ 2
11254
+ ].map((i) => /* @__PURE__ */ jsx("span", {
11255
+ "aria-hidden": "true",
11256
+ className: "h-1.5 w-1.5 animate-bounce rounded-full bg-current motion-reduce:animate-none",
11257
+ style: {
11258
+ animationDelay: `${i * 140}ms`,
11259
+ animationDuration: "1s"
11260
+ }
11261
+ }, i))]
11262
+ }) : null
11263
+ ]
11209
11264
  })
11210
11265
  }),
11211
11266
  /* @__PURE__ */ jsx("div", {
@@ -11237,9 +11292,21 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11237
11292
  onChange: (e) => onDraftChange(e.target.value),
11238
11293
  placeholder: labels.composerPlaceholder,
11239
11294
  dir: "auto",
11295
+ maxLength: WIDGET_MESSAGE_MAX_LENGTH,
11296
+ ...counting ? { "aria-describedby": `${inputId}-count` } : {},
11240
11297
  disabled: composerDisabled,
11241
- 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")
11298
+ 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")
11242
11299
  }),
11300
+ counting ? /* @__PURE__ */ jsxs("span", {
11301
+ id: `${inputId}-count`,
11302
+ "data-testid": "widget-composer-count",
11303
+ className: "absolute end-4 -top-5 text-[11px] text-[var(--widget-foreground-muted)] tabular-nums",
11304
+ children: [
11305
+ draft.length,
11306
+ "/",
11307
+ WIDGET_MESSAGE_MAX_LENGTH
11308
+ ]
11309
+ }) : null,
11243
11310
  draft.trim() && /* @__PURE__ */ jsx("button", {
11244
11311
  type: "submit",
11245
11312
  "aria-label": labels.send,
@@ -11314,7 +11381,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11314
11381
  target: "_blank",
11315
11382
  rel: "noopener noreferrer",
11316
11383
  "data-testid": "widget-branding",
11317
- 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"),
11384
+ 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"),
11318
11385
  children: [/* @__PURE__ */ jsx("span", {
11319
11386
  "aria-hidden": true,
11320
11387
  className: "size-2.5 rounded-full bg-gradient-to-br from-brand-rose to-brand-amber"
@@ -11327,7 +11394,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lau
11327
11394
  type: "button",
11328
11395
  onClick: privacyChoices.open,
11329
11396
  "data-testid": "widget-privacy-choices",
11330
- 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"),
11397
+ className: cn(FOOTER_PILL, "end-0 text-[var(--widget-foreground)] underline", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"),
11331
11398
  children: privacyChoices.label
11332
11399
  }) : null
11333
11400
  ]
@@ -11592,6 +11659,31 @@ function deriveWidgetView(snapshot, input) {
11592
11659
  throw new TypeError(`Unknown concierge state: ${JSON.stringify(state)}`);
11593
11660
  }
11594
11661
  //#endregion
11662
+ //#region src/widget/open-state.ts
11663
+ /**
11664
+ * Whether the widget's panel was open, for the rest of this browsing session
11665
+ * (SAA-435): an in-site navigation that remounts the widget, or a refresh,
11666
+ * reopens it instead of dropping the shopper back to the launcher.
11667
+ *
11668
+ * `sessionStorage`, so it ends with the tab. Every access is guarded: a
11669
+ * private window, blocked site data or a sandboxed frame throws, and the
11670
+ * widget then simply starts closed.
11671
+ */
11672
+ var KEY = "wgt_panel_open";
11673
+ function readOpen() {
11674
+ try {
11675
+ return sessionStorage.getItem(KEY) === "1";
11676
+ } catch {
11677
+ return false;
11678
+ }
11679
+ }
11680
+ function writeOpen(open) {
11681
+ try {
11682
+ if (open) sessionStorage.setItem(KEY, "1");
11683
+ else sessionStorage.removeItem(KEY);
11684
+ } catch {}
11685
+ }
11686
+ //#endregion
11595
11687
  //#region src/widget/shell-renderer.tsx
11596
11688
  /**
11597
11689
  * The widget — launcher and panel — as a `ConciergeRenderer`
@@ -11615,7 +11707,9 @@ function positionFor(dock) {
11615
11707
  return align === "left" || align === "right" ? `bottom-${align}` : DEFAULT_CONCIERGE_POSITION;
11616
11708
  }
11617
11709
  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 }) {
11618
- const [open, setOpen] = useState(dock?.initialMinimised === false);
11710
+ const [restored] = useState(readOpen);
11711
+ const [open, setOpen] = useState(dock?.initialMinimised === false || restored);
11712
+ useEffect(() => writeOpen(open), [open]);
11619
11713
  const onReady = dock?.onReady;
11620
11714
  useLayoutEffect(() => {
11621
11715
  onReady?.();
@@ -11720,7 +11814,9 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11720
11814
  * `resolveCaption` makes, for the same reason — a renderer that invented
11721
11815
  * copy would need translating twice.
11722
11816
  */
11723
- const statusText = view.status === null ? void 0 : view.status.kind === "text" ? view.status.text : messages[view.status.key] ?? void 0;
11817
+ const handoffAt = turns.findLastIndex((t) => t.event === "handoff");
11818
+ const promiseKept = view.status?.kind === "message" && view.status.key === "escalated_banner" && turns.slice(handoffAt + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "");
11819
+ const statusText = view.status === null || promiseKept ? void 0 : view.status.kind === "text" ? view.status.text : messages[view.status.key] ?? void 0;
11724
11820
  const voice = showMic ? {
11725
11821
  phase: callPhase,
11726
11822
  onStart: onToggleMic,
@@ -11770,6 +11866,7 @@ function ShellRenderer({ turns, showMic, callPhase, micOpen, onToggleMic, onEndC
11770
11866
  return /* @__PURE__ */ jsxs(ConciergeShell, {
11771
11867
  open,
11772
11868
  onOpenChange: setOpen,
11869
+ ...restored ? { focusOnOpen: false } : {},
11773
11870
  state: view.avatar,
11774
11871
  ...skinStyle !== void 0 ? { skinStyle } : {},
11775
11872
  ...avatar !== void 0 ? { avatar } : {},
@@ -11908,6 +12005,16 @@ function safeHref(raw) {
11908
12005
  return null;
11909
12006
  }
11910
12007
  /**
12008
+ * The bidi embedding and isolate controls (U+202A-U+202E, U+2066-U+2069),
12009
+ * removed from what a bubble shows (SAA-436). A right-to-left override typed
12010
+ * into a message reverses the rest of it on screen ("exe.txt" spoofing); the
12011
+ * bubble's own `dir="auto"` and `unicode-bidi: isolate` already order real
12012
+ * mixed-direction text, so nothing legitimate needs them.
12013
+ */
12014
+ function stripBidiControls(text) {
12015
+ return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "");
12016
+ }
12017
+ /**
11911
12018
  * Inline constructs, innermost-last.
11912
12019
  *
11913
12020
  * Code is matched FIRST and never recurses into its own body: `` `**not
@@ -11918,7 +12025,7 @@ function parseInline(src) {
11918
12025
  const out = [];
11919
12026
  let rest = src;
11920
12027
  while (rest.length > 0) {
11921
- const match = /`([^`]+)`|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|(?<!\*)\*(?!\s)([^*\n]+?)\*(?!\*)|(?<!_)_(?!\s)([^_\n]+?)_(?!_)|\[([^\]]*)\]\(([^)\s]+)\)/.exec(rest);
12028
+ const match = /`([^`]+)`|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|(?<!\*)\*(?!\s)([^*\n]+?)\*(?!\*)|(?<!_)_(?!\s)([^_\n]+?)_(?!_)|\[([^\]]*)\]\(([^)\s]+)\)|(https:\/\/[^\s<>"'`]*[^\s<>"'`.,;:!?)\]])/.exec(rest);
11922
12029
  if (!match || match.index === void 0) {
11923
12030
  out.push({
11924
12031
  kind: "text",
@@ -11930,7 +12037,7 @@ function parseInline(src) {
11930
12037
  kind: "text",
11931
12038
  text: rest.slice(0, match.index)
11932
12039
  });
11933
- const [full, code, boldStar, boldUnd, italStar, italUnd, linkText, linkHref] = match;
12040
+ const [full, code, boldStar, boldUnd, italStar, italUnd, linkText, linkHref, bare] = match;
11934
12041
  if (code !== void 0) out.push({
11935
12042
  kind: "code",
11936
12043
  text: code
@@ -11945,7 +12052,7 @@ function parseInline(src) {
11945
12052
  });
11946
12053
  else if (linkHref !== void 0) {
11947
12054
  const href = safeHref(linkHref);
11948
- const children = parseInline(linkText ?? "");
12055
+ const children = parseInline(linkText ?? "").flatMap((n) => n.kind === "link" ? n.children : [n]);
11949
12056
  out.push(href ? {
11950
12057
  kind: "link",
11951
12058
  href,
@@ -11954,11 +12061,25 @@ function parseInline(src) {
11954
12061
  kind: "text",
11955
12062
  text: linkText ?? ""
11956
12063
  });
11957
- }
12064
+ } else if (bare !== void 0) out.push({
12065
+ kind: "link",
12066
+ href: bare,
12067
+ children: [{
12068
+ kind: "text",
12069
+ text: bare
12070
+ }]
12071
+ });
11958
12072
  rest = rest.slice(match.index + full.length);
11959
12073
  }
11960
12074
  return out.filter((n) => !(n.kind === "text" && n.text === ""));
11961
12075
  }
12076
+ function sameOrigin(href) {
12077
+ try {
12078
+ return new URL(href).origin === window.location.origin;
12079
+ } catch {
12080
+ return false;
12081
+ }
12082
+ }
11962
12083
  function renderInline(nodes, keyPrefix) {
11963
12084
  return nodes.map((node, i) => {
11964
12085
  const key = `${keyPrefix}-${i}`;
@@ -11972,9 +12093,11 @@ function renderInline(nodes, keyPrefix) {
11972
12093
  }, key);
11973
12094
  case "link": return /* @__PURE__ */ jsx("a", {
11974
12095
  href: node.href,
11975
- target: "_blank",
11976
- rel: "noopener noreferrer nofollow",
11977
- className: "underline underline-offset-2",
12096
+ ...sameOrigin(node.href) ? {} : {
12097
+ target: "_blank",
12098
+ rel: "noopener noreferrer nofollow"
12099
+ },
12100
+ className: "underline underline-offset-2 [overflow-wrap:anywhere]",
11978
12101
  children: renderInline(node.children, key)
11979
12102
  }, key);
11980
12103
  }
@@ -12046,7 +12169,7 @@ function parseBlocks(markdown) {
12046
12169
  * briefly showing, and never a thrown parse error mid-stream.
12047
12170
  */
12048
12171
  function WidgetMarkdown({ text }) {
12049
- return parseBlocks(text).map((block, i) => {
12172
+ return parseBlocks(stripBidiControls(text)).map((block, i) => {
12050
12173
  if (block.kind === "list") return /* @__PURE__ */ jsx(block.ordered ? "ol" : "ul", {
12051
12174
  className: `my-1 space-y-1 ps-4 ${block.ordered ? "list-decimal" : "list-disc"}`,
12052
12175
  children: block.items.map((item, j) => /* @__PURE__ */ jsx("li", { children: renderInline(parseInline(item), `b${i}-i${j}`) }, `b${i}-i${j}`))
@@ -12665,11 +12788,12 @@ function TypingDots({ label }) {
12665
12788
  * it twice would be worse than announcing it once.
12666
12789
  */
12667
12790
  function TranscriptEvent({ event, awaitingReply, messages }) {
12668
- if (event !== "handoff" && event !== "handback") return null;
12669
- const handback = event === "handback";
12791
+ const key = event === void 0 ? void 0 : `${event}_event`;
12792
+ if (key === void 0 || !(key in defaultWidgetMessages)) return null;
12793
+ const handback = event !== "handoff";
12670
12794
  return /* @__PURE__ */ jsxs("div", {
12671
12795
  className: "wgt-turn-row flex flex-col items-center gap-1 py-1",
12672
- "data-testid": handback ? "widget-handback-event" : "widget-handoff-event",
12796
+ "data-testid": `widget-${event}-event`,
12673
12797
  "data-dock-follow": "",
12674
12798
  children: [/* @__PURE__ */ jsxs("p", {
12675
12799
  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",
@@ -12678,7 +12802,7 @@ function TranscriptEvent({ event, awaitingReply, messages }) {
12678
12802
  "aria-hidden": "true",
12679
12803
  className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
12680
12804
  }),
12681
- /* @__PURE__ */ jsx("span", { children: handback ? messages.handback_event ?? defaultWidgetMessages.handback_event : messages.handoff_event ?? defaultWidgetMessages.handoff_event }),
12805
+ /* @__PURE__ */ jsx("span", { children: messages[key] ?? defaultWidgetMessages[key] }),
12682
12806
  /* @__PURE__ */ jsx("span", {
12683
12807
  "aria-hidden": "true",
12684
12808
  className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
@@ -12959,7 +13083,7 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
12959
13083
  };
12960
13084
  const submit = async () => {
12961
13085
  const text = draft.trim();
12962
- if (text === "" || sending) return;
13086
+ if (text === "") return;
12963
13087
  setSending(true);
12964
13088
  setDraft("");
12965
13089
  try {
@@ -13016,7 +13140,7 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13016
13140
  }) : shown.map((turn, i) => turn.speaker === "event" ? /* @__PURE__ */ jsx(TranscriptEvent, {
13017
13141
  event: turn.event,
13018
13142
  messages,
13019
- awaitingReply: !shown.slice(i + 1).some((t) => t.speaker === "event" || t.speaker === "agent" && t.text.trim() !== "")
13143
+ awaitingReply: !shown.slice(i + 1).some((t) => t.event === "handoff" || t.event === "handback" || t.speaker === "agent" && t.text.trim() !== "")
13020
13144
  }, `event-${i}`) : /* @__PURE__ */ jsxs("div", {
13021
13145
  "data-dock-follow": "",
13022
13146
  className: turn.speaker === "caller" ? "wgt-turn-row flex flex-col items-end" : "wgt-turn-row flex flex-col items-start",
@@ -13031,13 +13155,13 @@ function VoiceWidgetWithRenderer({ renderer, state, turns, onToggleMic, onEndCal
13031
13155
  dir: textDirectionFor(turn.locale),
13032
13156
  lang: turn.locale,
13033
13157
  "data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
13034
- 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}`,
13158
+ 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}`,
13035
13159
  children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
13036
13160
  className: "flex items-center gap-2 italic",
13037
13161
  children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
13038
13162
  }) : turn.speaker === "agent" ? /* @__PURE__ */ jsx(WidgetMarkdown, { text: turn.text }) : /* @__PURE__ */ jsx("span", {
13039
13163
  className: `whitespace-pre-wrap ${turn.final === false ? "italic opacity-70" : ""}`,
13040
- children: turn.text
13164
+ children: stripBidiControls(turn.text)
13041
13165
  })
13042
13166
  }) : null,
13043
13167
  turn.attachments && turn.attachments.length > 0 ? /* @__PURE__ */ jsx("div", {
@@ -14088,6 +14212,8 @@ var DEFAULT_SOCKET_PATH = "/socket.io";
14088
14212
  var HANDOFF_EVENT_TURN_ID = "event-handoff";
14089
14213
  /** Prefix of a hand-back transcript event's id, suffixed with its ordinal — see `markHandbackToAi`. */
14090
14214
  var HANDBACK_EVENT_TURN_ID = "event-handback";
14215
+ /** The one line a failed boot shows: plain words, never a status code (SAA-434). */
14216
+ var BOOT_FAILED = "Could not start the conversation.";
14091
14217
  /** Must equal `WIDGET_DESK_MESSAGE_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
14092
14218
  var DESK_MESSAGE_EVENT = "desk:message";
14093
14219
  /** Must equal `WIDGET_DESK_TYPING_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
@@ -14389,6 +14515,9 @@ function useChatSession(options) {
14389
14515
  * `markHandbackToAi`.
14390
14516
  */
14391
14517
  const replyInFlightRef = useRef(null);
14518
+ /** Turns sent while a reply streams, posted in order after it (SAA-434). */
14519
+ const queuedTurnsRef = useRef([]);
14520
+ const captureEventCountRef = useRef(0);
14392
14521
  const pollTimerRef = useRef(void 0);
14393
14522
  const pollIntervalRef = useRef(pollIntervalMs);
14394
14523
  const mountedRef = useRef(true);
@@ -14597,11 +14726,11 @@ function useChatSession(options) {
14597
14726
  for (const seq of returned) seqGapsRef.current.delete(seq);
14598
14727
  lastSeqRef.current = top;
14599
14728
  }
14600
- const fresh = sorted.filter((t) => !seenSeqRef.current.has(t.seq));
14601
- const repeats = sorted.filter((t) => seenSeqRef.current.has(t.seq));
14729
+ const fresh = sorted.filter((t) => t.role === "event" || !seenSeqRef.current.has(t.seq));
14730
+ const repeats = sorted.filter((t) => t.role !== "event" && seenSeqRef.current.has(t.seq));
14602
14731
  if (fresh.length === 0 && repeats.length === 0) return;
14603
14732
  if (fresh.some((t) => speakerFor(t.role) === "agent")) clearDeskTyping();
14604
- for (const t of fresh) seenSeqRef.current.add(t.seq);
14733
+ for (const t of fresh) if (t.role !== "event") seenSeqRef.current.add(t.seq);
14605
14734
  setTurns((prev) => {
14606
14735
  const baseId = (id) => {
14607
14736
  const colon = id.indexOf(":");
@@ -14624,7 +14753,14 @@ function useChatSession(options) {
14624
14753
  });
14625
14754
  if (unseen.length === 0) return corrected ? patched : prev;
14626
14755
  const next = [...patched];
14627
- for (const turn of unseen.map((t) => ({
14756
+ for (const turn of unseen.map((t) => t.role === "event" ? {
14757
+ id: t.id,
14758
+ speaker: "event",
14759
+ event: t.event,
14760
+ text: "",
14761
+ final: true,
14762
+ seq: t.seq
14763
+ } : {
14628
14764
  id: t.id,
14629
14765
  speaker: speakerFor(t.role),
14630
14766
  text: t.text ?? "",
@@ -14633,7 +14769,7 @@ function useChatSession(options) {
14633
14769
  ...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {},
14634
14770
  ...t.cards && Array.isArray(t.cards.items) && t.cards.items.length > 0 ? { cards: t.cards } : {},
14635
14771
  ...typeof t.operatorName === "string" && t.operatorName !== "" ? { operatorName: t.operatorName } : {}
14636
- }))) insertBySeq(next, turn);
14772
+ })) insertBySeq(next, turn);
14637
14773
  return next;
14638
14774
  });
14639
14775
  }, [clearDeskTyping]);
@@ -14735,7 +14871,19 @@ function useChatSession(options) {
14735
14871
  }
14736
14872
  clearDeskTyping();
14737
14873
  }, [clearDeskTyping]);
14738
- const poll = useCallback(async (detectHandoff) => {
14874
+ /** See {@link UseChatSessionResult.markCaptureAnswered}. */
14875
+ const markCaptureAnswered = useCallback((outcome) => {
14876
+ if (!mountedRef.current) return;
14877
+ const id = `event-capture-${captureEventCountRef.current += 1}`;
14878
+ setTurns((prev) => [...prev, {
14879
+ id,
14880
+ speaker: "event",
14881
+ event: outcome === "saved" ? "capture_saved" : "capture_declined",
14882
+ text: "",
14883
+ final: true
14884
+ }]);
14885
+ }, []);
14886
+ const poll = useCallback(async (detectHandoff, events) => {
14739
14887
  const chatToken = chatTokenRef.current;
14740
14888
  if (chatToken === void 0) return;
14741
14889
  let afterSeq = lastSeqRef.current;
@@ -14743,11 +14891,15 @@ function useChatSession(options) {
14743
14891
  for (const [seq, missedAt] of seqGapsRef.current) if (seenSeqRef.current.has(seq) || now - missedAt > SEQ_GAP_HOLD_MS) seqGapsRef.current.delete(seq);
14744
14892
  else afterSeq = Math.min(afterSeq, seq - 1);
14745
14893
  try {
14746
- const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/messages?afterSeq=${afterSeq}`, embedKey), { headers: { authorization: `Bearer ${chatToken}` } });
14894
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/messages?afterSeq=${afterSeq}${events ? "&events=1" : ""}`, embedKey), { headers: { authorization: `Bearer ${chatToken}` } });
14747
14895
  if (!res.ok) return;
14748
14896
  const body = await res.json();
14749
14897
  const rows = body.messages ?? body.turns ?? [];
14750
14898
  if (detectHandoff && Array.isArray(rows) && rows.some((t) => t.role === "human" && !seenSeqRef.current.has(t.seq))) markHandoffToHuman();
14899
+ if (events && Array.isArray(rows)) {
14900
+ const last = rows.filter((t) => t.event === "handoff" || t.event === "handback").pop();
14901
+ if (last) handoffEventAppendedRef.current = last.event === "handoff";
14902
+ }
14751
14903
  mergeIncoming(rows, "poll");
14752
14904
  } catch {}
14753
14905
  }, [
@@ -14898,7 +15050,7 @@ function useChatSession(options) {
14898
15050
  ...hostRoutes !== void 0 ? { hostRoutes } : {}
14899
15051
  })
14900
15052
  });
14901
- if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
15053
+ if (!res.ok) throw new Error(BOOT_FAILED);
14902
15054
  const body = await res.json();
14903
15055
  if (isStale?.() || !mountedRef.current) return;
14904
15056
  const receivedAt = now();
@@ -14979,7 +15131,7 @@ function useChatSession(options) {
14979
15131
  if (isMount && body.resumed === true) {
14980
15132
  lastSeqRef.current = 0;
14981
15133
  seqGapsRef.current.clear();
14982
- poll();
15134
+ poll(false, true);
14983
15135
  }
14984
15136
  setStatus((prev) => prev === "escalated" ? prev : "idle");
14985
15137
  scheduleRefresh(ttlMs);
@@ -15010,10 +15162,10 @@ function useChatSession(options) {
15010
15162
  phase: "mount",
15011
15163
  isStale: () => cancelled
15012
15164
  });
15013
- } catch (err) {
15165
+ } catch {
15014
15166
  if (cancelled) return;
15015
15167
  setStatus("error");
15016
- setError(err instanceof Error ? err.message : "Could not start the conversation.");
15168
+ setError(BOOT_FAILED);
15017
15169
  } finally {
15018
15170
  if (!cancelled) setReady(true);
15019
15171
  }
@@ -15035,10 +15187,10 @@ function useChatSession(options) {
15035
15187
  const rebootSession = useCallback(async () => {
15036
15188
  try {
15037
15189
  await bootSession({ phase: "recovery" });
15038
- } catch (err) {
15190
+ } catch {
15039
15191
  if (!mountedRef.current) return;
15040
15192
  setStatus("error");
15041
- setError(err instanceof Error ? err.message : "Could not start the conversation.");
15193
+ setError(BOOT_FAILED);
15042
15194
  }
15043
15195
  }, [bootSession]);
15044
15196
  /**
@@ -15308,14 +15460,32 @@ function useChatSession(options) {
15308
15460
  */
15309
15461
  const postTurn = useCallback(async (payload, options) => {
15310
15462
  const chatToken = chatTokenRef.current;
15311
- if (chatToken === void 0 || status === "streaming") return false;
15463
+ if (chatToken === void 0) return false;
15312
15464
  const text = "message" in payload ? payload.message : "";
15313
15465
  const silent = options?.silent === true || !("message" in payload);
15314
- const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
15466
+ const callerTurnId = options?.queuedId ?? `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
15315
15467
  const agentTurnId = `agent-${callerTurnId}`;
15468
+ if (status === "streaming" || replyInFlightRef.current !== null && status !== "escalated") {
15469
+ if (options?.quietOnHttpError === true) return false;
15470
+ queuedTurnsRef.current.push({
15471
+ payload,
15472
+ options: {
15473
+ ...options,
15474
+ ...silent ? {} : { queuedId: callerTurnId }
15475
+ }
15476
+ });
15477
+ if (!silent) setTurns((prev) => [...prev, {
15478
+ id: callerTurnId,
15479
+ speaker: "caller",
15480
+ text,
15481
+ final: true,
15482
+ delivery: "sending"
15483
+ }]);
15484
+ return true;
15485
+ }
15316
15486
  setTurns((prev) => [
15317
15487
  ...prev,
15318
- ...silent ? [] : [{
15488
+ ...silent || options?.queuedId !== void 0 ? [] : [{
15319
15489
  id: callerTurnId,
15320
15490
  speaker: "caller",
15321
15491
  text,
@@ -15330,9 +15500,15 @@ function useChatSession(options) {
15330
15500
  }
15331
15501
  ]);
15332
15502
  setStatus((prev) => prev === "escalated" ? prev : "streaming");
15333
- replyInFlightRef.current = [callerTurnId, agentTurnId];
15334
- const rollBack = () => {
15503
+ const inFlight = [callerTurnId, agentTurnId];
15504
+ replyInFlightRef.current = inFlight;
15505
+ const release = () => {
15506
+ if (replyInFlightRef.current !== inFlight) return false;
15335
15507
  replyInFlightRef.current = null;
15508
+ return true;
15509
+ };
15510
+ const rollBack = () => {
15511
+ release();
15336
15512
  setTurns((prev) => prev.filter((t) => t.id !== callerTurnId && t.id !== agentTurnId));
15337
15513
  };
15338
15514
  const postChat = (cart) => fetchImpl(withEmbedKeyParam(`${apiBase}/chat`, embedKey), {
@@ -15368,7 +15544,7 @@ function useChatSession(options) {
15368
15544
  if (!res.ok || res.body === null) {
15369
15545
  rollBack();
15370
15546
  setStatus("error");
15371
- setError(`The conversation could not accept that message (${res.status}).`);
15547
+ 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.");
15372
15548
  return false;
15373
15549
  }
15374
15550
  if (mountedRef.current) setTurns((prev) => prev.map((t) => t.id === callerTurnId ? {
@@ -15401,7 +15577,7 @@ function useChatSession(options) {
15401
15577
  });
15402
15578
  },
15403
15579
  onDone: (turnId) => {
15404
- replyInFlightRef.current = null;
15580
+ release();
15405
15581
  if (!mountedRef.current) return;
15406
15582
  setTurns((prev) => prev.filter((t) => t.id !== turnId || t.id === agentTurnId).map((t) => t.id === agentTurnId ? {
15407
15583
  ...t,
@@ -15411,7 +15587,7 @@ function useChatSession(options) {
15411
15587
  setStatus((prev) => prev === "escalated" ? prev : "idle");
15412
15588
  },
15413
15589
  onError: (message) => {
15414
- replyInFlightRef.current = null;
15590
+ release();
15415
15591
  if (!mountedRef.current) return;
15416
15592
  setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
15417
15593
  ...t,
@@ -15422,7 +15598,12 @@ function useChatSession(options) {
15422
15598
  },
15423
15599
  isMounted: () => mountedRef.current
15424
15600
  }).finally(() => {
15425
- replyInFlightRef.current = null;
15601
+ if (!release() || !mountedRef.current) return;
15602
+ setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
15603
+ ...t,
15604
+ final: true
15605
+ } : t));
15606
+ setStatus((prev) => prev === "streaming" ? "idle" : prev);
15426
15607
  });
15427
15608
  return true;
15428
15609
  }, [
@@ -15433,6 +15614,21 @@ function useChatSession(options) {
15433
15614
  markHandoffToHuman,
15434
15615
  markHandbackToAi
15435
15616
  ]);
15617
+ useEffect(() => {
15618
+ if (status === "streaming" || replyInFlightRef.current !== null) return;
15619
+ if (status === "error") {
15620
+ const dropped = new Set(queuedTurnsRef.current.map((q) => q.options.queuedId));
15621
+ queuedTurnsRef.current = [];
15622
+ if (dropped.size > 0) setTurns((prev) => prev.filter((t) => !dropped.has(t.id)));
15623
+ return;
15624
+ }
15625
+ const next = queuedTurnsRef.current.shift();
15626
+ if (next) postTurn(next.payload, next.options);
15627
+ }, [
15628
+ status,
15629
+ turns,
15630
+ postTurn
15631
+ ]);
15436
15632
  const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
15437
15633
  const sendReport = useCallback(async (report, options) => postTurn({ report }, options?.quietOnHttpError === true ? { quietOnHttpError: true } : void 0), [postTurn]);
15438
15634
  /**
@@ -15839,7 +16035,8 @@ function useChatSession(options) {
15839
16035
  notifyTyping,
15840
16036
  checkout,
15841
16037
  sendAttachment,
15842
- markHandoffToHuman
16038
+ markHandoffToHuman,
16039
+ markCaptureAnswered
15843
16040
  };
15844
16041
  }
15845
16042
  /**
@@ -18559,6 +18756,8 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
18559
18756
  autoFocus: !inCallRef.current,
18560
18757
  submit: session.submitCapture,
18561
18758
  onAnswered: (outcome) => {
18759
+ setCaptureCard(null);
18760
+ session.markCaptureAnswered(outcome);
18562
18761
  if (!inCallRef.current) session.sendReport({
18563
18762
  kind: "capture_card",
18564
18763
  field: event.field,
@@ -19661,4 +19860,4 @@ function ConciergeHost({ renderer, embedKey, apiBase, socketUrl, socketPath, bri
19661
19860
  });
19662
19861
  }
19663
19862
  //#endregion
19664
- export { deriveDockState as $, themeToCss as $t, rendererFor as A, cn as An, SHEET_PEEK_MAX as At, nearestPosition as B, pillAnchor as Bt, readsAsCartViewIntent as C, DEFAULT_WIDGET_AVATAR as Cn, PILL_MARK as Ct, WidgetCardList as D, RopeKnot as Dn, SHEET_EXPANDED_DESKTOP_MAX as Dt, WidgetCartSummary as E, KNOT_PATH as En, ROW_H as Et, ConciergeLauncher as F, bottomLen as Ft, botStateFor as G, sheetMaxHeightLen as Gt, positionClasses as H, readStoredAlign as Ht, CONCIERGE_POSITIONS as I, containerAnchor as It, SessionLog as J, CARD_RADIUS_MAX_PX as Jt, SseFrameParser as K, snapAlign as Kt, DEFAULT_CONCIERGE_POSITION as L, geometryVars as Lt, ShellRenderer as M, SHEET_TUCK as Mt, deriveWidgetView as N, SHORT_VIEWPORT as Nt, WidgetMarkdown as O, BotFace as On, SHEET_EXPANDED_VH as Ot, ConciergeShell as P, Z_INDEX as Pt, DOCK_STATES as Q, deriveTheme as Qt, alignOf as R, persistAlign as Rt, basketIntentFromTurns as S, MorphingLoader as Sn, PILL_H as St, textDirectionFor as T, isWidgetAvatar as Tn, RADII as Tt, positionForArrow as U, readStoredMinimised as Ut, panelClasses as V, readStored as Vt, IDLE_SNAPSHOT as W, rowWidthLen as Wt, latencyBetween as X, SYSTEM_FONT_STACK as Xt, formatMs as Y, SHEET_RADIUS_MAX_PX as Yt, Dock as Z, WIDGET_THEME_TOKENS as Zt, isSameOriginPath as _, withAlpha as _n, FLOAT_DUCK_DISMISS_MS as _t, MAX_REPORTED_CART_LINES as a, linearRgbToOklab as an, formatMoney as at, VoiceWidget as b, resolveWidgetMessages as bn, MARK as bt, deriveCallPhase as c, oklabToHex as cn, CONTROL as ct, resolveCheckoutUrl as d, oklchToHex as dn, DESKTOP_GUTTER as dt, themeToInlineStyle as en, deriveDockView as et, toChatCart as f, oklchToOklab as fn, DESKTOP_WIDTHS as ft, CHECKOUT_CAPTURE_REQUIRED as g, srgbToLinear as gn, DRAG_TAP_SLOP_PX as gt, useVoiceSession as h, rotateHue as hn, DRAG_CLICK_WINDOW_MS as ht, ConciergeWidget as i, hexToOklch as in, idleConciergeInput as it, DockRenderer as j, SHEET_TOP_CLEARANCE as jt, parseBlocks as k, labelProps as kn, SHEET_GAP as kt, mergeAddedCartLine as l, oklabToLinearRgb as ln, DESKTOP_BOTTOM as lt, createWidgetVoiceTokenFetcher as m, relativeLuminance as mn, DOCK_MINIMISED_STORAGE_KEY as mt, CART_LINE_VARIANT_ID_SHAPE as n, formatHex as nn, CONCIERGE_STATES as nt, cartLinesFromSnapshot as o, linearToSrgb as on, ACTIVITY_W as ot, ROOM_EVENTS as p, parseHex as pn, DOCK_ALIGN_STORAGE_KEY as pt, SESSION_EVENTS as q, writeStored as qt, ConciergeHost as r, hexToOklab as rn, deriveConciergeState as rt, chooseOptionsAction as s, mixToward as sn, BOTTOM_FLOOR as st, CART_LINE_PLATFORM_VARIANT_ID_SHAPE as t, contrastRatio as tn, idleDockInput as tt, resolveAddToCartHandler as u, oklabToOklch as un, DESKTOP_BREAKPOINT as ut, useChatSession as v, defaultWidgetMessages as vn, FLOAT_GAP as vt, readsAsCheckoutIntent as w, WIDGET_AVATARS as wn, PROACTIVE_NUDGE_MS as wt, VoiceWidgetWithRenderer as x, widgetMessagesFromCopy as xn, MOBILE_MARGIN as xt, detectPage as y, formatMessage as yn, GLASS_IDLE_MS as yt, edgeOf as z, persistMinimised as zt };
19863
+ export { DOCK_STATES as $, WIDGET_THEME_TOKENS as $t, stripBidiControls as A, RopeKnot as An, SHEET_EXPANDED_VH as At, edgeOf as B, persistAlign as Bt, readsAsCartViewIntent as C, resolveWidgetMessages as Cn, MOBILE_MARGIN as Ct, WidgetCardList as D, WIDGET_AVATARS as Dn, RADII as Dt, WidgetCartSummary as E, DEFAULT_WIDGET_AVATAR 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, labelProps as Mn, SHEET_PEEK_MAX as Mt, ShellRenderer as N, cn as Nn, SHEET_TOP_CLEARANCE as Nt, WidgetMarkdown as O, isWidgetAvatar 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, formatMessage as Sn, MARK as St, textDirectionFor as T, MorphingLoader 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 _, relativeLuminance as _n, DRAG_CLICK_WINDOW_MS as _t, MAX_REPORTED_CART_LINES as a, formatHex as an, idleConciergeInput as at, VoiceWidget as b, withAlpha as bn, FLOAT_GAP as bt, deriveCallPhase as c, linearRgbToOklab as cn, ACTIVITY_W as ct, resolveCheckoutUrl as d, oklabToHex as dn, DESKTOP_BOTTOM as dt, deriveTheme as en, deriveDockState as et, toChatCart as f, oklabToLinearRgb as fn, DESKTOP_BREAKPOINT as ft, CHECKOUT_CAPTURE_REQUIRED as g, parseHex as gn, DOCK_MINIMISED_STORAGE_KEY as gt, useVoiceSession as h, oklchToOklab as hn, DOCK_ALIGN_STORAGE_KEY as ht, ConciergeWidget as i, contrastRatio as in, deriveConciergeState as it, rendererFor as j, BotFace as jn, SHEET_GAP as jt, parseBlocks as k, KNOT_PATH as kn, SHEET_EXPANDED_DESKTOP_MAX as kt, mergeAddedCartLine as l, linearToSrgb as ln, BOTTOM_FLOOR as lt, createWidgetVoiceTokenFetcher as m, oklchToHex as mn, DESKTOP_WIDTHS as mt, CART_LINE_VARIANT_ID_SHAPE as n, themeToInlineStyle as nn, idleDockInput as nt, cartLinesFromSnapshot as o, hexToOklab as on, formatMoney as ot, ROOM_EVENTS as p, oklabToOklch as pn, DESKTOP_GUTTER as pt, SseFrameParser as q, sheetMaxHeightLen as qt, ConciergeHost as r, themeToMarkedHostCss as rn, CONCIERGE_STATES as rt, chooseOptionsAction as s, hexToOklch 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, mixToward as un, CONTROL as ut, useChatSession as v, rotateHue as vn, DRAG_TAP_SLOP_PX as vt, readsAsCheckoutIntent as w, widgetMessagesFromCopy as wn, PILL_H as wt, VoiceWidgetWithRenderer as x, defaultWidgetMessages as xn, GLASS_IDLE_MS as xt, detectPage as y, srgbToLinear as yn, FLOAT_DUCK_DISMISS_MS as yt, alignOf as z, geometryVars as zt };