@saar-ai/web-widget 0.3.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.
@@ -4483,7 +4483,8 @@ var defaultWidgetMessages = {
4483
4483
  voice_state_connecting: "Connecting",
4484
4484
  voice_state_listening: "Listening",
4485
4485
  voice_state_thinking: "Thinking",
4486
- voice_state_speaking: "Speaking"
4486
+ voice_state_speaking: "Speaking",
4487
+ voice_unavailable_escalated: "Voice is unavailable while you’re talking to a person"
4487
4488
  };
4488
4489
  /**
4489
4490
  * Interpolates `{token}` placeholders in a message template. Deliberately the
@@ -4630,7 +4631,43 @@ function MorphingLoader({ size = "md", variant = "brand", className, label = "Lo
4630
4631
  });
4631
4632
  }
4632
4633
  //#endregion
4633
- //#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
+ */
4634
4671
  /**
4635
4672
  * Top ramp when the transcript starts at the panel's top, under the floating
4636
4673
  * orb — it has to span the orb, so a message is gone before it reaches it
@@ -4640,16 +4677,23 @@ function MorphingLoader({ size = "md", variant = "brand", className, label = "Lo
4640
4677
  * (`w-[min(97vw,50dvh)]` + `aspect-[5/8]`) ranges from ~582px tall (mobile,
4641
4678
  * width-bound) to 800px+ (desktop, height-bound) — a fixed 112px clearance
4642
4679
  * tuned for the OLD fixed-520px panel left too little air under the orb on a
4643
- * tall one and too much on a short one. `max(112px, 14cqh)` is a floor, not a
4644
- * fixed value: it stays exactly 112px (today's tuned figure) on a short
4645
- * panel, where 14cqh would fall below it, and grows with `cqh` — the query
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
4646
4683
  * container's own height, established by `[container-type:size]` on the
4647
- * panel div below — once the panel is tall enough that 14% of it exceeds
4684
+ * panel div below — once the panel is tall enough that 19.24% of it exceeds
4648
4685
  * 112px. `cqh` rather than `dvh` specifically: the panel's real rendered
4649
4686
  * height, not the viewport's, since the panel does not always fill the
4650
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.
4651
4695
  */
4652
- var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 14cqh)";
4696
+ var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 19.24cqh)";
4653
4697
  /**
4654
4698
  * Top ramp when a `badge` sits above the transcript.
4655
4699
  *
@@ -4662,9 +4706,133 @@ var TRANSCRIPT_FADE_TOP_LEN = "max(112px, 14cqh)";
4662
4706
  * scroll-edge length. Same floor+`cqh` scheme as {@link TRANSCRIPT_FADE_TOP_LEN}
4663
4707
  * above and for the same reason — this ramp needs to soften proportionally
4664
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.
4754
+ */
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.
4665
4832
  */
4666
- var TRANSCRIPT_FADE_TOP_WITH_BADGE_LEN = "max(28px, 4cqh)";
4667
- var TRANSCRIPT_FADE_BOTTOM_LEN = "max(118px, 15cqh)";
4833
+ var COMPOSER_GROUND_LEN = "max(132px, 22.68cqh)";
4834
+ //#endregion
4835
+ //#region src/concierge-shell.tsx
4668
4836
  /**
4669
4837
  * How far off the bottom still counts as "following the conversation".
4670
4838
  *
@@ -4699,6 +4867,12 @@ var FOLLOW_TOLERANCE_PX = 24;
4699
4867
  * that clearance is what `TRANSCRIPT_FADE_BOTTOM_LEN` (the transition point
4700
4868
  * this taper starts from, and the padding below) controls, and that is what
4701
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.
4702
4876
  */
