@saar-ai/web-widget 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{chat-ZLxYRTml.js → chat-DfajYOmN.js} +68 -1
- package/dist/chunks/{host-widget-BlihQKm5.js → host-widget-C9EyGeiN.js} +1202 -94
- package/dist/concierge-shell.d.ts +13 -0
- package/dist/concierge-shell.d.ts.map +1 -1
- package/dist/generated/widget-css.d.ts.map +1 -1
- package/dist/host-widget.d.ts +119 -4
- package/dist/host-widget.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/messages.d.ts +16 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/next/index.js +1 -1
- package/dist/transcript-geometry.d.ts +220 -0
- package/dist/transcript-geometry.d.ts.map +1 -0
- package/dist/use-chat-session.d.ts +86 -9
- package/dist/use-chat-session.d.ts.map +1 -1
- package/dist/use-voice-session.d.ts +10 -0
- package/dist/use-voice-session.d.ts.map +1 -1
- package/dist/voice-session-state.d.ts +17 -0
- package/dist/voice-session-state.d.ts.map +1 -1
- package/dist/voice-widget.d.ts +19 -0
- package/dist/voice-widget.d.ts.map +1 -1
- package/dist/widget.css +1 -1
- package/package.json +3 -3
|
@@ -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/
|
|
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,
|
|
4644
|
-
* fixed value: it stays exactly 112px (today's tuned figure) on a short
|
|
4645
|
-
* panel, where
|
|
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
|
|
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,
|
|
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
|
|
4667
|
-
|
|
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
|
-
/**
|
|
4947
|
-
|
|
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
|
|
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
|
|
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
|
|
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:
|
|
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
|
-
...
|
|
5110
|
-
|
|
5111
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
6252
|
-
*
|
|
6253
|
-
*
|
|
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
|
|
6256
|
-
|
|
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:
|
|
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:
|
|
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
|
}, []);
|
|
@@ -7021,14 +7464,18 @@ function useChatSession(options) {
|
|
|
7021
7464
|
* poll's `afterSeq` query param), regardless of which path saw it.
|
|
7022
7465
|
*/
|
|
7023
7466
|
const mergeIncoming = useCallback((incoming) => {
|
|
7024
|
-
if (!mountedRef.current || incoming.length === 0) return;
|
|
7467
|
+
if (!mountedRef.current || !Array.isArray(incoming) || incoming.length === 0) return;
|
|
7025
7468
|
const fresh = incoming.filter((t) => !seenSeqRef.current.has(t.seq)).slice().sort((a, b) => a.seq - b.seq);
|
|
7026
7469
|
if (fresh.length === 0) return;
|
|
7027
7470
|
for (const t of fresh) seenSeqRef.current.add(t.seq);
|
|
7028
7471
|
lastSeqRef.current = fresh.reduce((max, t) => Math.max(max, t.seq), lastSeqRef.current);
|
|
7029
7472
|
setTurns((prev) => {
|
|
7030
|
-
const
|
|
7031
|
-
|
|
7473
|
+
const baseId = (id) => {
|
|
7474
|
+
const colon = id.indexOf(":");
|
|
7475
|
+
return colon === -1 ? id : id.slice(0, colon);
|
|
7476
|
+
};
|
|
7477
|
+
const rendered = new Set(prev.map((t) => baseId(t.id)));
|
|
7478
|
+
const unseen = fresh.filter((t) => !rendered.has(baseId(t.id)));
|
|
7032
7479
|
if (unseen.length === 0) return prev;
|
|
7033
7480
|
return [...prev, ...unseen.map((t) => ({
|
|
7034
7481
|
id: t.id,
|
|
@@ -7055,7 +7502,10 @@ function useChatSession(options) {
|
|
|
7055
7502
|
*
|
|
7056
7503
|
* Appended once per session, guarded by `handoffEventAppendedRef`: the
|
|
7057
7504
|
* conversation is handed over once, however many times the transport
|
|
7058
|
-
* re-reports it
|
|
7505
|
+
* re-reports it — and there are now three transports that can, since this
|
|
7506
|
+
* is exposed on {@link UseChatSessionResult} for the VOICE leg to call
|
|
7507
|
+
* (see that field's doc comment). That guard plus React's own bail-out on
|
|
7508
|
+
* an unchanged `status` is what makes it safe to call from an effect.
|
|
7059
7509
|
*
|
|
7060
7510
|
* The id is a fixed literal, not a generated one, because there is at most
|
|
7061
7511
|
* one of these per session — and a stable id keeps this row from ever
|
|
@@ -7080,7 +7530,8 @@ function useChatSession(options) {
|
|
|
7080
7530
|
try {
|
|
7081
7531
|
const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/messages?afterSeq=${lastSeqRef.current}`, embedKey), { headers: { authorization: `Bearer ${chatToken}` } });
|
|
7082
7532
|
if (!res.ok) return;
|
|
7083
|
-
|
|
7533
|
+
const body = await res.json();
|
|
7534
|
+
mergeIncoming(body.messages ?? body.turns ?? []);
|
|
7084
7535
|
} catch {}
|
|
7085
7536
|
}, [
|
|
7086
7537
|
apiBase,
|
|
@@ -7102,6 +7553,174 @@ function useChatSession(options) {
|
|
|
7102
7553
|
pollIntervalRef.current = intervalMs;
|
|
7103
7554
|
pollTimerRef.current = setInterval(() => void poll(), intervalMs);
|
|
7104
7555
|
}, [poll]);
|
|
7556
|
+
/**
|
|
7557
|
+
* Swaps a freshly-minted chat token into every place the previous one was
|
|
7558
|
+
* held — the ONE function that writes it, so a rotation can never update
|
|
7559
|
+
* three of the four and leave the fourth presenting a dead credential.
|
|
7560
|
+
*
|
|
7561
|
+
* The ref is what every REST call in this file reads; the state is what
|
|
7562
|
+
* `host-widget.tsx` threads into `createWidgetVoiceTokenFetcher` (that
|
|
7563
|
+
* fetcher is rebuilt on each render from the CURRENT `session.chatToken`,
|
|
7564
|
+
* and `useVoiceSession` reads `optionsRef.current.fetchSession` at
|
|
7565
|
+
* `start()`, so a rotation reaches the voice leg with no extra plumbing);
|
|
7566
|
+
* the headers object is what a socket reconnect handshake replays.
|
|
7567
|
+
*/
|
|
7568
|
+
const adoptChatToken = useCallback((token) => {
|
|
7569
|
+
chatTokenRef.current = token;
|
|
7570
|
+
setChatToken(token);
|
|
7571
|
+
socketAuthHeadersRef.current.Authorization = `Bearer ${token}`;
|
|
7572
|
+
}, []);
|
|
7573
|
+
/**
|
|
7574
|
+
* Arms the single refresh timer for the token that was just minted, and
|
|
7575
|
+
* records its expiry ON THE CLIENT CLOCK.
|
|
7576
|
+
*
|
|
7577
|
+
* Takes a TTL — how long the token has left, per `tokenTtlMs` — never the
|
|
7578
|
+
* wire's absolute `expiresAt`. Everything downstream then lives in one frame
|
|
7579
|
+
* of reference: `expiresAtRef` is `now() + ttlMs` (this client's clock, at
|
|
7580
|
+
* this instant), the delay is that same duration minus the margin, and
|
|
7581
|
+
* `runRefresh`'s expiry shortcut compares a client instant against a client
|
|
7582
|
+
* instant. See `tokenTtlMs` for the re-boot loop this shape exists to
|
|
7583
|
+
* prevent.
|
|
7584
|
+
*
|
|
7585
|
+
* `ttlMs` `null` (an api build that predates `expiresAt`, or a value that
|
|
7586
|
+
* would not parse) ⇒ nothing is scheduled at all and `expiresAtRef` is left
|
|
7587
|
+
* untouched: a client that cannot tell when a token dies must not guess a
|
|
7588
|
+
* TTL, and the pre-refresh behaviour — the token simply lapses — is the
|
|
7589
|
+
* correct fallback, not a fabricated schedule.
|
|
7590
|
+
*
|
|
7591
|
+
* A NEGATIVE or tiny TTL is still scheduled, not discarded: it is a real
|
|
7592
|
+
* (if degenerate) statement about the token, and the clamp below turns it
|
|
7593
|
+
* into a timer that fires at the floor — where `runRefresh` routes it to a
|
|
7594
|
+
* re-boot. Refusing to schedule would instead leave the session with no
|
|
7595
|
+
* recovery armed at all.
|
|
7596
|
+
*
|
|
7597
|
+
* Always clears the outstanding timer first, so this is equally the
|
|
7598
|
+
* "reschedule" path after a successful refresh; there is never more than one
|
|
7599
|
+
* armed.
|
|
7600
|
+
*/
|
|
7601
|
+
const scheduleRefresh = useCallback((ttlMs) => {
|
|
7602
|
+
if (refreshTimerRef.current !== void 0) {
|
|
7603
|
+
clearTimeout(refreshTimerRef.current);
|
|
7604
|
+
refreshTimerRef.current = void 0;
|
|
7605
|
+
}
|
|
7606
|
+
if (ttlMs === null || !Number.isFinite(ttlMs)) return;
|
|
7607
|
+
expiresAtRef.current = now() + ttlMs;
|
|
7608
|
+
const delay = Math.min(MAX_REFRESH_DELAY_MS, Math.max(MIN_REFRESH_DELAY_MS, ttlMs - REFRESH_MARGIN_MS));
|
|
7609
|
+
refreshTimerRef.current = setTimeout(() => {
|
|
7610
|
+
refreshTimerRef.current = void 0;
|
|
7611
|
+
refreshDueRef.current();
|
|
7612
|
+
}, delay);
|
|
7613
|
+
}, [now]);
|
|
7614
|
+
/**
|
|
7615
|
+
* The ONE implementation of "start this widget session against
|
|
7616
|
+
* `POST /widget/session`", shared by the mount-time boot effect and by the
|
|
7617
|
+
* refresh path's silent recovery — extracted rather than duplicated because
|
|
7618
|
+
* the two must apply the SAME response identically: a recovery that forgot
|
|
7619
|
+
* to re-anchor `sessionOriginRef`, or to re-persist the visitor pair the
|
|
7620
|
+
* server may have rotated, would leave the session subtly wrong in ways
|
|
7621
|
+
* nothing on screen reveals.
|
|
7622
|
+
*
|
|
7623
|
+
* ## `phase` — what a RECOVERY deliberately does not re-apply
|
|
7624
|
+
*
|
|
7625
|
+
* A recovery restores a CREDENTIAL. Re-applying the tenant's published
|
|
7626
|
+
* config halfway through a live session is not part of that job, and doing
|
|
7627
|
+
* it can yank UI out from under a visitor who is using it. Each of these is
|
|
7628
|
+
* therefore gated on `phase === 'mount'`:
|
|
7629
|
+
*
|
|
7630
|
+
* - **The greeting.** `setTurns([greeting])` REPLACES the transcript. On
|
|
7631
|
+
* mount there is nothing to replace; on a recovery it would erase the
|
|
7632
|
+
* conversation the shopper is in the middle of, to re-show a greeting they
|
|
7633
|
+
* read half an hour ago.
|
|
7634
|
+
* - **`modalities`.** The concrete failure: a recovery landing DURING a
|
|
7635
|
+
* voice call, against a config whose `voice` is now false (a tenant toggled
|
|
7636
|
+
* it, or an api build that omits the field, which defaults it to false),
|
|
7637
|
+
* flips `modalities.voice` off — and `host-widget.tsx` derives every
|
|
7638
|
+
* in-call control from exactly that flag, so the shopper is left on a
|
|
7639
|
+
* connected LiveKit room with no way to mute, speak or hang up. The
|
|
7640
|
+
* credential was restored and the call was orphaned.
|
|
7641
|
+
* - **`launcher`.** Same class, milder symptom: re-anchoring or re-labelling
|
|
7642
|
+
* the collapsed widget mid-conversation (including moving it out from
|
|
7643
|
+
* under a visitor who had dragged it somewhere) is a config change
|
|
7644
|
+
* presented as a session recovery.
|
|
7645
|
+
*
|
|
7646
|
+
* And one thing that belongs to the mount path for a different reason:
|
|
7647
|
+
*
|
|
7648
|
+
* - **`ready`.** That flag means "the first boot attempt has resolved" and is
|
|
7649
|
+
* latched; a later recovery neither un-readies the widget nor re-readies
|
|
7650
|
+
* it. (Its caller owns it — this function never touches it.)
|
|
7651
|
+
*
|
|
7652
|
+
* `setStatus` preserves `'escalated'` for the same reason (the same guard
|
|
7653
|
+
* `send`'s `onDone` uses): a token expiring mid-handoff must not silently
|
|
7654
|
+
* demote a conversation a human is answering back to `'idle'`, which would
|
|
7655
|
+
* stop the poll loop and close the socket.
|
|
7656
|
+
*
|
|
7657
|
+
* Throws on a non-ok response or a network failure — both callers decide for
|
|
7658
|
+
* themselves what a failed boot means, which is the only thing they differ on.
|
|
7659
|
+
*/
|
|
7660
|
+
const bootSession = useCallback(async (args) => {
|
|
7661
|
+
const isStale = args.isStale;
|
|
7662
|
+
const isMount = args.phase === "mount";
|
|
7663
|
+
const stored = readStoredVisitor();
|
|
7664
|
+
const bootRequestedAt = now();
|
|
7665
|
+
const res = await fetchImpl(withEmbedKeyParam(`${apiBase}/session`, embedKey), {
|
|
7666
|
+
method: "POST",
|
|
7667
|
+
headers: { "content-type": "application/json" },
|
|
7668
|
+
body: JSON.stringify({
|
|
7669
|
+
embedKey,
|
|
7670
|
+
attribution,
|
|
7671
|
+
...stored.visitorId ? { visitorId: stored.visitorId } : {},
|
|
7672
|
+
...stored.visitorProof ? { visitorProof: stored.visitorProof } : {}
|
|
7673
|
+
})
|
|
7674
|
+
});
|
|
7675
|
+
if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
|
|
7676
|
+
const body = await res.json();
|
|
7677
|
+
if (isStale?.() || !mountedRef.current) return;
|
|
7678
|
+
const receivedAt = now();
|
|
7679
|
+
const ttlMs = tokenTtlMs(res, body.expiresAt, receivedAt);
|
|
7680
|
+
adoptChatToken(body.chatToken);
|
|
7681
|
+
lastSeqRef.current = 0;
|
|
7682
|
+
seenSeqRef.current.clear();
|
|
7683
|
+
visitorSessionIdRef.current = body.visitorSessionId;
|
|
7684
|
+
sessionOriginRef.current = bootRequestedAt;
|
|
7685
|
+
if (isMount) setModalities({
|
|
7686
|
+
text: body.modalities?.text ?? true,
|
|
7687
|
+
voice: body.modalities?.voice ?? false
|
|
7688
|
+
});
|
|
7689
|
+
persistVisitor(body.visitorId, body.visitorProof);
|
|
7690
|
+
if (collector && body.visitorSessionId !== void 0 && ttlMs !== null) collector.setSession({
|
|
7691
|
+
chatToken: body.chatToken,
|
|
7692
|
+
visitorSessionId: body.visitorSessionId,
|
|
7693
|
+
expiresAt: receivedAt + ttlMs
|
|
7694
|
+
});
|
|
7695
|
+
if (isMount && body.greeting) setTurns([{
|
|
7696
|
+
id: "greeting",
|
|
7697
|
+
speaker: "agent",
|
|
7698
|
+
text: body.greeting,
|
|
7699
|
+
final: true
|
|
7700
|
+
}]);
|
|
7701
|
+
if (isMount && body.resumed === true) {
|
|
7702
|
+
lastSeqRef.current = 0;
|
|
7703
|
+
poll();
|
|
7704
|
+
}
|
|
7705
|
+
if (isMount) setLauncher({
|
|
7706
|
+
...body.launcher?.label !== void 0 ? { label: body.launcher.label } : {},
|
|
7707
|
+
...isConciergePosition(body.launcher?.position) ? { position: body.launcher.position } : {},
|
|
7708
|
+
...typeof body.launcher?.draggable === "boolean" ? { draggable: body.launcher.draggable } : {}
|
|
7709
|
+
});
|
|
7710
|
+
setStatus((prev) => prev === "escalated" ? prev : "idle");
|
|
7711
|
+
scheduleRefresh(ttlMs);
|
|
7712
|
+
setBootGeneration((generation) => generation + 1);
|
|
7713
|
+
}, [
|
|
7714
|
+
adoptChatToken,
|
|
7715
|
+
apiBase,
|
|
7716
|
+
attribution,
|
|
7717
|
+
collector,
|
|
7718
|
+
embedKey,
|
|
7719
|
+
fetchImpl,
|
|
7720
|
+
now,
|
|
7721
|
+
poll,
|
|
7722
|
+
scheduleRefresh
|
|
7723
|
+
]);
|
|
7105
7724
|
useEffect(() => {
|
|
7106
7725
|
let cancelled = false;
|
|
7107
7726
|
if (!embedKey) {
|
|
@@ -7112,47 +7731,10 @@ function useChatSession(options) {
|
|
|
7112
7731
|
}
|
|
7113
7732
|
(async () => {
|
|
7114
7733
|
try {
|
|
7115
|
-
|
|
7116
|
-
|
|
7117
|
-
|
|
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 } : {}
|
|
7734
|
+
await bootSession({
|
|
7735
|
+
phase: "mount",
|
|
7736
|
+
isStale: () => cancelled
|
|
7154
7737
|
});
|
|
7155
|
-
setStatus("idle");
|
|
7156
7738
|
} catch (err) {
|
|
7157
7739
|
if (cancelled) return;
|
|
7158
7740
|
setStatus("error");
|
|
@@ -7165,10 +7747,184 @@ function useChatSession(options) {
|
|
|
7165
7747
|
cancelled = true;
|
|
7166
7748
|
};
|
|
7167
7749
|
}, []);
|
|
7168
|
-
|
|
7169
|
-
|
|
7750
|
+
/**
|
|
7751
|
+
* The recovery of last resort: mint a whole new session because the current
|
|
7752
|
+
* token could not be renewed.
|
|
7753
|
+
*
|
|
7754
|
+
* Silent by design — a shopper whose token rotated badly should see nothing
|
|
7755
|
+
* at all, because nothing about their conversation has actually failed. The
|
|
7756
|
+
* existing `status: 'error'` surface is reached ONLY if this second attempt
|
|
7757
|
+
* also fails, at which point the widget genuinely cannot reach the api and
|
|
7758
|
+
* saying so is honest.
|
|
7759
|
+
*/
|
|
7760
|
+
const rebootSession = useCallback(async () => {
|
|
7761
|
+
try {
|
|
7762
|
+
await bootSession({ phase: "recovery" });
|
|
7763
|
+
} catch (err) {
|
|
7764
|
+
if (!mountedRef.current) return;
|
|
7765
|
+
setStatus("error");
|
|
7766
|
+
setError(err instanceof Error ? err.message : "Could not start the conversation.");
|
|
7767
|
+
}
|
|
7768
|
+
}, [bootSession]);
|
|
7769
|
+
/**
|
|
7770
|
+
* One rotation attempt: `POST /widget/refresh`, authenticated by the token
|
|
7771
|
+
* being replaced.
|
|
7772
|
+
*
|
|
7773
|
+
* **PERMANENT and TRANSIENT failures are not the same failure.** They used
|
|
7774
|
+
* to be: every non-success — 401, 503, a dropped connection, a captive
|
|
7775
|
+
* portal's HTML served with a 200 — fell straight through to
|
|
7776
|
+
* `rebootSession`. A `401` genuinely IS permanent (the token expired, the
|
|
7777
|
+
* session hit its absolute 12-hour cap, or the Origin is not one this embed
|
|
7778
|
+
* key allows — see `SessionRefreshResponse`), and a whole new session is the
|
|
7779
|
+
* only way forward. Nothing else is: a five-second network blip five minutes
|
|
7780
|
+
* before expiry would abandon a perfectly renewable token and mint a brand
|
|
7781
|
+
* new session — a new conversation row, a new `visitorSessionId`, a socket
|
|
7782
|
+
* that has to rejoin, and a shopper's browsing session split in two in the
|
|
7783
|
+
* pipeline — because one request lost a race with a lift's wifi.
|
|
7784
|
+
*
|
|
7785
|
+
* So: `401` ⇒ `rebootSession`. Everything else — the network, a 5xx, a
|
|
7786
|
+
* response whose body does not parse or does not carry a usable token ⇒ ONE
|
|
7787
|
+
* retry of this same function, armed on the normal refresh timer at
|
|
7788
|
+
* `min(60s, remaining/2)` (never below the busy-loop floor).
|
|
7789
|
+
*
|
|
7790
|
+
* **No retry counter, because the expiry already bounds it.** Each retry is
|
|
7791
|
+
* scheduled at half the REMAINING life, so the attempts converge on the
|
|
7792
|
+
* expiry rather than continuing past it; the moment `remaining` reaches zero
|
|
7793
|
+
* the expiry shortcut below routes the next firing to a re-boot. A counter
|
|
7794
|
+
* would be a second, weaker statement of the same bound.
|
|
7795
|
+
*
|
|
7796
|
+
* **An already-expired token skips the refresh entirely.** The server 401s
|
|
7797
|
+
* it unconditionally, so spending the round trip to be told so — while the
|
|
7798
|
+
* shopper waits — buys nothing. This is the path a tab that was hidden past
|
|
7799
|
+
* its expiry takes when it comes back (see `handleRefreshDue`), and the path
|
|
7800
|
+
* a run of failed retries eventually reaches. The expiry it reads is
|
|
7801
|
+
* CLIENT-anchored (`scheduleRefresh`), so a wrong device clock cannot send
|
|
7802
|
+
* it here on a token that is in fact fine.
|
|
7803
|
+
*
|
|
7804
|
+
* **Nothing is adopted before it is validated.** A 200 carrying no
|
|
7805
|
+
* `chatToken`, or an `expiresAt` that yields no finite TTL, is a FAILED
|
|
7806
|
+
* refresh — not a token to install and a `NaN` expiry to hand the collector
|
|
7807
|
+
* and the scheduler.
|
|
7808
|
+
*
|
|
7809
|
+
* Never rejects: it is invoked as `void runRefresh()` from a timer and from
|
|
7810
|
+
* an event listener, neither of which has anywhere to put a rejection.
|
|
7811
|
+
*/
|
|
7812
|
+
const runRefresh = useCallback(async () => {
|
|
7170
7813
|
const chatToken = chatTokenRef.current;
|
|
7171
7814
|
if (chatToken === void 0) return;
|
|
7815
|
+
const expiresAt = expiresAtRef.current;
|
|
7816
|
+
if (expiresAt !== null && now() >= expiresAt) {
|
|
7817
|
+
await rebootSession();
|
|
7818
|
+
return;
|
|
7819
|
+
}
|
|
7820
|
+
/**
|
|
7821
|
+
* A TRANSIENT failure: try this same refresh again, later, on the one
|
|
7822
|
+
* refresh timer — via `refreshDueRef`, so a retry that comes due on a
|
|
7823
|
+
* hidden tab is declined and picked up on the shopper's return exactly
|
|
7824
|
+
* like a scheduled rotation is.
|
|
7825
|
+
*
|
|
7826
|
+
* A token already past its life by the client-anchored clock has nothing
|
|
7827
|
+
* left to renew, so that goes to the re-boot instead.
|
|
7828
|
+
*/
|
|
7829
|
+
const retryLater = async () => {
|
|
7830
|
+
if (!mountedRef.current) return;
|
|
7831
|
+
const remaining = expiresAtRef.current === null ? null : expiresAtRef.current - now();
|
|
7832
|
+
if (remaining !== null && remaining <= 0) {
|
|
7833
|
+
await rebootSession();
|
|
7834
|
+
return;
|
|
7835
|
+
}
|
|
7836
|
+
const delay = Math.max(MIN_REFRESH_DELAY_MS, Math.min(TRANSIENT_RETRY_MAX_DELAY_MS, remaining === null ? TRANSIENT_RETRY_MAX_DELAY_MS : remaining / 2));
|
|
7837
|
+
if (refreshTimerRef.current !== void 0) clearTimeout(refreshTimerRef.current);
|
|
7838
|
+
refreshTimerRef.current = setTimeout(() => {
|
|
7839
|
+
refreshTimerRef.current = void 0;
|
|
7840
|
+
refreshDueRef.current();
|
|
7841
|
+
}, delay);
|
|
7842
|
+
};
|
|
7843
|
+
let res;
|
|
7844
|
+
try {
|
|
7845
|
+
res = await fetchImpl(withEmbedKeyParam(`${apiBase}/refresh`, embedKey), {
|
|
7846
|
+
method: "POST",
|
|
7847
|
+
headers: {
|
|
7848
|
+
"content-type": "application/json",
|
|
7849
|
+
authorization: `Bearer ${chatToken}`
|
|
7850
|
+
},
|
|
7851
|
+
body: JSON.stringify({})
|
|
7852
|
+
});
|
|
7853
|
+
} catch {
|
|
7854
|
+
await retryLater();
|
|
7855
|
+
return;
|
|
7856
|
+
}
|
|
7857
|
+
if (res.status === 401) {
|
|
7858
|
+
await rebootSession();
|
|
7859
|
+
return;
|
|
7860
|
+
}
|
|
7861
|
+
if (!res.ok) {
|
|
7862
|
+
await retryLater();
|
|
7863
|
+
return;
|
|
7864
|
+
}
|
|
7865
|
+
let body;
|
|
7866
|
+
try {
|
|
7867
|
+
body = await res.json();
|
|
7868
|
+
} catch {
|
|
7869
|
+
body = void 0;
|
|
7870
|
+
}
|
|
7871
|
+
const receivedAt = now();
|
|
7872
|
+
const ttlMs = body === void 0 ? null : tokenTtlMs(res, body.expiresAt, receivedAt);
|
|
7873
|
+
if (body === void 0 || typeof body.chatToken !== "string" || body.chatToken === "" || ttlMs === null) {
|
|
7874
|
+
await retryLater();
|
|
7875
|
+
return;
|
|
7876
|
+
}
|
|
7877
|
+
if (!mountedRef.current) return;
|
|
7878
|
+
adoptChatToken(body.chatToken);
|
|
7879
|
+
const visitorSessionId = visitorSessionIdRef.current;
|
|
7880
|
+
if (collector && visitorSessionId !== void 0 && collector.currentVisitorSessionId === visitorSessionId) collector.setSession({
|
|
7881
|
+
chatToken: body.chatToken,
|
|
7882
|
+
visitorSessionId,
|
|
7883
|
+
expiresAt: receivedAt + ttlMs
|
|
7884
|
+
});
|
|
7885
|
+
scheduleRefresh(ttlMs);
|
|
7886
|
+
}, [
|
|
7887
|
+
adoptChatToken,
|
|
7888
|
+
apiBase,
|
|
7889
|
+
collector,
|
|
7890
|
+
embedKey,
|
|
7891
|
+
fetchImpl,
|
|
7892
|
+
now,
|
|
7893
|
+
rebootSession,
|
|
7894
|
+
scheduleRefresh
|
|
7895
|
+
]);
|
|
7896
|
+
refreshDueRef.current = useCallback(() => {
|
|
7897
|
+
if (!mountedRef.current) return;
|
|
7898
|
+
if (!isTabVisible()) {
|
|
7899
|
+
refreshPendingRef.current = true;
|
|
7900
|
+
return;
|
|
7901
|
+
}
|
|
7902
|
+
runRefresh();
|
|
7903
|
+
}, [runRefresh]);
|
|
7904
|
+
/**
|
|
7905
|
+
* The other half of the visibility gate: a refresh that came due while the
|
|
7906
|
+
* tab was hidden runs the moment the shopper comes back.
|
|
7907
|
+
*
|
|
7908
|
+
* `runRefresh` decides between an actual refresh and a re-boot by checking
|
|
7909
|
+
* the stored expiry itself, so this handler does not need to — a tab hidden
|
|
7910
|
+
* for two minutes rotates its still-valid token, and one hidden for two
|
|
7911
|
+
* hours goes straight to a re-boot without spending a round trip on a
|
|
7912
|
+
* refresh that could only 401.
|
|
7913
|
+
*/
|
|
7914
|
+
useEffect(() => {
|
|
7915
|
+
if (typeof document === "undefined") return;
|
|
7916
|
+
const onVisibilityChange = () => {
|
|
7917
|
+
if (!isTabVisible()) return;
|
|
7918
|
+
if (!refreshPendingRef.current) return;
|
|
7919
|
+
refreshPendingRef.current = false;
|
|
7920
|
+
runRefresh();
|
|
7921
|
+
};
|
|
7922
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
7923
|
+
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
7924
|
+
}, [runRefresh]);
|
|
7925
|
+
useEffect(() => {
|
|
7926
|
+
if (!socketUrl || !ready || status !== "escalated") return;
|
|
7927
|
+
if (chatTokenRef.current === void 0) return;
|
|
7172
7928
|
let cancelled = false;
|
|
7173
7929
|
setConnection("connecting");
|
|
7174
7930
|
(async () => {
|
|
@@ -7177,7 +7933,7 @@ function useChatSession(options) {
|
|
|
7177
7933
|
const socket = factory(`${socketUrl}${SOCKET_NAMESPACE}`, {
|
|
7178
7934
|
path: socketPath,
|
|
7179
7935
|
transports: ["polling", "websocket"],
|
|
7180
|
-
extraHeaders:
|
|
7936
|
+
extraHeaders: socketAuthHeadersRef.current,
|
|
7181
7937
|
withCredentials: false,
|
|
7182
7938
|
reconnection: true
|
|
7183
7939
|
});
|
|
@@ -7206,7 +7962,8 @@ function useChatSession(options) {
|
|
|
7206
7962
|
ready,
|
|
7207
7963
|
status,
|
|
7208
7964
|
socketFactory,
|
|
7209
|
-
mergeIncoming
|
|
7965
|
+
mergeIncoming,
|
|
7966
|
+
bootGeneration
|
|
7210
7967
|
]);
|
|
7211
7968
|
useEffect(() => {
|
|
7212
7969
|
if (status !== "escalated") return;
|
|
@@ -7218,14 +7975,27 @@ function useChatSession(options) {
|
|
|
7218
7975
|
pollIntervalMs,
|
|
7219
7976
|
idlePollIntervalMs
|
|
7220
7977
|
]);
|
|
7221
|
-
|
|
7978
|
+
/**
|
|
7979
|
+
* The ONE place a turn is posted to `POST /widget/chat`, shared by `send`
|
|
7980
|
+
* (shopper text) and `sendReport` (a typed storefront report).
|
|
7981
|
+
*
|
|
7982
|
+
* The two differ in exactly two ways — what goes in the request body, and
|
|
7983
|
+
* whether a caller bubble is appended — and in nothing else: both stream
|
|
7984
|
+
* the reply into an agent turn, both roll their optimistic turns back on a
|
|
7985
|
+
* failed POST, both resolve `false` rather than throwing. Keeping them one
|
|
7986
|
+
* function is what stops the report path from quietly losing a fix made to
|
|
7987
|
+
* the message path.
|
|
7988
|
+
*/
|
|
7989
|
+
const postTurn = useCallback(async (payload, options) => {
|
|
7222
7990
|
const chatToken = chatTokenRef.current;
|
|
7223
7991
|
if (chatToken === void 0 || status === "streaming") return false;
|
|
7992
|
+
const text = "message" in payload ? payload.message : "";
|
|
7993
|
+
const silent = options?.silent === true || !("message" in payload);
|
|
7224
7994
|
const callerTurnId = `caller-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
7225
7995
|
const agentTurnId = `agent-${callerTurnId}`;
|
|
7226
7996
|
setTurns((prev) => [
|
|
7227
7997
|
...prev,
|
|
7228
|
-
...
|
|
7998
|
+
...silent ? [] : [{
|
|
7229
7999
|
id: callerTurnId,
|
|
7230
8000
|
speaker: "caller",
|
|
7231
8001
|
text,
|
|
@@ -7251,7 +8021,7 @@ function useChatSession(options) {
|
|
|
7251
8021
|
"content-type": "application/json",
|
|
7252
8022
|
authorization: `Bearer ${chatToken}`
|
|
7253
8023
|
},
|
|
7254
|
-
body: JSON.stringify(
|
|
8024
|
+
body: JSON.stringify(payload)
|
|
7255
8025
|
});
|
|
7256
8026
|
} catch {
|
|
7257
8027
|
rollBack();
|
|
@@ -7310,6 +8080,8 @@ function useChatSession(options) {
|
|
|
7310
8080
|
status,
|
|
7311
8081
|
markHandoffToHuman
|
|
7312
8082
|
]);
|
|
8083
|
+
const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
|
|
8084
|
+
const sendReport = useCallback(async (report) => postTurn({ report }), [postTurn]);
|
|
7313
8085
|
const sendEvent = useCallback(async (events) => {
|
|
7314
8086
|
const chatToken = chatTokenRef.current;
|
|
7315
8087
|
if (chatToken === void 0 || events.length === 0) return false;
|
|
@@ -7456,7 +8228,7 @@ function useChatSession(options) {
|
|
|
7456
8228
|
const reportReceipts = () => {
|
|
7457
8229
|
const delivered = deliveredTurnIdsRef.current;
|
|
7458
8230
|
const read = readTurnIdsRef.current;
|
|
7459
|
-
const visible =
|
|
8231
|
+
const visible = isTabVisible();
|
|
7460
8232
|
const kinds = [];
|
|
7461
8233
|
let sawNewDelivery = false;
|
|
7462
8234
|
let sawNewRead = false;
|
|
@@ -7493,6 +8265,7 @@ function useChatSession(options) {
|
|
|
7493
8265
|
ready,
|
|
7494
8266
|
connection,
|
|
7495
8267
|
send,
|
|
8268
|
+
sendReport,
|
|
7496
8269
|
sendEvent,
|
|
7497
8270
|
checkout: useCallback(async (items, curationId, cartAttributionToken) => {
|
|
7498
8271
|
const chatToken = chatTokenRef.current;
|
|
@@ -7588,7 +8361,8 @@ function useChatSession(options) {
|
|
|
7588
8361
|
embedKey,
|
|
7589
8362
|
fetchImpl,
|
|
7590
8363
|
markHandoffToHuman
|
|
7591
|
-
])
|
|
8364
|
+
]),
|
|
8365
|
+
markHandoffToHuman
|
|
7592
8366
|
};
|
|
7593
8367
|
}
|
|
7594
8368
|
/**
|
|
@@ -7674,7 +8448,7 @@ async function streamReply(args) {
|
|
|
7674
8448
|
* cache makes a second `start()` after `stop()` free).
|
|
7675
8449
|
*/
|
|
7676
8450
|
async function loadVoiceProtocol() {
|
|
7677
|
-
const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-
|
|
8451
|
+
const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-DfajYOmN.js")]);
|
|
7678
8452
|
return {
|
|
7679
8453
|
decodeTelemetry: telemetry.decodeTelemetry,
|
|
7680
8454
|
encodeCallerText: telemetry.encodeCallerText,
|
|
@@ -8083,7 +8857,8 @@ function useVoiceSession(options = {}) {
|
|
|
8083
8857
|
setError(null);
|
|
8084
8858
|
setSnapshot({
|
|
8085
8859
|
...IDLE_SNAPSHOT,
|
|
8086
|
-
phase: "connecting"
|
|
8860
|
+
phase: "connecting",
|
|
8861
|
+
micPending: true
|
|
8087
8862
|
});
|
|
8088
8863
|
logRef.current?.clear();
|
|
8089
8864
|
setEvents([]);
|
|
@@ -8227,7 +9002,8 @@ function useVoiceSession(options = {}) {
|
|
|
8227
9002
|
record("mic_published");
|
|
8228
9003
|
setSnapshot((s) => ({
|
|
8229
9004
|
...s,
|
|
8230
|
-
micPublished: true
|
|
9005
|
+
micPublished: true,
|
|
9006
|
+
micPending: false
|
|
8231
9007
|
}));
|
|
8232
9008
|
} catch (micError) {
|
|
8233
9009
|
const reason = micError instanceof Error ? micError.message : String(micError);
|
|
@@ -8235,7 +9011,8 @@ function useVoiceSession(options = {}) {
|
|
|
8235
9011
|
setError(`microphone unavailable: ${reason}`);
|
|
8236
9012
|
setSnapshot((s) => ({
|
|
8237
9013
|
...s,
|
|
8238
|
-
micPublished: false
|
|
9014
|
+
micPublished: false,
|
|
9015
|
+
micPending: false
|
|
8239
9016
|
}));
|
|
8240
9017
|
}
|
|
8241
9018
|
} catch (cause) {
|
|
@@ -8339,6 +9116,7 @@ function useVoiceSession(options = {}) {
|
|
|
8339
9116
|
state: botStateFor(snapshot),
|
|
8340
9117
|
phase: snapshot.phase,
|
|
8341
9118
|
micOpen: snapshot.micPublished,
|
|
9119
|
+
micPending: snapshot.micPending,
|
|
8342
9120
|
error,
|
|
8343
9121
|
events,
|
|
8344
9122
|
agentLevel,
|
|
@@ -8387,7 +9165,7 @@ function useVoiceSession(options = {}) {
|
|
|
8387
9165
|
* resolve a bare id into a title/price/image the way a real platform's
|
|
8388
9166
|
* own cart API does.
|
|
8389
9167
|
*/
|
|
8390
|
-
function resolveAddToCartHandler(bridge, productHref) {
|
|
9168
|
+
function resolveAddToCartHandler(bridge, productHref, onAdded) {
|
|
8391
9169
|
if (!bridge) return void 0;
|
|
8392
9170
|
const canAddToCart = bridge.addToCart !== void 0;
|
|
8393
9171
|
const canNavigateToPdp = bridge.navigate !== void 0 && productHref !== void 0;
|
|
@@ -8398,6 +9176,7 @@ function resolveAddToCartHandler(bridge, productHref) {
|
|
|
8398
9176
|
if (bridge.addToCart && cartId) try {
|
|
8399
9177
|
if (idSpace === "catalog") await bridge.addToCart(cartId, 1, buildCartLineContext(item));
|
|
8400
9178
|
else await bridge.addToCart(cartId, 1);
|
|
9179
|
+
onAdded?.(item);
|
|
8401
9180
|
return;
|
|
8402
9181
|
} catch (err) {
|
|
8403
9182
|
if (bridge.navigate && productHref && item.handle) {
|
|
@@ -8426,6 +9205,125 @@ function buildCartLineContext(item) {
|
|
|
8426
9205
|
};
|
|
8427
9206
|
}
|
|
8428
9207
|
/**
|
|
9208
|
+
* Folds one successful add into the widget's own basket, merging a repeat add
|
|
9209
|
+
* of the SAME variant into the existing row rather than drawing it twice —
|
|
9210
|
+
* two identical rows read as two different products at a glance, which is
|
|
9211
|
+
* exactly the misread a confirmation surface must not produce.
|
|
9212
|
+
*
|
|
9213
|
+
* Keyed by the internal `variantId` where the card has one, since that is
|
|
9214
|
+
* what checkout will group on too; a card without one falls back to its
|
|
9215
|
+
* platform id and then its product id, so a repeat add of the same card still
|
|
9216
|
+
* merges.
|
|
9217
|
+
*/
|
|
9218
|
+
function mergeAddedCartLine(lines, item) {
|
|
9219
|
+
const key = item.variantId ?? item.platformVariantId ?? item.productId;
|
|
9220
|
+
const existing = lines.findIndex((line) => line.key === key);
|
|
9221
|
+
if (existing >= 0) return lines.map((line, i) => i === existing ? {
|
|
9222
|
+
...line,
|
|
9223
|
+
quantity: line.quantity + 1
|
|
9224
|
+
} : line);
|
|
9225
|
+
return [...lines, {
|
|
9226
|
+
key,
|
|
9227
|
+
title: item.title,
|
|
9228
|
+
...item.imageUrl !== void 0 ? { imageUrl: item.imageUrl } : {},
|
|
9229
|
+
priceMinor: item.priceMinor,
|
|
9230
|
+
currency: item.currency,
|
|
9231
|
+
quantity: 1,
|
|
9232
|
+
...item.variantId !== void 0 ? { variantId: item.variantId } : {}
|
|
9233
|
+
}];
|
|
9234
|
+
}
|
|
9235
|
+
/**
|
|
9236
|
+
* Turns the host's OWN cart rows into what the summary renders, or
|
|
9237
|
+
* `undefined` when the host reported no `lines` array at all.
|
|
9238
|
+
*
|
|
9239
|
+
* `undefined` and `[]` are deliberately different answers — see
|
|
9240
|
+
* `CartSnapshot.lines` (`@saar-ai/widget-bridge`). Absent means "this host
|
|
9241
|
+
* does not track lines" and the caller falls back to its own accumulation;
|
|
9242
|
+
* empty means "the cart is empty" and is rendered as such (i.e. no summary).
|
|
9243
|
+
*
|
|
9244
|
+
* Every field of a host line is optional, so the missing ones are given the
|
|
9245
|
+
* only neutral values a row can be drawn with (`quantity: 1`,
|
|
9246
|
+
* `priceMinor: 0`). A line with no `title` never reaches here — the bridge
|
|
9247
|
+
* drops it, because there is no row to draw without a name.
|
|
9248
|
+
*/
|
|
9249
|
+
function cartLinesFromSnapshot(snapshot, currency) {
|
|
9250
|
+
if (!snapshot?.lines) return void 0;
|
|
9251
|
+
return snapshot.lines.map((line, index) => ({
|
|
9252
|
+
key: `host-${index}`,
|
|
9253
|
+
title: line.title ?? "",
|
|
9254
|
+
...line.imageUrl !== void 0 ? { imageUrl: line.imageUrl } : {},
|
|
9255
|
+
priceMinor: line.unitPriceMinor ?? 0,
|
|
9256
|
+
currency,
|
|
9257
|
+
quantity: line.quantity ?? 1
|
|
9258
|
+
}));
|
|
9259
|
+
}
|
|
9260
|
+
/**
|
|
9261
|
+
* Where "Checkout" sends the shopper, and the order the two answers are
|
|
9262
|
+
* tried in.
|
|
9263
|
+
*
|
|
9264
|
+
* 1. **The host's own checkout** (`bridge.getCheckoutUrl`), when it has one.
|
|
9265
|
+
* It is the only answer that carries the shopper's WHOLE cart, including
|
|
9266
|
+
* whatever was in it before this conversation started.
|
|
9267
|
+
* 2. **A server-built permalink** (`POST /widget/checkout`), built from the
|
|
9268
|
+
* items the concierge itself recommended. It carries our own attribution
|
|
9269
|
+
* and is the better answer on a platform we can build a permalink for,
|
|
9270
|
+
* which is why `ShopifyBridge` deliberately implements no
|
|
9271
|
+
* `getCheckoutUrl`.
|
|
9272
|
+
*
|
|
9273
|
+
* Every failure of (1) — absent, `null`, throwing, non-`http(s)` — falls
|
|
9274
|
+
* through to (2) rather than surfacing, because a bridge that cannot answer
|
|
9275
|
+
* is exactly the case (2) exists for. `null` from BOTH is a real outcome and
|
|
9276
|
+
* is returned as such: `WidgetCartSummary`'s button renders its failure line
|
|
9277
|
+
* and stays pressable. It must never throw — the button's own `await` has no
|
|
9278
|
+
* catch, so a throw here is a permanent spinner.
|
|
9279
|
+
*/
|
|
9280
|
+
async function resolveCheckoutUrl(bridge, startHandoff) {
|
|
9281
|
+
try {
|
|
9282
|
+
const hosted = await bridge?.getCheckoutUrl?.();
|
|
9283
|
+
if (typeof hosted === "string" && hosted.length > 0) return hosted;
|
|
9284
|
+
} catch {}
|
|
9285
|
+
try {
|
|
9286
|
+
return (await startHandoff())?.url ?? null;
|
|
9287
|
+
} catch {
|
|
9288
|
+
return null;
|
|
9289
|
+
}
|
|
9290
|
+
}
|
|
9291
|
+
/**
|
|
9292
|
+
* Where the call is, in the CALLER's terms — the mapping from the voice
|
|
9293
|
+
* session's own five-field state onto the one phase the mic control renders.
|
|
9294
|
+
*
|
|
9295
|
+
* Extracted from `ConciergeWidget` and written as early returns because the
|
|
9296
|
+
* precedence between these branches is the whole content of the mapping, and
|
|
9297
|
+
* a six-level nested ternary states it only by indentation. Reading order IS
|
|
9298
|
+
* the precedence order:
|
|
9299
|
+
*
|
|
9300
|
+
* - **Voice off** ⇒ `'idle'`. There is no call and no control.
|
|
9301
|
+
* - **`'connecting'` deliberately spans MORE than the transport's own
|
|
9302
|
+
* connecting phase**: it lasts from the press until the call is either
|
|
9303
|
+
* usable or definitively refused, which is exactly the window the mic
|
|
9304
|
+
* control draws a spinner for. Its second half is `micPending` — LiveKit
|
|
9305
|
+
* reports the room connected BEFORE the browser is asked for the
|
|
9306
|
+
* microphone, so the permission prompt sits open over `phase: 'connected'`,
|
|
9307
|
+
* and this mapping once called that a live call and handed the caller a
|
|
9308
|
+
* microphone they could not yet speak into. `micPending` therefore ranks
|
|
9309
|
+
* ABOVE `error`: an error left over from an earlier attempt must not end
|
|
9310
|
+
* a wait that is still genuinely open.
|
|
9311
|
+
* - **Refusal ends the wait**: the moment the browser says no, `micPending`
|
|
9312
|
+
* clears and an error with no open mic reads as `'blocked'` — ahead of
|
|
9313
|
+
* `state`, because a caller who cannot speak is not "waiting for the
|
|
9314
|
+
* agent to think".
|
|
9315
|
+
* - Otherwise the agent's own state decides: `'thinking'` ⇒ `'waiting'`,
|
|
9316
|
+
* anything else ⇒ `'live'`.
|
|
9317
|
+
*/
|
|
9318
|
+
function deriveCallPhase(voice) {
|
|
9319
|
+
if (!voice.voiceEnabled) return "idle";
|
|
9320
|
+
if (voice.phase === "connecting") return "connecting";
|
|
9321
|
+
if (voice.phase !== "connected") return "idle";
|
|
9322
|
+
if (voice.micPending) return "connecting";
|
|
9323
|
+
if (voice.error !== null && !voice.micOpen) return "blocked";
|
|
9324
|
+
return voice.state === "thinking" ? "waiting" : "live";
|
|
9325
|
+
}
|
|
9326
|
+
/**
|
|
8429
9327
|
* The plain React widget component — for a Next.js host (Phase 5's npm
|
|
8430
9328
|
* package) that renders it directly, without the shadow-DOM mount
|
|
8431
9329
|
* `mountConciergeWidget` performs for the CDN embed. Boots its own chat session
|
|
@@ -8507,7 +9405,84 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8507
9405
|
chatToken
|
|
8508
9406
|
}) } : {});
|
|
8509
9407
|
const inCall = voiceEnabled && (voice.phase === "connecting" || voice.phase === "connected");
|
|
8510
|
-
|
|
9408
|
+
/**
|
|
9409
|
+
* A PERSON holds this conversation — see `UseChatSessionResult.status`.
|
|
9410
|
+
*
|
|
9411
|
+
* Gates the voice leg at runtime, because voice is AI-only: the desk gives
|
|
9412
|
+
* an operator the TEXT transport (the socket, the `/widget/messages` poll)
|
|
9413
|
+
* and nothing joins the shopper's LiveKit room on their behalf. Read three
|
|
9414
|
+
* times below and in exactly one direction each — the handler refuses to
|
|
9415
|
+
* start a call, the effect ends one already running, and `VoiceWidget`
|
|
9416
|
+
* dims the control and says why. None of them touches
|
|
9417
|
+
* `session.modalities.voice`: the tenant's published capability is
|
|
9418
|
+
* unchanged, and the microphone returns by itself on de-escalation.
|
|
9419
|
+
*/
|
|
9420
|
+
const escalated = session.status === "escalated";
|
|
9421
|
+
/**
|
|
9422
|
+
* The basket this widget built from its OWN adds — see `AddedCartLine`.
|
|
9423
|
+
* Always accumulated, even when the host has a `readCart` that reports
|
|
9424
|
+
* lines: the host read is asynchronous and can fail, and this is what the
|
|
9425
|
+
* summary falls back to when it does.
|
|
9426
|
+
*/
|
|
9427
|
+
const [addedLines, setAddedLines] = useState([]);
|
|
9428
|
+
/** The host's own last answer, or `null` while it has given none. */
|
|
9429
|
+
const [hostCart, setHostCart] = useState(null);
|
|
9430
|
+
const mountedRef = useRef(true);
|
|
9431
|
+
useEffect(() => {
|
|
9432
|
+
mountedRef.current = true;
|
|
9433
|
+
return () => {
|
|
9434
|
+
mountedRef.current = false;
|
|
9435
|
+
};
|
|
9436
|
+
}, []);
|
|
9437
|
+
/**
|
|
9438
|
+
* Monotonic issue number for `refreshHostCart`, so a read can tell whether
|
|
9439
|
+
* a NEWER one was started after it. See that callback for why.
|
|
9440
|
+
*
|
|
9441
|
+
* A ref, not state: it must be readable and writable without a re-render,
|
|
9442
|
+
* and nothing renders from it.
|
|
9443
|
+
*/
|
|
9444
|
+
const cartReadSeqRef = useRef(0);
|
|
9445
|
+
/**
|
|
9446
|
+
* Re-reads the host's cart. Silent on every failure — a bridge that cannot
|
|
9447
|
+
* answer leaves the last good snapshot (or `null`) standing, and the
|
|
9448
|
+
* summary falls back to `addedLines`. Never awaited by anything the
|
|
9449
|
+
* shopper is waiting on.
|
|
9450
|
+
*
|
|
9451
|
+
* **Only the LATEST-ISSUED read may set the snapshot.** Two triggers fire
|
|
9452
|
+
* this — a successful add, and a checkout intent — so overlapping reads are
|
|
9453
|
+
* ordinary, not a corner case, and `readCart` promises nothing about the
|
|
9454
|
+
* order they RESOLVE in (a host answering one from the network and the next
|
|
9455
|
+
* from a warm cache resolves them backwards). Without this guard the winner
|
|
9456
|
+
* is whichever resolves last, so a read issued BEFORE the add can land
|
|
9457
|
+
* after it and repaint the basket as it was before — the shopper then
|
|
9458
|
+
* checks out looking at a cart that is one add out of date. Comparing the
|
|
9459
|
+
* issue number, not a timestamp: it is exact, and it needs no clock.
|
|
9460
|
+
*/
|
|
9461
|
+
const refreshHostCart = useCallback(async () => {
|
|
9462
|
+
if (!bridge?.readCart) return;
|
|
9463
|
+
const seq = ++cartReadSeqRef.current;
|
|
9464
|
+
try {
|
|
9465
|
+
const snapshot = await bridge.readCart();
|
|
9466
|
+
if (mountedRef.current && seq === cartReadSeqRef.current) setHostCart(snapshot);
|
|
9467
|
+
} catch {}
|
|
9468
|
+
}, [bridge]);
|
|
9469
|
+
const onAddToCart = resolveAddToCartHandler(bridge, productHref, useCallback((item) => {
|
|
9470
|
+
setAddedLines((prev) => mergeAddedCartLine(prev, item));
|
|
9471
|
+
refreshHostCart();
|
|
9472
|
+
if (chatToken === void 0 || inCall) return;
|
|
9473
|
+
session.sendReport({
|
|
9474
|
+
kind: "cart_add",
|
|
9475
|
+
title: item.title,
|
|
9476
|
+
quantity: 1,
|
|
9477
|
+
productId: item.productId,
|
|
9478
|
+
...item.variantId !== void 0 ? { variantId: item.variantId } : {}
|
|
9479
|
+
});
|
|
9480
|
+
}, [
|
|
9481
|
+
chatToken,
|
|
9482
|
+
inCall,
|
|
9483
|
+
session,
|
|
9484
|
+
refreshHostCart
|
|
9485
|
+
]));
|
|
8511
9486
|
const navigate = useMemo(() => bridge?.navigate?.bind(bridge), [bridge]);
|
|
8512
9487
|
const onSendText = useCallback(async (text) => session.send(text), [session]);
|
|
8513
9488
|
/**
|
|
@@ -8541,6 +9516,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8541
9516
|
*/
|
|
8542
9517
|
const onToggleMic = useCallback(() => {
|
|
8543
9518
|
if (!voiceEnabled) return;
|
|
9519
|
+
if (escalated) return;
|
|
8544
9520
|
if (inCall) {
|
|
8545
9521
|
voice.toggleMic();
|
|
8546
9522
|
return;
|
|
@@ -8548,11 +9524,91 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8548
9524
|
voice.start({ greet: true });
|
|
8549
9525
|
}, [
|
|
8550
9526
|
voiceEnabled,
|
|
9527
|
+
escalated,
|
|
8551
9528
|
inCall,
|
|
8552
9529
|
voice
|
|
8553
9530
|
]);
|
|
8554
|
-
/**
|
|
8555
|
-
|
|
9531
|
+
/**
|
|
9532
|
+
* A call that outlives the handoff is a shopper talking to an AI leg the
|
|
9533
|
+
* person on the other end cannot hear, so the escalation ENDS it.
|
|
9534
|
+
*
|
|
9535
|
+
* The mid-call handoff is reachable, not theoretical: the composer only
|
|
9536
|
+
* DIMS during a call (`ConciergeShell`, `inCall && draft === ''` → an
|
|
9537
|
+
* opacity class, never `disabled`), so a shopper can type "get me a human"
|
|
9538
|
+
* while the call runs and `POST /widget/chat` answers with the SSE
|
|
9539
|
+
* `escalated` event — and the voice leg's own data channel carries a
|
|
9540
|
+
* `{ type: 'escalated' }` widget event (`WidgetToolEventSchema`) for the
|
|
9541
|
+
* same handoff asked for out loud.
|
|
9542
|
+
*
|
|
9543
|
+
* Depends on `voice.stop` rather than `voice`: the session object is a new
|
|
9544
|
+
* literal on every render of `useVoiceSession`, and an effect keyed on it
|
|
9545
|
+
* would re-run — and re-`stop()` — for the whole life of the escalated
|
|
9546
|
+
* conversation. `stop` is a `useCallback`, so this fires once per
|
|
9547
|
+
* escalation, and nothing here fights a caller who starts a fresh call
|
|
9548
|
+
* after de-escalation.
|
|
9549
|
+
*/
|
|
9550
|
+
const stopVoice = voice.stop;
|
|
9551
|
+
useEffect(() => {
|
|
9552
|
+
if (!escalated || !inCall) return;
|
|
9553
|
+
stopVoice();
|
|
9554
|
+
}, [
|
|
9555
|
+
escalated,
|
|
9556
|
+
inCall,
|
|
9557
|
+
stopVoice
|
|
9558
|
+
]);
|
|
9559
|
+
/**
|
|
9560
|
+
* The handoff asked for OUT LOUD, carried into the typed session.
|
|
9561
|
+
*
|
|
9562
|
+
* `useChatSession` learns of an escalation on its own transports only (the
|
|
9563
|
+
* SSE `escalated` frame, `sendAttachment`, the desk socket). A shopper who
|
|
9564
|
+
* says "get me a person" mid-call escalates on the VOICE leg instead — the
|
|
9565
|
+
* worker writes `{ type: 'escalated' }` to the LiveKit data channel and
|
|
9566
|
+
* `useVoiceSession` parses it into `widgetEvents`. This is the ONE hop that
|
|
9567
|
+
* joins the two: without it `escalated` above stayed false after a spoken
|
|
9568
|
+
* handoff, so the microphone gate, the attach control and the transcript
|
|
9569
|
+
* marker all waited for the shopper to ALSO type something.
|
|
9570
|
+
*
|
|
9571
|
+
* **Reacts to the EVENT, never to the contents of the list.** `widgetEvents`
|
|
9572
|
+
* is append-only and `stop()` does not clear it — the last call's cards stay
|
|
9573
|
+
* on screen — so `widgetEvents.some((e) => e.type === 'escalated')` would be
|
|
9574
|
+
* a boolean that can only ever turn on, and a shopper de-escalated back to
|
|
9575
|
+
* the AI would be re-escalated by the corpse of the call before it.
|
|
9576
|
+
*
|
|
9577
|
+
* **Consumed by IDENTITY, not by an index.** The hook caps the list
|
|
9578
|
+
* (`MAX_WIDGET_EVENTS`, a sliding `slice(-20)`), so a "how many have I
|
|
9579
|
+
* consumed" counter drifts past new entries the moment the cap is reached
|
|
9580
|
+
* and silently stops escalating. The parsed events are distinct objects
|
|
9581
|
+
* (`WidgetToolEventSchema.safeParse` mints one per frame), which makes
|
|
9582
|
+
* "have I already acted on THIS one" exact under both the cap and a
|
|
9583
|
+
* restart. A `WeakSet` because nothing here should keep a dropped event
|
|
9584
|
+
* alive.
|
|
9585
|
+
*
|
|
9586
|
+
* Not gated on `voiceEnabled`: an escalation frame is a fact the server
|
|
9587
|
+
* asserted about the conversation, and a tenant config that flips mid-call
|
|
9588
|
+
* must not be able to swallow it. `markHandoffToHuman` is idempotent and
|
|
9589
|
+
* stable (see `UseChatSessionResult.markHandoffToHuman`), so this fires once
|
|
9590
|
+
* per frame and a repeat costs nothing.
|
|
9591
|
+
*/
|
|
9592
|
+
const markHandoffToHuman = session.markHandoffToHuman;
|
|
9593
|
+
const consumedVoiceEventsRef = useRef(/* @__PURE__ */ new WeakSet());
|
|
9594
|
+
useEffect(() => {
|
|
9595
|
+
let handoff = false;
|
|
9596
|
+
for (const event of voice.widgetEvents) {
|
|
9597
|
+
if (consumedVoiceEventsRef.current.has(event)) continue;
|
|
9598
|
+
consumedVoiceEventsRef.current.add(event);
|
|
9599
|
+
if (event.type === "escalated") handoff = true;
|
|
9600
|
+
}
|
|
9601
|
+
if (handoff) markHandoffToHuman();
|
|
9602
|
+
}, [voice.widgetEvents, markHandoffToHuman]);
|
|
9603
|
+
/** Where the call is, in the caller's terms — see `deriveCallPhase`. */
|
|
9604
|
+
const callPhase = deriveCallPhase({
|
|
9605
|
+
voiceEnabled,
|
|
9606
|
+
phase: voice.phase,
|
|
9607
|
+
micPending: voice.micPending,
|
|
9608
|
+
micOpen: voice.micOpen,
|
|
9609
|
+
error: voice.error,
|
|
9610
|
+
state: voice.state
|
|
9611
|
+
});
|
|
8556
9612
|
/**
|
|
8557
9613
|
* One conversation. Simpler than `apps/web`'s own merge
|
|
8558
9614
|
* (`widget-launcher.tsx`'s `widgetTurns`): this component does not
|
|
@@ -8605,6 +9661,57 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8605
9661
|
voiceEnabled,
|
|
8606
9662
|
locale
|
|
8607
9663
|
]);
|
|
9664
|
+
/**
|
|
9665
|
+
* The SAME read `VoiceWidget` makes to decide whether to draw the summary —
|
|
9666
|
+
* literally the same function (`checkoutIntentFromTurns`), not a second
|
|
9667
|
+
* copy of it — put to a different use here: this is the moment to re-read
|
|
9668
|
+
* the host's cart, so the basket the shopper is about to check out with is
|
|
9669
|
+
* the one that exists NOW and not the one that existed at the last add.
|
|
9670
|
+
* Reading the merged turns rather than `session.turns` alone is what makes
|
|
9671
|
+
* a SPOKEN "let's check out" refresh too.
|
|
9672
|
+
*/
|
|
9673
|
+
const wantsCheckout = useMemo(() => checkoutIntentFromTurns(widgetTurns), [widgetTurns]);
|
|
9674
|
+
useEffect(() => {
|
|
9675
|
+
if (wantsCheckout) refreshHostCart();
|
|
9676
|
+
}, [wantsCheckout, refreshHostCart]);
|
|
9677
|
+
/**
|
|
9678
|
+
* The host's answer wins wherever it HAS one, and the widget's own
|
|
9679
|
+
* accumulation covers the rest:
|
|
9680
|
+
*
|
|
9681
|
+
* - `lines` — the host's basket is the real one, so it replaces this
|
|
9682
|
+
* widget's outright. Absent (never reported) falls back to `addedLines`;
|
|
9683
|
+
* an EMPTY array does not, because "the cart is empty" is a real answer
|
|
9684
|
+
* and rendering our own stale rows over it would be a lie.
|
|
9685
|
+
* - `subtotalCents` — the host's total survives discounts and bundle
|
|
9686
|
+
* pricing that multiplying a unit price by a quantity cannot reproduce.
|
|
9687
|
+
* - `currency` — likewise the host's, falling back to whatever the cards
|
|
9688
|
+
* themselves were priced in.
|
|
9689
|
+
*/
|
|
9690
|
+
const cartCurrency = hostCart?.currency ?? addedLines[0]?.currency ?? "USD";
|
|
9691
|
+
const cartLines = useMemo(() => cartLinesFromSnapshot(hostCart, cartCurrency), [hostCart, cartCurrency]) ?? addedLines;
|
|
9692
|
+
const cartSubtotalMinor = hostCart?.subtotalCents ?? cartLines.reduce((total, line) => total + line.priceMinor * line.quantity, 0);
|
|
9693
|
+
/**
|
|
9694
|
+
* Fire the checkout. `undefined` (rather than an `onCheckout` that always
|
|
9695
|
+
* fails) whenever there is no basket at all, so `VoiceWidget` renders no
|
|
9696
|
+
* summary — the same "additive per caller" posture `onAddToCart` keeps.
|
|
9697
|
+
*/
|
|
9698
|
+
const onCheckout = useCallback(async () => {
|
|
9699
|
+
const items = addedLines.filter((line) => line.variantId !== void 0).map((line) => ({
|
|
9700
|
+
variantId: line.variantId,
|
|
9701
|
+
quantity: line.quantity
|
|
9702
|
+
}));
|
|
9703
|
+
return resolveCheckoutUrl(bridge, () => session.checkout(items, void 0, session.cartAttributionToken ?? void 0));
|
|
9704
|
+
}, [
|
|
9705
|
+
addedLines,
|
|
9706
|
+
bridge,
|
|
9707
|
+
session
|
|
9708
|
+
]);
|
|
9709
|
+
const cart = cartLines.length > 0 ? {
|
|
9710
|
+
lines: cartLines,
|
|
9711
|
+
subtotalMinor: cartSubtotalMinor,
|
|
9712
|
+
currency: cartCurrency,
|
|
9713
|
+
onCheckout
|
|
9714
|
+
} : void 0;
|
|
8608
9715
|
return /* @__PURE__ */ jsx(VoiceWidget, {
|
|
8609
9716
|
state: inCall ? voice.state : "idle",
|
|
8610
9717
|
turns: widgetTurns,
|
|
@@ -8618,9 +9725,10 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8618
9725
|
onSendText,
|
|
8619
9726
|
open,
|
|
8620
9727
|
onOpenChange: setOpen,
|
|
8621
|
-
escalated
|
|
9728
|
+
escalated,
|
|
8622
9729
|
status: session.status === "error" ? session.error ?? "error" : voiceEnabled ? voice.error ?? void 0 : void 0,
|
|
8623
9730
|
...onAddToCart ? { onAddToCart } : {},
|
|
9731
|
+
...cart ? { cart } : {},
|
|
8624
9732
|
...curationHref ? { curationHref } : {},
|
|
8625
9733
|
...productHref ? { productHref } : {},
|
|
8626
9734
|
...navigate ? { navigate } : {},
|
|
@@ -8634,4 +9742,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
8634
9742
|
});
|
|
8635
9743
|
}
|
|
8636
9744
|
//#endregion
|
|
8637
|
-
export {
|
|
9745
|
+
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 };
|