@saar-ai/web-widget 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/avatar-face.d.ts +33 -0
  2. package/dist/avatar-face.d.ts.map +1 -0
  3. package/dist/avatar.d.ts +17 -0
  4. package/dist/avatar.d.ts.map +1 -0
  5. package/dist/bot-face.d.ts +17 -0
  6. package/dist/bot-face.d.ts.map +1 -1
  7. package/dist/chunks/{chat-ZLxYRTml.js → chat-DfajYOmN.js} +68 -1
  8. package/dist/chunks/{host-widget-iy3qC-1p.js → host-widget-Bt41rE9U.js} +2562 -499
  9. package/dist/concierge-launcher.d.ts +4 -1
  10. package/dist/concierge-launcher.d.ts.map +1 -1
  11. package/dist/concierge-shell.d.ts +68 -6
  12. package/dist/concierge-shell.d.ts.map +1 -1
  13. package/dist/generated/widget-css.d.ts.map +1 -1
  14. package/dist/host-widget.d.ts +138 -4
  15. package/dist/host-widget.d.ts.map +1 -1
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +5 -5
  19. package/dist/messages.d.ts +71 -1
  20. package/dist/messages.d.ts.map +1 -1
  21. package/dist/next/index.js +1 -1
  22. package/dist/rope-knot.d.ts +13 -0
  23. package/dist/rope-knot.d.ts.map +1 -0
  24. package/dist/session-log.d.ts +1 -1
  25. package/dist/session-log.d.ts.map +1 -1
  26. package/dist/transcript-geometry.d.ts +220 -0
  27. package/dist/transcript-geometry.d.ts.map +1 -0
  28. package/dist/use-chat-session.d.ts +151 -10
  29. package/dist/use-chat-session.d.ts.map +1 -1
  30. package/dist/use-voice-session.d.ts +10 -0
  31. package/dist/use-voice-session.d.ts.map +1 -1
  32. package/dist/voice-session-state.d.ts +17 -0
  33. package/dist/voice-session-state.d.ts.map +1 -1
  34. package/dist/voice-widget.d.ts +52 -4
  35. package/dist/voice-widget.d.ts.map +1 -1
  36. package/dist/widget-cards.d.ts +5 -2
  37. package/dist/widget-cards.d.ts.map +1 -1
  38. package/dist/widget.css +1 -1
  39. package/package.json +4 -3
  40. package/src/styles/concierge.css +377 -0
@@ -3422,7 +3422,14 @@ function BotFace({ state = "idle", size = "sm", messageArrived = false, label })
3422
3422
  label
3423
3423
  });
3424
3424
  }