4703
4877
  function transcriptEdgeFade(topLen) {
4704
4878
  const at = (fraction) => `calc(${topLen} * ${fraction})`;
@@ -4720,7 +4894,8 @@ function transcriptEdgeFade(topLen) {
4720
4894
  maskImage: gradient,
4721
4895
  WebkitMaskImage: gradient,
4722
4896
  paddingTop: topLen,
4723
- paddingBottom: TRANSCRIPT_FADE_BOTTOM_LEN
4897
+ paddingBottom: TRANSCRIPT_FADE_BOTTOM_LEN,
4898
+ paddingInline: TRANSCRIPT_INSET_X
4724
4899
  };
4725
4900
  }
4726
4901
  /** Both variants built once — neither depends on props beyond badge presence. */
@@ -4943,8 +5118,38 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, ava
4943
5118
  * how to draw — see `voiceStatePillState`'s own doc comment).
4944
5119
  */
4945
5120
  const voicePillState = voiceStatePillState(voice);
4946
- /** Start, mute or unmute — whichever the one round control means right now. */
4947
- const micLabel = inCall ? (voice?.muted === true ? voice.labels.unmute : voice.labels.mute) ?? voice.labels.start : voice?.labels.start ?? "";
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 ?? "";
4948
5153
  const submit = (e) => {
4949
5154
  e.preventDefault();
4950
5155
  if (!draft.trim() || composerDisabled) return;
@@ -5051,7 +5256,7 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, ava
5051
5256
  }),
5052
5257
  /* @__PURE__ */ jsx("div", {
5053
5258
  ref: transcriptRef,
5054
- className: "no-scrollbar w-full min-h-0 flex-1 overflow-y-auto px-2",
5259
+ className: "no-scrollbar w-full min-h-0 flex-1 overflow-y-auto",
5055
5260
  style: badge == null ? TRANSCRIPT_EDGE_FADE : TRANSCRIPT_EDGE_FADE_WITH_BADGE,
5056
5261
  children: /* @__PURE__ */ jsx("div", {
5057
5262
  ref: transcriptContentRef,
@@ -5060,12 +5265,15 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, ava
5060
5265
  }),
5061
5266
  /* @__PURE__ */ jsx("div", {
5062
5267
  "aria-hidden": true,
5063
- 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))]"
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 }
5064
5270
  }),