3425
- /** `role="img"` + a name, or nothing at all — never a name we invented. */
3425
+ /**
3426
+ * `role="img"` + a name, or nothing at all — never a name we invented.
3427
+ *
3428
+ * Exported so `rope-knot.tsx` (the 'knot' avatar) shares this exact
3429
+ * accessibility contract rather than redeclaring it — both avatars are
3430
+ * decorative-by-default for the identical reason (see this module's doc
3431
+ * comment), and a second copy would be free to drift.
3432
+ */
3426
3433
  function labelProps(label) {
3427
3434
  return label === void 0 ? { "aria-hidden": true } : {
3428
3435
  role: "img",
@@ -3432,7 +3439,7 @@ function labelProps(label) {
3432
3439
  function BotFaceSmall({ state, label }) {
3433
3440
  return /* @__PURE__ */ jsxs("div", {
3434
3441
  ...labelProps(label),
3435
- className: "relative flex h-16 w-16 items-center justify-center rounded-3xl border border-brand-plum/10 bg-card/90 p-3 backdrop-blur-md",
3442
+ className: "relative flex h-16 w-16 items-center justify-center rounded-3xl border border-brand-plum/10 bg-card/90 p-0 backdrop-blur-md",
3436
3443
  children: [/* @__PURE__ */ jsx("div", {
3437
3444
  "aria-hidden": true,
3438
3445
  className: cn("absolute inset-0 rounded-3xl bg-gradient-to-tr from-brand-rose/12 via-brand-amber/8 to-brand-plum/8 blur-md transition-opacity duration-500", state === "speaking" && "opacity-90 animate-[bot-halo-speak_1.8s_ease-in-out_infinite]", state === "listening" && "opacity-75 animate-[bot-halo-listen_2.2s_ease-in-out_infinite]", state === "thinking" && "opacity-55", state === "idle" && "opacity-45")
@@ -3618,6 +3625,285 @@ function BotOrbLarge({ state, messageArrived, label }) {
3618
3625
  });
3619
3626
  }
3620
3627
  //#endregion
3628
+ //#region src/rope-knot.tsx
3629
+ /**
3630
+ * The `'knot'` avatar — a single hand-drawn line that loops through itself
3631
+ * into a knot, in the two sizes the widget uses (`sm` trigger, `lg` panel
3632
+ * orb-slot) and the same four {@link BotState}s `BotFace` (the `'orb'`
3633
+ * avatar) renders. Selected per tenant via `appearance.avatar` — see
3634
+ * `avatar.ts` — and otherwise a drop-in for `BotFace` at every call site:
3635
+ * same `state`/`size`/`label` contract, same `labelProps` accessibility rule
3636
+ * (imported from `bot-face.tsx` rather than redeclared).
3637
+ *
3638
+ * Ported from the Lovable prototype's `RopeKnot.tsx`.
3639
+ *
3640
+ * ## Why the colour vars are declared HERE, not in `concierge.css`
3641
+ *
3642
+ * The rope's colour is never hardcoded — `--knot-ink` and its
3643
+ * `-faint`/`-halo`/`-surface` derivatives alias `--brand-plum`, the same
3644
+ * tenant-config-driven variable `BotFace`'s gradient reads. They used to
3645
+ * live in a `:root { --knot-ink: var(--brand-plum, …); … }` block in
3646
+ * `concierge.css`, which was broken two ways at once: `:root` matches
3647
+ * nothing inside the CDN embed's shadow tree (the tenant's brand colours
3648
+ * never reach a shadow-mounted widget at all), and even in light DOM, a
3649
+ * `--x: var(--y)` declaration resolves `var(--y)` using the DECLARING
3650
+ * element's own cascade AT THAT MOMENT — `:root` has no tenant override on
3651
+ * it, that override lives on a DESCENDANT (`ConciergeShell`'s
3652
+ * `skinStyle`-carrying wrapper), so every tenant silently got the built-in
3653
+ * plum default regardless of what they published.
3654
+ *
3655
+ * `RopeKnotFrame`'s own root div is always rendered somewhere INSIDE that
3656
+ * `skinStyle` wrapper (`ConciergeShell` renders both the panel orb and,
3657
+ * via `ConciergeLauncher`, the collapsed pill, and both sit inside the one
3658
+ * `<div data-skin style={skinStyle}>` root). Declaring the vars on THIS
3659
+ * element via inline `style` means `var(--brand-plum, …)` resolves using
3660
+ * THIS element's own cascade — which, by the time render reaches here, has
3661
+ * already inherited whatever override the ancestor set. Everything BELOW
3662
+ * this div (the halo, the svg, the drawn path) then just inherits the
3663
+ * already-resolved values normally, in both light and shadow DOM, no
3664
+ * selector needed at all. Same fix `concierge.css`'s own `@theme inline`
3665
+ * block uses for `--color-brand-plum` (see that block's doc comment) —
3666
+ * "resolve where it's used," not "resolve once at the top."
3667
+ *
3668
+ * ## The crossfade
3669
+ *
3670
+ * Every state change freezes the `stroke-dasharray` the rope was showing —
3671
+ * read directly off the live element via `getComputedStyle` at the instant
3672
+ * the state actually changes — into `--rk-from`, then remounts the drawn
3673
+ * path so the incoming state's `rk-blend-to-*` animation eases OUT of that
3674
+ * exact shape instead of snapping back to the self-tying intro. This is a
3675
+ * single synchronous read inside the state-change effect, not a polling
3676
+ * loop: a CSS animation keeps an element's OWN computed style live at every
3677
+ * instant, so there is nothing to gain by sampling continuously, and a
3678
+ * `requestAnimationFrame` loop that ran forever — for the life of the
3679
+ * component, including a launcher pill that never leaves `state="idle"` and
3680
+ * can never blend at all, and regardless of `prefers-reduced-motion`, where
3681
+ * the dash never even changes — was a real cost on a merchant's page for no
3682
+ * benefit.
3683
+ */
3684
+ var KNOT_PATH = "M2 54 C15 54 24 55 31 53 C40 50 44 40 54 41 C64 42 67 51 60 57 C52 64 38 64 33 57 C29 51 34 45 42 46 C50 47 58 52 68 53.5 C80 55 90 54 98 54";
3685
+ /** Short pulse rider used while listening/thinking. Dash-array sum equals `pathLength={100}`. */
3686
+ var PULSE_DASH = "9 91";
3687
+ /**
3688
+ * The colour vars every layer below reads — declared once, as inline style,
3689
+ * on `RopeKnotFrame`'s own root (see this module's doc comment for why not
3690
+ * `concierge.css`'s `:root`).
3691
+ *
3692
+ * `color-mix()` has no literal fallback here, consistent with the rest of
3693
+ * this package: `concierge-shell.tsx`'s glow/shadow effects and
3694
+ * `bot-face.tsx`'s halo already use unguarded `color-mix()` throughout, with
3695
+ * no `@supports` branch anywhere in this codebase. Adding one just for the
3696
+ * knot would be new, inconsistent machinery for a real but narrow gap — of
3697
+ * this widget's stated browser floor (`AGENTS.md` → "The browser floor",
3698
+ * ~March 2023), only the FLOOR's exact Chrome version (110) predates
3699
+ * `color-mix()` (Chrome 111); Safari's floor (16.4) and Firefox's (115) both
3700
+ * postdate their own `color-mix()` landings (16.2, 113). The honest
3701
+ * degradation on that one version: `stroke`/`background` are inherited
3702
+ * properties, so an unresolvable `var()` falls back to the inherited value
3703
+ * (effectively transparent/unset) rather than to solid ink — a fainter knot,
3704
+ * not a broken one.
3705
+ */
3706
+ var KNOT_COLOR_VARS = {
3707
+ ["--knot-ink"]: "var(--brand-plum, oklch(0.34 0.0728 128.34))",
3708
+ ["--knot-ink-faint"]: "color-mix(in oklab, var(--knot-ink) 12%, transparent)",
3709
+ ["--knot-halo"]: "color-mix(in oklab, var(--knot-ink) 12%, transparent)",
3710
+ ["--knot-surface"]: "color-mix(in oklab, var(--knot-ink) 4%, var(--widget-card, oklch(0.99 0 0)))"
3711
+ };
3712
+ var PULSE_SPEED = {
3713
+ idle: "0s",
3714
+ listening: "2.2s",
3715
+ thinking: "1.6s",
3716
+ speaking: "1.1s"
3717
+ };
3718
+ function RopeKnot({ state = "idle", size = "sm", label, tightenKey = 0 }) {
3719
+ if (size === "lg") return /* @__PURE__ */ jsx(RopeKnotFrame, {
3720
+ state,
3721
+ label,
3722
+ tightenKey,
3723
+ outerClassName: "flex h-24 w-24 items-center justify-center",
3724
+ artClassName: "h-[4.8rem] w-[4.8rem]"
3725
+ });
3726
+ return /* @__PURE__ */ jsx(RopeKnotFrame, {
3727
+ state,
3728
+ label,
3729
+ tightenKey,
3730
+ outerClassName: "relative flex h-16 w-16 items-center justify-center rounded-3xl border border-brand-plum/10 bg-card/90 p-0 backdrop-blur-md",
3731
+ artClassName: "h-full w-full",
3732
+ chrome: true
3733
+ });
3734
+ }
3735
+ /**
3736
+ * The halo + sway wrapper both sizes share, and the ONE structural
3737
+ * difference between them: the small trigger carries `BotFaceSmall`'s card
3738
+ * chrome (border, blurred backdrop, rounded corners) so swapping avatars
3739
+ * never changes the trigger's frame — only what is drawn inside it. The
3740
+ * large slot carries none of that; `ConciergeShell` already gives the orb
3741
+ * slot its own ground (see that file's "opaque ground under the orb").
3742
+ */
3743
+ function RopeKnotFrame({ state, label, tightenKey, outerClassName, artClassName, chrome = false }) {
3744
+ const halo = /* @__PURE__ */ jsx("div", {
3745
+ "aria-hidden": true,
3746
+ className: cn("pointer-events-none absolute inset-0 rounded-full bg-[radial-gradient(circle,var(--knot-halo),transparent_70%)] blur-md transition-opacity duration-500", state === "idle" && "opacity-0", state === "listening" && "rk-halo opacity-70", state === "thinking" && "opacity-40", state === "speaking" && "rk-halo opacity-60")
3747
+ });
3748
+ /**
3749
+ * Restarts the `rk-tighten` cinch on every `tightenKey` bump WITHOUT
3750
+ * remounting `KnotSvg` — this used to be `<div key={tightenKey}>`, which
3751
+ * looks like the obvious way to "replay" a CSS animation but tears down
3752
+ * and rebuilds the ENTIRE subtree underneath it on every bump. `KnotSvg`
3753
+ * carries the crossfade state (`blend`/`fromDash`/`tap`) in refs and
3754
+ * state that a remount wipes to their initial values — so a tighten
3755
+ * pulse that happened to land in the SAME commit as a state change (a
3756
+ * real, deterministic sequence: `useChatSession.sendText` sets the
3757
+ * transcript and flips `awaitingAgent` in one batch, which is exactly
3758
+ * `messageArrived`'s rising edge — `concierge-shell.tsx`'s tighten
3759
+ * trigger — landing together with a `listening` → `thinking` state
3760
+ * transition) both skipped the crossfade AND replayed the self-tying
3761
+ * intro from scratch, because the remount reset `blend` to 0.
3762
+ *
3763
+ * The fix is the standard "restart a CSS animation without touching the
3764
+ * DOM subtree" technique: remove the class, force a synchronous reflow
3765
+ * (reading `offsetWidth` — the read is what forces the browser to flush
3766
+ * layout, so the SUBSEQUENT class add is seen as a genuinely NEW
3767
+ * animation start rather than a no-op), then re-add it. `KnotSvg` is
3768
+ * never unmounted, so its own state survives untouched.
3769
+ */
3770
+ const artRef = useRef(null);
3771
+ const prevTighten = useRef(tightenKey);
3772
+ useEffect(() => {
3773
+ if (tightenKey === prevTighten.current) return;
3774
+ prevTighten.current = tightenKey;
3775
+ const el = artRef.current;
3776
+ if (!el) return;
3777
+ el.classList.remove("rk-tighten");
3778
+ el.offsetWidth;
3779
+ el.classList.add("rk-tighten");
3780
+ }, [tightenKey]);
3781
+ const art = /* @__PURE__ */ jsx("div", {
3782
+ ref: artRef,
3783
+ className: cn("rk-tighten relative", artClassName),
3784
+ children: /* @__PURE__ */ jsx(KnotSvg, {
3785
+ state,
3786
+ tightenKey
3787
+ })
3788
+ });
3789
+ return /* @__PURE__ */ jsxs("div", {
3790
+ ...labelProps(label),
3791
+ className: cn("rk-sway relative", outerClassName),
3792
+ style: {
3793
+ ...KNOT_COLOR_VARS,
3794
+ animationDuration: state === "idle" ? "6s" : "7s"
3795
+ },
3796
+ children: [halo, chrome ? /* @__PURE__ */ jsx("div", {
3797
+ className: "relative z-10 flex h-full w-full items-center justify-center rounded-2xl border border-brand-plum/10 bg-[var(--knot-surface)]",
3798
+ children: art
3799
+ }) : art]
3800
+ });
3801
+ }
3802
+ /** The drawn line itself — the part of the source `RopeKnot` component with no size opinion. */
3803
+ function KnotSvg({ state, tightenKey }) {
3804
+ const glowId = `rk-glow${useId()}`;
3805
+ const pathRef = useRef(null);
3806
+ const prev = useRef(state);
3807
+ const [blend, setBlend] = useState(0);
3808
+ const fromDash = useRef("100 0 0");
3809
+ useEffect(() => {
3810
+ if (prev.current === state) return;
3811
+ prev.current = state;
3812
+ const el = pathRef.current;
3813
+ if (el) {
3814
+ const d = getComputedStyle(el).strokeDasharray;
3815
+ if (d && d !== "none") fromDash.current = d.replace(/px/g, "");
3816
+ }
3817
+ setBlend((b) => b + 1);
3818
+ }, [state]);
3819
+ const [tap, setTap] = useState(false);
3820
+ useEffect(() => {
3821
+ if (tightenKey === 0) return;
3822
+ setTap(true);
3823
+ const t = setTimeout(() => setTap(false), 750);
3824
+ return () => clearTimeout(t);
3825
+ }, [tightenKey]);
3826
+ return /* @__PURE__ */ jsxs("svg", {
3827
+ viewBox: "0 0 100 100",
3828
+ className: cn("h-full w-full overflow-visible", state === "thinking" && "rk-thinking"),
3829
+ children: [
3830
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsxs("linearGradient", {
3831
+ id: glowId,
3832
+ x1: "0",
3833
+ y1: "0",
3834
+ x2: "1",
3835
+ y2: "0",
3836
+ children: [
3837
+ /* @__PURE__ */ jsx("stop", {
3838
+ offset: "0%",
3839
+ stopColor: "var(--knot-ink)",
3840
+ stopOpacity: "0"
3841
+ }),
3842
+ /* @__PURE__ */ jsx("stop", {
3843
+ offset: "50%",
3844
+ stopColor: "var(--knot-ink)",
3845
+ stopOpacity: "1"
3846
+ }),
3847
+ /* @__PURE__ */ jsx("stop", {
3848
+ offset: "100%",
3849
+ stopColor: "var(--knot-ink)",
3850
+ stopOpacity: "0"
3851
+ })
3852
+ ]
3853
+ }) }),
3854
+ /* @__PURE__ */ jsx("path", {
3855
+ d: KNOT_PATH,
3856
+ fill: "none",
3857
+ stroke: "var(--knot-ink-faint)",
3858
+ strokeWidth: "3",
3859
+ strokeLinecap: "round",
3860
+ className: cn("transition-opacity duration-500", state === "listening" ? "opacity-100" : "opacity-60")
3861
+ }),
3862
+ /* @__PURE__ */ jsx("path", {
3863
+ ref: pathRef,
3864
+ d: KNOT_PATH,
3865
+ pathLength: 100,
3866
+ style: { ["--rk-from"]: fromDash.current },
3867
+ className: cn("rk-draw", state === "idle" && "rk-idle", state === "listening" && "rk-listening", state === "thinking" && "rk-thread", state === "speaking" && "rk-speaking", blend > 0 && !tap && "rk-blend", tap && "rk-tap"),
3868
+ fill: "none",
3869
+ stroke: "var(--knot-ink)",
3870
+ strokeLinecap: "round",
3871
+ strokeLinejoin: "round"
3872
+ }, blend),
3873
+ state !== "idle" && /* @__PURE__ */ jsx("path", {
3874
+ d: KNOT_PATH,
3875
+ pathLength: 100,
3876
+ className: cn("rk-pulse transition-opacity duration-500", state === "speaking" ? "opacity-0" : "opacity-100"),
3877
+ style: { animationDuration: PULSE_SPEED[state] },
3878
+ fill: "none",
3879
+ stroke: `url(#${glowId})`,
3880
+ strokeWidth: "4",
3881
+ strokeLinecap: "round",
3882
+ strokeDasharray: PULSE_DASH
3883
+ })
3884
+ ]
3885
+ });
3886
+ }
3887
+ //#endregion
3888
+ //#region src/avatar.ts
3889
+ /**
3890
+ * Which face the widget draws — a per-tenant `appearance.avatar` choice.
3891
+ *
3892
+ * `'orb'` is `BotFace`, the animated gradient blob this widget has always
3893
+ * shipped. `'knot'` is `RopeKnot`, a hand-drawn rope line that ties and
3894
+ * unties itself through the same four {@link BotState}s. Kept as data,
3895
+ * separate from the components, for the same reason `bot-state.ts` keeps
3896
+ * `BotState` separate from `BotFace`: parsing and defaulting have to be
3897
+ * assertable without rendering either avatar.
3898
+ */
3899
+ var WIDGET_AVATARS = ["orb", "knot"];
3900
+ /** What every layer in this package falls back to when a tenant never published one. */
3901
+ var DEFAULT_WIDGET_AVATAR = "orb";
3902
+ /** Whether a value is an avatar this widget knows how to render. Mirrors `bot-state.ts`'s `isBotState`. */
3903
+ function isWidgetAvatar(value) {
3904
+ return typeof value === "string" && WIDGET_AVATARS.includes(value);
3905
+ }
3906
+ //#endregion
3621
3907
  //#region ../../node_modules/.pnpm/lucide-react@1.25.0_react@19.2.7/node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
3622
3908
  /**
3623
3909
  * @license lucide-react v1.25.0 - ISC
@@ -3887,6 +4173,25 @@ var X = createLucideIcon("x", [["path", {
3887
4173
  key: "d8bk6v"
3888
4174
  }]]);
3889
4175
  //#endregion
4176
+ //#region src/avatar-face.tsx
4177
+ function AvatarFace({ avatar, state, size, label, messageArrived, tightenKey }) {
4178
+ switch (avatar) {
4179
+ case "orb": return /* @__PURE__ */ jsx(BotFace, {
4180
+ state,
4181
+ size,
4182
+ label,
4183
+ messageArrived
4184
+ });
4185
+ case "knot": return /* @__PURE__ */ jsx(RopeKnot, {
4186
+ state,
4187
+ size,
4188
+ label,
4189
+ tightenKey
4190
+ });
4191
+ default: throw new Error(`Unhandled widget avatar: ${String(avatar)}`);
4192
+ }
4193
+ }
4194
+ //#endregion
3890
4195
  //#region src/position.ts
3891
4196
  /**
3892
4197
  * Where the concierge sits on the host page, and how a visitor moves it.
@@ -3984,11 +4289,18 @@ function panelClasses(position) {
3984
4289
  }
3985
4290
  //#endregion
3986
4291
  //#region src/concierge-launcher.tsx
3987
- function ConciergeLauncher({ label, srLabel, moveLabel, position, onPositionChange, onOpen, hidden, id, testId }) {
4292
+ function ConciergeLauncher({ label, srLabel, moveLabel, position, onPositionChange, onOpen, hidden, id, testId, avatar = "orb" }) {
3988
4293
  const rootRef = useRef(null);
3989
4294
  /** Pixel offset while a drag is in flight; `null` when it is not. */
3990
4295
  const [drag, setDrag] = useState(null);
3991
4296
  /**
4297
+ * Bumped on every press — `RopeKnot`'s click feedback (`rk-tighten` +
4298
+ * `rk-tap`), the same gesture the Lovable prototype's `RopeKnotTrigger`
4299
+ * wired directly into its own `onClick`. `BotFace` has no equivalent prop
4300
+ * and ignores an unused number, so this costs the orb nothing.
4301
+ */
4302
+ const [tightenKey, setTightenKey] = useState(0);
4303
+ /**
3992
4304
  * Where the drag started: the pointer, and the pill's centre AT THAT MOMENT.
3993
4305
  *
3994
4306
  * The centre is captured on pointer-DOWN rather than measured on pointer-up,
@@ -4089,17 +4401,22 @@ function ConciergeLauncher({ label, srLabel, moveLabel, position, onPositionChan
4089
4401
  type: "button",
4090
4402
  "aria-label": label === void 0 ? srLabel : void 0,
4091
4403
  tabIndex: hidden ? -1 : 0,
4092
- onClick: onOpen,
4404
+ onClick: () => {
4405
+ setTightenKey((k) => k + 1);
4406
+ onOpen();
4407
+ },
4093
4408
  "data-testid": testId ? `${testId}-open` : void 0,
4094
4409
  className: "flex items-center gap-2.5 rounded-full focus-visible:ring-brand-plum/30 focus-visible:ring-2 focus-visible:outline-none",
4095
4410
  children: [/* @__PURE__ */ jsx("span", {
4096
4411
  "aria-hidden": true,
4097
- className: "relative block size-10 shrink-0",
4412
+ className: "relative block size-12 shrink-0",
4098
4413
  children: /* @__PURE__ */ jsx("span", {
4099
- className: "absolute start-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 scale-[0.625] rtl:translate-x-1/2",
4100
- children: /* @__PURE__ */ jsx(BotFace, {
4414
+ className: "absolute start-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 scale-[0.75] rtl:translate-x-1/2",
4415
+ children: /* @__PURE__ */ jsx(AvatarFace, {
4416
+ avatar,
4101
4417
  state: "idle",
4102
- size: "sm"
4418
+ size: "sm",
4419
+ tightenKey
4103
4420
  })
4104
4421
  })
4105
4422
  }), label === void 0 ? null : /* @__PURE__ */ jsx("span", {
@@ -4111,6 +4428,109 @@ function ConciergeLauncher({ label, srLabel, moveLabel, position, onPositionChan
4111
4428
  });
4112
4429
  }
4113
4430
  //#endregion
4431
+ //#region src/messages.ts
4432
+ /**
4433
+ * Message keys that carry a `{product}` placeholder — the avatar's
4434
+ * accessible-name states. Kept as a literal template, interpolated at
4435
+ * render time, never a brand name baked into this file (see the module doc
4436
+ * comment).
4437
+ */
4438
+ /**
4439
+ * `Required<...>`, not `WidgetMessages`: keys added after 0.2.0 are optional
4440
+ * on the INTERFACE so a host's own complete catalogue keeps compiling, but
4441
+ * this object is the fallback every one of them resolves against, so it must
4442
+ * define all of them. The type is what makes a forgotten default a compile
4443
+ * error rather than an empty string on somebody's storefront.
4444
+ */
4445
+ var defaultWidgetMessages = {
4446
+ state_idle: "{product} — idle",
4447
+ state_listening: "{product} — listening",
4448
+ state_thinking: "{product} — thinking",
4449
+ state_speaking: "{product} — speaking",
4450
+ mic_start: "Start talking",
4451
+ mic_stop: "Stop talking",
4452
+ open: "Open chat",
4453
+ minimize: "Minimise",
4454
+ conversation: "Chat conversation",
4455
+ empty: "Ask a question — speak or type.",
4456
+ type_placeholder: "Type a message",
4457
+ send: "Send",
4458
+ move: "Move the assistant",
4459
+ call_end: "End the call",
4460
+ handoff_event: "Handed to a human teammate",
4461
+ escalated_banner: "A human teammate will pick this up shortly.",
4462
+ status_sending: "Sending",
4463
+ status_sent: "Sent",
4464
+ typing: "Typing",
4465
+ suggestions_label: "Suggested questions",
4466
+ suggestion_1: "What is popular right now?",
4467
+ suggestion_2: "Help me pick something",
4468
+ suggestion_3: "Talk to a human",
4469
+ attach_label: "Attach a file",
4470
+ attach_uploading: "Sending {filename}…",
4471
+ attach_error: "Could not send {filename}. Try again.",
4472
+ attach_image_alt: "Attached image: {filename}",
4473
+ attach_download_hint: "Opens or downloads in a new tab",
4474
+ add_to_cart: "Add to cart",
4475
+ adding_to_cart: "Adding…",
4476
+ added_to_cart: "Added to cart",
4477
+ unavailable: "Unavailable",
4478
+ see_all: "See all {count}",
4479
+ cart_summary_title: "Your cart",
4480
+ cart_summary_total: "Total",
4481
+ checkout_now: "Checkout",
4482
+ checkout_failed: "Could not start checkout. Try again.",
4483
+ voice_state_connecting: "Connecting",
4484
+ voice_state_listening: "Listening",
4485
+ voice_state_thinking: "Thinking",
4486
+ voice_state_speaking: "Speaking",
4487
+ voice_unavailable_escalated: "Voice is unavailable while you’re talking to a person"
4488
+ };
4489
+ /**
4490
+ * Interpolates `{token}` placeholders in a message template. Deliberately the
4491
+ * same `{token}` syntax `next-intl`'s ICU messages use for a plain variable,
4492
+ * so `apps/web`'s adapter can hand this package `t.raw(key)` (the
4493
+ * UN-interpolated template) and let this one function do the substitution —
4494
+ * one interpolation implementation, not two.
4495
+ *
4496
+ * A token with no matching var, or a var that isn't a string/number, is left
4497
+ * as literal text rather than thrown on — a missing translation must degrade
4498
+ * to a visibly-odd string, never a broken render.
4499
+ */
4500
+ function formatMessage(template, vars) {
4501
+ if (!vars) return template;
4502
+ return template.replace(/\{(\w+)\}/g, (match, key) => {
4503
+ const value = vars[key];
4504
+ return value === void 0 ? match : String(value);
4505
+ });
4506
+ }
4507
+ /**
4508
+ * Merges tenant-authored overrides (typically the `widgetMessagesFromCopy`
4509
+ * result) over `defaultWidgetMessages`. An override that is `undefined`,
4510
+ * empty, or whitespace-only is skipped — a blank tenant string must not blank
4511
+ * out a working default, same "absent means unset" contract
4512
+ * `PublicWidgetConfig.copy`'s own fields carry.
4513
+ */
4514
+ function resolveWidgetMessages(overrides) {
4515
+ if (!overrides) return defaultWidgetMessages;
4516
+ const merged = { ...defaultWidgetMessages };
4517
+ for (const [key, value] of Object.entries(overrides)) if (typeof value === "string" && value.trim() !== "") merged[key] = value;
4518
+ return merged;
4519
+ }
4520
+ /**
4521
+ * Maps `PublicWidgetConfig.copy`'s fields onto the `WidgetMessages` keys they
4522
+ * overlap with. `greeting` is deliberately NOT mapped here — it seeds the
4523
+ * first turn (`SessionBootResponse.greeting`), it is not a UI label, so a
4524
+ * caller that wants it has it already from the session boot response.
4525
+ * `offlineMessage` has no current `WidgetMessages` counterpart (nothing here
4526
+ * renders an "offline" state yet) and is likewise omitted rather than
4527
+ * guessed onto the nearest-sounding key.
4528
+ */
4529
+ function widgetMessagesFromCopy(copy) {
4530
+ if (!copy) return {};
4531
+ return copy.placeholder !== void 0 ? { type_placeholder: copy.placeholder } : {};
4532
+ }
4533
+ //#endregion
4114
4534
  //#region src/morphing-loader.tsx
4115
4535
  /**
4116
4536
  * A voice-frequency visualizer loader.
@@ -4190,7 +4610,7 @@ function MorphingLoader({ size = "md", variant = "brand", className, label = "Lo
4190
4610
  ];
4191
4611
  const isLight = variant === "light";
4192
4612
  return /* @__PURE__ */ jsxs("div", {
4193
- className: cn("relative inline-flex items-end justify-center", dims, gap, isLight && "text-primary-foreground", className),
4613
+ className: cn("relative inline-flex items-end justify-center", dims, gap, isLight && "text-[var(--widget-accent-foreground)]", className),
4194
4614
  role: "status",
4195
4615
  "aria-label": label,
4196
4616
  children: [bars.map((bar, i) => /* @__PURE__ */ jsx("span", {
@@ -4211,13 +4631,69 @@ function MorphingLoader({ size = "md", variant = "brand", className, label = "Lo
4211
4631
  });
4212
4632
  }
4213
4633
  //#endregion
4214
- //#region src/concierge-shell.tsx
4634
+ //#region src/transcript-geometry.ts
4635
+ /**
4636
+ * PANEL GEOMETRY — where the conversation's first row sits, as a FRACTION of
4637
+ * the panel's height, and what that costs horizontally.
4638
+ *
4639
+ * Four CSS length expressions and the arithmetic behind them, used by
4640
+ * `concierge-shell.tsx`'s `transcriptEdgeFade`. Their own module, and NOT
4641
+ * re-exported from `index.ts`: `concierge-shell.geometry.test.tsx` has to read
4642
+ * the exact strings the component ships (jsdom's CSS serializer mangles a
4643
+ * `max()` containing a subtraction, so reading them back off a rendered element
4644
+ * tests jsdom rather than this widget), while the package's public API stays
4645
+ * the components themselves.
4646
+ *
4647
+ * One ratio ties the four lengths together, and it is the whole
4648
+ * repair for a bug that shipped: the panel is an ellipse (`rounded-full` on a
4649
+ * `w x 1.6w` box), so how much width it offers depends entirely on how far down
4650
+ * you are. The clearances below scaled with `cqh` while the transcript's
4651
+ * horizontal inset was a fixed 8px tuned for the oval's wide middle, so the
4652
+ * taller the panel got the HIGHER the first message sat proportionally — into a
4653
+ * narrower part of the curve, with no matching inset. Measured live in
4654
+ * Storybook, first agent bubble's top-left corner against the curve at its own
4655
+ * top edge: 14px inside the ellipse at a 582px panel, 37px at 720px, 62px at
4656
+ * 920px (the 2000x1150 desktop it was reported on). `overflow-clip` on the
4657
+ * surface then cut exactly that much off the bubble.
4658
+ *
4659
+ * 0.1924 is not chosen, it is READ OFF the short panel: 112px (the tuned
4660
+ * clearance, see {@link TRANSCRIPT_FADE_TOP_LEN}) over 582px (the panel a
4661
+ * 375x812 phone renders) is 0.19244. Holding that ratio at every size is what
4662
+ * makes the geometry scale-invariant — every panel then presents the first row
4663
+ * at the same point on the same curve, and ONE horizontal inset serves all of
4664
+ * them ({@link TRANSCRIPT_INSET_X}). Expressed as `19.24cqh` in the lengths
4665
+ * below; `cqh` is the panel's own height, via `[container-type:size]` on the
4666
+ * panel div (verified live: `14cqh` resolved to 128.8px on a 920px panel).
4667
+ *
4668
+ * Not a JS constant that gets multiplied out — the panel's height is never
4669
+ * known to JS, only to CSS, which is why every length here is an expression.
4670
+ */
4215
4671
  /**
4216
4672
  * Top ramp when the transcript starts at the panel's top, under the floating
4217
4673
  * orb — it has to span the orb, so a message is gone before it reaches it
4218
4674
  * rather than sliding out from behind it half-visible.
4675
+ *
4676
+ * A CSS length EXPRESSION, not a bare number, since the aspect-ratio panel
4677
+ * (`w-[min(97vw,50dvh)]` + `aspect-[5/8]`) ranges from ~582px tall (mobile,
4678
+ * width-bound) to 800px+ (desktop, height-bound) — a fixed 112px clearance
4679
+ * tuned for the OLD fixed-520px panel left too little air under the orb on a
4680
+ * tall one and too much on a short one. `max(112px, 19.24cqh)` is a floor, not
4681
+ * a fixed value: it stays exactly 112px (today's tuned figure) on a short
4682
+ * panel, where 19.24cqh would fall below it, and grows with `cqh` — the query
4683
+ * container's own height, established by `[container-type:size]` on the
4684
+ * panel div below — once the panel is tall enough that 19.24% of it exceeds
4685
+ * 112px. `cqh` rather than `dvh` specifically: the panel's real rendered
4686
+ * height, not the viewport's, since the panel does not always fill the
4687
+ * viewport (mobile: width-bound, height is `w / (8/5)`, shorter than 100dvh).
4688
+ *
4689
+ * 19.24, not the 14 this shipped with: 14cqh gave a TALL panel proportionally
4690
+ * LESS clearance than the 112px floor gives a short one (14% against 19.24%),
4691
+ * which pushed the first message up into the narrowing part of the ellipse —
4692
+ * see the ratio's own note above for the measurements. The floor and the
4693
+ * scaling term now agree at 582px (19.24% of 582 = 111.98), so the two meet
4694
+ * without a step rather than crossing over at some unrelated height.
4219
4695
  */
4220
- var TRANSCRIPT_FADE_TOP_PX = 112;
4696
+ var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 19.24cqh)";
4221
4697
  /**
4222
4698
  * Top ramp when a `badge` sits above the transcript.
4223
4699
  *
@@ -4227,10 +4703,145 @@ var TRANSCRIPT_FADE_TOP_PX = 112;
4227
4703
  * reason (measured in `WithABadgeAndNoVoice` — orb ends 565, badge 573-598,
4228
4704
  * first message could not start above 710). At that point the fade is only
4229
4705
  * doing its ordinary job of softening a scroll edge, so it wants an ordinary
4230
- * scroll-edge length.
4706
+ * scroll-edge length. Same floor+`cqh` scheme as {@link TRANSCRIPT_FADE_TOP_LEN}
4707
+ * above and for the same reason — this ramp needs to soften proportionally
4708
+ * more of a tall panel's scroll edge than a short one's.
4709
+ *
4710
+ * The third arm is the ellipse, and it is what keeps this variant honest at
4711
+ * sizes the badge's own fixed offsets stop covering. With a badge the first row
4712
+ * is pushed down by chrome that does NOT scale — 1px surface border + 6px
4713
+ * column padding + the badge wrapper's `mt-[104px]` + 4px list padding = 115px
4714
+ * — so the row lands at `(115px + this ramp) / panelHeight`, a fraction that
4715
+ * SHRINKS as the panel grows. `19.24cqh - 115px` is that equation solved for
4716
+ * the ramp, so the row lands on the same point of the curve the no-badge
4717
+ * variant does. It is inert on the panels this variant was tuned against
4718
+ * (negative at 582px, 4.5px at 720px, so the other two arms win) and takes over
4719
+ * only above ~745px, where the fixed 115px has stopped being enough.
4720
+ *
4721
+ * The badge's own height is counted as ZERO in that 115px, deliberately:
4722
+ * `badge` is an arbitrary node from the host (`voice-widget.tsx` passes a
4723
+ * one-line status pill, ~26px), and only the shortest-badge bound holds for
4724
+ * every caller. A taller badge pushes the row further down, which is the safe
4725
+ * direction.
4726
+ */
4727
+ var TRANSCRIPT_FADE_TOP_WITH_BADGE_LEN = "max(28px, 4cqh, 19.24cqh - 115px)";
4728
+ var TRANSCRIPT_FADE_BOTTOM_LEN = "max(118px, 20.27cqh)";
4729
+ /**
4730
+ * The transcript's horizontal inset — the width the ellipse actually costs.
4731
+ *
4732
+ * `10.6cqw` is where the curve is at the first row's height: on an ellipse of
4733
+ * width `w`, at the fraction 0.1924 of the way down (the ratio the clearances
4734
+ * above hold at every size), the left edge lies `w * (1 - sqrt(1 - (2*0.1924 -
4735
+ * 1)^2)) / 2` = `0.1058 * w` in from the bounding box. Rounded up to 10.6% so
4736
+ * the rounding goes toward clearance rather than away from it.
4737
+ *
4738
+ * `- 11px` because 11px of that is already paid for by fixed chrome outside
4739
+ * this element: the surface's 1px border plus the inner column's `px-2.5`. The
4740
+ * inset is measured from the PANEL's box, which is where the curve is; this
4741
+ * padding only has to make up the difference. Verified live: a 363.8px-wide
4742
+ * panel put the first bubble's left edge at 19px = 11px chrome + the 8px this
4743
+ * replaces.
4744
+ *
4745
+ * The `8px` floor is the value this shipped with, kept as a lower bound so a
4746
+ * degenerately small panel can never end up with less padding than a plain
4747
+ * scroll edge wants. It is inert at every real size (the formula gives 27.6px
4748
+ * on the smallest panel the widget renders).
4749
+ *
4750
+ * Symmetric on purpose, and applied as `padding-inline` so it stays symmetric
4751
+ * in RTL: the ellipse is symmetric, the visitor's own bubbles are `justify-end`
4752
+ * against the other side of it, and either side is the first row's side
4753
+ * depending on who spoke.
4231
4754
  */
4232
- var TRANSCRIPT_FADE_TOP_WITH_BADGE_PX = 28;
4233
- var TRANSCRIPT_FADE_BOTTOM_PX = 118;
4755
+ var TRANSCRIPT_INSET_X = "max(8px, 10.6cqw - 11px)";
4756
+ /**
4757
+ * The composer overlay's bottom offset when the microphone is drawn.
4758
+ *
4759
+ * `11.86cqh` is {@link COMPOSER_ROW_FRACTION} as a length. `- 63px` is
4760
+ * everything between this offset and the input's bottom edge that does NOT
4761
+ * scale: the surface's 1px border (the overlay is positioned against the inner
4762
+ * column's padding box, one border inside the panel) plus the 62px microphone
4763
+ * block — a 10px `gap-2.5`, the row's 4px `mt-1`, and a 48px `size-12` button.
4764
+ *
4765
+ * `max(6px, …)` keeps the 6px this shipped with as a floor, and the two arms
4766
+ * MEET at the panel it was tuned on rather than crossing somewhere unrelated:
4767
+ * `11.86cqh - 63px` is 6.03px at 582px, so a phone renders what it rendered
4768
+ * before to a hundredth of a pixel and only larger panels lift the composer.
4769
+ */
4770
+ var COMPOSER_BOTTOM_LEN = "max(6px, 11.86cqh - 63px)";
4771
+ /**
4772
+ * The composer overlay's bottom offset when there is NO microphone.
4773
+ *
4774
+ * Same target row, minus only the 1px surface border: with `voice` omitted the
4775
+ * overlay's last child IS the input, so the 62px the microphone block
4776
+ * contributed above has to come from this offset instead. That is a real move —
4777
+ * 6px to 68px on a phone — and it is the fix rather than a side effect. Left at
4778
+ * 6px the input sits 7px off a `rounded-full` panel's bottom tip, where the
4779
+ * ellipse offers 79px of width in total; no width cap can rescue that row, so
4780
+ * the row itself has to come up to where the panel is wide enough to hold it.
4781
+ *
4782
+ * The band it moves into is the one the microphone would have occupied, which
4783
+ * the transcript already clears ({@link TRANSCRIPT_FADE_BOTTOM_LEN} is sized
4784
+ * for the input + microphone pair regardless of whether the pair is drawn), so
4785
+ * nothing above has to move to make room.
4786
+ */
4787
+ var COMPOSER_BOTTOM_NO_VOICE_LEN = "max(6px, 11.86cqh - 1px)";
4788
+ /**
4789
+ * The composer's width cap — what the ellipse actually offers at that row.
4790
+ *
4791
+ * On an ellipse of width `w`, at the fraction `1 - 0.1186` of the way down, the
4792
+ * full chord is `w * sqrt(1 - (2*0.8814 - 1)^2)` = `0.6465 * w`. So `64.65cqw`
4793
+ * is not a taste-tuned percentage, it is the panel's own width at the row the
4794
+ * two offsets above pin the input to — where `w-[71%]`, the class this caps,
4795
+ * was 6.4% of the panel too wide at EVERY size (10.8px of overhang on a phone,
4796
+ * 52.0px on a 920px panel, because the row also drifts lower as the panel
4797
+ * grows).
4798
+ *
4799
+ * `- 10px` is clearance, 5px each side, matching the 5px the transcript's rows
4800
+ * clear the curve by — the panel paints a 1.5px gradient ring plus a 1px
4801
+ * surface border at that edge, and the input's own rounding means the arc, not
4802
+ * the corner, is what approaches the curve.
4803
+ *
4804
+ * Applied as `max-width` over the existing `w-[71%]`, not in place of it: 71%
4805
+ * stays the upper bound the composer had, and this only ever tightens it (the
4806
+ * ellipse term is below 71% for any panel, since 0.6465 < 0.71). The `160px`
4807
+ * floor is the "cap it sensibly" arm — it stops a degenerately small panel from
4808
+ * resolving the composer to a few dozen pixels of unusable input, and it is
4809
+ * inert at every size the widget really renders (it binds only below a 248px
4810
+ * panel; the narrowest phone in circulation, 320px, gives 310px).
4811
+ */
4812
+ var COMPOSER_MAX_WIDTH_LEN = "max(160px, 64.65cqw - 10px)";
4813
+ /**
4814
+ * The opaque ground the composer sits on, which has to keep covering it.
4815
+ *
4816
+ * The transcript runs the panel's whole height and passes BEHIND this row, so
4817
+ * this gradient is the only thing between a message and the input's own
4818
+ * translucent chip fill. It was a fixed `h-[132px]`, tuned when the composer
4819
+ * was pinned 6px off the bottom on every panel — and the moment the offsets
4820
+ * above start lifting the composer on a tall panel, a fixed ground stops
4821
+ * reaching its top edge (the composer's top is `11.86cqh + 40px` above the
4822
+ * panel's bottom: 109px at 582px, but 149px at 920px, against 132px of ground).
4823
+ *
4824
+ * 22.68cqh is the same read-off-the-short-panel derivation as everything else
4825
+ * here — 132/582 = 0.22680 — so a phone renders exactly the 132px it rendered
4826
+ * before and the ground grows with the row it is under. It stays above the
4827
+ * composer's own top at every size, and stays the same shade taller than the
4828
+ * transcript's bottom clearance that it is today ({@link
4829
+ * TRANSCRIPT_FADE_BOTTOM_LEN} is 20.27cqh against this 22.68cqh, exactly the
4830
+ * 118:132 relationship the two were tuned at), so they still meet without a
4831
+ * seam or a band of doubly-darkened panel.
4832
+ */
4833
+ var COMPOSER_GROUND_LEN = "max(132px, 22.68cqh)";
4834
+ //#endregion
4835
+ //#region src/concierge-shell.tsx
4836
+ /**
4837
+ * How far off the bottom still counts as "following the conversation".
4838
+ *
4839
+ * Not zero: fractional scroll metrics on zoomed and hi-dpi displays never
4840
+ * land exactly on the bottom, and a smooth scroll is still in flight when the
4841
+ * next streamed token resizes the content. Both would read as the visitor
4842
+ * having deliberately scrolled up, and stop the transcript following.
4843
+ */
4844
+ var FOLLOW_TOLERANCE_PX = 24;
4234
4845
  /**
4235
4846
  * Build the transcript's mask + the padding that matches it.
4236
4847
  *
@@ -4238,20 +4849,41 @@ var TRANSCRIPT_FADE_BOTTOM_PX = 118;
4238
4849
  * last messages scroll clear of the ramp, so a ramp length that is not also
4239
4850
  * the padding leaves the newest message permanently half-dissolved.
4240
4851
  *
4241
- * The top ramp's stops are scaled from `topPx` rather than hardcoded, so the
4852
+ * The top ramp's stops are scaled from `topLen` rather than hardcoded, so the
4242
4853
  * shortened badge variant keeps the same eased shape instead of becoming a
4243
- * steep two-point cut.
4854
+ * steep two-point cut. `topLen` is a CSS length EXPRESSION now (a `max(<px>,
4855
+ * <N>cqh)` floor, see the constants above), not a plain number — `at(fraction)`
4856
+ * therefore emits `calc(<topLen> * <fraction>)` rather than doing the
4857
+ * multiplication in JS, so each stop scales with the query container's
4858
+ * height (`cqh`) exactly the way `topLen` itself does. `calc()` accepts a
4859
+ * `max()` expression as its left operand (`max()` resolves to a `<length>`,
4860
+ * and a `<length>` may be multiplied by a bare `<number>` inside `calc()`),
4861
+ * so this composes without a second unit-handling special case.
4862
+ *
4863
+ * The bottom ramp's own inner taper (the last four stops, `96px`/`72px`/
4864
+ * `48px`/`24px`) stays fixed pixels, deliberately NOT scaled by `cqh`: it is
4865
+ * a small, fixed-shape cosmetic fade against the very bottom edge, sized
4866
+ * once and unrelated to how much CLEARANCE the composer needs above it —
4867
+ * that clearance is what `TRANSCRIPT_FADE_BOTTOM_LEN` (the transition point
4868
+ * this taper starts from, and the padding below) controls, and that is what
4869
+ * scales.
4870
+ *
4871
+ * The horizontal inset rides along here rather than staying a `px-2` class for
4872
+ * the same reason the vertical padding does: it is derived from `topLen` — the
4873
+ * curve is only knowable once you know how far down the first row starts (see
4874
+ * {@link TRANSCRIPT_INSET_X}) — and splitting a derived pair across a class and
4875
+ * a style object is exactly how the two drift apart.
4244
4876
  */
4245
- function transcriptEdgeFade(topPx) {
4246
- const at = (fraction) => Math.round(topPx * fraction);
4877
+ function transcriptEdgeFade(topLen) {
4878
+ const at = (fraction) => `calc(${topLen} * ${fraction})`;
4247
4879
  const gradient = `linear-gradient(to bottom, ${[
4248
4880
  "transparent 0",
4249
- `rgba(0,0,0,0.06) ${at(.21)}px`,
4250
- `rgba(0,0,0,0.20) ${at(.43)}px`,
4251
- `rgba(0,0,0,0.45) ${at(.64)}px`,
4252
- `rgba(0,0,0,0.75) ${at(.82)}px`,
4253
- `#000 ${topPx}px`,
4254
- `#000 calc(100% - ${TRANSCRIPT_FADE_BOTTOM_PX}px)`,
4881
+ `rgba(0,0,0,0.06) ${at(.21)}`,
4882
+ `rgba(0,0,0,0.20) ${at(.43)}`,
4883
+ `rgba(0,0,0,0.45) ${at(.64)}`,
4884
+ `rgba(0,0,0,0.75) ${at(.82)}`,
4885
+ `#000 ${topLen}`,
4886
+ `#000 calc(100% - ${TRANSCRIPT_FADE_BOTTOM_LEN})`,
4255
4887
  "rgba(0,0,0,0.86) calc(100% - 96px)",
4256
4888
  "rgba(0,0,0,0.60) calc(100% - 72px)",
4257
4889
  "rgba(0,0,0,0.32) calc(100% - 48px)",
@@ -4261,35 +4893,177 @@ function transcriptEdgeFade(topPx) {
4261
4893
  return {
4262
4894
  maskImage: gradient,
4263
4895
  WebkitMaskImage: gradient,
4264
- paddingTop: `${topPx}px`,
4265
- paddingBottom: `${TRANSCRIPT_FADE_BOTTOM_PX}px`
4896
+ paddingTop: topLen,
4897
+ paddingBottom: TRANSCRIPT_FADE_BOTTOM_LEN,
4898
+ paddingInline: TRANSCRIPT_INSET_X
4266
4899
  };
4267
4900
  }
4268
4901
  /** Both variants built once — neither depends on props beyond badge presence. */
4269
- var TRANSCRIPT_EDGE_FADE = transcriptEdgeFade(TRANSCRIPT_FADE_TOP_PX);
4270
- var TRANSCRIPT_EDGE_FADE_WITH_BADGE = transcriptEdgeFade(TRANSCRIPT_FADE_TOP_WITH_BADGE_PX);
4902
+ var TRANSCRIPT_EDGE_FADE = transcriptEdgeFade(TRANSCRIPT_FADE_TOP_LEN);
4903
+ var TRANSCRIPT_EDGE_FADE_WITH_BADGE = transcriptEdgeFade(TRANSCRIPT_FADE_TOP_WITH_BADGE_LEN);
4904
+ /**
4905
+ * Maps the call onto the pill it shows, reusing fields `ConciergeShellVoice`
4906
+ * already carries rather than inventing new plumbing:
4907
+ *
4908
+ * - `'connecting'` → `connecting`
4909
+ * - `'waiting'` (the agent is thinking, between the caller's turn ending and
4910
+ * the reply starting) → `thinking`
4911
+ * - `'live'` + `agentSpeaking` → `speaking`
4912
+ * - `'live'` otherwise → `listening`
4913
+ * - `'idle'` / `'blocked'` → `null`, no pill
4914
+ *
4915
+ * `agentSpeaking` is already a real field on {@link ConciergeShellVoice} —
4916
+ * this function only reads it, it does not require every caller to start
4917
+ * setting it; a caller that never populates it simply never reaches
4918
+ * `'speaking'`, which is exactly the same "renders sensibly with what it is
4919
+ * given" contract every other optional field on this interface follows.
4920
+ */
4921
+ function voiceStatePillState(voice) {
4922
+ if (!voice) return null;
4923
+ switch (voice.phase) {
4924
+ case "connecting": return "connecting";
4925
+ case "waiting": return "thinking";
4926
+ case "live": return voice.agentSpeaking ? "speaking" : "listening";
4927
+ default: return null;
4928
+ }
4929
+ }
4930
+ /**
4931
+ * The label a pill state shows, falling back to the package's brand-neutral
4932
+ * English word (`defaultWidgetMessages`) when the host's own `labels` omit
4933
+ * it — the same "an existing caller renders sensibly without changes"
4934
+ * contract every field added to `ConciergeShellVoice.labels` after 0.2.0
4935
+ * follows.
4936
+ */
4937
+ function voiceStatePillLabel(pillState, labels) {
4938
+ switch (pillState) {
4939
+ case "connecting": return labels?.connecting ?? defaultWidgetMessages.voice_state_connecting;
4940
+ case "listening": return labels?.listening ?? defaultWidgetMessages.voice_state_listening;
4941
+ case "thinking": return labels?.thinking ?? defaultWidgetMessages.voice_state_thinking;
4942
+ case "speaking": return labels?.speaking ?? defaultWidgetMessages.voice_state_speaking;
4943
+ }
4944
+ }
4945
+ /**
4946
+ * The leading dot's colour, in brand tokens — never a literal, so it follows
4947
+ * `skinStyle` when a tenant publishes their own brand colours, the same
4948
+ * reasoning every other brand-coloured glow in this file already states.
4949
+ * `listening` and `speaking` share `--brand-rose`: both are "the room is
4950
+ * live" states from the caller's point of view (a caller talking and an
4951
+ * agent talking back both read as "the call is active"), where
4952
+ * `connecting`/`thinking` are the two states with genuinely nothing to
4953
+ * listen to yet.
4954
+ */
4955
+ function voiceStatePillDotColor(pillState) {
4956
+ switch (pillState) {
4957
+ case "connecting": return "var(--brand-amber)";
4958
+ case "thinking": return "var(--brand-plum)";
4959
+ case "listening":
4960
+ case "speaking": return "var(--brand-rose)";
4961
+ }
4962
+ }
4271
4963
  /** How long the opening flourish runs. Matches `.widget-portal`'s own duration. */
4272
4964
  var PORTAL_MS = 720;
4273
- function ConciergeShell({ open, onOpenChange, state, messageArrived = false, labels, children, badge, draft, onDraftChange, onSubmit, composerDisabled = false, voice, announcement, skin, skinStyle, idPrefix = "concierge", scrollKey, composerLeading, testIds, position = DEFAULT_CONCIERGE_POSITION, onPositionChange }) {
4965
+ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, 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 }) {
4274
4966
  const triggerId = `${idPrefix}-trigger`;
4275
4967
  const inputId = `${idPrefix}-input`;
4276
4968
  const [portalActive, setPortalActive] = useState(false);
4277
4969
  const panelRef = useRef(null);
4278
4970
  const transcriptRef = useRef(null);
4971
+ /** The transcript's content box — what grows as a reply streams in. */
4972
+ const transcriptContentRef = useRef(null);
4279
4973
  useEffect(() => {
4280
4974
  if (!open) return;
4281
4975
  setPortalActive(true);
4282
4976
  const id = window.setTimeout(() => setPortalActive(false), PORTAL_MS);
4283
4977
  return () => window.clearTimeout(id);
4284
4978
  }, [open]);
4979
+ /**
4980
+ * The knot's equivalent of the orb's `bot-nod` flourish — `BotFace` fires
4981
+ * `messageArrived` off `className` presence alone (a CSS animation restarts
4982
+ * whenever a class newly APPLIES), which works because `messageArrived`
4983
+ * itself is a derived, level-triggered boolean ("was the last turn from the
4984
+ * caller") that a component only needs to read once per render. `RopeKnot`'s
4985
+ * tighten/tap flourish is EDGE-triggered instead — it plays once per bump of
4986
+ * `tightenKey`, the exact vehicle a launcher press already uses
4987
+ * (`concierge-launcher.tsx`) — so this only bumps it on the RISING edge
4988
+ * (`false` → `true`), not on every render where `messageArrived` merely
4989
+ * stays `true` (e.g. while the agent is still thinking about the same
4990
+ * caller turn).
4991
+ */
4992
+ const wasMessageArrived = useRef(false);
4993
+ const [knotTightenKey, setKnotTightenKey] = useState(0);
4994
+ useEffect(() => {
4995
+ if (messageArrived && !wasMessageArrived.current) setKnotTightenKey((k) => k + 1);
4996
+ wasMessageArrived.current = messageArrived;
4997
+ }, [messageArrived]);
4998
+ /**
4999
+ * Whether the transcript is following the conversation.
5000
+ *
5001
+ * True while the visitor is at (or near) the bottom, false the moment they
5002
+ * scroll up to re-read something — see the observer below for why the
5003
+ * distinction has to exist rather than always scrolling.
5004
+ */
5005
+ const following = useRef(true);
4285
5006
  useEffect(() => {
4286
5007
  const el = transcriptRef.current;
4287
5008
  if (typeof el?.scrollTo !== "function") return;
5009
+ following.current = true;
4288
5010
  el.scrollTo({
4289
5011
  top: el.scrollHeight,
4290
5012
  behavior: "smooth"
4291
5013
  });
4292
5014
  }, [scrollKey, state]);
5015
+ /**
5016
+ * Follow the reply as it STREAMS, not just as it starts.
5017
+ *
5018
+ * `scrollKey` is `turns.length` (`voice-widget.tsx`), so the effect above
5019
+ * fires once, when the agent's turn is appended and still empty or one
5020
+ * token long. Everything after that arrives by SSE into the SAME turn: the
5021
+ * bubble grows downward under a scroll position that was correct when it
5022
+ * was pinned and is stale a word later. The visitor watched the TOP of a
5023
+ * long answer and had to scroll for every line of it — the newest text, the
5024
+ * only part they had not read, was the part off-screen.
5025
+ *
5026
+ * A `ResizeObserver` on the content is what closes that gap: it fires on
5027
+ * every layout change the growing text produces, at whatever rate the
5028
+ * tokens land, with no polling and no dependency on how the host chooses to
5029
+ * stream. `scrollKey` still owns the jump to a NEW turn; this owns staying
5030
+ * there while that turn fills in.
5031
+ *
5032
+ * Gated on `following` so it never fights the visitor. Scrolling up to
5033
+ * re-read an earlier answer while the agent is still typing is an ordinary
5034
+ * thing to do, and a transcript that yanks itself back down every 50ms
5035
+ * makes it impossible. `atBottom` uses a tolerance rather than an equality
5036
+ * — fractional scroll metrics on zoomed or hi-dpi displays never land
5037
+ * exactly, and smooth scrolling is still in flight when the next resize
5038
+ * arrives.
5039
+ *
5040
+ * `behavior: 'auto'`, unlike the jump above: a smooth scroll started every
5041
+ * time a token lands never finishes before the next one restarts it, which
5042
+ * reads as the transcript lagging behind its own text.
5043
+ */
5044
+ useEffect(() => {
5045
+ const el = transcriptRef.current;
5046
+ if (!el || typeof el.scrollTo !== "function") return;
5047
+ if (typeof ResizeObserver === "undefined") return;
5048
+ const atBottom = () => el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_TOLERANCE_PX;
5049
+ const onScroll = () => {
5050
+ following.current = atBottom();
5051
+ };
5052
+ const observer = new ResizeObserver(() => {
5053
+ if (!following.current) return;
5054
+ el.scrollTo({
5055
+ top: el.scrollHeight,
5056
+ behavior: "auto"
5057
+ });
5058
+ });
5059
+ const content = transcriptContentRef.current;
5060
+ if (content) observer.observe(content);
5061
+ el.addEventListener("scroll", onScroll, { passive: true });
5062
+ return () => {
5063
+ observer.disconnect();
5064
+ el.removeEventListener("scroll", onScroll);
5065
+ };
5066
+ }, [open]);
4293
5067
  const handleClose = useCallback(() => {
4294
5068
  onOpenChange(false);
4295
5069
  window.setTimeout(() => {
@@ -4336,8 +5110,46 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lab
4336
5110
  * voice, not only once the transport catches up.
4337
5111
  */
4338
5112
  const inCall = voice !== void 0 && voice.phase !== "idle";
4339
- /** Start, mute or unmute — whichever the one round control means right now. */
4340
- const micLabel = inCall ? (voice?.muted === true ? voice.labels.unmute : voice.labels.mute) ?? voice.labels.start : voice?.labels.start ?? "";
5113
+ /**
5114
+ * The voice-state pill's own state — `null` for `'idle'` (covered by
5115
+ * `inCall` too) AND `'blocked'` (NOT covered by `inCall`, which is why this
5116
+ * is its own value rather than reusing that boolean: a refused microphone
5117
+ * is still "a call", but it is not one of the four states the pill knows
5118
+ * how to draw — see `voiceStatePillState`'s own doc comment).
5119
+ */
5120
+ const voicePillState = voiceStatePillState(voice);
5121
+ /**
5122
+ * The call has been asked for and has not answered yet — the transport
5123
+ * dialing, or the browser's own microphone prompt still open in front of
5124
+ * the caller (the host folds both into this one phase; see
5125
+ * `useVoiceSession`'s `micPending` and `host-widget.tsx`'s `callPhase`).
5126
+ *
5127
+ * For as long as it lasts, the round control is a SPINNER and is inert. A
5128
+ * microphone glyph here says "talk now" during the one stretch where
5129
+ * talking provably does nothing, and a pressable one turns a single
5130
+ * impatient gesture into either a second call or a mute of a call that does
5131
+ * not exist yet. The wait ends by itself, in one of two directions: `live`
5132
+ * (the microphone comes back) or `blocked` (the existing refused
5133
+ * presentation) — never in a spinner nobody can clear.
5134
+ */
5135
+ const connecting = voice?.phase === "connecting";
5136
+ /** No voice leg to press at all, or a microphone the browser refused. */
5137
+ const micUnusable = voice !== void 0 && (voice.disabled === true || voice.phase === "blocked");
5138
+ /** Same fallback contract as the pill's own labels — see `voiceStatePillLabel`. */
5139
+ const connectingLabel = voice?.labels.connecting ?? defaultWidgetMessages.voice_state_connecting;
5140
+ /**
5141
+ * Start, mute or unmute — whichever the one round control means right now —
5142
+ * or, ahead of all three, the REASON it means nothing at all.
5143
+ *
5144
+ * `labels.unavailable` wins whenever `micUnusable` holds, because none of
5145
+ * the other three describe this button any more: every one of them names an
5146
+ * action, and an unusable control performs none. It is checked before
5147
+ * `connecting` too, so a host that disables the control mid-dial (an
5148
+ * escalation landing while the transport is still connecting) never leaves
5149
+ * "Connecting" as the name of a button that will now never connect. See
5150
+ * `ConciergeShellVoice.labels.unavailable`.
5151
+ */
5152
+ 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 ?? "";
4341
5153
  const submit = (e) => {
4342
5154
  e.preventDefault();
4343
5155
  if (!draft.trim() || composerDisabled) return;
@@ -4357,263 +5169,217 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, lab
4357
5169
  position,
4358
5170
  ...onPositionChange !== void 0 ? { onPositionChange } : {},
4359
5171
  onOpen: () => onOpenChange(true),
4360
- hidden: open
5172
+ hidden: open,
5173
+ avatar
4361
5174
  }),
4362
5175
  /* @__PURE__ */ jsx("div", {
4363
5176
  "aria-hidden": true,
4364
- onClick: handleClose,
4365
- className: cn("bg-brand-ink/10 fixed inset-0 z-40 backdrop-blur-[2px] transition-opacity duration-500", open ? "opacity-100" : "pointer-events-none opacity-0")
5177
+ className: cn("bg-brand-ink/10 fixed inset-0 z-40 backdrop-blur-[2px] transition-opacity duration-500", open ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0")
4366
5178
  }),
4367
5179
  /* @__PURE__ */ jsx("div", {
4368
5180
  "aria-hidden": !open,
4369
5181
  className: cn("pointer-events-none fixed inset-x-0 z-50 flex", panelClasses(position)),
4370
5182
  children: /* @__PURE__ */ jsxs("div", {
4371
- ref: panelRef,
4372
- role: "dialog",
4373
- "aria-modal": "true",
4374
- "aria-label": labels.dialog,
4375
- "data-testid": testIds?.panel,
4376
- className: cn("origin-bottom rounded-full transition-all duration-[700ms] motion-reduce:transition-none", open ? "pointer-events-auto h-[min(520px,calc(100dvh-5rem))] w-[min(400px,calc(100vw-2rem))] scale-100 opacity-100" : "pointer-events-none size-16 scale-90 opacity-0"),
4377
- style: { transitionTimingFunction: "cubic-bezier(0.16, 1, 0.3, 1)" },
4378
- children: [
4379
- /* @__PURE__ */ jsx("div", {
4380
- "aria-hidden": true,
4381
- className: cn("pointer-events-none absolute -inset-4 rounded-full opacity-25 blur-xl motion-reduce:animate-none", open ? "animate-[spin_18s_linear_infinite]" : "opacity-0"),
4382
- style: { background: "conic-gradient(from 0deg, color-mix(in oklab, var(--brand-plum) 14%, transparent), color-mix(in oklab, var(--brand-rose) 16%, transparent), color-mix(in oklab, var(--brand-amber) 16%, transparent), color-mix(in oklab, var(--brand-plum) 14%, transparent))" }
4383
- }),
4384
- /* @__PURE__ */ jsx("div", {
4385
- "aria-hidden": true,
4386
- className: "pointer-events-none absolute inset-0 rounded-full p-[1.5px]",
4387
- style: {
4388
- background: "conic-gradient(from 140deg, color-mix(in oklab, var(--brand-plum) 45%, transparent), color-mix(in oklab, var(--brand-rose) 40%, transparent), color-mix(in oklab, var(--brand-amber) 45%, transparent), color-mix(in oklab, var(--brand-plum) 45%, transparent))",
4389
- WebkitMask: "linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)",
4390
- WebkitMaskComposite: "xor",
4391
- maskComposite: "exclude"
4392
- }
4393
- }),
4394
- /* @__PURE__ */ jsxs("div", {
4395
- className: cn("relative flex h-full w-full flex-col items-center overflow-clip rounded-full border border-white/40 bg-[var(--widget-card)] backdrop-blur-xl", "shadow-[0_30px_80px_-20px_color-mix(in_oklab,var(--brand-plum)_25%,transparent),inset_0_1px_0_rgba(255,255,255,0.75)]"),
4396
- children: [
4397
- /* @__PURE__ */ jsx("div", {
4398
- "aria-hidden": true,
4399
- className: "pointer-events-none absolute -top-16 -right-10 h-56 w-56 rounded-full bg-[radial-gradient(circle,color-mix(in_oklab,var(--brand-amber)_7%,transparent),transparent_70%)] blur-2xl"
4400
- }),
4401
- /* @__PURE__ */ jsx("div", {
4402
- "aria-hidden": true,
4403
- className: "pointer-events-none absolute -bottom-20 -left-12 h-52 w-52 rounded-full bg-[radial-gradient(circle,color-mix(in_oklab,var(--brand-rose)_5%,transparent),transparent_70%)] blur-2xl"
4404
- }),
4405
- /* @__PURE__ */ jsx("button", {
4406
- type: "button",
4407
- "aria-label": labels.close,
4408
- onClick: handleClose,
4409
- className: cn("absolute end-5 top-5 z-10 rounded-full p-1.5 text-[var(--widget-foreground)] transition-all duration-300", "hover:bg-brand-plum/10 hover:text-brand-plum focus-visible:ring-brand-plum/30 focus-visible:ring-2 focus-visible:outline-none", open ? "opacity-100 delay-[350ms]" : "opacity-0"),
4410
- children: /* @__PURE__ */ jsx(X, { className: "size-4" })
4411
- }),
4412
- /* @__PURE__ */ jsxs("div", {
4413
- className: cn("relative flex h-full w-full flex-col items-center justify-center px-2.5 py-1.5 transition-all duration-300 motion-reduce:transition-none", open ? "translate-y-0 opacity-100 delay-[300ms]" : "translate-y-2 opacity-0"),
4414
- children: [
4415
- /* @__PURE__ */ jsx("div", {
4416
- className: "pointer-events-none absolute inset-x-0 top-1.5 z-10 flex justify-center",
4417
- children: /* @__PURE__ */ jsxs("div", {
4418
- className: "relative",
4419
- children: [/* @__PURE__ */ jsx("div", {
4420
- "aria-hidden": true,
4421
- className: "absolute inset-0 rounded-full bg-[radial-gradient(circle,var(--widget-card)_58%,transparent_72%)]"
4422
- }), /* @__PURE__ */ jsx(BotFace, {
4423
- state,
4424
- size: "lg",
4425
- messageArrived
4426
- })]
4427
- })
4428
- }),
4429
- badge === void 0 ? null : /* @__PURE__ */ jsx("div", {
4430
- className: "z-10 mt-[104px] w-[68%] shrink-0 text-center",
4431
- children: badge
4432
- }),
4433
- /* @__PURE__ */ jsx("div", {
4434
- ref: transcriptRef,
4435
- className: "w-full max-w-[86%] min-h-0 flex-1 overflow-y-auto px-1",
4436
- style: badge === void 0 ? TRANSCRIPT_EDGE_FADE : TRANSCRIPT_EDGE_FADE_WITH_BADGE,
4437
- children
4438
- }),
4439
- /* @__PURE__ */ jsx("div", {
4440
- "aria-hidden": true,
4441
- className: "pointer-events-none absolute inset-x-0 bottom-0 z-10 h-[132px] bg-[linear-gradient(to_bottom,transparent,var(--widget-card)_38%,var(--widget-card))]"
4442
- }),
4443
- /* @__PURE__ */ jsx("div", {
4444
- className: "pointer-events-none absolute inset-x-0 bottom-1.5 z-20 flex justify-center",
4445
- children: /* @__PURE__ */ jsxs("div", {
4446
- className: cn("flex w-[71%] flex-col items-center gap-2.5", open ? "pointer-events-auto" : "pointer-events-none"),
4447
- children: [/* @__PURE__ */ jsxs("form", {
4448
- className: "flex w-full items-center gap-2",
4449
- onSubmit: submit,
4450
- children: [composerLeading, /* @__PURE__ */ jsxs("div", {
4451
- className: "relative flex-1",
4452
- children: [
4453
- /* @__PURE__ */ jsx("label", {
4454
- htmlFor: inputId,
4455
- className: "sr-only",
4456
- children: labels.composerPlaceholder
4457
- }),
4458
- /* @__PURE__ */ jsx("input", {
4459
- id: inputId,
4460
- "data-testid": testIds?.input,
4461
- value: draft,
4462
- onChange: (e) => onDraftChange(e.target.value),
4463
- placeholder: labels.composerPlaceholder,
4464
- dir: "auto",
4465
- disabled: composerDisabled,
4466
- 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-all focus:bg-[var(--widget-bubble)] focus:ring-2 focus:outline-none disabled:opacity-50", inCall && draft === "" && "opacity-60 focus:opacity-100")
4467
- }),
4468
- draft.trim() && /* @__PURE__ */ jsx("button", {
4469
- type: "submit",
4470
- "aria-label": labels.send,
4471
- "data-testid": testIds?.send,
4472
- disabled: composerDisabled,
4473
- className: "from-brand-plum to-brand-rose text-primary-foreground absolute end-2 top-1/2 flex size-9 -translate-y-1/2 items-center justify-center rounded-full bg-gradient-to-br transition-all hover:scale-105 disabled:opacity-40",
4474
- children: /* @__PURE__ */ jsx(Send, { className: "size-4 rtl:-scale-x-100" })
4475
- })
4476
- ]
5183
+ className: "relative flex flex-col items-center",
5184
+ children: [/* @__PURE__ */ jsxs("div", {
5185
+ ref: panelRef,
5186
+ role: "dialog",
5187
+ "aria-modal": "true",
5188
+ "aria-label": labels.dialog,
5189
+ "data-testid": testIds?.panel,
5190
+ className: cn("origin-bottom rounded-full transition-all duration-[700ms] motion-reduce:transition-none", open ? "pointer-events-auto aspect-[5/8] w-[min(97vw,50dvh)] min-h-0 scale-100 opacity-100 [container-type:size]" : "pointer-events-none size-16 scale-90 opacity-0"),
5191
+ style: { transitionTimingFunction: "cubic-bezier(0.16, 1, 0.3, 1)" },
5192
+ children: [
5193
+ /* @__PURE__ */ jsx("div", {
5194
+ "aria-hidden": true,
5195
+ className: cn("pointer-events-none absolute -inset-4 rounded-full opacity-25 blur-xl motion-reduce:animate-none", open ? "animate-[spin_18s_linear_infinite]" : "opacity-0"),
5196
+ style: { background: "conic-gradient(from 0deg, color-mix(in oklab, var(--brand-plum) 14%, transparent), color-mix(in oklab, var(--brand-rose) 16%, transparent), color-mix(in oklab, var(--brand-amber) 16%, transparent), color-mix(in oklab, var(--brand-plum) 14%, transparent))" }
5197
+ }),
5198
+ /* @__PURE__ */ jsx("div", {
5199
+ "aria-hidden": true,
5200
+ className: "pointer-events-none absolute inset-0 rounded-full p-[1.5px]",
5201
+ style: {
5202
+ background: "conic-gradient(from 140deg, color-mix(in oklab, var(--brand-plum) 45%, transparent), color-mix(in oklab, var(--brand-rose) 40%, transparent), color-mix(in oklab, var(--brand-amber) 45%, transparent), color-mix(in oklab, var(--brand-plum) 45%, transparent))",
5203
+ WebkitMask: "linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)",
5204
+ WebkitMaskComposite: "xor",
5205
+ maskComposite: "exclude"
5206
+ }
5207
+ }),
5208
+ /* @__PURE__ */ jsx("button", {
5209
+ type: "button",
5210
+ "aria-label": labels.close,
5211
+ onClick: handleClose,
5212
+ className: cn("absolute end-[8%] top-[8%] z-20 rounded-full bg-[var(--widget-card)] p-1.5 text-[var(--widget-foreground)] shadow-[0_2px_10px_-2px_color-mix(in_oklab,var(--brand-plum)_35%,transparent)] ring-1 ring-black/5 transition-all duration-300", "hover:text-brand-plum hover:ring-brand-plum/30 focus-visible:ring-brand-plum/50 focus-visible:ring-2 focus-visible:outline-none", open ? "opacity-100 delay-[350ms]" : "opacity-0"),
5213
+ children: /* @__PURE__ */ jsx(X, { className: "size-4" })
5214
+ }),
5215
+ /* @__PURE__ */ jsxs("div", {
5216
+ className: cn("relative flex h-full w-full flex-col items-center overflow-clip rounded-full border border-white/40 bg-[var(--widget-card)] backdrop-blur-xl", "shadow-[0_30px_80px_-20px_color-mix(in_oklab,var(--brand-plum)_25%,transparent),inset_0_1px_0_rgba(255,255,255,0.75)]"),
5217
+ children: [
5218
+ /* @__PURE__ */ jsx("div", {
5219
+ "aria-hidden": true,
5220
+ className: "pointer-events-none absolute -top-16 -right-10 h-56 w-56 rounded-full bg-[radial-gradient(circle,color-mix(in_oklab,var(--brand-amber)_7%,transparent),transparent_70%)] blur-2xl"
5221
+ }),
5222
+ /* @__PURE__ */ jsx("div", {
5223
+ "aria-hidden": true,
5224
+ className: "pointer-events-none absolute -bottom-20 -left-12 h-52 w-52 rounded-full bg-[radial-gradient(circle,color-mix(in_oklab,var(--brand-rose)_5%,transparent),transparent_70%)] blur-2xl"
5225
+ }),
5226
+ /* @__PURE__ */ jsxs("div", {
5227
+ className: cn("relative flex h-full w-full flex-col items-center justify-center px-2.5 py-1.5 transition-all duration-300 motion-reduce:transition-none", open ? "translate-y-0 opacity-100 delay-[300ms]" : "translate-y-2 opacity-0"),
5228
+ children: [
5229
+ /* @__PURE__ */ jsxs("div", {
5230
+ className: "pointer-events-none absolute inset-x-0 top-1.5 z-10 flex flex-col items-center gap-1",
5231
+ children: [/* @__PURE__ */ jsxs("div", {
5232
+ className: "relative",
5233
+ children: [/* @__PURE__ */ jsx("div", {
5234
+ "aria-hidden": true,
5235
+ className: "absolute inset-0 rounded-full bg-[radial-gradient(circle,var(--widget-card)_58%,transparent_72%)]"
5236
+ }), /* @__PURE__ */ jsx(AvatarFace, {
5237
+ avatar,
5238
+ state,
5239
+ size: "lg",
5240
+ messageArrived,
5241
+ tightenKey: knotTightenKey
4477
5242
  })]
4478
- }), voice ? /* @__PURE__ */ jsxs("div", {
4479
- className: "mt-1 flex items-center gap-3",
4480
- children: [/* @__PURE__ */ jsx("button", {
4481
- type: "button",
4482
- onClick: inCall ? voice.onToggleMute ?? voice.onStart : voice.onStart,
4483
- disabled: voice.disabled || voice.phase === "blocked",
4484
- "data-testid": testIds?.mic,
4485
- title: micLabel,
4486
- "aria-label": micLabel,
4487
- ...inCall ? { "aria-pressed": voice.muted ?? false } : {},
4488
- className: cn("from-brand-plum to-brand-rose text-primary-foreground flex size-12 shrink-0 items-center justify-center rounded-full bg-gradient-to-br transition-all", voice.disabled || voice.phase === "blocked" ? "cursor-not-allowed opacity-40" : cn("hover:scale-105 focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:outline-none", "shadow-[0_0_0_1px_color-mix(in_oklab,var(--brand-plum)_18%,transparent),0_4px_14px_-2px_color-mix(in_oklab,var(--brand-plum)_45%,transparent),0_0_22px_-4px_color-mix(in_oklab,var(--brand-rose)_40%,transparent)]", "hover:shadow-[0_0_0_1px_color-mix(in_oklab,var(--brand-plum)_26%,transparent),0_6px_18px_-2px_color-mix(in_oklab,var(--brand-plum)_60%,transparent),0_0_30px_-4px_color-mix(in_oklab,var(--brand-rose)_55%,transparent)]"), inCall && voice.muted !== true && "ring-brand-rose/50 ring-4"),
4489
- children: inCall && voice.muted === true ? /* @__PURE__ */ jsx(MicOff, { className: "size-5" }) : /* @__PURE__ */ jsx(Mic, { className: "size-5" })
4490
- }), inCall && voice.onEnd !== void 0 ? /* @__PURE__ */ jsx("button", {
4491
- type: "button",
4492
- onClick: voice.onEnd,
4493
- "data-testid": testIds?.endCall,
4494
- title: voice.labels.end ?? "",
4495
- "aria-label": voice.labels.end ?? "",
4496
- className: cn("bg-destructive/10 text-destructive hover:bg-destructive/20 flex size-10 shrink-0 items-center justify-center rounded-full transition-colors", "focus-visible:ring-destructive/30 focus-visible:ring-2 focus-visible:outline-none"),
4497
- children: /* @__PURE__ */ jsx(PhoneOff, { className: "size-4" })
5243
+ }), /* @__PURE__ */ jsx("div", {
5244
+ "data-testid": "widget-voice-state",
5245
+ className: cn("flex items-center gap-1.5 rounded-full bg-[var(--widget-card)] px-2.5 py-1 text-[10px] font-medium tracking-wider text-[var(--widget-foreground-muted)] uppercase ring-1 ring-black/5 shadow-[0_2px_8px_-2px_rgba(0,0,0,0.15)] transition-opacity duration-300", voicePillState ? "opacity-100" : "opacity-0"),
5246
+ children: voicePillState ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
5247
+ "aria-hidden": true,
5248
+ className: cn("size-1.5 shrink-0 rounded-full", voicePillState !== "listening" && "animate-pulse motion-reduce:animate-none"),
5249
+ style: { backgroundColor: voiceStatePillDotColor(voicePillState) }
5250
+ }), /* @__PURE__ */ jsx("span", { children: voiceStatePillLabel(voicePillState, voice?.labels) })] }) : null
5251
+ })]
5252
+ }),
5253
+ badge == null ? null : /* @__PURE__ */ jsx("div", {
5254
+ className: "z-10 mt-[104px] w-[68%] shrink-0 text-center",
5255
+ children: badge
5256
+ }),
5257
+ /* @__PURE__ */ jsx("div", {
5258
+ ref: transcriptRef,
5259
+ className: "no-scrollbar w-full min-h-0 flex-1 overflow-y-auto",
5260
+ style: badge == null ? TRANSCRIPT_EDGE_FADE : TRANSCRIPT_EDGE_FADE_WITH_BADGE,
5261
+ children: /* @__PURE__ */ jsx("div", {
5262
+ ref: transcriptContentRef,
5263
+ children
5264
+ })
5265
+ }),
5266
+ /* @__PURE__ */ jsx("div", {
5267
+ "aria-hidden": true,
5268
+ className: "pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-[linear-gradient(to_bottom,transparent,var(--widget-card)_38%,var(--widget-card))]",
5269
+ style: { height: COMPOSER_GROUND_LEN }
5270
+ }),
5271
+ /* @__PURE__ */ jsx("div", {
5272
+ className: "pointer-events-none absolute inset-x-0 z-20 flex justify-center",
5273
+ style: { bottom: voice ? COMPOSER_BOTTOM_LEN : COMPOSER_BOTTOM_NO_VOICE_LEN },
5274
+ children: /* @__PURE__ */ jsxs("div", {
5275
+ className: cn("flex w-[71%] flex-col items-center gap-2.5", open ? "pointer-events-auto" : "pointer-events-none"),
5276
+ style: { maxWidth: COMPOSER_MAX_WIDTH_LEN },
5277
+ children: [/* @__PURE__ */ jsxs("form", {
5278
+ className: "flex w-full items-center gap-2",
5279
+ onSubmit: submit,
5280
+ children: [composerLeading, /* @__PURE__ */ jsxs("div", {
5281
+ className: "relative flex-1",
5282
+ children: [
5283
+ /* @__PURE__ */ jsx("label", {
5284
+ htmlFor: inputId,
5285
+ className: "sr-only",
5286
+ children: labels.composerPlaceholder
5287
+ }),
5288
+ /* @__PURE__ */ jsx("input", {
5289
+ id: inputId,
5290
+ "data-testid": testIds?.input,
5291
+ value: draft,
5292
+ onChange: (e) => onDraftChange(e.target.value),
5293
+ placeholder: labels.composerPlaceholder,
5294
+ dir: "auto",
5295
+ disabled: composerDisabled,
5296
+ 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-all focus:bg-[var(--widget-bubble)] focus:ring-2 focus:outline-none disabled:opacity-50", inCall && draft === "" && "opacity-60 focus:opacity-100")
5297
+ }),
5298
+ draft.trim() && /* @__PURE__ */ jsx("button", {
5299
+ type: "submit",
5300
+ "aria-label": labels.send,
5301
+ "data-testid": testIds?.send,
5302
+ disabled: composerDisabled,
5303
+ className: "from-brand-plum to-brand-rose text-[var(--widget-accent-foreground)] absolute end-2 top-1/2 flex size-9 -translate-y-1/2 items-center justify-center rounded-full bg-gradient-to-br transition-all hover:scale-105 disabled:opacity-40",
5304
+ children: /* @__PURE__ */ jsx(Send, { className: "size-4 rtl:-scale-x-100" })
5305
+ })
5306
+ ]
5307
+ })]
5308
+ }), voice ? /* @__PURE__ */ jsxs("div", {
5309
+ className: "mt-1 flex items-center gap-3",
5310
+ children: [/* @__PURE__ */ jsx("button", {
5311
+ type: "button",
5312
+ onClick: connecting ? void 0 : inCall ? voice.onToggleMute ?? voice.onStart : voice.onStart,
5313
+ disabled: micUnusable || connecting,
5314
+ "data-testid": testIds?.mic,
5315
+ title: micLabel,
5316
+ "aria-label": micLabel,
5317
+ ...connecting ? { "aria-busy": true } : {},
5318
+ ...inCall && !connecting ? { "aria-pressed": voice.muted ?? false } : {},
5319
+ className: cn("from-brand-plum to-brand-rose text-[var(--widget-accent-foreground)] flex size-12 shrink-0 items-center justify-center rounded-full bg-gradient-to-br transition-all", micUnusable ? "cursor-not-allowed opacity-40" : connecting ? "cursor-wait" : cn("hover:scale-105 focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:outline-none", "shadow-[0_0_0_1px_color-mix(in_oklab,var(--brand-plum)_18%,transparent),0_4px_14px_-2px_color-mix(in_oklab,var(--brand-plum)_45%,transparent),0_0_22px_-4px_color-mix(in_oklab,var(--brand-rose)_40%,transparent)]", "hover:shadow-[0_0_0_1px_color-mix(in_oklab,var(--brand-plum)_26%,transparent),0_6px_18px_-2px_color-mix(in_oklab,var(--brand-plum)_60%,transparent),0_0_30px_-4px_color-mix(in_oklab,var(--brand-rose)_55%,transparent)]"), inCall && !connecting && voice.muted !== true && "ring-brand-rose/50 ring-4"),
5320
+ children: connecting ? /* @__PURE__ */ jsx("span", {
5321
+ "aria-hidden": "true",
5322
+ "data-testid": "widget-mic-spinner",
5323
+ className: "flex items-center justify-center",
5324
+ children: /* @__PURE__ */ jsx(MorphingLoader, {
5325
+ size: "md",
5326
+ variant: "light",
5327
+ label: connectingLabel
5328
+ })
5329
+ }) : inCall && voice.muted === true ? /* @__PURE__ */ jsx(MicOff, { className: "size-5" }) : /* @__PURE__ */ jsx(Mic, { className: "size-5" })
5330
+ }), inCall && voice.onEnd !== void 0 ? /* @__PURE__ */ jsx("button", {
5331
+ type: "button",
5332
+ onClick: voice.onEnd,
5333
+ "data-testid": testIds?.endCall,
5334
+ title: voice.labels.end ?? "",
5335
+ "aria-label": voice.labels.end ?? "",
5336
+ className: cn("bg-destructive/10 text-destructive hover:bg-destructive/20 flex size-10 shrink-0 items-center justify-center rounded-full transition-colors", "focus-visible:ring-destructive/30 focus-visible:ring-2 focus-visible:outline-none"),
5337
+ children: /* @__PURE__ */ jsx(PhoneOff, { className: "size-4" })
5338
+ }) : null]
4498
5339
  }) : null]
4499
- }) : null]
4500
- })
4501
- })
4502
- ]
4503
- })
4504
- ]
4505
- })
4506
- ]
4507
- })
4508
- }),
4509
- portalActive && /* @__PURE__ */ jsx("div", {
4510
- "aria-hidden": true,
4511
- className: cn("pointer-events-none fixed z-[55]", positionClasses(position)),
4512
- children: /* @__PURE__ */ jsx("div", {
4513
- className: "widget-portal size-16",
4514
- children: /* @__PURE__ */ jsx(MorphingLoader, {
4515
- size: "full",
4516
- label: labels.open
4517
- })
4518
- })
4519
- }),
4520
- /* @__PURE__ */ jsx("div", {
4521
- "aria-live": "polite",
4522
- "aria-atomic": "false",
4523
- className: "sr-only",
4524
- children: announcement
4525
- })
4526
- ]
4527
- });
4528
- }
4529
- //#endregion
4530
- //#region src/messages.ts
4531
- /**
4532
- * Message keys that carry a `{product}` placeholder — the avatar's
4533
- * accessible-name states. Kept as a literal template, interpolated at
4534
- * render time, never a brand name baked into this file (see the module doc
4535
- * comment).
4536
- */
4537
- var defaultWidgetMessages = {
4538
- state_idle: "{product} — idle",
4539
- state_listening: "{product} — listening",
4540
- state_thinking: "{product} — thinking",
4541
- state_speaking: "{product} — speaking",
4542
- mic_start: "Start talking",
4543
- mic_stop: "Stop talking",
4544
- open: "Open chat",
4545
- minimize: "Minimise",
4546
- conversation: "Chat conversation",
4547
- empty: "Ask a question — speak or type.",
4548
- type_placeholder: "Type a message",
4549
- send: "Send",
4550
- move: "Move the assistant",
4551
- call_end: "End the call",
4552
- escalated_banner: "A human teammate will pick this up shortly.",
4553
- typing: "Typing",
4554
- suggestions_label: "Suggested questions",
4555
- suggestion_1: "What is popular right now?",
4556
- suggestion_2: "Help me pick something",
4557
- suggestion_3: "Talk to a human",
4558
- attach_label: "Attach a file",
4559
- attach_uploading: "Sending {filename}…",
4560
- attach_error: "Could not send {filename}. Try again.",
4561
- attach_image_alt: "Attached image: {filename}",
4562
- attach_download_hint: "Opens or downloads in a new tab",
4563
- add_to_cart: "Add to cart",
4564
- adding_to_cart: "Adding…",
4565
- added_to_cart: "Added to cart",
4566
- unavailable: "Unavailable",
4567
- see_all: "See all {count}",
4568
- cart_summary_title: "Your cart",
4569
- cart_summary_total: "Total",
4570
- checkout_now: "Checkout",
4571
- checkout_failed: "Could not start checkout. Try again."
4572
- };
4573
- /**
4574
- * Interpolates `{token}` placeholders in a message template. Deliberately the
4575
- * same `{token}` syntax `next-intl`'s ICU messages use for a plain variable,
4576
- * so `apps/web`'s adapter can hand this package `t.raw(key)` (the
4577
- * UN-interpolated template) and let this one function do the substitution —
4578
- * one interpolation implementation, not two.
4579
- *
4580
- * A token with no matching var, or a var that isn't a string/number, is left
4581
- * as literal text rather than thrown on — a missing translation must degrade
4582
- * to a visibly-odd string, never a broken render.
4583
- */
4584
- function formatMessage(template, vars) {
4585
- if (!vars) return template;
4586
- return template.replace(/\{(\w+)\}/g, (match, key) => {
4587
- const value = vars[key];
4588
- return value === void 0 ? match : String(value);
5340
+ })
5341
+ })
5342
+ ]
5343
+ })
5344
+ ]
5345
+ })
5346
+ ]
5347
+ }), attribution ? /* @__PURE__ */ jsxs("a", {
5348
+ href: attribution.href,
5349
+ target: "_blank",
5350
+ rel: "noopener noreferrer",
5351
+ "data-testid": "widget-branding",
5352
+ 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"),
5353
+ children: [/* @__PURE__ */ jsx("span", {
5354
+ "aria-hidden": true,
5355
+ className: "size-2.5 rounded-full bg-gradient-to-br from-brand-rose to-brand-amber"
5356
+ }), /* @__PURE__ */ jsx("span", {
5357
+ className: "text-brand-plum font-semibold tracking-tight",
5358
+ children: attribution.name
5359
+ })]
5360
+ }) : null]
5361
+ })
5362
+ }),
5363
+ portalActive && /* @__PURE__ */ jsx("div", {
5364
+ "aria-hidden": true,
5365
+ className: cn("pointer-events-none fixed z-[55]", positionClasses(position)),
5366
+ children: /* @__PURE__ */ jsx("div", {
5367
+ className: "widget-portal size-16",
5368
+ children: /* @__PURE__ */ jsx(MorphingLoader, {
5369
+ size: "full",
5370
+ label: labels.open
5371
+ })
5372
+ })
5373
+ }),
5374
+ /* @__PURE__ */ jsx("div", {
5375
+ "aria-live": "polite",
5376
+ "aria-atomic": "false",
5377
+ className: "sr-only",
5378
+ children: announcement
5379
+ })
5380
+ ]
4589
5381
  });
4590
5382
  }
4591
- /**
4592
- * Merges tenant-authored overrides (typically the `widgetMessagesFromCopy`
4593
- * result) over `defaultWidgetMessages`. An override that is `undefined`,
4594
- * empty, or whitespace-only is skipped — a blank tenant string must not blank
4595
- * out a working default, same "absent means unset" contract
4596
- * `PublicWidgetConfig.copy`'s own fields carry.
4597
- */
4598
- function resolveWidgetMessages(overrides) {
4599
- if (!overrides) return defaultWidgetMessages;
4600
- const merged = { ...defaultWidgetMessages };
4601
- for (const [key, value] of Object.entries(overrides)) if (typeof value === "string" && value.trim() !== "") merged[key] = value;
4602
- return merged;
4603
- }
4604
- /**
4605
- * Maps `PublicWidgetConfig.copy`'s fields onto the `WidgetMessages` keys they
4606
- * overlap with. `greeting` is deliberately NOT mapped here — it seeds the
4607
- * first turn (`SessionBootResponse.greeting`), it is not a UI label, so a
4608
- * caller that wants it has it already from the session boot response.
4609
- * `offlineMessage` has no current `WidgetMessages` counterpart (nothing here
4610
- * renders an "offline" state yet) and is likewise omitted rather than
4611
- * guessed onto the nearest-sounding key.
4612
- */
4613
- function widgetMessagesFromCopy(copy) {
4614
- if (!copy) return {};
4615
- return copy.placeholder !== void 0 ? { type_placeholder: copy.placeholder } : {};
4616
- }
4617
5383
  //#endregion
4618
5384
  //#region src/session-log.ts
4619
5385
  /**
@@ -4664,7 +5430,9 @@ var SESSION_EVENTS = [
4664
5430
  "widget_event_invalid",
4665
5431
  "disconnected",
4666
5432
  "stopped",
4667
- "error"
5433
+ "error",
5434
+ "messages_read",
5435
+ "messages_delivered"
4668
5436
  ];
4669
5437
  var DEFAULT_LIMIT = 200;
4670
5438
  var SessionLog = class {
@@ -4788,6 +5556,7 @@ function parseFrame(raw) {
4788
5556
  var IDLE_SNAPSHOT = {
4789
5557
  phase: "idle",
4790
5558
  micPublished: false,
5559
+ micPending: false,
4791
5560
  agentPresent: false,
4792
5561
  agentSpeaking: false,
4793
5562
  callerSpeaking: false,
@@ -5018,6 +5787,22 @@ function formatMoney(priceMinor, currency, locale) {
5018
5787
  //#endregion
5019
5788
  //#region src/widget-cards.tsx
5020
5789
  /**
5790
+ * Is this click a plain, unmodified left click — the only kind that should
5791
+ * ever trigger a soft-nav `navigate()` call instead of falling through to the
5792
+ * anchor's own default handling.
5793
+ *
5794
+ * A modifier click (Cmd/Ctrl-click to open in a new tab, Shift-click for a
5795
+ * new window, a middle-click) or one a caller upstream already called
5796
+ * `preventDefault()` on has to keep working exactly like a bare `<a>` would —
5797
+ * soft-navigating over any of those would break "open in new tab", "copy
5798
+ * link", and middle-click. Same convention every SPA router's own `<Link>`
5799
+ * follows, and shared by both anchors this component renders (a product
5800
+ * card's link and the "See all N" link) rather than duplicated per call site.
5801
+ */
5802
+ function isPlainLeftClick(event) {
5803
+ return !event.defaultPrevented && event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
5804
+ }
5805
+ /**
5021
5806
  * How many cards the inline chat strip shows before handing off to the
5022
5807
  * curation results page instead of growing taller. A live curation
5023
5808
  * verified against the demo tenant returns 4 items for a typical
@@ -5041,15 +5826,27 @@ var INLINE_CARD_LIMIT = 4;
5041
5826
  * new tab, copy link, middle-click all keep working — and `navigate` is only
5042
5827
  * consulted on a plain, unmodified left click, same convention every SPA
5043
5828
  * router's own `<Link>` follows.
5829
+ *
5830
+ * ## The `roomy` switch is a LAYOUT variant, not just a size bump
5831
+ *
5832
+ * `roomy` (the expanded grid) keeps its original ROW arrangement — a fixed
5833
+ * square image beside the text, because a grid cell already has width to
5834
+ * spare. `!roomy` used to mean the same row, only smaller (the old vertical
5835
+ * stack, one full-width row per card). It now means the CAROUSEL card
5836
+ * instead: a narrow `basis-[calc(100%/1.25)]` slice with no width to spare
5837
+ * beside an image, so the image moves ABOVE the text — a COLUMN arrangement,
5838
+ * full-width and `aspect-square` rather than a fixed box. One switch, two
5839
+ * branches, each still driving image sizing/shape and the wrapper's flex
5840
+ * direction together — extended, not duplicated into a second component.
5044
5841
  */
5045
5842
  function CardBody({ item, href, roomy, locale, navigate }) {
5046
5843
  const inner = /* @__PURE__ */ jsxs(Fragment, { children: [item.imageUrl ? /* @__PURE__ */ jsx("img", {
5047
5844
  src: item.imageUrl,
5048
5845
  alt: item.title,
5049
- className: `shrink-0 rounded-lg object-cover ${roomy ? "h-[4.5rem] w-[4.5rem]" : "h-12 w-12"}`
5846
+ className: roomy ? "h-[4.5rem] w-[4.5rem] shrink-0 rounded-lg object-cover" : "aspect-square w-full rounded-lg object-cover"
5050
5847
  }) : /* @__PURE__ */ jsx("span", {
5051
5848
  "aria-hidden": "true",
5052
- className: `shrink-0 rounded-lg bg-black/5 ${roomy ? "h-[4.5rem] w-[4.5rem]" : "h-12 w-12"}`
5849
+ className: roomy ? "h-[4.5rem] w-[4.5rem] shrink-0 rounded-lg bg-black/5" : "aspect-square w-full rounded-lg bg-black/5"
5053
5850
  }), /* @__PURE__ */ jsxs("div", {
5054
5851
  className: "w-full min-w-0 flex-1",
5055
5852
  children: [
@@ -5062,12 +5859,12 @@ function CardBody({ item, href, roomy, locale, navigate }) {
5062
5859
  children: formatMoney(item.priceMinor, item.currency, locale)
5063
5860
  }),
5064
5861
  item.reason ? /* @__PURE__ */ jsx("p", {
5065
- className: `text-xs text-[var(--widget-foreground-muted)] italic ${roomy ? "line-clamp-2 text-pretty" : "truncate"}`,
5862
+ className: "line-clamp-2 text-pretty text-xs text-[var(--widget-foreground-muted)] italic",
5066
5863
  children: item.reason
5067
5864
  }) : null
5068
5865
  ]
5069
5866
  })] });
5070
- const shared = `flex w-full min-w-0 items-center gap-3 ${roomy ? "flex-1" : ""}`;
5867
+ const shared = `flex w-full min-w-0 gap-3 ${roomy ? "flex-1 items-center" : "flex-col"}`;
5071
5868
  if (href === void 0) return /* @__PURE__ */ jsx("div", {
5072
5869
  className: shared,
5073
5870
  children: inner
@@ -5077,7 +5874,7 @@ function CardBody({ item, href, roomy, locale, navigate }) {
5077
5874
  "data-testid": "widget-card-link",
5078
5875
  className: `${shared} cursor-pointer`,
5079
5876
  onClick: (event) => {
5080
- if (!navigate || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
5877
+ if (!navigate || !isPlainLeftClick(event)) return;
5081
5878
  event.preventDefault();
5082
5879
  navigate(href);
5083
5880
  },
@@ -5100,7 +5897,7 @@ function CardBody({ item, href, roomy, locale, navigate }) {
5100
5897
  * Changing quantity is the cart drawer's job, which is a surface that can show
5101
5898
  * the quantity it is changing.
5102
5899
  */
5103
- function AddToCartButton({ item, onAddToCart, messages }) {
5900
+ function AddToCartButton({ item, onAddToCart, messages, fullWidth = false }) {
5104
5901
  const [phase, setPhase] = useState("idle");
5105
5902
  const mounted = useRef(true);
5106
5903
  useEffect(() => {
@@ -5125,7 +5922,7 @@ function AddToCartButton({ item, onAddToCart, messages }) {
5125
5922
  "data-testid": "widget-card-add-to-cart",
5126
5923
  "data-phase": "unavailable",
5127
5924
  disabled: true,
5128
- className: "shrink-0 cursor-default rounded-full bg-black/5 px-3 py-1.5 text-xs font-medium text-[var(--widget-foreground-muted)]",
5925
+ className: `cursor-default rounded-full bg-black/5 px-3 py-1.5 text-xs font-medium text-[var(--widget-foreground-muted)] ${fullWidth ? "w-full text-center" : "shrink-0"}`,
5129
5926
  children: messages.unavailable
5130
5927
  });
5131
5928
  return /* @__PURE__ */ jsx("button", {
@@ -5135,7 +5932,7 @@ function AddToCartButton({ item, onAddToCart, messages }) {
5135
5932
  disabled,
5136
5933
  "aria-live": "polite",
5137
5934
  onClick: () => void onClick(),
5138
- className: `flex shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors disabled:cursor-default ${phase === "added" ? "bg-[var(--widget-accent)]/15 text-[var(--widget-accent)] ring-1 ring-[var(--widget-accent)]/30" : "bg-[var(--widget-accent)] text-[var(--widget-accent-foreground)] disabled:opacity-60"}`,
5935
+ className: `flex cursor-pointer items-center justify-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors disabled:cursor-default ${fullWidth ? "w-full" : "shrink-0"} ${phase === "added" ? "bg-[var(--widget-accent)]/15 text-[var(--widget-accent)] ring-1 ring-[var(--widget-accent)]/30" : "bg-[var(--widget-accent)] text-[var(--widget-accent-foreground)] disabled:opacity-60"}`,
5139
5936
  children: phase === "adding" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
5140
5937
  "aria-hidden": "true",
5141
5938
  className: "h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent motion-reduce:animate-none"
@@ -5176,13 +5973,13 @@ function WidgetCardList({ cards, onAddToCart, curationHref, productHref, navigat
5176
5973
  className: "mt-2 flex flex-col gap-2",
5177
5974
  children: [/* @__PURE__ */ jsx("ul", {
5178
5975
  "data-testid": "widget-card-list",
5179
- "data-layout": roomy ? "grid" : "stack",
5180
- className: roomy ? "grid grid-cols-[repeat(auto-fit,minmax(15rem,1fr))] gap-2" : "flex flex-col gap-2",
5976
+ "data-layout": roomy ? "grid" : "carousel",
5977
+ className: roomy ? "grid grid-cols-[repeat(auto-fit,minmax(15rem,1fr))] gap-2" : "no-scrollbar flex snap-x snap-mandatory gap-2 overflow-x-auto overscroll-x-contain",
5181
5978
  children: visibleItems.map((item) => {
5182
5979
  const href = item.handle && productHref ? productHref(item.handle) : void 0;
5183
5980
  return /* @__PURE__ */ jsxs("li", {
5184
5981
  "data-testid": "widget-card",
5185
- className: `gap-3 rounded-xl border border-black/10 bg-[var(--widget-card)] p-2 ${roomy ? "flex flex-col items-start" : "flex items-center"}`,
5982
+ className: `flex flex-col items-start gap-3 rounded-xl border border-black/10 bg-[var(--widget-card)] p-2 ${roomy ? "" : "min-w-0 shrink-0 basis-[calc(100%/1.25)] max-w-[180px] snap-start"}`,
5186
5983
  children: [/* @__PURE__ */ jsx(CardBody, {
5187
5984
  item,
5188
5985
  href,
@@ -5192,7 +5989,8 @@ function WidgetCardList({ cards, onAddToCart, curationHref, productHref, navigat
5192
5989
  }), /* @__PURE__ */ jsx(AddToCartButton, {
5193
5990
  item,
5194
5991
  onAddToCart,
5195
- messages
5992
+ messages,
5993
+ fullWidth: !roomy
5196
5994
  })]
5197
5995
  }, `${item.productId}-${item.variantId ?? ""}`);
5198
5996
  })
@@ -5201,7 +5999,7 @@ function WidgetCardList({ cards, onAddToCart, curationHref, productHref, navigat
5201
5999
  "data-testid": "widget-card-see-all",
5202
6000
  className: "self-start text-xs font-medium text-[var(--widget-foreground)] underline",
5203
6001
  onClick: (event) => {
5204
- if (!navigate || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
6002
+ if (!navigate || !isPlainLeftClick(event)) return;
5205
6003
  event.preventDefault();
5206
6004
  navigate(seeAllHref);
5207
6005
  },
@@ -5470,6 +6268,87 @@ function TypingDots({ label }) {
5470
6268
  }, i))]
5471
6269
  });
5472
6270
  }
6271
+ /**
6272
+ * A transcript EVENT — something that happened at a point in the
6273
+ * conversation, drawn as a quiet centred divider between the bubbles either
6274
+ * side of it.
6275
+ *
6276
+ * ## Why this is a row and not a bar
6277
+ *
6278
+ * The handoff to a human used to be a bar pinned under the whole transcript,
6279
+ * driven by `escalated`. It was reported from a live storefront still saying
6280
+ * a person "will pick this up shortly" while a person was already replying.
6281
+ * That is not a copy bug — chrome keyed on a transport flag has no position
6282
+ * in the conversation, so it cannot say WHEN the handoff happened and no
6283
+ * later message can retire it. As a row it has both: it sits where the
6284
+ * handoff occurred, it scrolls with the thread, and its pending line is
6285
+ * decided by what comes AFTER it.
6286
+ *
6287
+ * ## Two lines, and only one of them can go stale
6288
+ *
6289
+ * The marker is past tense ("Handed to a human teammate") and permanent — it
6290
+ * is a record, and a record does not expire. The promise ("… will pick this
6291
+ * up shortly") is future tense and shown ONLY while `awaitingReply`; the
6292
+ * moment an answer lands below the marker it disappears, because the answer
6293
+ * is the proof it was kept.
6294
+ *
6295
+ * `role="status"` on the pending line only: the marker is narrated as part of
6296
+ * the surrounding `role="log"` like any other transcript row, and announcing
6297
+ * it twice would be worse than announcing it once.
6298
+ */
6299
+ function TranscriptEvent({ event, awaitingReply, messages }) {
6300
+ if (event !== "handoff") return null;
6301
+ return /* @__PURE__ */ jsxs("div", {
6302
+ className: "flex flex-col items-center gap-1 py-1",
6303
+ "data-testid": "widget-handoff-event",
6304
+ children: [/* @__PURE__ */ jsxs("p", {
6305
+ className: "flex w-full items-center gap-3 text-[11px] font-medium tracking-wide text-[var(--widget-foreground-muted)]",
6306
+ children: [
6307
+ /* @__PURE__ */ jsx("span", {
6308
+ "aria-hidden": "true",
6309
+ className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
6310
+ }),
6311
+ /* @__PURE__ */ jsx("span", { children: messages.handoff_event ?? defaultWidgetMessages.handoff_event }),
6312
+ /* @__PURE__ */ jsx("span", {
6313
+ "aria-hidden": "true",
6314
+ className: "h-px flex-1 bg-[var(--widget-foreground-muted)]/25"
6315
+ })
6316
+ ]
6317
+ }), awaitingReply ? /* @__PURE__ */ jsx("p", {
6318
+ role: "status",
6319
+ "data-testid": "widget-handoff-pending",
6320
+ className: "text-center text-[11px] text-[var(--widget-foreground-muted)]",
6321
+ children: messages.escalated_banner
6322
+ }) : null]
6323
+ });
6324
+ }
6325
+ /**
6326
+ * The shopper's own send state, under their own bubble.
6327
+ *
6328
+ * Two states, deliberately — see `ChatTurnDelivery`. A third ("delivered" or
6329
+ * "read" on a message the shopper SENT) would have to be inferred from the
6330
+ * absence of an error or from the arrival of a reply, and this codebase does
6331
+ * not ship a tick it cannot back with an observation.
6332
+ *
6333
+ * The state is carried on `data-delivery` as well as in the accessible name
6334
+ * so that the assertion in a test — and any host styling — reads the actual
6335
+ * state rather than matching on a glyph.
6336
+ */
6337
+ function TurnDeliveryStatus({ delivery, messages }) {
6338
+ const label = delivery === "sent" ? messages.status_sent ?? defaultWidgetMessages.status_sent : messages.status_sending ?? defaultWidgetMessages.status_sending;
6339
+ return /* @__PURE__ */ jsxs("span", {
6340
+ "data-testid": "widget-turn-status",
6341
+ "data-delivery": delivery,
6342
+ className: `pt-0.5 pe-0.5 text-[10px] leading-none text-[var(--widget-foreground-muted)] ${delivery === "sending" ? "opacity-60" : ""}`,
6343
+ children: [/* @__PURE__ */ jsx("span", {
6344
+ className: "sr-only",
6345
+ children: label
6346
+ }), /* @__PURE__ */ jsx("span", {
6347
+ "aria-hidden": "true",
6348
+ children: delivery === "sent" ? "✓" : "◦"
6349
+ })]
6350
+ });
6351
+ }
5473
6352
  /** Kept in sync with `ATTACHMENT_IMAGE_CONTENT_TYPES` in `apps/api/src/conversations/attachment-limits.ts` — display-only, never a security decision on this side. */
5474
6353
  var INLINE_IMAGE_TYPES = new Set([
5475
6354
  "image/png",
@@ -5550,6 +6429,28 @@ function readsAsCheckoutIntent(text) {
5550
6429
  ].some((phrase) => t.includes(phrase));
5551
6430
  }
5552
6431
  /**
6432
+ * Does this thread, as it stands, want to check out?
6433
+ *
6434
+ * The shopper's MOST RECENT line, not "any line ever": once they carry on
6435
+ * shopping past the summary the basket should get out of the way again, and a
6436
+ * sticky flag would leave it wedged at the bottom of every later answer.
6437
+ *
6438
+ * There is exactly ONE of these because two consumers ask the same question
6439
+ * of the same transcript and must never disagree about the answer:
6440
+ * `VoiceWidget` below draws the basket from it, and `ConciergeWidget`
6441
+ * (`host-widget.tsx`) re-reads the HOST's cart from it, so the basket the
6442
+ * shopper is about to check out with is the one that exists now. Two copies
6443
+ * of the same `reverse().find()` is how those two quietly drift apart.
6444
+ *
6445
+ * Takes only what it reads, so a caller with its own merged turn shape (which
6446
+ * `ConciergeWidget` has — typed turns plus spoken lines plus rendered cards)
6447
+ * can pass it without conversion.
6448
+ */
6449
+ function checkoutIntentFromTurns(turns) {
6450
+ const lastCallerLine = [...turns].reverse().find((turn) => turn.speaker === "caller");
6451
+ return lastCallerLine !== void 0 && readsAsCheckoutIntent(lastCallerLine.text);
6452
+ }
6453
+ /**
5553
6454
  * The end-user agent widget: a launcher bubble that expands into a conversation
5554
6455
  * with both a microphone and a text box.
5555
6456
  *
@@ -5577,7 +6478,7 @@ function readsAsCheckoutIntent(text) {
5577
6478
  * `dir`, resolved from that line's locale rather than inherited from the page —
5578
6479
  * inheriting is what renders Arabic punctuation on the wrong end of a sentence.
5579
6480
  */
5580
- function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, open, onOpenChange, status, mode = "voice", escalated = false, onAddToCart, curationHref, productHref, onAttachFile, launcherLabel, position, onPositionChange, cart, messages = defaultWidgetMessages, navigate, locale = "en", skinStyle }) {
6481
+ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, open, onOpenChange, status, mode = "voice", escalated = false, onAddToCart, curationHref, productHref, onAttachFile, launcherLabel, position, onPositionChange, cart, messages = defaultWidgetMessages, navigate, locale = "en", skinStyle, avatar, attribution }) {
5581
6482
  const [draft, setDraft] = useState("");
5582
6483
  const [sending, setSending] = useState(false);
5583
6484
  /** Roomy mode — see the expand control in the header. Collapses back on close, so a reopened widget starts small. */
@@ -5586,14 +6487,34 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5586
6487
  const fileInputRef = useRef(null);
5587
6488
  const showMic = mode !== "text";
5588
6489
  /**
5589
- * Whether the shopper's MOST RECENT line asked to check out.
6490
+ * Why the microphone is off, or `undefined` while it is on.
6491
+ *
6492
+ * **Voice is an AI-only channel.** An escalated conversation reaches an
6493
+ * operator over the desk's TEXT transport (`useChatSession`'s socket and
6494
+ * `/widget/messages` poll) — nothing anywhere joins the shopper's LiveKit
6495
+ * room on the operator's behalf. A call started after the handoff is
6496
+ * therefore the shopper talking into a room the person they asked for
6497
+ * cannot hear, which is worse than no microphone at all.
5590
6498
  *
5591
- * Most recent, not "any line ever": once they carry on shopping past the
5592
- * summary the basket should get out of the way again, and a sticky flag
5593
- * would leave it wedged at the bottom of every later answer.
6499
+ * The control is DISABLED rather than hidden, the same posture this widget
6500
+ * takes towards voice everywhere else (see the `voice` prop below and
6501
+ * `ConciergeShellVoice.disabled`): a mic that vanishes at the handoff reads
6502
+ * as a bug, while a dimmed one with a reason on it reads as the product.
6503
+ *
6504
+ * A runtime STATE gate, not a config one — `mode`/`modalities.voice` are
6505
+ * untouched, so the microphone comes back by itself the moment `escalated`
6506
+ * goes false again.
5594
6507
  */
5595
- const lastCallerLine = [...turns].reverse().find((turn) => turn.speaker === "caller");
5596
- const wantsCheckout = lastCallerLine !== void 0 && readsAsCheckoutIntent(lastCallerLine.text);
6508
+ const voiceUnavailable = showMic && escalated ? messages.voice_unavailable_escalated ?? defaultWidgetMessages.voice_unavailable_escalated : void 0;
6509
+ /**
6510
+ * The host's own line wins wherever it has one: a refused microphone or a
6511
+ * dead speech vendor is the more actionable of the two, and this line is
6512
+ * the only place either reaches the caller. The escalation reason fills the
6513
+ * line only when the host left it empty, which is the ordinary case.
6514
+ */
6515
+ const statusLine = status ?? voiceUnavailable;
6516
+ /** Whether the shopper's MOST RECENT line asked to check out — see `checkoutIntentFromTurns`, the same read `ConciergeWidget` makes. */
6517
+ const wantsCheckout = checkoutIntentFromTurns(turns);
5597
6518
  const onFileSelected = async (event) => {
5598
6519
  const file = event.target.files?.[0];
5599
6520
  event.target.value = "";
@@ -5637,6 +6558,8 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5637
6558
  onOpenChange,
5638
6559
  state,
5639
6560
  ...skinStyle !== void 0 ? { skinStyle } : {},
6561
+ ...avatar !== void 0 ? { avatar } : {},
6562
+ ...attribution !== void 0 ? { attribution } : {},
5640
6563
  messageArrived: lastTurn?.speaker === "caller",
5641
6564
  idPrefix: "widget",
5642
6565
  scrollKey: turns.length,
@@ -5660,11 +6583,17 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5660
6583
  ...onEndCall !== void 0 ? { onEnd: onEndCall } : {},
5661
6584
  onToggleMute: onToggleMic,
5662
6585
  muted: !micOpen,
6586
+ ...voiceUnavailable !== void 0 ? { disabled: true } : {},
5663
6587
  labels: {
5664
6588
  start: messages.mic_start,
5665
6589
  end: messages.call_end,
5666
6590
  mute: messages.mic_stop,
5667
- unmute: messages.mic_start
6591
+ unmute: messages.mic_start,
6592
+ connecting: messages.voice_state_connecting,
6593
+ listening: messages.voice_state_listening,
6594
+ thinking: messages.voice_state_thinking,
6595
+ speaking: messages.voice_state_speaking,
6596
+ ...voiceUnavailable !== void 0 ? { unavailable: voiceUnavailable } : {}
5668
6597
  }
5669
6598
  } : void 0,
5670
6599
  composerLeading: onAttachFile && escalated ? /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -5705,10 +6634,10 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5705
6634
  })]
5706
6635
  })
5707
6636
  ] }) : null,
5708
- badge: status === void 0 ? null : /* @__PURE__ */ jsx("p", {
6637
+ badge: statusLine === void 0 ? null : /* @__PURE__ */ jsx("p", {
5709
6638
  "data-testid": "widget-status",
5710
6639
  className: "mt-1 max-w-full rounded-2xl bg-[var(--widget-chip)] px-2.5 py-1 text-center text-[10px] leading-snug font-semibold tracking-wide uppercase text-[var(--widget-foreground-muted)]",
5711
- children: status
6640
+ children: statusLine
5712
6641
  }),
5713
6642
  testIds: {
5714
6643
  trigger: "voice-widget-launcher",
@@ -5727,14 +6656,18 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5727
6656
  turns.length === 0 ? /* @__PURE__ */ jsx("p", {
5728
6657
  className: "py-8 text-center text-sm text-[var(--widget-foreground-muted)]",
5729
6658
  children: messages.empty
5730
- }) : turns.map((turn, i) => /* @__PURE__ */ jsxs("div", {
6659
+ }) : turns.map((turn, i) => turn.speaker === "event" ? /* @__PURE__ */ jsx(TranscriptEvent, {
6660
+ event: turn.event,
6661
+ messages,
6662
+ awaitingReply: !turns.slice(i + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "")
6663
+ }, `event-${i}`) : /* @__PURE__ */ jsxs("div", {
5731
6664
  className: turn.speaker === "caller" ? "flex flex-col items-end" : "flex flex-col items-start",
5732
6665
  children: [
5733
6666
  turn.text !== "" || turn.speaker === "agent" && turn.final === false ? /* @__PURE__ */ jsx("div", {
5734
6667
  dir: textDirectionFor(turn.locale),
5735
6668
  lang: turn.locale,
5736
6669
  "data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
5737
- className: `max-w-[85%] px-3.5 py-2 text-[13px] leading-[1.55] shadow-sm ${turn.speaker === "caller" ? "from-brand-plum to-brand-plum/90 text-primary-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" : "ring-brand-plum/10 rounded-2xl rounded-es-md bg-[var(--widget-bubble)] text-[var(--widget-foreground)] ring-1"}`,
6670
+ 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" : "ring-brand-plum/10 rounded-2xl rounded-es-md bg-[var(--widget-bubble)] text-[var(--widget-foreground)] ring-1"}`,
5738
6671
  children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
5739
6672
  className: "flex items-center gap-2 italic",
5740
6673
  children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
@@ -5762,6 +6695,10 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5762
6695
  messages,
5763
6696
  roomy: false
5764
6697
  })
6698
+ }) : null,
6699
+ turn.delivery !== void 0 ? /* @__PURE__ */ jsx(TurnDeliveryStatus, {
6700
+ delivery: turn.delivery,
6701
+ messages
5765
6702
  }) : null
5766
6703
  ]
5767
6704
  }, `${turn.speaker}-${i}`)),
@@ -5787,12 +6724,6 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5787
6724
  messages,
5788
6725
  ...navigate ? { navigate } : {}
5789
6726
  }) : null,
5790
- escalated ? /* @__PURE__ */ jsx("p", {
5791
- role: "status",
5792
- "data-testid": "widget-escalated-banner",
5793
- className: "rounded-xl bg-[var(--widget-chip)] ring-1 ring-black/5 px-3 py-2 text-center text-xs font-medium text-[var(--widget-foreground)]",
5794
- children: messages.escalated_banner
5795
- }) : null,
5796
6727
  attaching ? /* @__PURE__ */ jsx("p", {
5797
6728
  role: "status",
5798
6729
  className: `text-xs ${attaching.failed ? "text-destructive" : "text-[var(--widget-foreground-muted)]"}`,
@@ -6158,11 +7089,135 @@ var DEFAULT_POLL_INTERVAL_MS = 4e3;
6158
7089
  var DEFAULT_IDLE_POLL_INTERVAL_MS = 3e4;
6159
7090
  /** `socket.io-client`'s `path` default — kept in sync with `apps/api/src/config/config.ts`'s `WIDGET_SOCKET_PATH` default. */
6160
7091
  var DEFAULT_SOCKET_PATH = "/socket.io";
7092
+ /**
7093
+ * The `ChatTurn.id` of the handoff transcript event. A fixed literal because
7094
+ * there is at most one per session (see `markHandoffToHuman`), and prefixed
7095
+ * so it can never be mistaken for — or collide with — a server-minted turn
7096
+ * id in the id-keyed `setTurns` passes `send`/`streamReply` run.
7097
+ */
7098
+ var HANDOFF_EVENT_TURN_ID = "event-handoff";
6161
7099
  /** Must equal `WIDGET_DESK_MESSAGE_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
6162
7100
  var DESK_MESSAGE_EVENT = "desk:message";
6163
7101
  /** Must equal the namespace `WidgetGateway` (`apps/api/src/realtime/widget.gateway.ts`) is mounted on. */
6164
7102
  var SOCKET_NAMESPACE = "/widget";
6165
7103
  /**
7104
+ * How far AHEAD of a chat token's own `expiresAt` the refresh timer fires.
7105
+ *
7106
+ * Five minutes on a thirty-minute token, so a rotation has five minutes of
7107
+ * slack to survive a slow network, a throttled background timer that fires
7108
+ * late, or a request the shopper's captive-portal proxy stalls — and, if it
7109
+ * fails outright, still leaves time for the silent re-boot fallback to land
7110
+ * before anything the shopper can see starts 401ing.
7111
+ */
7112
+ var REFRESH_MARGIN_MS = 300 * 1e3;
7113
+ /**
7114
+ * The floor on the scheduled delay — never refresh sooner than this, however
7115
+ * imminent the computed TTL.
7116
+ *
7117
+ * A pure BUSY-LOOP GUARD, and nothing more. An unclamped `setTimeout(0)` on a
7118
+ * refresh that immediately schedules the next one is a request loop against
7119
+ * the api at the browser's timer resolution, for as long as the tab stays
7120
+ * open; the floor turns that worst case into one request every thirty
7121
+ * seconds.
7122
+ *
7123
+ * It is deliberately NOT the answer to clock skew, which is where this floor's
7124
+ * reasoning used to sit. `expiresAt` is a SERVER instant, and comparing it to
7125
+ * a CLIENT clock is what produced the near-zero delays in the first place —
7126
+ * fixed at the source now by `tokenTtlMs`, which turns the wire's absolute
7127
+ * instant into a DURATION measured against the server's own `Date` header and
7128
+ * re-anchors it on the client clock at response receipt (see that function).
7129
+ * The delay is a duration minus a margin from that point on, so a device whose
7130
+ * clock is simply set wrong no longer shortens it at all.
7131
+ *
7132
+ * Nor is the loop "self-terminating" — an earlier version of this comment
7133
+ * claimed the server 401s a refresh it considers premature, and it does not:
7134
+ * `POST /widget/refresh` renews any token that is still valid, however
7135
+ * recently it was minted. A tight loop would have been answered with a tight
7136
+ * loop of 200s.
7137
+ */
7138
+ var MIN_REFRESH_DELAY_MS = 30 * 1e3;
7139
+ /**
7140
+ * `setTimeout`'s 32-bit delay ceiling. A delay past this silently wraps and
7141
+ * fires the callback IMMEDIATELY (both in browsers and in Node), which would
7142
+ * turn an absurd `expiresAt` — a wildly wrong device clock, a malformed wire
7143
+ * value that still parses — into exactly the busy-loop `MIN_REFRESH_DELAY_MS`
7144
+ * exists to prevent, from the other direction. Capping instead makes the timer
7145
+ * fire late-but-sane, and `runRefresh`'s own expiry check then routes it to a
7146
+ * re-boot rather than a refresh that could only 401.
7147
+ */
7148
+ var MAX_REFRESH_DELAY_MS = 2147483647;
7149
+ /**
7150
+ * The ceiling on the delay before a TRANSIENT refresh failure is retried —
7151
+ * see `runRefresh`'s `retryLater`. A minute is short enough that a rotation
7152
+ * which lost one request to a flaky network still lands well inside the
7153
+ * five-minute margin, and long enough that a server having a bad thirty
7154
+ * seconds is not asked again every timer tick.
7155
+ */
7156
+ var TRANSIENT_RETRY_MAX_DELAY_MS = 6e4;
7157
+ /**
7158
+ * `document.visibilityState === 'visible'`, with an absent `document` (SSR, a
7159
+ * non-browser runtime) treated as VISIBLE.
7160
+ *
7161
+ * One function for the three places that ask — the refresh timer, the
7162
+ * `visibilitychange` handler that picks up a declined refresh, and the read-
7163
+ * receipt reporter. They used to spell the same question three different ways
7164
+ * (two of them inverted), which is precisely how a fourth caller ends up
7165
+ * getting the SSR default backwards: "no tab" must mean "nothing is hidden",
7166
+ * never "nothing is visible" — the latter would silently stop refreshing and
7167
+ * stop reporting read receipts in every non-browser runtime.
7168
+ */
7169
+ function isTabVisible() {
7170
+ return typeof document === "undefined" || document.visibilityState === "visible";
7171
+ }
7172
+ /**
7173
+ * How long the token in a boot/refresh response has left to live, in
7174
+ * MILLISECONDS — the one conversion from the wire's absolute `expiresAt` into
7175
+ * something this hook may compare against its own clock.
7176
+ *
7177
+ * ## Why a duration, and not the instant the wire actually sends
7178
+ *
7179
+ * `expiresAt` is an instant on the SERVER's clock. Every earlier version of
7180
+ * this code stored `Date.parse(expiresAt)` and compared it against
7181
+ * `Date.now()` on the CLIENT, which silently assumed the two agree. A device
7182
+ * whose clock runs 45 minutes fast makes a freshly minted 30-minute token look
7183
+ * ALREADY EXPIRED: `runRefresh`'s expiry shortcut fires a re-boot instead of a
7184
+ * refresh, the boot returns another 30-minute token that is equally "expired"
7185
+ * by the same wrong clock, and the widget re-boots forever — a session-mint
7186
+ * loop against the api, on the shopper's very first page view. A device whose
7187
+ * clock runs slow has the mirror defect: the token lapses long before the
7188
+ * timer this hook armed for it ever fires.
7189
+ *
7190
+ * A DURATION has neither failure mode. The server states when the token dies;
7191
+ * the `Date` response header states what the server thinks "now" is; the
7192
+ * difference is a TTL both clocks agree on, because it never leaves the
7193
+ * server's frame of reference. The caller then re-anchors it on the client
7194
+ * clock at the moment the response was received (`now() + ttlMs`), so every
7195
+ * later comparison is client-clock against client-clock and any constant
7196
+ * offset cancels out entirely — the same discipline
7197
+ * `UseChatSessionOptions.now` already documents for the receipt reporter's
7198
+ * relative offsets.
7199
+ *
7200
+ * ## The `Date` header is reliably readable here
7201
+ *
7202
+ * `Date` is one of the CORS-safelisted response headers, exposed to script on
7203
+ * a cross-origin response by default with no `Access-Control-Expose-Headers`
7204
+ * cooperation needed, and trivially present on a same-origin one. When it is
7205
+ * absent or unparseable anyway (a proxy that strips it, a test double built
7206
+ * from a bare `Response`), `clientNow` stands in — which reproduces exactly
7207
+ * the old same-clock arithmetic for that response, and no worse.
7208
+ *
7209
+ * Returns `null` when `expiresAtIso` is absent (an api build that predates the
7210
+ * field) or unparseable — the caller must then schedule NOTHING rather than
7211
+ * invent a TTL, and must not hand the value on to the collector either.
7212
+ */
7213
+ function tokenTtlMs(res, expiresAtIso, clientNow) {
7214
+ if (expiresAtIso === void 0) return null;
7215
+ const expiresAt = Date.parse(expiresAtIso);
7216
+ if (!Number.isFinite(expiresAt)) return null;
7217
+ const serverNow = Date.parse(res.headers?.get("date") ?? "");
7218
+ return expiresAt - (Number.isFinite(serverNow) ? serverNow : clientNow);
7219
+ }
7220
+ /**
6166
7221
  * Neutral key names — see apps/web/AGENTS.md branding guardrail. Both are
6167
7222
  * first-party, non-cryptographic-on-this-side values: `visitorId` only needs
6168
7223
  * to survive a page reload, and `visitorProof` is the OPAQUE, server-signed
@@ -6214,6 +7269,7 @@ function useChatSession(options) {
6214
7269
  const { embedKey, attribution, apiBase = DEFAULT_API_BASE, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, idlePollIntervalMs = DEFAULT_IDLE_POLL_INTERVAL_MS, socketUrl, socketPath = DEFAULT_SOCKET_PATH, collector } = options;
6215
7270
  const fetchImpl = options.fetchImpl ?? fetch;
6216
7271
  const socketFactory = options.socketImpl;
7272
+ const now = useMemo(() => options.now ?? (() => Date.now()), []);
6217
7273
  const [turns, setTurns] = useState([]);
6218
7274
  /**
6219
7275
  * The tenant's collapsed-widget config, once the session has booted.
@@ -6240,6 +7296,22 @@ function useChatSession(options) {
6240
7296
  const [error, setError] = useState(void 0);
6241
7297
  const [ready, setReady] = useState(false);
6242
7298
  const [connection, setConnection] = useState("idle");
7299
+ /**
7300
+ * Counts SESSIONS, not renders — bumped once per successful `bootSession`,
7301
+ * and by nothing else. A token ROTATION deliberately does not bump it.
7302
+ *
7303
+ * The socket effect depends on it, which is the entire point. A rotation
7304
+ * leaves the conversation alone (same `visitorSessionId`, same conversation
7305
+ * room, an already-authenticated connection) so its socket must survive
7306
+ * untouched. A recovery re-boot is the opposite in every respect: the server
7307
+ * mints a NEW conversation and a new session row, and a socket still joined
7308
+ * to the OLD conversation's room would sit there connected, healthy, and
7309
+ * permanently silent — pushing nothing, while the poll it was supposed to
7310
+ * outrun is the only channel left. Bumping the generation makes this effect
7311
+ * tear the old socket down and hand the new handshake the rotated headers,
7312
+ * which is what actually joins the new room.
7313
+ */
7314
+ const [bootGeneration, setBootGeneration] = useState(0);
6243
7315
  const chatTokenRef = useRef(void 0);
6244
7316
  const lastSeqRef = useRef(0);
6245
7317
  /** Every `seq` already rendered, from EITHER path — the actual dedupe guard; see the module doc comment. */
@@ -6248,11 +7320,140 @@ function useChatSession(options) {
6248
7320
  const pollIntervalRef = useRef(pollIntervalMs);
6249
7321
  const mountedRef = useRef(true);
6250
7322
  const socketRef = useRef(null);
7323
+ /**
7324
+ * `StartWidgetSessionResult.visitorSessionId` — same value `collector`
7325
+ * (when supplied) receives via `setSession`, stored here too because the
7326
+ * read-receipt reporter below (SAA-137) needs it on every POST and has no
7327
+ * other source: `UseChatSessionResult` never exposes this id publicly (see
7328
+ * `SessionBootResponse.visitorSessionId`'s own doc comment).
7329
+ */
7330
+ const visitorSessionIdRef = useRef(void 0);
7331
+ /**
7332
+ * The receipt reporters' `sinceStartMs` zero-point — captured once, at the
7333
+ * instant `POST /widget/session` is ISSUED.
7334
+ *
7335
+ * ## Why the request, not the response — the bug this fixes
7336
+ *
7337
+ * The server records `occurredAt = conversation_sessions.started_at +
7338
+ * sinceStartMs` (`WidgetChatService.recordClientIngestBatch`), and
7339
+ * `Turn.readAt`/`Turn.deliveredAt` only honour a receipt whose `occurredAt`
7340
+ * is at or after the turn's own `completedAt`. That makes the anchor's
7341
+ * ERROR DIRECTION decide whether the feature works at all.
7342
+ *
7343
+ * `started_at` is minted DURING the boot request, so the client instant it
7344
+ * corresponds to lies somewhere between issuing that request and receiving
7345
+ * its response. Anchoring on the RESPONSE — what this used to do — takes
7346
+ * the latest point in that interval, which makes every offset SHORT by the
7347
+ * whole boot round trip: a session boot resolves a visitor, a contact, a
7348
+ * conversation, a session row and a timeline event (plus, on the demo
7349
+ * storefront, a same-origin proxy hop), so that is hundreds of
7350
+ * milliseconds, while the gap between a turn committing and its `done`
7351
+ * frame reaching this browser is a fraction of it. The receipt for a reply
7352
+ * the shopper watched land was therefore stamped BEFORE that reply
7353
+ * completed, `readAt` returned null for it, and the console's second tick
7354
+ * never appeared on a real deployment — while every unit test passed,
7355
+ * because a fake clock that does not advance during the boot request makes
7356
+ * both anchors identical.
7357
+ *
7358
+ * Anchoring on the REQUEST takes the earliest point in the same interval,
7359
+ * so a receipt is never recorded before the moment it describes. The cost
7360
+ * is the mirror image: a receipt may be recorded LATE by however long that
7361
+ * boot round trip took, and an outbound turn completing inside that window
7362
+ * could be swept into a receipt fired just before it.
7363
+ *
7364
+ * Nothing on THIS side bounds that overshoot — a tab frozen or slept
7365
+ * between issuing the boot request and receiving its response stretches it
7366
+ * arbitrarily — so the bound is enforced where it can be witnessed rather
7367
+ * than estimated: `WidgetChatService.recordClientIngestBatch` clamps every
7368
+ * event to the instant the batch arrived, because whatever the client
7369
+ * believes, the thing it is reporting happened no later than the request
7370
+ * carrying it. The two halves are a pair; neither is sufficient alone.
7371
+ */
7372
+ const sessionOriginRef = useRef(null);
7373
+ /**
7374
+ * Monotonic per session, half of a receipt's dedupe key
7375
+ * (`clientEventDedupeKey`, api-side). ONE counter across both receipt
7376
+ * kinds: the contract says "monotonic per session", not per kind, and the
7377
+ * key already carries `kind` so two kinds sharing a session cannot collide.
7378
+ */
7379
+ const clientSeqRef = useRef(0);
7380
+ /**
7381
+ * `ChatTurn.id` of every FINAL inbound turn each reporter has already
7382
+ * accounted for — see the effect below for why finality, not array
7383
+ * length, is the watermark: `mergeIncoming`/the streaming reducer both
7384
+ * mutate a turn'S `text`/`final` IN PLACE as text arrives (same array
7385
+ * index, new content), so "have I seen this many turns" is not the same
7386
+ * question as "have I seen this turn's FINISHED content".
7387
+ *
7388
+ * TWO sets, not one, because the two receipts answer different questions
7389
+ * and fire at different moments: a turn that arrives on a hidden tab is
7390
+ * delivered immediately and read only when the shopper comes back, so a
7391
+ * shared watermark would silently swallow one of the two.
7392
+ */
7393
+ const deliveredTurnIdsRef = useRef(/* @__PURE__ */ new Set());
7394
+ const readTurnIdsRef = useRef(/* @__PURE__ */ new Set());
7395
+ /**
7396
+ * Guards the handoff transcript event against a second append.
7397
+ *
7398
+ * `status` can be set to `'escalated'` more than once in a session — a
7399
+ * later turn can stream another `escalated` event, and `sendAttachment`
7400
+ * sets it independently — but the conversation is handed over once, and a
7401
+ * second marker in the thread would read as a second handoff that never
7402
+ * happened.
7403
+ */
7404
+ const handoffEventAppendedRef = useRef(false);
7405
+ /**
7406
+ * The CURRENT chat token's expiry, epoch ms — `Date.parse` of whatever
7407
+ * `expiresAt` the last successful boot or refresh returned, `null` before
7408
+ * the first one (or when an api build predates the field, in which case
7409
+ * nothing is ever scheduled and the hook behaves exactly as it did before
7410
+ * refresh existed).
7411
+ *
7412
+ * Internal on purpose: `UseChatSessionResult` exposes `chatToken` because a
7413
+ * caller needs it to authenticate the voice leg, but a caller has no use for
7414
+ * — and must never make a decision on — when it lapses. That decision lives
7415
+ * here, in the one place that can act on it.
7416
+ */
7417
+ const expiresAtRef = useRef(null);
7418
+ const refreshTimerRef = useRef(void 0);
7419
+ /**
7420
+ * Set when the refresh timer fired on a HIDDEN tab and was therefore
7421
+ * declined; cleared by the `visibilitychange` handler that finally acts on
7422
+ * it. See `handleRefreshDue` for why a hidden tab does not refresh at all.
7423
+ */
7424
+ const refreshPendingRef = useRef(false);
7425
+ /**
7426
+ * The ONE `extraHeaders` object the socket is ever created with — held here,
7427
+ * mutated in place on rotation, never replaced.
7428
+ *
7429
+ * `socket.io-client` captures the options object at creation and re-reads it
7430
+ * for each reconnect handshake, so mutating this one field is what lets a
7431
+ * reconnect that happens ten minutes after a rotation present the CURRENT
7432
+ * token instead of the one that was live when the socket was first opened.
7433
+ * Handing it a fresh object per rotation would not work: the client holds
7434
+ * the original reference, and this hook does not recreate the socket on
7435
+ * rotation (a live connection is already authenticated — see the socket
7436
+ * effect).
7437
+ *
7438
+ * It has to be a header rather than an auth payload for the reason the
7439
+ * socket effect already documents at length: the handshake is an ordinary
7440
+ * XHR precisely because a browser's native WebSocket cannot set custom
7441
+ * headers on its upgrade request.
7442
+ */
7443
+ const socketAuthHeadersRef = useRef({ Authorization: "" });
7444
+ /**
7445
+ * Indirection that lets `scheduleRefresh` arm a timer whose handler is
7446
+ * declared BELOW it (the handler schedules the next one, so the two are
7447
+ * mutually recursive). A ref rather than a `useCallback` cycle keeps both
7448
+ * halves free of each other in their dependency arrays.
7449
+ */
7450
+ const refreshDueRef = useRef(() => {});
6251
7451
  useEffect(() => {
6252
7452
  mountedRef.current = true;
6253
7453
  return () => {
6254
7454
  mountedRef.current = false;
6255
7455
  if (pollTimerRef.current !== void 0) clearInterval(pollTimerRef.current);
7456
+ if (refreshTimerRef.current !== void 0) clearTimeout(refreshTimerRef.current);
6256
7457
  socketRef.current?.disconnect();
6257
7458
  };
6258
7459
  }, []);
@@ -6268,13 +7469,56 @@ function useChatSession(options) {
6268
7469
  if (fresh.length === 0) return;
6269
7470
  for (const t of fresh) seenSeqRef.current.add(t.seq);
6270
7471
  lastSeqRef.current = fresh.reduce((max, t) => Math.max(max, t.seq), lastSeqRef.current);
6271
- setTurns((prev) => [...prev, ...fresh.map((t) => ({
6272
- id: t.id,
6273
- speaker: speakerFor(t.role),
6274
- text: t.text ?? "",
6275
- final: true,
6276
- ...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {}
6277
- }))]);
7472
+ setTurns((prev) => {
7473
+ const rendered = new Set(prev.map((t) => t.id));
7474
+ const unseen = fresh.filter((t) => !rendered.has(t.id));
7475
+ if (unseen.length === 0) return prev;
7476
+ return [...prev, ...unseen.map((t) => ({
7477
+ id: t.id,
7478
+ speaker: speakerFor(t.role),
7479
+ text: t.text ?? "",
7480
+ final: true,
7481
+ ...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {}
7482
+ }))];
7483
+ });
7484
+ }, []);
7485
+ /**
7486
+ * Records the handoff to a human AS AN EVENT IN THE TRANSCRIPT, at the
7487
+ * point in the thread where it happened, and flips `status`.
7488
+ *
7489
+ * The two used to be separate concerns: `status === 'escalated'` drove a
7490
+ * banner rendered under the whole conversation. That banner was reported
7491
+ * from a live storefront still telling a shopper a human "will pick this
7492
+ * up shortly" while a human was already answering them — inevitable for
7493
+ * chrome keyed on a transport state, because it has no position in the
7494
+ * conversation and no later event can retire it. An event turn has both: a
7495
+ * position (here, immediately after the exchange that escalated) and
7496
+ * neighbours (a reply landing after it is exactly what tells the renderer
7497
+ * the promise is spent — see `VoiceWidget`).
7498
+ *
7499
+ * Appended once per session, guarded by `handoffEventAppendedRef`: the
7500
+ * conversation is handed over once, however many times the transport
7501
+ * re-reports it — and there are now three transports that can, since this
7502
+ * is exposed on {@link UseChatSessionResult} for the VOICE leg to call
7503
+ * (see that field's doc comment). That guard plus React's own bail-out on
7504
+ * an unchanged `status` is what makes it safe to call from an effect.
7505
+ *
7506
+ * The id is a fixed literal, not a generated one, because there is at most
7507
+ * one of these per session — and a stable id keeps this row from ever
7508
+ * colliding with a server turn id in `setTurns`' own map/filter passes.
7509
+ */
7510
+ const markHandoffToHuman = useCallback(() => {
7511
+ if (!mountedRef.current) return;
7512
+ setStatus("escalated");
7513
+ if (handoffEventAppendedRef.current) return;
7514
+ handoffEventAppendedRef.current = true;
7515
+ setTurns((prev) => [...prev, {
7516
+ id: HANDOFF_EVENT_TURN_ID,
7517
+ speaker: "event",
7518
+ event: "handoff",
7519
+ text: "",
7520
+ final: true
7521
+ }]);
6278
7522
  }, []);
6279
7523
  const poll = useCallback(async () => {
6280
7524
  const chatToken = chatTokenRef.current;
@@ -6304,6 +7548,174 @@ function useChatSession(options) {
6304
7548
  pollIntervalRef.current = intervalMs;
6305
7549
  pollTimerRef.current = setInterval(() => void poll(), intervalMs);
6306
7550
  }, [poll]);
7551
+ /**
7552
+ * Swaps a freshly-minted chat token into every place the previous one was
7553
+ * held — the ONE function that writes it, so a rotation can never update
7554
+ * three of the four and leave the fourth presenting a dead credential.
7555
+ *
7556
+ * The ref is what every REST call in this file reads; the state is what
7557
+ * `host-widget.tsx` threads into `createWidgetVoiceTokenFetcher` (that
7558
+ * fetcher is rebuilt on each render from the CURRENT `session.chatToken`,
7559
+ * and `useVoiceSession` reads `optionsRef.current.fetchSession` at
7560
+ * `start()`, so a rotation reaches the voice leg with no extra plumbing);
7561
+ * the headers object is what a socket reconnect handshake replays.
7562
+ */
7563
+ const adoptChatToken = useCallback((token) => {
7564
+ chatTokenRef.current = token;
7565
+ setChatToken(token);
7566
+ socketAuthHeadersRef.current.Authorization = `Bearer ${token}`;
7567
+ }, []);
7568
+ /**
7569
+ * Arms the single refresh timer for the token that was just minted, and
7570
+ * records its expiry ON THE CLIENT CLOCK.
7571
+ *
7572
+ * Takes a TTL — how long the token has left, per `tokenTtlMs` — never the
7573
+ * wire's absolute `expiresAt`. Everything downstream then lives in one frame
7574
+ * of reference: `expiresAtRef` is `now() + ttlMs` (this client's clock, at
7575
+ * this instant), the delay is that same duration minus the margin, and
7576
+ * `runRefresh`'s expiry shortcut compares a client instant against a client
7577
+ * instant. See `tokenTtlMs` for the re-boot loop this shape exists to
7578
+ * prevent.
7579
+ *
7580
+ * `ttlMs` `null` (an api build that predates `expiresAt`, or a value that
7581
+ * would not parse) ⇒ nothing is scheduled at all and `expiresAtRef` is left
7582
+ * untouched: a client that cannot tell when a token dies must not guess a
7583
+ * TTL, and the pre-refresh behaviour — the token simply lapses — is the
7584
+ * correct fallback, not a fabricated schedule.
7585
+ *
7586
+ * A NEGATIVE or tiny TTL is still scheduled, not discarded: it is a real
7587
+ * (if degenerate) statement about the token, and the clamp below turns it
7588
+ * into a timer that fires at the floor — where `runRefresh` routes it to a
7589
+ * re-boot. Refusing to schedule would instead leave the session with no
7590
+ * recovery armed at all.
7591
+ *
7592
+ * Always clears the outstanding timer first, so this is equally the
7593
+ * "reschedule" path after a successful refresh; there is never more than one
7594
+ * armed.
7595
+ */
7596
+ const scheduleRefresh = useCallback((ttlMs) => {
7597
+ if (refreshTimerRef.current !== void 0) {
7598
+ clearTimeout(refreshTimerRef.current);
7599
+ refreshTimerRef.current = void 0;
7600
+ }
7601
+ if (ttlMs === null || !Number.isFinite(ttlMs)) return;
7602
+ expiresAtRef.current = now() + ttlMs;
7603
+ const delay = Math.min(MAX_REFRESH_DELAY_MS, Math.max(MIN_REFRESH_DELAY_MS, ttlMs - REFRESH_MARGIN_MS));
7604
+ refreshTimerRef.current = setTimeout(() => {
7605
+ refreshTimerRef.current = void 0;
7606
+ refreshDueRef.current();
7607
+ }, delay);
7608
+ }, [now]);
7609
+ /**
7610
+ * The ONE implementation of "start this widget session against
7611
+ * `POST /widget/session`", shared by the mount-time boot effect and by the
7612
+ * refresh path's silent recovery — extracted rather than duplicated because
7613
+ * the two must apply the SAME response identically: a recovery that forgot
7614
+ * to re-anchor `sessionOriginRef`, or to re-persist the visitor pair the
7615
+ * server may have rotated, would leave the session subtly wrong in ways
7616
+ * nothing on screen reveals.
7617
+ *
7618
+ * ## `phase` — what a RECOVERY deliberately does not re-apply
7619
+ *
7620
+ * A recovery restores a CREDENTIAL. Re-applying the tenant's published
7621
+ * config halfway through a live session is not part of that job, and doing
7622
+ * it can yank UI out from under a visitor who is using it. Each of these is
7623
+ * therefore gated on `phase === 'mount'`:
7624
+ *
7625
+ * - **The greeting.** `setTurns([greeting])` REPLACES the transcript. On
7626
+ * mount there is nothing to replace; on a recovery it would erase the
7627
+ * conversation the shopper is in the middle of, to re-show a greeting they
7628
+ * read half an hour ago.
7629
+ * - **`modalities`.** The concrete failure: a recovery landing DURING a
7630
+ * voice call, against a config whose `voice` is now false (a tenant toggled
7631
+ * it, or an api build that omits the field, which defaults it to false),
7632
+ * flips `modalities.voice` off — and `host-widget.tsx` derives every
7633
+ * in-call control from exactly that flag, so the shopper is left on a
7634
+ * connected LiveKit room with no way to mute, speak or hang up. The
7635
+ * credential was restored and the call was orphaned.
7636
+ * - **`launcher`.** Same class, milder symptom: re-anchoring or re-labelling
7637
+ * the collapsed widget mid-conversation (including moving it out from
7638
+ * under a visitor who had dragged it somewhere) is a config change
7639
+ * presented as a session recovery.
7640
+ *
7641
+ * And one thing that belongs to the mount path for a different reason:
7642
+ *
7643
+ * - **`ready`.** That flag means "the first boot attempt has resolved" and is
7644
+ * latched; a later recovery neither un-readies the widget nor re-readies
7645
+ * it. (Its caller owns it — this function never touches it.)
7646
+ *
7647
+ * `setStatus` preserves `'escalated'` for the same reason (the same guard
7648
+ * `send`'s `onDone` uses): a token expiring mid-handoff must not silently
7649
+ * demote a conversation a human is answering back to `'idle'`, which would
7650
+ * stop the poll loop and close the socket.
7651
+ *
7652
+ * Throws on a non-ok response or a network failure — both callers decide for
7653
+ * themselves what a failed boot means, which is the only thing they differ on.
7654
+ */
7655
+ const bootSession = useCallback(async (args) => {
7656
+ const isStale = args.isStale;
7657
+ const isMount = args.phase === "mount";
7658
+ const stored = readStoredVisitor();
7659
+ const bootRequestedAt = now();
7660
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/session`, embedKey), {
7661
+ method: "POST",
7662
+ headers: { "content-type": "application/json" },
7663
+ body: JSON.stringify({
7664
+ embedKey,
7665
+ attribution,
7666
+ ...stored.visitorId ? { visitorId: stored.visitorId } : {},
7667
+ ...stored.visitorProof ? { visitorProof: stored.visitorProof } : {}
7668
+ })
7669
+ });
7670
+ if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
7671
+ const body = await res.json();
7672
+ if (isStale?.() || !mountedRef.current) return;
7673
+ const receivedAt = now();
7674
+ const ttlMs = tokenTtlMs(res, body.expiresAt, receivedAt);
7675
+ adoptChatToken(body.chatToken);
7676
+ lastSeqRef.current = 0;
7677
+ seenSeqRef.current.clear();
7678
+ visitorSessionIdRef.current = body.visitorSessionId;
7679
+ sessionOriginRef.current = bootRequestedAt;
7680
+ if (isMount) setModalities({
7681
+ text: body.modalities?.text ?? true,
7682
+ voice: body.modalities?.voice ?? false
7683
+ });
7684
+ persistVisitor(body.visitorId, body.visitorProof);
7685
+ if (collector && body.visitorSessionId !== void 0 && ttlMs !== null) collector.setSession({
7686
+ chatToken: body.chatToken,
7687
+ visitorSessionId: body.visitorSessionId,
7688
+ expiresAt: receivedAt + ttlMs
7689
+ });
7690
+ if (isMount && body.greeting) setTurns([{
7691
+ id: "greeting",
7692
+ speaker: "agent",
7693
+ text: body.greeting,
7694
+ final: true
7695
+ }]);
7696
+ if (isMount && body.resumed === true) {
7697
+ lastSeqRef.current = 0;
7698
+ poll();
7699
+ }
7700
+ if (isMount) setLauncher({
7701
+ ...body.launcher?.label !== void 0 ? { label: body.launcher.label } : {},
7702
+ ...isConciergePosition(body.launcher?.position) ? { position: body.launcher.position } : {},
7703
+ ...typeof body.launcher?.draggable === "boolean" ? { draggable: body.launcher.draggable } : {}
7704
+ });
7705
+ setStatus((prev) => prev === "escalated" ? prev : "idle");
7706
+ scheduleRefresh(ttlMs);
7707
+ setBootGeneration((generation) => generation + 1);
7708
+ }, [
7709
+ adoptChatToken,
7710
+ apiBase,
7711
+ attribution,
7712
+ collector,
7713
+ embedKey,
7714
+ fetchImpl,
7715
+ now,
7716
+ poll,
7717
+ scheduleRefresh
7718
+ ]);
6307
7719
  useEffect(() => {
6308
7720
  let cancelled = false;
6309
7721
  if (!embedKey) {
@@ -6312,62 +7724,202 @@ function useChatSession(options) {
6312
7724
  setReady(true);
6313
7725
  return;
6314
7726
  }
6315
- (async () => {
6316
- try {
6317
- const stored = readStoredVisitor();
6318
- const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/session`, embedKey), {
6319
- method: "POST",
6320
- headers: { "content-type": "application/json" },
6321
- body: JSON.stringify({
6322
- embedKey,
6323
- attribution,
6324
- ...stored.visitorId ? { visitorId: stored.visitorId } : {},
6325
- ...stored.visitorProof ? { visitorProof: stored.visitorProof } : {}
6326
- })
6327
- });
6328
- if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
6329
- const body = await res.json();
6330
- if (cancelled) return;
6331
- chatTokenRef.current = body.chatToken;
6332
- setChatToken(body.chatToken);
6333
- setModalities({
6334
- text: body.modalities?.text ?? true,
6335
- voice: body.modalities?.voice ?? false
6336
- });
6337
- persistVisitor(body.visitorId, body.visitorProof);
6338
- if (collector && body.visitorSessionId !== void 0 && body.expiresAt !== void 0) collector.setSession({
6339
- chatToken: body.chatToken,
6340
- visitorSessionId: body.visitorSessionId,
6341
- expiresAt: Date.parse(body.expiresAt)
6342
- });
6343
- if (body.greeting) setTurns([{
6344
- id: "greeting",
6345
- speaker: "agent",
6346
- text: body.greeting,
6347
- final: true
6348
- }]);
6349
- setLauncher({
6350
- ...body.launcher?.label !== void 0 ? { label: body.launcher.label } : {},
6351
- ...isConciergePosition(body.launcher?.position) ? { position: body.launcher.position } : {},
6352
- ...typeof body.launcher?.draggable === "boolean" ? { draggable: body.launcher.draggable } : {}
6353
- });
6354
- setStatus("idle");
6355
- } catch (err) {
6356
- if (cancelled) return;
6357
- setStatus("error");
6358
- setError(err instanceof Error ? err.message : "Could not start the conversation.");
6359
- } finally {
6360
- if (!cancelled) setReady(true);
6361
- }
6362
- })();
6363
- return () => {
6364
- cancelled = true;
7727
+ (async () => {
7728
+ try {
7729
+ await bootSession({
7730
+ phase: "mount",
7731
+ isStale: () => cancelled
7732
+ });
7733
+ } catch (err) {
7734
+ if (cancelled) return;
7735
+ setStatus("error");
7736
+ setError(err instanceof Error ? err.message : "Could not start the conversation.");
7737
+ } finally {
7738
+ if (!cancelled) setReady(true);
7739
+ }
7740
+ })();
7741
+ return () => {
7742
+ cancelled = true;
7743
+ };
7744
+ }, []);
7745
+ /**
7746
+ * The recovery of last resort: mint a whole new session because the current
7747
+ * token could not be renewed.
7748
+ *
7749
+ * Silent by design — a shopper whose token rotated badly should see nothing
7750
+ * at all, because nothing about their conversation has actually failed. The
7751
+ * existing `status: 'error'` surface is reached ONLY if this second attempt
7752
+ * also fails, at which point the widget genuinely cannot reach the api and
7753
+ * saying so is honest.
7754
+ */
7755
+ const rebootSession = useCallback(async () => {
7756
+ try {
7757
+ await bootSession({ phase: "recovery" });
7758
+ } catch (err) {
7759
+ if (!mountedRef.current) return;
7760
+ setStatus("error");
7761
+ setError(err instanceof Error ? err.message : "Could not start the conversation.");
7762
+ }
7763
+ }, [bootSession]);
7764
+ /**
7765
+ * One rotation attempt: `POST /widget/refresh`, authenticated by the token
7766
+ * being replaced.
7767
+ *
7768
+ * **PERMANENT and TRANSIENT failures are not the same failure.** They used
7769
+ * to be: every non-success — 401, 503, a dropped connection, a captive
7770
+ * portal's HTML served with a 200 — fell straight through to
7771
+ * `rebootSession`. A `401` genuinely IS permanent (the token expired, the
7772
+ * session hit its absolute 12-hour cap, or the Origin is not one this embed
7773
+ * key allows — see `SessionRefreshResponse`), and a whole new session is the
7774
+ * only way forward. Nothing else is: a five-second network blip five minutes
7775
+ * before expiry would abandon a perfectly renewable token and mint a brand
7776
+ * new session — a new conversation row, a new `visitorSessionId`, a socket
7777
+ * that has to rejoin, and a shopper's browsing session split in two in the
7778
+ * pipeline — because one request lost a race with a lift's wifi.
7779
+ *
7780
+ * So: `401` ⇒ `rebootSession`. Everything else — the network, a 5xx, a
7781
+ * response whose body does not parse or does not carry a usable token ⇒ ONE
7782
+ * retry of this same function, armed on the normal refresh timer at
7783
+ * `min(60s, remaining/2)` (never below the busy-loop floor).
7784
+ *
7785
+ * **No retry counter, because the expiry already bounds it.** Each retry is
7786
+ * scheduled at half the REMAINING life, so the attempts converge on the
7787
+ * expiry rather than continuing past it; the moment `remaining` reaches zero
7788
+ * the expiry shortcut below routes the next firing to a re-boot. A counter
7789
+ * would be a second, weaker statement of the same bound.
7790
+ *
7791
+ * **An already-expired token skips the refresh entirely.** The server 401s
7792
+ * it unconditionally, so spending the round trip to be told so — while the
7793
+ * shopper waits — buys nothing. This is the path a tab that was hidden past
7794
+ * its expiry takes when it comes back (see `handleRefreshDue`), and the path
7795
+ * a run of failed retries eventually reaches. The expiry it reads is
7796
+ * CLIENT-anchored (`scheduleRefresh`), so a wrong device clock cannot send
7797
+ * it here on a token that is in fact fine.
7798
+ *
7799
+ * **Nothing is adopted before it is validated.** A 200 carrying no
7800
+ * `chatToken`, or an `expiresAt` that yields no finite TTL, is a FAILED
7801
+ * refresh — not a token to install and a `NaN` expiry to hand the collector
7802
+ * and the scheduler.
7803
+ *
7804
+ * Never rejects: it is invoked as `void runRefresh()` from a timer and from
7805
+ * an event listener, neither of which has anywhere to put a rejection.
7806
+ */
7807
+ const runRefresh = useCallback(async () => {
7808
+ const chatToken = chatTokenRef.current;
7809
+ if (chatToken === void 0) return;
7810
+ const expiresAt = expiresAtRef.current;
7811
+ if (expiresAt !== null && now() >= expiresAt) {
7812
+ await rebootSession();
7813
+ return;
7814
+ }
7815
+ /**
7816
+ * A TRANSIENT failure: try this same refresh again, later, on the one
7817
+ * refresh timer — via `refreshDueRef`, so a retry that comes due on a
7818
+ * hidden tab is declined and picked up on the shopper's return exactly
7819
+ * like a scheduled rotation is.
7820
+ *
7821
+ * A token already past its life by the client-anchored clock has nothing
7822
+ * left to renew, so that goes to the re-boot instead.
7823
+ */
7824
+ const retryLater = async () => {
7825
+ if (!mountedRef.current) return;
7826
+ const remaining = expiresAtRef.current === null ? null : expiresAtRef.current - now();
7827
+ if (remaining !== null && remaining <= 0) {
7828
+ await rebootSession();
7829
+ return;
7830
+ }
7831
+ const delay = Math.max(MIN_REFRESH_DELAY_MS, Math.min(TRANSIENT_RETRY_MAX_DELAY_MS, remaining === null ? TRANSIENT_RETRY_MAX_DELAY_MS : remaining / 2));
7832
+ if (refreshTimerRef.current !== void 0) clearTimeout(refreshTimerRef.current);
7833
+ refreshTimerRef.current = setTimeout(() => {
7834
+ refreshTimerRef.current = void 0;
7835
+ refreshDueRef.current();
7836
+ }, delay);
7837
+ };
7838
+ let res;
7839
+ try {
7840
+ res = await fetchImpl(withEmbedKeyParam(`${apiBase}/refresh`, embedKey), {
7841
+ method: "POST",
7842
+ headers: {
7843
+ "content-type": "application/json",
7844
+ authorization: `Bearer ${chatToken}`
7845
+ },
7846
+ body: JSON.stringify({})
7847
+ });
7848
+ } catch {
7849
+ await retryLater();
7850
+ return;
7851
+ }
7852
+ if (res.status === 401) {
7853
+ await rebootSession();
7854
+ return;
7855
+ }
7856
+ if (!res.ok) {
7857
+ await retryLater();
7858
+ return;
7859
+ }
7860
+ let body;
7861
+ try {
7862
+ body = await res.json();
7863
+ } catch {
7864
+ body = void 0;
7865
+ }
7866
+ const receivedAt = now();
7867
+ const ttlMs = body === void 0 ? null : tokenTtlMs(res, body.expiresAt, receivedAt);
7868
+ if (body === void 0 || typeof body.chatToken !== "string" || body.chatToken === "" || ttlMs === null) {
7869
+ await retryLater();
7870
+ return;
7871
+ }
7872
+ if (!mountedRef.current) return;
7873
+ adoptChatToken(body.chatToken);
7874
+ const visitorSessionId = visitorSessionIdRef.current;
7875
+ if (collector && visitorSessionId !== void 0 && collector.currentVisitorSessionId === visitorSessionId) collector.setSession({
7876
+ chatToken: body.chatToken,
7877
+ visitorSessionId,
7878
+ expiresAt: receivedAt + ttlMs
7879
+ });
7880
+ scheduleRefresh(ttlMs);
7881
+ }, [
7882
+ adoptChatToken,
7883
+ apiBase,
7884
+ collector,
7885
+ embedKey,
7886
+ fetchImpl,
7887
+ now,
7888
+ rebootSession,
7889
+ scheduleRefresh
7890
+ ]);
7891
+ refreshDueRef.current = useCallback(() => {
7892
+ if (!mountedRef.current) return;
7893
+ if (!isTabVisible()) {
7894
+ refreshPendingRef.current = true;
7895
+ return;
7896
+ }
7897
+ runRefresh();
7898
+ }, [runRefresh]);
7899
+ /**
7900
+ * The other half of the visibility gate: a refresh that came due while the
7901
+ * tab was hidden runs the moment the shopper comes back.
7902
+ *
7903
+ * `runRefresh` decides between an actual refresh and a re-boot by checking
7904
+ * the stored expiry itself, so this handler does not need to — a tab hidden
7905
+ * for two minutes rotates its still-valid token, and one hidden for two
7906
+ * hours goes straight to a re-boot without spending a round trip on a
7907
+ * refresh that could only 401.
7908
+ */
7909
+ useEffect(() => {
7910
+ if (typeof document === "undefined") return;
7911
+ const onVisibilityChange = () => {
7912
+ if (!isTabVisible()) return;
7913
+ if (!refreshPendingRef.current) return;
7914
+ refreshPendingRef.current = false;
7915
+ runRefresh();
6365
7916
  };
6366
- }, []);
7917
+ document.addEventListener("visibilitychange", onVisibilityChange);
7918
+ return () => document.removeEventListener("visibilitychange", onVisibilityChange);
7919
+ }, [runRefresh]);
6367
7920
  useEffect(() => {
6368
7921
  if (!socketUrl || !ready || status !== "escalated") return;
6369
- const chatToken = chatTokenRef.current;
6370
- if (chatToken === void 0) return;
7922
+ if (chatTokenRef.current === void 0) return;
6371
7923
  let cancelled = false;
6372
7924
  setConnection("connecting");
6373
7925
  (async () => {
@@ -6376,7 +7928,7 @@ function useChatSession(options) {
6376
7928
  const socket = factory(`${socketUrl}${SOCKET_NAMESPACE}`, {
6377
7929
  path: socketPath,
6378
7930
  transports: ["polling", "websocket"],
6379
- extraHeaders: { Authorization: `Bearer ${chatToken}` },
7931
+ extraHeaders: socketAuthHeadersRef.current,
6380
7932
  withCredentials: false,
6381
7933
  reconnection: true
6382
7934
  });
@@ -6405,7 +7957,8 @@ function useChatSession(options) {
6405
7957
  ready,
6406
7958
  status,
6407
7959
  socketFactory,
6408
- mergeIncoming
7960
+ mergeIncoming,
7961
+ bootGeneration
6409
7962
  ]);
6410
7963
  useEffect(() => {
6411
7964
  if (status !== "escalated") return;
@@ -6417,6 +7970,283 @@ function useChatSession(options) {
6417
7970
  pollIntervalMs,
6418
7971
  idlePollIntervalMs
6419
7972
  ]);
7973
+ /**
7974
+ * The ONE place a turn is posted to `POST /widget/chat`, shared by `send`
7975
+ * (shopper text) and `sendReport` (a typed storefront report).
7976
+ *
7977
+ * The two differ in exactly two ways — what goes in the request body, and
7978
+ * whether a caller bubble is appended — and in nothing else: both stream
7979
+ * the reply into an agent turn, both roll their optimistic turns back on a
7980
+ * failed POST, both resolve `false` rather than throwing. Keeping them one
7981
+ * function is what stops the report path from quietly losing a fix made to
7982
+ * the message path.
7983
+ */
7984
+ const postTurn = useCallback(async (payload, options) => {
7985
+ const chatToken = chatTokenRef.current;
7986
+ if (chatToken === void 0 || status === "streaming") return false;
7987
+ const text = "message" in payload ? payload.message : "";
7988
+ const silent = options?.silent === true || !("message" in payload);
7989
+ const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
7990
+ const agentTurnId = `agent-${callerTurnId}`;
7991
+ setTurns((prev) => [
7992
+ ...prev,
7993
+ ...silent ? [] : [{
7994
+ id: callerTurnId,
7995
+ speaker: "caller",
7996
+ text,
7997
+ final: true,
7998
+ delivery: "sending"
7999
+ }],
8000
+ {
8001
+ id: agentTurnId,
8002
+ speaker: "agent",
8003
+ text: "",
8004
+ final: false
8005
+ }
8006
+ ]);
8007
+ setStatus((prev) => prev === "escalated" ? prev : "streaming");
8008
+ const rollBack = () => {
8009
+ setTurns((prev) => prev.filter((t) => t.id !== callerTurnId && t.id !== agentTurnId));
8010
+ };
8011
+ let res;
8012
+ try {
8013
+ res = await fetchImpl(withEmbedKeyParam(`${apiBase}/chat`, embedKey), {
8014
+ method: "POST",
8015
+ headers: {
8016
+ "content-type": "application/json",
8017
+ authorization: `Bearer ${chatToken}`
8018
+ },
8019
+ body: JSON.stringify(payload)
8020
+ });
8021
+ } catch {
8022
+ rollBack();
8023
+ setStatus("error");
8024
+ setError("Could not reach the conversation.");
8025
+ return false;
8026
+ }
8027
+ if (!res.ok || res.body === null) {
8028
+ rollBack();
8029
+ setStatus("error");
8030
+ setError(`The conversation could not accept that message (${res.status}).`);
8031
+ return false;
8032
+ }
8033
+ if (mountedRef.current) setTurns((prev) => prev.map((t) => t.id === callerTurnId ? {
8034
+ ...t,
8035
+ delivery: "sent"
8036
+ } : t));
8037
+ streamReply({
8038
+ body: res.body,
8039
+ agentTurnId,
8040
+ setTurns,
8041
+ onCardsEvent: (evt) => {
8042
+ if (mountedRef.current) setCards((prev) => [...prev, evt]);
8043
+ },
8044
+ onCheckoutEvent: (evt) => {
8045
+ if (mountedRef.current) setCheckoutHandoffs((prev) => [...prev, evt]);
8046
+ },
8047
+ onEscalated: () => {
8048
+ markHandoffToHuman();
8049
+ },
8050
+ onDone: (turnId) => {
8051
+ if (!mountedRef.current) return;
8052
+ setTurns((prev) => prev.filter((t) => t.id !== turnId || t.id === agentTurnId).map((t) => t.id === agentTurnId ? {
8053
+ ...t,
8054
+ id: turnId,
8055
+ final: true
8056
+ } : t));
8057
+ setStatus((prev) => prev === "escalated" ? prev : "idle");
8058
+ },
8059
+ onError: (message) => {
8060
+ if (!mountedRef.current) return;
8061
+ setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
8062
+ ...t,
8063
+ final: true
8064
+ } : t));
8065
+ setStatus("error");
8066
+ setError(message);
8067
+ },
8068
+ isMounted: () => mountedRef.current
8069
+ });
8070
+ return true;
8071
+ }, [
8072
+ apiBase,
8073
+ embedKey,
8074
+ fetchImpl,
8075
+ status,
8076
+ markHandoffToHuman
8077
+ ]);
8078
+ const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
8079
+ const sendReport = useCallback(async (report) => postTurn({ report }), [postTurn]);
8080
+ const sendEvent = useCallback(async (events) => {
8081
+ const chatToken = chatTokenRef.current;
8082
+ if (chatToken === void 0 || events.length === 0) return false;
8083
+ try {
8084
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/event`, embedKey), {
8085
+ method: "POST",
8086
+ headers: {
8087
+ "content-type": "application/json",
8088
+ authorization: `Bearer ${chatToken}`
8089
+ },
8090
+ body: JSON.stringify({ events })
8091
+ });
8092
+ if (res.ok) try {
8093
+ const body = await res.json();
8094
+ if (mountedRef.current && typeof body?.cartAttributionToken === "string") setCartAttributionToken(body.cartAttributionToken);
8095
+ } catch {}
8096
+ return res.ok;
8097
+ } catch {
8098
+ return false;
8099
+ }
8100
+ }, [
8101
+ apiBase,
8102
+ embedKey,
8103
+ fetchImpl
8104
+ ]);
8105
+ /**
8106
+ * `POST /widget/ingest` with one event per receipt kind that just became
8107
+ * true — the two receipts behind the console's ticks on an outbound
8108
+ * bubble: `client.messages_delivered` (it reached this browser) and
8109
+ * `client.messages_read` (the shopper could actually see it).
8110
+ *
8111
+ * ## Two kinds, one POST
8112
+ *
8113
+ * The common case — a reply landing on a tab the shopper is looking at —
8114
+ * is both facts at once, and posting them separately would double the
8115
+ * requests to say one thing. They stay two EVENTS because they are two
8116
+ * claims: a turn that arrives on a backgrounded tab is delivered and not
8117
+ * read, and collapsing them would re-invent the inference this whole
8118
+ * feature exists to avoid.
8119
+ *
8120
+ * ## `sinceStartMs`, anchored to `sessionOriginRef` — never a wall clock
8121
+ *
8122
+ * Same discipline `@wesence/conversation-events`'s `ingest-contract.ts`
8123
+ * spells out at length: the SERVER converts this offset to
8124
+ * `occurredAt = conversation_sessions.started_at + sinceStartMs`, so the
8125
+ * offset has to be relative to the SAME real-world instant that row was
8126
+ * minted, not to an arbitrary browser timestamp. See `sessionOriginRef`'s
8127
+ * own doc comment for which END of the boot round trip that has to be, and
8128
+ * what silently broke while it was the other one.
8129
+ *
8130
+ * ## A WATERMARK, not a per-turn claim
8131
+ *
8132
+ * Each event means "as of now, the shopper's client had received (or had
8133
+ * on screen) the conversation" — never a specific turn id, because the
8134
+ * ingest contract carries none (see its own doc comment). The api-side
8135
+ * resolvers (`Turn.deliveredAt` / `Turn.readAt`) turn that into a per-turn
8136
+ * answer by comparing the event's `occurredAt` against each turn's own
8137
+ * `completedAt`.
8138
+ *
8139
+ * ## Best-effort, always — same posture as `sendEvent`
8140
+ *
8141
+ * Never throws, never surfaces to the caller as anything but a resolved
8142
+ * promise: a failed receipt POST must never read as a storefront error,
8143
+ * and the watermark sets are advanced regardless of the request's outcome
8144
+ * (a transient failure here is not worth retrying — the NEXT genuinely-new
8145
+ * inbound turn, or the next visibility change, naturally produces another
8146
+ * attempt).
8147
+ */
8148
+ const sendClientReceipts = useCallback(async (kinds) => {
8149
+ const chatToken = chatTokenRef.current;
8150
+ const sessionId = visitorSessionIdRef.current;
8151
+ const origin = sessionOriginRef.current;
8152
+ if (chatToken === void 0 || sessionId === void 0 || origin === null) return;
8153
+ if (kinds.length === 0) return;
8154
+ const sinceStartMs = Math.max(0, Math.round(now() - origin));
8155
+ const events = kinds.map((kind) => {
8156
+ const clientSeq = clientSeqRef.current;
8157
+ clientSeqRef.current += 1;
8158
+ return {
8159
+ kind,
8160
+ clientSeq,
8161
+ sinceStartMs
8162
+ };
8163
+ });
8164
+ try {
8165
+ await fetchImpl(withEmbedKeyParam(`${apiBase}/ingest`, embedKey), {
8166
+ method: "POST",
8167
+ headers: {
8168
+ "content-type": "application/json",
8169
+ authorization: `Bearer ${chatToken}`
8170
+ },
8171
+ body: JSON.stringify({
8172
+ sessionId,
8173
+ events
8174
+ })
8175
+ });
8176
+ } catch {}
8177
+ }, [
8178
+ apiBase,
8179
+ embedKey,
8180
+ fetchImpl,
8181
+ now
8182
+ ]);
8183
+ /**
8184
+ * Decides, on every `turns` change and every visibility flip, which of the
8185
+ * two receipts a NEW FINAL inbound (agent/human) turn has just earned.
8186
+ *
8187
+ * **Delivery does not wait for the tab.** A turn in `turns` has arrived in
8188
+ * this browser and been put in the transcript — that is the whole claim,
8189
+ * and it is equally true of a backgrounded tab. Gating it on visibility
8190
+ * (as the read receipt is, rightly) would have made "delivered" a slower
8191
+ * synonym for "read" and left the state it exists to express — reached
8192
+ * them, has not been looked at — unrepresentable.
8193
+ *
8194
+ * **Read waits for the tab, and nothing else.** `document.visibilityState
8195
+ * === 'visible'` is the honest limit of what a browser can say about the
8196
+ * shopper having seen a reply. It over-claims (a visible tab in another
8197
+ * window, a shopper who walked away) and this is stated plainly in the
8198
+ * field's own GraphQL description rather than dressed up.
8199
+ *
8200
+ * **`final`, not merely present, is what counts — for both.** A streaming
8201
+ * reply renders as an agent-speaker turn from its FIRST token
8202
+ * (`final: false`, `text: ''` at the instant `send()`'s optimistic caller
8203
+ * turn lands) — see `mergeIncoming`/the streaming reducer. Reporting that
8204
+ * placeholder as delivered or read would claim a receipt for content that
8205
+ * does not exist yet. Waiting for `final: true` is also why the watermarks
8206
+ * below are Sets of turn ids, not array-length cursors: the placeholder is
8207
+ * updated IN PLACE as tokens arrive (same index, growing text), so "how
8208
+ * many turns are there" never changes across that transition — only
8209
+ * `final` does.
8210
+ *
8211
+ * One event per kind per detection, not one per turn: several turns can
8212
+ * become final between two checks (a fast exchange, or turns that arrived
8213
+ * while the tab was hidden), and a receipt is a high-water mark anyway —
8214
+ * a single event covers all of them.
8215
+ *
8216
+ * Two triggers, not one: a NEW `turns` value fires it, and a
8217
+ * `visibilitychange` re-fires it so a turn that was DELIVERED to a hidden
8218
+ * tab still earns its read receipt when the shopper comes back —
8219
+ * otherwise no further `turns` change occurs once they do, and the read
8220
+ * tick would never arrive.
8221
+ */
8222
+ useEffect(() => {
8223
+ const reportReceipts = () => {
8224
+ const delivered = deliveredTurnIdsRef.current;
8225
+ const read = readTurnIdsRef.current;
8226
+ const visible = isTabVisible();
8227
+ const kinds = [];
8228
+ let sawNewDelivery = false;
8229
+ let sawNewRead = false;
8230
+ for (const t of turns) {
8231
+ if (t.speaker !== "agent" || !t.final) continue;
8232
+ if (!delivered.has(t.id)) {
8233
+ delivered.add(t.id);
8234
+ sawNewDelivery = true;
8235
+ }
8236
+ if (visible && !read.has(t.id)) {
8237
+ read.add(t.id);
8238
+ sawNewRead = true;
8239
+ }
8240
+ }
8241
+ if (sawNewDelivery) kinds.push("client.messages_delivered");
8242
+ if (sawNewRead) kinds.push("client.messages_read");
8243
+ if (kinds.length > 0) sendClientReceipts(kinds);
8244
+ };
8245
+ reportReceipts();
8246
+ if (typeof document === "undefined") return;
8247
+ document.addEventListener("visibilitychange", reportReceipts);
8248
+ return () => document.removeEventListener("visibilitychange", reportReceipts);
8249
+ }, [turns, sendClientReceipts]);
6420
8250
  return {
6421
8251
  turns,
6422
8252
  launcher,
@@ -6429,118 +8259,9 @@ function useChatSession(options) {
6429
8259
  error,
6430
8260
  ready,
6431
8261
  connection,
6432
- send: useCallback(async (text, options) => {
6433
- const chatToken = chatTokenRef.current;
6434
- if (chatToken === void 0 || status === "streaming") return false;
6435
- const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
6436
- const agentTurnId = `agent-${callerTurnId}`;
6437
- setTurns((prev) => [
6438
- ...prev,
6439
- ...options?.silent ? [] : [{
6440
- id: callerTurnId,
6441
- speaker: "caller",
6442
- text,
6443
- final: true
6444
- }],
6445
- {
6446
- id: agentTurnId,
6447
- speaker: "agent",
6448
- text: "",
6449
- final: false
6450
- }
6451
- ]);
6452
- setStatus((prev) => prev === "escalated" ? prev : "streaming");
6453
- const rollBack = () => {
6454
- setTurns((prev) => prev.filter((t) => t.id !== callerTurnId && t.id !== agentTurnId));
6455
- };
6456
- let res;
6457
- try {
6458
- res = await fetchImpl(withEmbedKeyParam(`${apiBase}/chat`, embedKey), {
6459
- method: "POST",
6460
- headers: {
6461
- "content-type": "application/json",
6462
- authorization: `Bearer ${chatToken}`
6463
- },
6464
- body: JSON.stringify({ message: text })
6465
- });
6466
- } catch {
6467
- rollBack();
6468
- setStatus("error");
6469
- setError("Could not reach the conversation.");
6470
- return false;
6471
- }
6472
- if (!res.ok || res.body === null) {
6473
- rollBack();
6474
- setStatus("error");
6475
- setError(`The conversation could not accept that message (${res.status}).`);
6476
- return false;
6477
- }
6478
- streamReply({
6479
- body: res.body,
6480
- agentTurnId,
6481
- setTurns,
6482
- onCardsEvent: (evt) => {
6483
- if (mountedRef.current) setCards((prev) => [...prev, evt]);
6484
- },
6485
- onCheckoutEvent: (evt) => {
6486
- if (mountedRef.current) setCheckoutHandoffs((prev) => [...prev, evt]);
6487
- },
6488
- onEscalated: () => {
6489
- if (!mountedRef.current) return;
6490
- setStatus("escalated");
6491
- },
6492
- onDone: (turnId) => {
6493
- if (!mountedRef.current) return;
6494
- setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
6495
- ...t,
6496
- id: turnId,
6497
- final: true
6498
- } : t));
6499
- setStatus((prev) => prev === "escalated" ? prev : "idle");
6500
- },
6501
- onError: (message) => {
6502
- if (!mountedRef.current) return;
6503
- setTurns((prev) => prev.map((t) => t.id === agentTurnId ? {
6504
- ...t,
6505
- final: true
6506
- } : t));
6507
- setStatus("error");
6508
- setError(message);
6509
- },
6510
- isMounted: () => mountedRef.current
6511
- });
6512
- return true;
6513
- }, [
6514
- apiBase,
6515
- embedKey,
6516
- fetchImpl,
6517
- status
6518
- ]),
6519
- sendEvent: useCallback(async (events) => {
6520
- const chatToken = chatTokenRef.current;
6521
- if (chatToken === void 0 || events.length === 0) return false;
6522
- try {
6523
- const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/event`, embedKey), {
6524
- method: "POST",
6525
- headers: {
6526
- "content-type": "application/json",
6527
- authorization: `Bearer ${chatToken}`
6528
- },
6529
- body: JSON.stringify({ events })
6530
- });
6531
- if (res.ok) try {
6532
- const body = await res.json();
6533
- if (mountedRef.current && typeof body?.cartAttributionToken === "string") setCartAttributionToken(body.cartAttributionToken);
6534
- } catch {}
6535
- return res.ok;
6536
- } catch {
6537
- return false;
6538
- }
6539
- }, [
6540
- apiBase,
6541
- embedKey,
6542
- fetchImpl
6543
- ]),
8262
+ send,
8263
+ sendReport,
8264
+ sendEvent,
6544
8265
  checkout: useCallback(async (items, curationId, cartAttributionToken) => {
6545
8266
  const chatToken = chatTokenRef.current;
6546
8267
  if (chatToken === void 0 || items.length === 0) return null;
@@ -6611,9 +8332,10 @@ function useChatSession(options) {
6611
8332
  speaker: "caller",
6612
8333
  text: message ?? "",
6613
8334
  final: true,
8335
+ delivery: "sent",
6614
8336
  attachments: [sent.attachment]
6615
8337
  }]);
6616
- if (sent.escalated) setStatus("escalated");
8338
+ if (sent.escalated) markHandoffToHuman();
6617
8339
  else if (sent.message) {
6618
8340
  /**
6619
8341
  * Nobody could be put on the conversation, and this endpoint never
@@ -6632,8 +8354,10 @@ function useChatSession(options) {
6632
8354
  }, [
6633
8355
  apiBase,
6634
8356
  embedKey,
6635
- fetchImpl
6636
- ])
8357
+ fetchImpl,
8358
+ markHandoffToHuman
8359
+ ]),
8360
+ markHandoffToHuman
6637
8361
  };
6638
8362
  }
6639
8363
  /**
@@ -6719,7 +8443,7 @@ async function streamReply(args) {
6719
8443
  * cache makes a second `start()` after `stop()` free).
6720
8444
  */
6721
8445
  async function loadVoiceProtocol() {
6722
- const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-ZLxYRTml.js")]);
8446
+ const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-DfajYOmN.js")]);
6723
8447
  return {
6724
8448
  decodeTelemetry: telemetry.decodeTelemetry,
6725
8449
  encodeCallerText: telemetry.encodeCallerText,
@@ -7128,7 +8852,8 @@ function useVoiceSession(options = {}) {
7128
8852
  setError(null);
7129
8853
  setSnapshot({
7130
8854
  ...IDLE_SNAPSHOT,
7131
- phase: "connecting"
8855
+ phase: "connecting",
8856
+ micPending: true
7132
8857
  });
7133
8858
  logRef.current?.clear();
7134
8859
  setEvents([]);
@@ -7272,7 +8997,8 @@ function useVoiceSession(options = {}) {
7272
8997
  record("mic_published");
7273
8998
  setSnapshot((s) => ({
7274
8999
  ...s,
7275
- micPublished: true
9000
+ micPublished: true,
9001
+ micPending: false
7276
9002
  }));
7277
9003
  } catch (micError) {
7278
9004
  const reason = micError instanceof Error ? micError.message : String(micError);
@@ -7280,7 +9006,8 @@ function useVoiceSession(options = {}) {
7280
9006
  setError(`microphone unavailable: ${reason}`);
7281
9007
  setSnapshot((s) => ({
7282
9008
  ...s,
7283
- micPublished: false
9009
+ micPublished: false,
9010
+ micPending: false
7284
9011
  }));
7285
9012
  }
7286
9013
  } catch (cause) {
@@ -7384,6 +9111,7 @@ function useVoiceSession(options = {}) {
7384
9111
  state: botStateFor(snapshot),
7385
9112
  phase: snapshot.phase,
7386
9113
  micOpen: snapshot.micPublished,
9114
+ micPending: snapshot.micPending,
7387
9115
  error,
7388
9116
  events,
7389
9117
  agentLevel,
@@ -7432,7 +9160,7 @@ function useVoiceSession(options = {}) {
7432
9160
  * resolve a bare id into a title/price/image the way a real platform's
7433
9161
  * own cart API does.
7434
9162
  */
7435
- function resolveAddToCartHandler(bridge, productHref) {
9163
+ function resolveAddToCartHandler(bridge, productHref, onAdded) {
7436
9164
  if (!bridge) return void 0;
7437
9165
  const canAddToCart = bridge.addToCart !== void 0;
7438
9166
  const canNavigateToPdp = bridge.navigate !== void 0 && productHref !== void 0;
@@ -7443,6 +9171,7 @@ function resolveAddToCartHandler(bridge, productHref) {
7443
9171
  if (bridge.addToCart && cartId) try {
7444
9172
  if (idSpace === "catalog") await bridge.addToCart(cartId, 1, buildCartLineContext(item));
7445
9173
  else await bridge.addToCart(cartId, 1);
9174
+ onAdded?.(item);
7446
9175
  return;
7447
9176
  } catch (err) {
7448
9177
  if (bridge.navigate && productHref && item.handle) {
@@ -7466,10 +9195,130 @@ function buildCartLineContext(item) {
7466
9195
  ...item.imageUrl !== void 0 ? { imageUrl: item.imageUrl } : {},
7467
9196
  priceMinor: item.priceMinor,
7468
9197
  currency: item.currency,
7469
- ...item.handle !== void 0 ? { handle: item.handle } : {}
9198
+ ...item.handle !== void 0 ? { handle: item.handle } : {},
9199
+ ...item.platformVariantId !== void 0 ? { platformVariantId: item.platformVariantId } : {}
7470
9200
  };
7471
9201
  }
7472
9202
  /**
9203
+ * Folds one successful add into the widget's own basket, merging a repeat add
9204
+ * of the SAME variant into the existing row rather than drawing it twice —
9205
+ * two identical rows read as two different products at a glance, which is
9206
+ * exactly the misread a confirmation surface must not produce.
9207
+ *
9208
+ * Keyed by the internal `variantId` where the card has one, since that is
9209
+ * what checkout will group on too; a card without one falls back to its
9210
+ * platform id and then its product id, so a repeat add of the same card still
9211
+ * merges.
9212
+ */
9213
+ function mergeAddedCartLine(lines, item) {
9214
+ const key = item.variantId ?? item.platformVariantId ?? item.productId;
9215
+ const existing = lines.findIndex((line) => line.key === key);
9216
+ if (existing >= 0) return lines.map((line, i) => i === existing ? {
9217
+ ...line,
9218
+ quantity: line.quantity + 1
9219
+ } : line);
9220
+ return [...lines, {
9221
+ key,
9222
+ title: item.title,
9223
+ ...item.imageUrl !== void 0 ? { imageUrl: item.imageUrl } : {},
9224
+ priceMinor: item.priceMinor,
9225
+ currency: item.currency,
9226
+ quantity: 1,
9227
+ ...item.variantId !== void 0 ? { variantId: item.variantId } : {}
9228
+ }];
9229
+ }
9230
+ /**
9231
+ * Turns the host's OWN cart rows into what the summary renders, or
9232
+ * `undefined` when the host reported no `lines` array at all.
9233
+ *
9234
+ * `undefined` and `[]` are deliberately different answers — see
9235
+ * `CartSnapshot.lines` (`@saar-ai/widget-bridge`). Absent means "this host
9236
+ * does not track lines" and the caller falls back to its own accumulation;
9237
+ * empty means "the cart is empty" and is rendered as such (i.e. no summary).
9238
+ *
9239
+ * Every field of a host line is optional, so the missing ones are given the
9240
+ * only neutral values a row can be drawn with (`quantity: 1`,
9241
+ * `priceMinor: 0`). A line with no `title` never reaches here — the bridge
9242
+ * drops it, because there is no row to draw without a name.
9243
+ */
9244
+ function cartLinesFromSnapshot(snapshot, currency) {
9245
+ if (!snapshot?.lines) return void 0;
9246
+ return snapshot.lines.map((line, index) => ({
9247
+ key: `host-${index}`,
9248
+ title: line.title ?? "",
9249
+ ...line.imageUrl !== void 0 ? { imageUrl: line.imageUrl } : {},
9250
+ priceMinor: line.unitPriceMinor ?? 0,
9251
+ currency,
9252
+ quantity: line.quantity ?? 1
9253
+ }));
9254
+ }
9255
+ /**
9256
+ * Where "Checkout" sends the shopper, and the order the two answers are
9257
+ * tried in.
9258
+ *
9259
+ * 1. **The host's own checkout** (`bridge.getCheckoutUrl`), when it has one.
9260
+ * It is the only answer that carries the shopper's WHOLE cart, including
9261
+ * whatever was in it before this conversation started.
9262
+ * 2. **A server-built permalink** (`POST /widget/checkout`), built from the
9263
+ * items the concierge itself recommended. It carries our own attribution
9264
+ * and is the better answer on a platform we can build a permalink for,
9265
+ * which is why `ShopifyBridge` deliberately implements no
9266
+ * `getCheckoutUrl`.
9267
+ *
9268
+ * Every failure of (1) — absent, `null`, throwing, non-`http(s)` — falls
9269
+ * through to (2) rather than surfacing, because a bridge that cannot answer
9270
+ * is exactly the case (2) exists for. `null` from BOTH is a real outcome and
9271
+ * is returned as such: `WidgetCartSummary`'s button renders its failure line
9272
+ * and stays pressable. It must never throw — the button's own `await` has no
9273
+ * catch, so a throw here is a permanent spinner.
9274
+ */
9275
+ async function resolveCheckoutUrl(bridge, startHandoff) {
9276
+ try {
9277
+ const hosted = await bridge?.getCheckoutUrl?.();
9278
+ if (typeof hosted === "string" && hosted.length > 0) return hosted;
9279
+ } catch {}
9280
+ try {
9281
+ return (await startHandoff())?.url ?? null;
9282
+ } catch {
9283
+ return null;
9284
+ }
9285
+ }
9286
+ /**
9287
+ * Where the call is, in the CALLER's terms — the mapping from the voice
9288
+ * session's own five-field state onto the one phase the mic control renders.
9289
+ *
9290
+ * Extracted from `ConciergeWidget` and written as early returns because the
9291
+ * precedence between these branches is the whole content of the mapping, and
9292
+ * a six-level nested ternary states it only by indentation. Reading order IS
9293
+ * the precedence order:
9294
+ *
9295
+ * - **Voice off** ⇒ `'idle'`. There is no call and no control.
9296
+ * - **`'connecting'` deliberately spans MORE than the transport's own
9297
+ * connecting phase**: it lasts from the press until the call is either
9298
+ * usable or definitively refused, which is exactly the window the mic
9299
+ * control draws a spinner for. Its second half is `micPending` — LiveKit
9300
+ * reports the room connected BEFORE the browser is asked for the
9301
+ * microphone, so the permission prompt sits open over `phase: 'connected'`,
9302
+ * and this mapping once called that a live call and handed the caller a
9303
+ * microphone they could not yet speak into. `micPending` therefore ranks
9304
+ * ABOVE `error`: an error left over from an earlier attempt must not end
9305
+ * a wait that is still genuinely open.
9306
+ * - **Refusal ends the wait**: the moment the browser says no, `micPending`
9307
+ * clears and an error with no open mic reads as `'blocked'` — ahead of
9308
+ * `state`, because a caller who cannot speak is not "waiting for the
9309
+ * agent to think".
9310
+ * - Otherwise the agent's own state decides: `'thinking'` ⇒ `'waiting'`,
9311
+ * anything else ⇒ `'live'`.
9312
+ */
9313
+ function deriveCallPhase(voice) {
9314
+ if (!voice.voiceEnabled) return "idle";
9315
+ if (voice.phase === "connecting") return "connecting";
9316
+ if (voice.phase !== "connected") return "idle";
9317
+ if (voice.micPending) return "connecting";
9318
+ if (voice.error !== null && !voice.micOpen) return "blocked";
9319
+ return voice.state === "thinking" ? "waiting" : "live";
9320
+ }
9321
+ /**
7473
9322
  * The plain React widget component — for a Next.js host (Phase 5's npm
7474
9323
  * package) that renders it directly, without the shadow-DOM mount
7475
9324
  * `mountConciergeWidget` performs for the CDN embed. Boots its own chat session
@@ -7505,7 +9354,7 @@ function buildCartLineContext(item) {
7505
9354
  * about offering voice here costs a byte until a caller actually presses
7506
9355
  * the microphone.
7507
9356
  */
7508
- function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, defaultOpen = false }) {
9357
+ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, defaultOpen = false, attribution }) {
7509
9358
  const [open, setOpen] = useState(defaultOpen);
7510
9359
  /**
7511
9360
  * Maps the tenant's semantic config fields onto the widget's historical
@@ -7551,8 +9400,85 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7551
9400
  chatToken
7552
9401
  }) } : {});
7553
9402
  const inCall = voiceEnabled && (voice.phase === "connecting" || voice.phase === "connected");
7554
- const onAddToCart = resolveAddToCartHandler(bridge, productHref);
7555
- const navigate = bridge?.navigate;
9403
+ /**
9404
+ * A PERSON holds this conversation — see `UseChatSessionResult.status`.
9405
+ *
9406
+ * Gates the voice leg at runtime, because voice is AI-only: the desk gives
9407
+ * an operator the TEXT transport (the socket, the `/widget/messages` poll)
9408
+ * and nothing joins the shopper's LiveKit room on their behalf. Read three
9409
+ * times below and in exactly one direction each — the handler refuses to
9410
+ * start a call, the effect ends one already running, and `VoiceWidget`
9411
+ * dims the control and says why. None of them touches
9412
+ * `session.modalities.voice`: the tenant's published capability is
9413
+ * unchanged, and the microphone returns by itself on de-escalation.
9414
+ */
9415
+ const escalated = session.status === "escalated";
9416
+ /**
9417
+ * The basket this widget built from its OWN adds — see `AddedCartLine`.
9418
+ * Always accumulated, even when the host has a `readCart` that reports
9419
+ * lines: the host read is asynchronous and can fail, and this is what the
9420
+ * summary falls back to when it does.
9421
+ */
9422
+ const [addedLines, setAddedLines] = useState([]);
9423
+ /** The host's own last answer, or `null` while it has given none. */
9424
+ const [hostCart, setHostCart] = useState(null);
9425
+ const mountedRef = useRef(true);
9426
+ useEffect(() => {
9427
+ mountedRef.current = true;
9428
+ return () => {
9429
+ mountedRef.current = false;
9430
+ };
9431
+ }, []);
9432
+ /**
9433
+ * Monotonic issue number for `refreshHostCart`, so a read can tell whether
9434
+ * a NEWER one was started after it. See that callback for why.
9435
+ *
9436
+ * A ref, not state: it must be readable and writable without a re-render,
9437
+ * and nothing renders from it.
9438
+ */
9439
+ const cartReadSeqRef = useRef(0);
9440
+ /**
9441
+ * Re-reads the host's cart. Silent on every failure — a bridge that cannot
9442
+ * answer leaves the last good snapshot (or `null`) standing, and the
9443
+ * summary falls back to `addedLines`. Never awaited by anything the
9444
+ * shopper is waiting on.
9445
+ *
9446
+ * **Only the LATEST-ISSUED read may set the snapshot.** Two triggers fire
9447
+ * this — a successful add, and a checkout intent — so overlapping reads are
9448
+ * ordinary, not a corner case, and `readCart` promises nothing about the
9449
+ * order they RESOLVE in (a host answering one from the network and the next
9450
+ * from a warm cache resolves them backwards). Without this guard the winner
9451
+ * is whichever resolves last, so a read issued BEFORE the add can land
9452
+ * after it and repaint the basket as it was before — the shopper then
9453
+ * checks out looking at a cart that is one add out of date. Comparing the
9454
+ * issue number, not a timestamp: it is exact, and it needs no clock.
9455
+ */
9456
+ const refreshHostCart = useCallback(async () => {
9457
+ if (!bridge?.readCart) return;
9458
+ const seq = ++cartReadSeqRef.current;
9459
+ try {
9460
+ const snapshot = await bridge.readCart();
9461
+ if (mountedRef.current && seq === cartReadSeqRef.current) setHostCart(snapshot);
9462
+ } catch {}
9463
+ }, [bridge]);
9464
+ const onAddToCart = resolveAddToCartHandler(bridge, productHref, useCallback((item) => {
9465
+ setAddedLines((prev) => mergeAddedCartLine(prev, item));
9466
+ refreshHostCart();
9467
+ if (chatToken === void 0 || inCall) return;
9468
+ session.sendReport({
9469
+ kind: "cart_add",
9470
+ title: item.title,
9471
+ quantity: 1,
9472
+ productId: item.productId,
9473
+ ...item.variantId !== void 0 ? { variantId: item.variantId } : {}
9474
+ });
9475
+ }, [
9476
+ chatToken,
9477
+ inCall,
9478
+ session,
9479
+ refreshHostCart
9480
+ ]));
9481
+ const navigate = useMemo(() => bridge?.navigate?.bind(bridge), [bridge]);
7556
9482
  const onSendText = useCallback(async (text) => session.send(text), [session]);
7557
9483
  /**
7558
9484
  * The microphone is the only control that starts the voice leg — a
@@ -7585,6 +9511,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7585
9511
  */
7586
9512
  const onToggleMic = useCallback(() => {
7587
9513
  if (!voiceEnabled) return;
9514
+ if (escalated) return;
7588
9515
  if (inCall) {
7589
9516
  voice.toggleMic();
7590
9517
  return;
@@ -7592,11 +9519,91 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7592
9519
  voice.start({ greet: true });
7593
9520
  }, [
7594
9521
  voiceEnabled,
9522
+ escalated,
7595
9523
  inCall,
7596
9524
  voice
7597
9525
  ]);
7598
- /** Where the call is, in the caller's terms — same mapping `apps/web`'s own `widget-launcher.tsx` uses for its call bar. */
7599
- const callPhase = !voiceEnabled ? "idle" : voice.phase === "connecting" ? "connecting" : voice.phase !== "connected" ? "idle" : voice.error !== null && !voice.micOpen ? "blocked" : voice.state === "thinking" ? "waiting" : "live";
9526
+ /**
9527
+ * A call that outlives the handoff is a shopper talking to an AI leg the
9528
+ * person on the other end cannot hear, so the escalation ENDS it.
9529
+ *
9530
+ * The mid-call handoff is reachable, not theoretical: the composer only
9531
+ * DIMS during a call (`ConciergeShell`, `inCall && draft === ''` → an
9532
+ * opacity class, never `disabled`), so a shopper can type "get me a human"
9533
+ * while the call runs and `POST /widget/chat` answers with the SSE
9534
+ * `escalated` event — and the voice leg's own data channel carries a
9535
+ * `{ type: 'escalated' }` widget event (`WidgetToolEventSchema`) for the
9536
+ * same handoff asked for out loud.
9537
+ *
9538
+ * Depends on `voice.stop` rather than `voice`: the session object is a new
9539
+ * literal on every render of `useVoiceSession`, and an effect keyed on it
9540
+ * would re-run — and re-`stop()` — for the whole life of the escalated
9541
+ * conversation. `stop` is a `useCallback`, so this fires once per
9542
+ * escalation, and nothing here fights a caller who starts a fresh call
9543
+ * after de-escalation.
9544
+ */
9545
+ const stopVoice = voice.stop;
9546
+ useEffect(() => {
9547
+ if (!escalated || !inCall) return;
9548
+ stopVoice();
9549
+ }, [
9550
+ escalated,
9551
+ inCall,
9552
+ stopVoice
9553
+ ]);
9554
+ /**
9555
+ * The handoff asked for OUT LOUD, carried into the typed session.
9556
+ *
9557
+ * `useChatSession` learns of an escalation on its own transports only (the
9558
+ * SSE `escalated` frame, `sendAttachment`, the desk socket). A shopper who
9559
+ * says "get me a person" mid-call escalates on the VOICE leg instead — the
9560
+ * worker writes `{ type: 'escalated' }` to the LiveKit data channel and
9561
+ * `useVoiceSession` parses it into `widgetEvents`. This is the ONE hop that
9562
+ * joins the two: without it `escalated` above stayed false after a spoken
9563
+ * handoff, so the microphone gate, the attach control and the transcript
9564
+ * marker all waited for the shopper to ALSO type something.
9565
+ *
9566
+ * **Reacts to the EVENT, never to the contents of the list.** `widgetEvents`
9567
+ * is append-only and `stop()` does not clear it — the last call's cards stay
9568
+ * on screen — so `widgetEvents.some((e) => e.type === 'escalated')` would be
9569
+ * a boolean that can only ever turn on, and a shopper de-escalated back to
9570
+ * the AI would be re-escalated by the corpse of the call before it.
9571
+ *
9572
+ * **Consumed by IDENTITY, not by an index.** The hook caps the list
9573
+ * (`MAX_WIDGET_EVENTS`, a sliding `slice(-20)`), so a "how many have I
9574
+ * consumed" counter drifts past new entries the moment the cap is reached
9575
+ * and silently stops escalating. The parsed events are distinct objects
9576
+ * (`WidgetToolEventSchema.safeParse` mints one per frame), which makes
9577
+ * "have I already acted on THIS one" exact under both the cap and a
9578
+ * restart. A `WeakSet` because nothing here should keep a dropped event
9579
+ * alive.
9580
+ *
9581
+ * Not gated on `voiceEnabled`: an escalation frame is a fact the server
9582
+ * asserted about the conversation, and a tenant config that flips mid-call
9583
+ * must not be able to swallow it. `markHandoffToHuman` is idempotent and
9584
+ * stable (see `UseChatSessionResult.markHandoffToHuman`), so this fires once
9585
+ * per frame and a repeat costs nothing.
9586
+ */
9587
+ const markHandoffToHuman = session.markHandoffToHuman;
9588
+ const consumedVoiceEventsRef = useRef(/* @__PURE__ */ new WeakSet());
9589
+ useEffect(() => {
9590
+ let handoff = false;
9591
+ for (const event of voice.widgetEvents) {
9592
+ if (consumedVoiceEventsRef.current.has(event)) continue;
9593
+ consumedVoiceEventsRef.current.add(event);
9594
+ if (event.type === "escalated") handoff = true;
9595
+ }
9596
+ if (handoff) markHandoffToHuman();
9597
+ }, [voice.widgetEvents, markHandoffToHuman]);
9598
+ /** Where the call is, in the caller's terms — see `deriveCallPhase`. */
9599
+ const callPhase = deriveCallPhase({
9600
+ voiceEnabled,
9601
+ phase: voice.phase,
9602
+ micPending: voice.micPending,
9603
+ micOpen: voice.micOpen,
9604
+ error: voice.error,
9605
+ state: voice.state
9606
+ });
7600
9607
  /**
7601
9608
  * One conversation. Simpler than `apps/web`'s own merge
7602
9609
  * (`widget-launcher.tsx`'s `widgetTurns`): this component does not
@@ -7613,6 +9620,8 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7613
9620
  text: turn.text,
7614
9621
  locale,
7615
9622
  final: turn.final,
9623
+ ...turn.event ? { event: turn.event } : {},
9624
+ ...turn.delivery ? { delivery: turn.delivery } : {},
7616
9625
  ...turn.cards ? { cards: turn.cards } : {},
7617
9626
  ...turn.attachments ? { attachments: turn.attachments } : {}
7618
9627
  }));
@@ -7647,6 +9656,57 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7647
9656
  voiceEnabled,
7648
9657
  locale
7649
9658
  ]);
9659
+ /**
9660
+ * The SAME read `VoiceWidget` makes to decide whether to draw the summary —
9661
+ * literally the same function (`checkoutIntentFromTurns`), not a second
9662
+ * copy of it — put to a different use here: this is the moment to re-read
9663
+ * the host's cart, so the basket the shopper is about to check out with is
9664
+ * the one that exists NOW and not the one that existed at the last add.
9665
+ * Reading the merged turns rather than `session.turns` alone is what makes
9666
+ * a SPOKEN "let's check out" refresh too.
9667
+ */
9668
+ const wantsCheckout = useMemo(() => checkoutIntentFromTurns(widgetTurns), [widgetTurns]);
9669
+ useEffect(() => {
9670
+ if (wantsCheckout) refreshHostCart();
9671
+ }, [wantsCheckout, refreshHostCart]);
9672
+ /**
9673
+ * The host's answer wins wherever it HAS one, and the widget's own
9674
+ * accumulation covers the rest:
9675
+ *
9676
+ * - `lines` — the host's basket is the real one, so it replaces this
9677
+ * widget's outright. Absent (never reported) falls back to `addedLines`;
9678
+ * an EMPTY array does not, because "the cart is empty" is a real answer
9679
+ * and rendering our own stale rows over it would be a lie.
9680
+ * - `subtotalCents` — the host's total survives discounts and bundle
9681
+ * pricing that multiplying a unit price by a quantity cannot reproduce.
9682
+ * - `currency` — likewise the host's, falling back to whatever the cards
9683
+ * themselves were priced in.
9684
+ */
9685
+ const cartCurrency = hostCart?.currency ?? addedLines[0]?.currency ?? "USD";
9686
+ const cartLines = useMemo(() => cartLinesFromSnapshot(hostCart, cartCurrency), [hostCart, cartCurrency]) ?? addedLines;
9687
+ const cartSubtotalMinor = hostCart?.subtotalCents ?? cartLines.reduce((total, line) => total + line.priceMinor * line.quantity, 0);
9688
+ /**
9689
+ * Fire the checkout. `undefined` (rather than an `onCheckout` that always
9690
+ * fails) whenever there is no basket at all, so `VoiceWidget` renders no
9691
+ * summary — the same "additive per caller" posture `onAddToCart` keeps.
9692
+ */
9693
+ const onCheckout = useCallback(async () => {
9694
+ const items = addedLines.filter((line) => line.variantId !== void 0).map((line) => ({
9695
+ variantId: line.variantId,
9696
+ quantity: line.quantity
9697
+ }));
9698
+ return resolveCheckoutUrl(bridge, () => session.checkout(items, void 0, session.cartAttributionToken ?? void 0));
9699
+ }, [
9700
+ addedLines,
9701
+ bridge,
9702
+ session
9703
+ ]);
9704
+ const cart = cartLines.length > 0 ? {
9705
+ lines: cartLines,
9706
+ subtotalMinor: cartSubtotalMinor,
9707
+ currency: cartCurrency,
9708
+ onCheckout
9709
+ } : void 0;
7650
9710
  return /* @__PURE__ */ jsx(VoiceWidget, {
7651
9711
  state: inCall ? voice.state : "idle",
7652
9712
  turns: widgetTurns,
@@ -7660,9 +9720,10 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7660
9720
  onSendText,
7661
9721
  open,
7662
9722
  onOpenChange: setOpen,
7663
- escalated: session.status === "escalated",
9723
+ escalated,
7664
9724
  status: session.status === "error" ? session.error ?? "error" : voiceEnabled ? voice.error ?? void 0 : void 0,
7665
9725
  ...onAddToCart ? { onAddToCart } : {},
9726
+ ...cart ? { cart } : {},
7666
9727
  ...curationHref ? { curationHref } : {},
7667
9728
  ...productHref ? { productHref } : {},
7668
9729
  ...navigate ? { navigate } : {},
@@ -7670,8 +9731,10 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
7670
9731
  locale,
7671
9732
  ...session.launcher.label !== void 0 ? { launcherLabel: session.launcher.label } : {},
7672
9733
  ...session.launcher.position !== void 0 ? { position: session.launcher.position } : {},
7673
- ...skinStyle !== void 0 ? { skinStyle } : {}
9734
+ ...skinStyle !== void 0 ? { skinStyle } : {},
9735
+ ...avatar !== void 0 ? { avatar } : {},
9736
+ ...attribution !== void 0 ? { attribution } : {}
7674
9737
  });
7675
9738
  }
7676
9739
  //#endregion
7677
- export { CONCIERGE_POSITIONS as A, defaultWidgetMessages as C, ConciergeShell as D, widgetMessagesFromCopy as E, panelClasses as F, positionClasses as I, positionForArrow as L, alignOf as M, edgeOf as N, MorphingLoader as O, nearestPosition as P, BotFace as R, latencyBetween as S, resolveWidgetMessages as T, botStateFor as _, useVoiceSession as a, SessionLog as b, VoiceWidget as c, WidgetCartSummary as d, WidgetCardList as f, IDLE_SNAPSHOT as g, parseBlocks as h, createWidgetVoiceTokenFetcher as i, DEFAULT_CONCIERGE_POSITION as j, ConciergeLauncher as k, readsAsCheckoutIntent as l, WidgetMarkdown as m, resolveAddToCartHandler as n, useChatSession as o, formatMoney as p, ROOM_EVENTS as r, detectPage as s, ConciergeWidget as t, textDirectionFor as u, SseFrameParser as v, formatMessage as w, formatMs as x, SESSION_EVENTS as y, cn as z };
9740
+ export { defaultWidgetMessages as A, panelClasses as B, SseFrameParser as C, latencyBetween as D, formatMs as E, CONCIERGE_POSITIONS as F, isWidgetAvatar as G, positionForArrow as H, DEFAULT_CONCIERGE_POSITION as I, labelProps as J, RopeKnot as K, alignOf as L, resolveWidgetMessages as M, widgetMessagesFromCopy as N, ConciergeShell as O, ConciergeLauncher as P, edgeOf as R, botStateFor as S, SessionLog as T, DEFAULT_WIDGET_AVATAR as U, positionClasses as V, WIDGET_AVATARS as W, cn as Y, WidgetCardList as _, resolveAddToCartHandler as a, parseBlocks as b, createWidgetVoiceTokenFetcher as c, detectPage as d, VoiceWidget as f, WidgetCartSummary as g, textDirectionFor as h, mergeAddedCartLine as i, formatMessage as j, MorphingLoader as k, useVoiceSession as l, readsAsCheckoutIntent as m, cartLinesFromSnapshot as n, resolveCheckoutUrl as o, checkoutIntentFromTurns as p, BotFace as q, deriveCallPhase as r, ROOM_EVENTS as s, ConciergeWidget as t, useChatSession as u, formatMoney as v, SESSION_EVENTS as w, IDLE_SNAPSHOT as x, WidgetMarkdown as y, nearestPosition as z };