5065
5271
  /* @__PURE__ */ jsx("div", {
5066
- className: "pointer-events-none absolute inset-x-0 bottom-1.5 z-20 flex justify-center",
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 },
5067
5274
  children: /* @__PURE__ */ jsxs("div", {
5068
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 },
5069
5277
  children: [/* @__PURE__ */ jsxs("form", {
5070
5278
  className: "flex w-full items-center gap-2",
5071
5279
  onSubmit: submit,
@@ -5101,14 +5309,24 @@ function ConciergeShell({ open, onOpenChange, state, messageArrived = false, ava
5101
5309
  className: "mt-1 flex items-center gap-3",
5102
5310
  children: [/* @__PURE__ */ jsx("button", {
5103
5311
  type: "button",
5104
- onClick: inCall ? voice.onToggleMute ?? voice.onStart : voice.onStart,
5105
- disabled: voice.disabled || voice.phase === "blocked",
5312
+ onClick: connecting ? void 0 : inCall ? voice.onToggleMute ?? voice.onStart : voice.onStart,
5313
+ disabled: micUnusable || connecting,
5106
5314
  "data-testid": testIds?.mic,
5107
5315
  title: micLabel,
5108
5316
  "aria-label": micLabel,
5109
- ...inCall ? { "aria-pressed": voice.muted ?? false } : {},
5110
- 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", 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"),
5111
- children: inCall && voice.muted === true ? /* @__PURE__ */ jsx(MicOff, { className: "size-5" }) : /* @__PURE__ */ jsx(Mic, { className: "size-5" })
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" })
5112
5330
  }), inCall && voice.onEnd !== void 0 ? /* @__PURE__ */ jsx("button", {
5113
5331
  type: "button",
5114
5332
  onClick: voice.onEnd,
@@ -5338,6 +5556,7 @@ function parseFrame(raw) {
5338
5556
  var IDLE_SNAPSHOT = {
5339
5557
  phase: "idle",
5340
5558
  micPublished: false,
5559
+ micPending: false,
5341
5560
  agentPresent: false,
5342
5561
  agentSpeaking: false,
5343
5562
  callerSpeaking: false,
@@ -6210,6 +6429,28 @@ function readsAsCheckoutIntent(text) {
6210
6429
  ].some((phrase) => t.includes(phrase));
6211
6430
  }
6212
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
+ /**
6213
6454
  * The end-user agent widget: a launcher bubble that expands into a conversation
6214
6455
  * with both a microphone and a text box.
6215
6456
  *
@@ -6246,14 +6487,34 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
6246
6487
  const fileInputRef = useRef(null);
6247
6488
  const showMic = mode !== "text";
6248
6489
  /**
6249
- * 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.
6250
6498
  *
6251
- * Most recent, not "any line ever": once they carry on shopping past the
6252
- * summary the basket should get out of the way again, and a sticky flag
6253
- * 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.
6254
6507
  */
6255
- const lastCallerLine = [...turns].reverse().find((turn) => turn.speaker === "caller");
6256
- 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);
6257
6518
  const onFileSelected = async (event) => {
6258
6519
  const file = event.target.files?.[0];
6259
6520
  event.target.value = "";
@@ -6322,6 +6583,7 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
6322
6583
  ...onEndCall !== void 0 ? { onEnd: onEndCall } : {},
6323
6584
  onToggleMute: onToggleMic,
6324
6585
  muted: !micOpen,
6586
+ ...voiceUnavailable !== void 0 ? { disabled: true } : {},
6325
6587
  labels: {
6326
6588
  start: messages.mic_start,
6327
6589
  end: messages.call_end,
@@ -6330,7 +6592,8 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
6330
6592
  connecting: messages.voice_state_connecting,
6331
6593
  listening: messages.voice_state_listening,
6332
6594
  thinking: messages.voice_state_thinking,
6333
- speaking: messages.voice_state_speaking
6595
+ speaking: messages.voice_state_speaking,
6596
+ ...voiceUnavailable !== void 0 ? { unavailable: voiceUnavailable } : {}
6334
6597
  }
6335
6598
  } : void 0,
6336
6599
  composerLeading: onAttachFile && escalated ? /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -6371,10 +6634,10 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
6371
6634
  })]
6372
6635
  })
6373
6636
  ] }) : null,
6374
- badge: status === void 0 ? null : /* @__PURE__ */ jsx("p", {
6637
+ badge: statusLine === void 0 ? null : /* @__PURE__ */ jsx("p", {
6375
6638
  "data-testid": "widget-status",
6376
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)]",
6377
- children: status
6640
+ children: statusLine
6378
6641
  }),
6379
6642
  testIds: {
6380
6643
  trigger: "voice-widget-launcher",
@@ -6838,6 +7101,123 @@ var DESK_MESSAGE_EVENT = "desk:message";
6838
7101
  /** Must equal the namespace `WidgetGateway` (`apps/api/src/realtime/widget.gateway.ts`) is mounted on. */
6839
7102
  var SOCKET_NAMESPACE = "/widget";
6840
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
+ /**
6841
7221
  * Neutral key names — see apps/web/AGENTS.md branding guardrail. Both are
6842
7222
  * first-party, non-cryptographic-on-this-side values: `visitorId` only needs
6843
7223
  * to survive a page reload, and `visitorProof` is the OPAQUE, server-signed
@@ -6889,7 +7269,7 @@ function useChatSession(options) {
6889
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;
6890
7270
  const fetchImpl = options.fetchImpl ?? fetch;
6891
7271
  const socketFactory = options.socketImpl;
6892
- const now = options.now ?? (() => Date.now());
7272
+ const now = useMemo(() => options.now ?? (() => Date.now()), []);
6893
7273
  const [turns, setTurns] = useState([]);
6894
7274
  /**
6895
7275
  * The tenant's collapsed-widget config, once the session has booted.
@@ -6916,6 +7296,22 @@ function useChatSession(options) {
6916
7296
  const [error, setError] = useState(void 0);
6917
7297
  const [ready, setReady] = useState(false);
6918
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);
6919
7315
  const chatTokenRef = useRef(void 0);
6920
7316
  const lastSeqRef = useRef(0);
6921
7317
  /** Every `seq` already rendered, from EITHER path — the actual dedupe guard; see the module doc comment. */
@@ -7006,11 +7402,58 @@ function useChatSession(options) {
7006
7402
  * happened.
7007
7403
  */
7008
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(() => {});
7009
7451
  useEffect(() => {
7010
7452
  mountedRef.current = true;
7011
7453
  return () => {
7012
7454
  mountedRef.current = false;
7013
7455
  if (pollTimerRef.current !== void 0) clearInterval(pollTimerRef.current);
7456
+ if (refreshTimerRef.current !== void 0) clearTimeout(refreshTimerRef.current);
7014
7457
  socketRef.current?.disconnect();
7015
7458
  };
7016
7459
  }, []);
@@ -7055,7 +7498,10 @@ function useChatSession(options) {
7055
7498
  *
7056
7499
  * Appended once per session, guarded by `handoffEventAppendedRef`: the
7057
7500
  * conversation is handed over once, however many times the transport
7058
- * re-reports it.
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.
7059
7505
  *
7060
7506
  * The id is a fixed literal, not a generated one, because there is at most
7061
7507
  * one of these per session — and a stable id keeps this row from ever
@@ -7102,6 +7548,174 @@ function useChatSession(options) {
7102
7548
  pollIntervalRef.current = intervalMs;
7103
7549
  pollTimerRef.current = setInterval(() => void poll(), intervalMs);
7104
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
+ ]);
7105
7719
  useEffect(() => {
7106
7720
  let cancelled = false;
7107
7721
  if (!embedKey) {
@@ -7112,47 +7726,10 @@ function useChatSession(options) {
7112
7726
  }
7113
7727
  (async () => {
7114
7728
  try {
7115
- const stored = readStoredVisitor();
7116
- const bootRequestedAt = now();
7117
- const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/session`, embedKey), {
7118
- method: "POST",
7119
- headers: { "content-type": "application/json" },
7120
- body: JSON.stringify({
7121
- embedKey,
7122
- attribution,
7123
- ...stored.visitorId ? { visitorId: stored.visitorId } : {},
7124
- ...stored.visitorProof ? { visitorProof: stored.visitorProof } : {}
7125
- })
7126
- });
7127
- if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
7128
- const body = await res.json();
7129
- if (cancelled) return;
7130
- chatTokenRef.current = body.chatToken;
7131
- setChatToken(body.chatToken);
7132
- visitorSessionIdRef.current = body.visitorSessionId;
7133
- sessionOriginRef.current = bootRequestedAt;
7134
- setModalities({
7135
- text: body.modalities?.text ?? true,
7136
- voice: body.modalities?.voice ?? false
7137
- });
7138
- persistVisitor(body.visitorId, body.visitorProof);
7139
- if (collector && body.visitorSessionId !== void 0 && body.expiresAt !== void 0) collector.setSession({
7140
- chatToken: body.chatToken,
7141
- visitorSessionId: body.visitorSessionId,
7142
- expiresAt: Date.parse(body.expiresAt)
7143
- });
7144
- if (body.greeting) setTurns([{
7145
- id: "greeting",
7146
- speaker: "agent",
7147
- text: body.greeting,
7148
- final: true
7149
- }]);
7150
- setLauncher({
7151
- ...body.launcher?.label !== void 0 ? { label: body.launcher.label } : {},
7152
- ...isConciergePosition(body.launcher?.position) ? { position: body.launcher.position } : {},
7153
- ...typeof body.launcher?.draggable === "boolean" ? { draggable: body.launcher.draggable } : {}
7729
+ await bootSession({
7730
+ phase: "mount",
7731
+ isStale: () => cancelled
7154
7732
  });
7155
- setStatus("idle");
7156
7733
  } catch (err) {
7157
7734
  if (cancelled) return;
7158
7735
  setStatus("error");
@@ -7165,10 +7742,184 @@ function useChatSession(options) {
7165
7742
  cancelled = true;
7166
7743
  };
7167
7744
  }, []);
7168
- useEffect(() => {
7169
- if (!socketUrl || !ready || status !== "escalated") return;
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 () => {
7170
7808
  const chatToken = chatTokenRef.current;
7171
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();
7916
+ };
7917
+ document.addEventListener("visibilitychange", onVisibilityChange);
7918
+ return () => document.removeEventListener("visibilitychange", onVisibilityChange);
7919
+ }, [runRefresh]);
7920
+ useEffect(() => {
7921
+ if (!socketUrl || !ready || status !== "escalated") return;
7922
+ if (chatTokenRef.current === void 0) return;
7172
7923
  let cancelled = false;
7173
7924
  setConnection("connecting");
7174
7925
  (async () => {
@@ -7177,7 +7928,7 @@ function useChatSession(options) {
7177
7928
  const socket = factory(`${socketUrl}${SOCKET_NAMESPACE}`, {
7178
7929
  path: socketPath,
7179
7930
  transports: ["polling", "websocket"],
7180
- extraHeaders: { Authorization: `Bearer ${chatToken}` },
7931
+ extraHeaders: socketAuthHeadersRef.current,
7181
7932
  withCredentials: false,
7182
7933
  reconnection: true
7183
7934
  });
@@ -7206,7 +7957,8 @@ function useChatSession(options) {
7206
7957
  ready,
7207
7958
  status,
7208
7959
  socketFactory,
7209
- mergeIncoming
7960
+ mergeIncoming,
7961
+ bootGeneration
7210
7962
  ]);
7211
7963
  useEffect(() => {
7212
7964
  if (status !== "escalated") return;
@@ -7218,14 +7970,27 @@ function useChatSession(options) {
7218
7970
  pollIntervalMs,
7219
7971
  idlePollIntervalMs
7220
7972
  ]);
7221
- const send = useCallback(async (text, options) => {
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) => {
7222
7985
  const chatToken = chatTokenRef.current;
7223
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);
7224
7989
  const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
7225
7990
  const agentTurnId = `agent-${callerTurnId}`;
7226
7991
  setTurns((prev) => [
7227
7992
  ...prev,
7228
- ...options?.silent ? [] : [{
7993
+ ...silent ? [] : [{
7229
7994
  id: callerTurnId,
7230
7995
  speaker: "caller",
7231
7996
  text,
@@ -7251,7 +8016,7 @@ function useChatSession(options) {
7251
8016
  "content-type": "application/json",
7252
8017
  authorization: `Bearer ${chatToken}`
7253
8018
  },
7254
- body: JSON.stringify({ message: text })
8019
+ body: JSON.stringify(payload)
7255
8020
  });
7256
8021
  } catch {
7257
8022
  rollBack();
@@ -7310,6 +8075,8 @@ function useChatSession(options) {
7310
8075
  status,
7311
8076
  markHandoffToHuman
7312
8077
  ]);
8078
+ const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
8079
+ const sendReport = useCallback(async (report) => postTurn({ report }), [postTurn]);
7313
8080
  const sendEvent = useCallback(async (events) => {
7314
8081
  const chatToken = chatTokenRef.current;
7315
8082
  if (chatToken === void 0 || events.length === 0) return false;
@@ -7456,7 +8223,7 @@ function useChatSession(options) {
7456
8223
  const reportReceipts = () => {
7457
8224
  const delivered = deliveredTurnIdsRef.current;
7458
8225
  const read = readTurnIdsRef.current;
7459
- const visible = typeof document === "undefined" || document.visibilityState === "visible";
8226
+ const visible = isTabVisible();
7460
8227
  const kinds = [];
7461
8228
  let sawNewDelivery = false;
7462
8229
  let sawNewRead = false;
@@ -7493,6 +8260,7 @@ function useChatSession(options) {
7493
8260
  ready,
7494
8261
  connection,
7495
8262
  send,
8263
+ sendReport,
7496
8264
  sendEvent,
7497
8265
  checkout: useCallback(async (items, curationId, cartAttributionToken) => {
7498
8266
  const chatToken = chatTokenRef.current;
@@ -7588,7 +8356,8 @@ function useChatSession(options) {
7588
8356
  embedKey,
7589
8357
  fetchImpl,
7590
8358
  markHandoffToHuman
7591
- ])
8359
+ ]),
8360
+ markHandoffToHuman
7592
8361
  };
7593
8362
  }
7594
8363
  /**
@@ -7674,7 +8443,7 @@ async function streamReply(args) {
7674
8443
  * cache makes a second `start()` after `stop()` free).
7675
8444
  */
7676
8445
  async function loadVoiceProtocol() {
7677
- 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")]);
7678
8447
  return {
7679
8448
  decodeTelemetry: telemetry.decodeTelemetry,
7680
8449
  encodeCallerText: telemetry.encodeCallerText,
@@ -8083,7 +8852,8 @@ function useVoiceSession(options = {}) {
8083
8852
  setError(null);
8084
8853
  setSnapshot({
8085
8854
  ...IDLE_SNAPSHOT,
8086
- phase: "connecting"
8855
+ phase: "connecting",
8856
+ micPending: true
8087
8857
  });
8088
8858
  logRef.current?.clear();
8089
8859
  setEvents([]);
@@ -8227,7 +8997,8 @@ function useVoiceSession(options = {}) {
8227
8997
  record("mic_published");
8228
8998
  setSnapshot((s) => ({
8229
8999
  ...s,
8230
- micPublished: true
9000
+ micPublished: true,
9001
+ micPending: false
8231
9002
  }));
8232
9003
  } catch (micError) {
8233
9004
  const reason = micError instanceof Error ? micError.message : String(micError);
@@ -8235,7 +9006,8 @@ function useVoiceSession(options = {}) {
8235
9006
  setError(`microphone unavailable: ${reason}`);
8236
9007
  setSnapshot((s) => ({
8237
9008
  ...s,
8238
- micPublished: false
9009
+ micPublished: false,
9010
+ micPending: false
8239
9011
  }));
8240
9012
  }
8241
9013
  } catch (cause) {
@@ -8339,6 +9111,7 @@ function useVoiceSession(options = {}) {
8339
9111
  state: botStateFor(snapshot),
8340
9112
  phase: snapshot.phase,
8341
9113
  micOpen: snapshot.micPublished,
9114
+ micPending: snapshot.micPending,
8342
9115
  error,
8343
9116
  events,
8344
9117
  agentLevel,
@@ -8387,7 +9160,7 @@ function useVoiceSession(options = {}) {
8387
9160
  * resolve a bare id into a title/price/image the way a real platform's
8388
9161
  * own cart API does.
8389
9162
  */
8390
- function resolveAddToCartHandler(bridge, productHref) {
9163
+ function resolveAddToCartHandler(bridge, productHref, onAdded) {
8391
9164
  if (!bridge) return void 0;
8392
9165
  const canAddToCart = bridge.addToCart !== void 0;
8393
9166
  const canNavigateToPdp = bridge.navigate !== void 0 && productHref !== void 0;
@@ -8398,6 +9171,7 @@ function resolveAddToCartHandler(bridge, productHref) {
8398
9171
  if (bridge.addToCart && cartId) try {
8399
9172
  if (idSpace === "catalog") await bridge.addToCart(cartId, 1, buildCartLineContext(item));
8400
9173
  else await bridge.addToCart(cartId, 1);
9174
+ onAdded?.(item);
8401
9175
  return;
8402
9176
  } catch (err) {
8403
9177
  if (bridge.navigate && productHref && item.handle) {
@@ -8426,6 +9200,125 @@ function buildCartLineContext(item) {
8426
9200
  };
8427
9201
  }
8428
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
+ /**
8429
9322
  * The plain React widget component — for a Next.js host (Phase 5's npm
8430
9323
  * package) that renders it directly, without the shadow-DOM mount
8431
9324
  * `mountConciergeWidget` performs for the CDN embed. Boots its own chat session
@@ -8507,7 +9400,84 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8507
9400
  chatToken
8508
9401
  }) } : {});
8509
9402
  const inCall = voiceEnabled && (voice.phase === "connecting" || voice.phase === "connected");
8510
- const onAddToCart = resolveAddToCartHandler(bridge, productHref);
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
+ ]));
8511
9481
  const navigate = useMemo(() => bridge?.navigate?.bind(bridge), [bridge]);
8512
9482
  const onSendText = useCallback(async (text) => session.send(text), [session]);
8513
9483
  /**
@@ -8541,6 +9511,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8541
9511
  */
8542
9512
  const onToggleMic = useCallback(() => {
8543
9513
  if (!voiceEnabled) return;
9514
+ if (escalated) return;
8544
9515
  if (inCall) {
8545
9516
  voice.toggleMic();
8546
9517
  return;
@@ -8548,11 +9519,91 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8548
9519
  voice.start({ greet: true });
8549
9520
  }, [
8550
9521
  voiceEnabled,
9522
+ escalated,
8551
9523
  inCall,
8552
9524
  voice
8553
9525
  ]);
8554
- /** Where the call is, in the caller's terms — same mapping `apps/web`'s own `widget-launcher.tsx` uses for its call bar. */
8555
- 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
+ });
8556
9607
  /**
8557
9608
  * One conversation. Simpler than `apps/web`'s own merge
8558
9609
  * (`widget-launcher.tsx`'s `widgetTurns`): this component does not
@@ -8605,6 +9656,57 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8605
9656
  voiceEnabled,
8606
9657
  locale
8607
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;
8608
9710
  return /* @__PURE__ */ jsx(VoiceWidget, {
8609
9711
  state: inCall ? voice.state : "idle",
8610
9712
  turns: widgetTurns,
@@ -8618,9 +9720,10 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8618
9720
  onSendText,
8619
9721
  open,
8620
9722
  onOpenChange: setOpen,
8621
- escalated: session.status === "escalated",
9723
+ escalated,
8622
9724
  status: session.status === "error" ? session.error ?? "error" : voiceEnabled ? voice.error ?? void 0 : void 0,
8623
9725
  ...onAddToCart ? { onAddToCart } : {},
9726
+ ...cart ? { cart } : {},
8624
9727
  ...curationHref ? { curationHref } : {},
8625
9728
  ...productHref ? { productHref } : {},
8626
9729
  ...navigate ? { navigate } : {},
@@ -8634,4 +9737,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8634
9737
  });
8635
9738
  }
8636
9739
  //#endregion
8637
- export { CONCIERGE_POSITIONS as A, isWidgetAvatar as B, ConciergeShell as C, resolveWidgetMessages as D, formatMessage as E, panelClasses as F, BotFace as H, positionClasses as I, positionForArrow as L, alignOf as M, edgeOf as N, widgetMessagesFromCopy as O, nearestPosition as P, DEFAULT_WIDGET_AVATAR as R, latencyBetween as S, defaultWidgetMessages as T, labelProps as U, RopeKnot as V, cn as W, 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, MorphingLoader as w, formatMs as x, SESSION_EVENTS as y, WIDGET_AVATARS 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 };