@saar-ai/web-widget 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/chat-tMKkYmTC.js +592 -0
- package/dist/chunks/{host-widget-C9EyGeiN.js → host-widget-B0SkhMIs.js} +1450 -103
- package/dist/format-money.d.ts +54 -17
- package/dist/format-money.d.ts.map +1 -1
- package/dist/generated/widget-css.d.ts.map +1 -1
- package/dist/host-widget.d.ts +62 -0
- package/dist/host-widget.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/messages.d.ts +17 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/next/index.js +1 -1
- package/dist/turn-order.d.ts +106 -0
- package/dist/turn-order.d.ts.map +1 -0
- package/dist/use-chat-session.d.ts +128 -1
- package/dist/use-chat-session.d.ts.map +1 -1
- package/dist/use-voice-session.d.ts +31 -1
- package/dist/use-voice-session.d.ts.map +1 -1
- package/dist/voice-widget.d.ts +66 -6
- package/dist/voice-widget.d.ts.map +1 -1
- package/dist/widget-cards.d.ts.map +1 -1
- package/dist/widget.css +1 -1
- package/package.json +3 -3
- package/src/styles/concierge.css +45 -0
- package/dist/chunks/chat-DfajYOmN.js +0 -240
|
@@ -4480,6 +4480,7 @@ var defaultWidgetMessages = {
|
|
|
4480
4480
|
cart_summary_total: "Total",
|
|
4481
4481
|
checkout_now: "Checkout",
|
|
4482
4482
|
checkout_failed: "Could not start checkout. Try again.",
|
|
4483
|
+
cart_add_failed: "That could not be added here — open the product page to add it",
|
|
4483
4484
|
voice_state_connecting: "Connecting",
|
|
4484
4485
|
voice_state_listening: "Listening",
|
|
4485
4486
|
voice_state_thinking: "Thinking",
|
|
@@ -5754,37 +5755,274 @@ function WidgetMarkdown({ text }) {
|
|
|
5754
5755
|
});
|
|
5755
5756
|
}
|
|
5756
5757
|
//#endregion
|
|
5757
|
-
//#region
|
|
5758
|
+
//#region ../widget-protocol/dist/money.js
|
|
5759
|
+
/**
|
|
5760
|
+
* The ISO 4217 minor-unit table, and the ONE way a money figure is written
|
|
5761
|
+
* on a shopper's screen.
|
|
5762
|
+
*
|
|
5763
|
+
* ## Why it lives here, in a wire-contract package
|
|
5764
|
+
*
|
|
5765
|
+
* Because a price is answered by two processes that must agree, and one of
|
|
5766
|
+
* them runs in a merchant's browser.
|
|
5767
|
+
*
|
|
5768
|
+
* The turn tier already owned the table: `@wesence/agent-core`'s
|
|
5769
|
+
* `commerce/money.ts` holds `formatMinorUnitsForModel`, the renderer that
|
|
5770
|
+
* builds the shopper-cart block BOTH legs of a conversation read, so that a
|
|
5771
|
+
* JPY basket is not "9900 JPY" when the shopper types and "99 JPY" when they
|
|
5772
|
+
* call. Meanwhile `@saar-ai/web-widget`'s own `format-money.ts` divided
|
|
5773
|
+
* `priceMinor` by a hardcoded 100 and said so — "SIMPLIFICATION, stated
|
|
5774
|
+
* rather than hidden". Once the server's table was completed, that
|
|
5775
|
+
* simplification became the same two-answers-to-one-question bug the table
|
|
5776
|
+
* exists to prevent, one layer out: the concierge would say "9900 JPY" in
|
|
5777
|
+
* prose and the product card beside it would read "¥99".
|
|
5778
|
+
*
|
|
5779
|
+
* The table could not simply be imported from `@wesence/agent-core`.
|
|
5780
|
+
* `@saar-ai/web-widget` publishes publicly to npm and **no `@wesence/*`
|
|
5781
|
+
* specifier may survive into its tarball** (`docs/PACKAGE_DISTRIBUTION.md`,
|
|
5782
|
+
* enforced by `tools/npm-bundle-provenance.mjs` with an empty allowlist), so
|
|
5783
|
+
* a `@wesence/*` home is a dead end for anything the widget bundles. And a
|
|
5784
|
+
* fourth hand-kept copy was the wrong answer twice over: `web-widget`'s own
|
|
5785
|
+
* `AGENTS.md` says outright that "a third copy anywhere is the signal to
|
|
5786
|
+
* extract a shared package instead of copying again", and a currency table
|
|
5787
|
+
* is precisely the kind of thing that gets a code added on one side only.
|
|
5788
|
+
*
|
|
5789
|
+
* So the table moved DOWN rather than sideways. `@wesence/agent-core`
|
|
5790
|
+
* re-exports it from here — the same "re-exported rather than relocated in
|
|
5791
|
+
* the callers' import statements" move `apps/api/src/catalog/money.ts`
|
|
5792
|
+
* already makes for agent-core — so `apps/api`, `apps/agent`,
|
|
5793
|
+
* `@saar-ai/web-widget` and `apps/web` all read ONE set of constants. There
|
|
5794
|
+
* is no second table to drift from the first; there is only this one.
|
|
5795
|
+
*
|
|
5796
|
+
* ## Why it is safe to put it in this package
|
|
5797
|
+
*
|
|
5798
|
+
* This file is zero-dependency and zod-free, deliberately, exactly like
|
|
5799
|
+
* `./desk-typing`: `@saar-ai/web-widget` imports it STATICALLY into the chat
|
|
5800
|
+
* bundle a shopper downloads, which must not pull the protocol's validation
|
|
5801
|
+
* machinery in behind a currency table. Keep it that way. It is reached
|
|
5802
|
+
* through its own `./money` subpath and is deliberately NOT re-exported from
|
|
5803
|
+
* the barrel, so there is no import path that drags zod in with it.
|
|
5804
|
+
*
|
|
5805
|
+
* `@wesence/agent-core` gaining a runtime dependency on a `@saar-ai/*`
|
|
5806
|
+
* package is the direction this repo has already sanctioned once, for the
|
|
5807
|
+
* same reason: `@wesence/voice-protocol` depends on `@saar-ai/widget-protocol`
|
|
5808
|
+
* today (see `packages/widget-protocol/AGENTS.md`), and `agent-core`, like
|
|
5809
|
+
* `voice-protocol`, is this repo's OWN code rather than framework-inherited
|
|
5810
|
+
* despite the scope (root `AGENTS.md` → "the `@wesence/*` scope is framework
|
|
5811
|
+
* IDENTITY, not framework OWNERSHIP"). `apps/agent` already resolves this package
|
|
5812
|
+
* transitively through `voice-protocol`, so nothing new reaches the turn
|
|
5813
|
+
* tier's deployment.
|
|
5814
|
+
*/
|
|
5815
|
+
/**
|
|
5816
|
+
* ISO-4217 currencies with zero minor-unit digits. **Exhaustive**, the same
|
|
5817
|
+
* way {@link THREE_DECIMAL_CURRENCIES} below already is.
|
|
5818
|
+
*
|
|
5819
|
+
* ## Why it used to be a sample, and why that reasoning expired
|
|
5820
|
+
*
|
|
5821
|
+
* This list held six codes and defended the gap: an unlisted zero-decimal
|
|
5822
|
+
* currency falls back to the 2-decimal default, which "is never silently
|
|
5823
|
+
* wrong in the dangerous direction — treating a real zero-decimal amount as
|
|
5824
|
+
* 2-decimal produces a value 100x too LARGE", i.e. loud enough to catch in
|
|
5825
|
+
* review.
|
|
5826
|
+
*
|
|
5827
|
+
* That argument is about the INGEST direction only, where the output of a
|
|
5828
|
+
* wrong guess is a stored integer a human eventually eyeballs. It does not
|
|
5829
|
+
* survive the DISPLAY direction, which runs on both legs of the concierge and
|
|
5830
|
+
* now on the product card too: there the same omission makes `5000 XOF`
|
|
5831
|
+
* render as `"50.00 XOF"` — understated by 100x, the QUIET direction — and
|
|
5832
|
+
* the guardrail beside it instructs the model to quote the cart block's
|
|
5833
|
+
* figures exactly and never recompute them. A shopper is told their basket
|
|
5834
|
+
* costs a hundredth of what it does, by a store that sounds certain.
|
|
5835
|
+
*
|
|
5836
|
+
* So the set is completed rather than defended. It is the full ISO 4217
|
|
5837
|
+
* zero-decimal list (BIF, CLP, DJF, GNF, ISK, JPY, KMF, KRW, PYG, RWF, UGX,
|
|
5838
|
+
* VND, VUV, XAF, XOF, XPF) — eleven of which are West/Central African and
|
|
5839
|
+
* Pacific franc-zone currencies that a merchant can absolutely settle in.
|
|
5840
|
+
* `UYI` (Uruguay Peso en Unidades Indexadas) is the one ISO zero-decimal
|
|
5841
|
+
* code deliberately left out: it is a FUND code, an accounting unit no
|
|
5842
|
+
* storefront prices in, and Shopify does not settle in it.
|
|
5843
|
+
*
|
|
5844
|
+
* **`HUF` is in this set and is NOT an ISO zero-decimal currency** (ISO 4217
|
|
5845
|
+
* gives the forint two digits). It predates this change and stays, because
|
|
5846
|
+
* every reader of this table reads THIS table, so the system is
|
|
5847
|
+
* self-consistent either way — but flipping it now would reinterpret every
|
|
5848
|
+
* already-stored HUF integer by 100x, which is a backfill, not a fix. Worth
|
|
5849
|
+
* knowing before someone "corrects" it: the fillér was withdrawn from
|
|
5850
|
+
* circulation, so HUF prices are whole numbers in practice and the payment
|
|
5851
|
+
* processors treat it as zero-decimal too.
|
|
5852
|
+
*
|
|
5853
|
+
* That deviation is exactly why {@link formatMoney} below passes the digit
|
|
5854
|
+
* count to `Intl` explicitly instead of letting ICU decide: ICU knows the ISO
|
|
5855
|
+
* answer for HUF (two digits) and would render a card as `9 900,00 Ft` beside
|
|
5856
|
+
* a concierge saying `9900 HUF`. Same magnitude, two different claims about
|
|
5857
|
+
* how precise the price is — which is the same class of disagreement this
|
|
5858
|
+
* table exists to end, just smaller.
|
|
5859
|
+
*
|
|
5860
|
+
* Both directions of the commerce domain's minor/major boundary read this
|
|
5861
|
+
* table. The conversions themselves — a provider's decimal string in at sync
|
|
5862
|
+
* time, a shopper's typed "max price" in at query time — stay in
|
|
5863
|
+
* `apps/api/src/catalog/money.ts`, which re-exports these constants (through
|
|
5864
|
+
* `@wesence/agent-core`) rather than keeping a copy; that file's own doc
|
|
5865
|
+
* comment carries the two 100x incidents that made the boundary worth naming.
|
|
5866
|
+
*/
|
|
5867
|
+
var ZERO_DECIMAL_CURRENCIES = new Set([
|
|
5868
|
+
"BIF",
|
|
5869
|
+
"CLP",
|
|
5870
|
+
"DJF",
|
|
5871
|
+
"GNF",
|
|
5872
|
+
"HUF",
|
|
5873
|
+
"ISK",
|
|
5874
|
+
"JPY",
|
|
5875
|
+
"KMF",
|
|
5876
|
+
"KRW",
|
|
5877
|
+
"PYG",
|
|
5878
|
+
"RWF",
|
|
5879
|
+
"UGX",
|
|
5880
|
+
"VND",
|
|
5881
|
+
"VUV",
|
|
5882
|
+
"XAF",
|
|
5883
|
+
"XOF",
|
|
5884
|
+
"XPF"
|
|
5885
|
+
]);
|
|
5758
5886
|
/**
|
|
5759
|
-
*
|
|
5760
|
-
*
|
|
5761
|
-
*
|
|
5762
|
-
*
|
|
5763
|
-
*
|
|
5764
|
-
* and
|
|
5765
|
-
*
|
|
5766
|
-
*
|
|
5767
|
-
*
|
|
5768
|
-
*
|
|
5769
|
-
*
|
|
5770
|
-
* already committed to.
|
|
5771
|
-
*
|
|
5772
|
-
* SIMPLIFICATION, stated rather than hidden: this assumes a 2-decimal minor
|
|
5773
|
-
* unit (cents → dollars). A zero-decimal currency (JPY) or a 3-decimal one
|
|
5774
|
-
* (KWD, BHD) would need a per-currency minor-unit table.
|
|
5887
|
+
* ISO-4217 currencies with THREE minor-unit digits.
|
|
5888
|
+
*
|
|
5889
|
+
* The complete ISO-4217 three-decimal list, not a sample — it is short enough
|
|
5890
|
+
* to be exhaustive, and a partial list here would reintroduce the bug it
|
|
5891
|
+
* exists to close. Without it these currencies fall through to the 2-decimal
|
|
5892
|
+
* default and the third digit is DISCARDED, which unlike the zero-decimal
|
|
5893
|
+
* case above is SMALL and therefore quiet: a 100x figure is caught in review,
|
|
5894
|
+
* a figure short by half a fils is not.
|
|
5895
|
+
*
|
|
5896
|
+
* Gulf-relevant rather than theoretical: three of these seven (BHD, KWD, OMR)
|
|
5897
|
+
* are GCC currencies.
|
|
5775
5898
|
*/
|
|
5776
|
-
|
|
5777
|
-
|
|
5899
|
+
var THREE_DECIMAL_CURRENCIES = new Set([
|
|
5900
|
+
"BHD",
|
|
5901
|
+
"IQD",
|
|
5902
|
+
"JOD",
|
|
5903
|
+
"KWD",
|
|
5904
|
+
"OMR",
|
|
5905
|
+
"TND",
|
|
5906
|
+
"LYD"
|
|
5907
|
+
]);
|
|
5908
|
+
/**
|
|
5909
|
+
* Minor units per major unit, as a power of ten.
|
|
5910
|
+
*
|
|
5911
|
+
* An unknown code gets 2 — the overwhelmingly common shape, and the only
|
|
5912
|
+
* honest default when the alternative is throwing inside a product card.
|
|
5913
|
+
*
|
|
5914
|
+
* @param currency an ISO 4217 code; case is not significant
|
|
5915
|
+
*/
|
|
5916
|
+
function minorUnitDecimals(currency) {
|
|
5917
|
+
const code = currency.toUpperCase();
|
|
5918
|
+
if (ZERO_DECIMAL_CURRENCIES.has(code)) return 0;
|
|
5919
|
+
if (THREE_DECIMAL_CURRENCIES.has(code)) return 3;
|
|
5920
|
+
return 2;
|
|
5921
|
+
}
|
|
5922
|
+
/**
|
|
5923
|
+
* Format a minor-unit integer price (cents, paise, fils, yen) as localized
|
|
5924
|
+
* currency text — what a product card, a cart line and the demo storefront
|
|
5925
|
+
* all render.
|
|
5926
|
+
*
|
|
5927
|
+
* Pure and locale-explicit: every caller passes its own resolved locale
|
|
5928
|
+
* rather than relying on a browser default that could silently disagree with
|
|
5929
|
+
* the `dir`/`lang` the page already committed to.
|
|
5930
|
+
*
|
|
5931
|
+
* ## The digit count is passed to `Intl`, not left to it
|
|
5932
|
+
*
|
|
5933
|
+
* `Intl.NumberFormat`'s currency style already knows how many fraction digits
|
|
5934
|
+
* a currency has — and for every code except `HUF` it agrees with
|
|
5935
|
+
* {@link minorUnitDecimals}. `HUF` is the whole reason this is explicit: the
|
|
5936
|
+
* table treats the forint as zero-decimal (see
|
|
5937
|
+
* {@link ZERO_DECIMAL_CURRENCIES}) and ICU treats it as two-decimal, so
|
|
5938
|
+
* leaving the choice to ICU would draw a card reading `9 900,00 Ft` next to a
|
|
5939
|
+
* concierge saying `9900 HUF`. Forcing the digit count makes the card and the
|
|
5940
|
+
* cart block one answer, for every currency, including the one where this
|
|
5941
|
+
* repo knowingly departs from ISO.
|
|
5942
|
+
*
|
|
5943
|
+
* It also makes the rendering independent of the ICU data a given browser
|
|
5944
|
+
* happens to ship, which is the same reason `formatMinorUnitsForModel`
|
|
5945
|
+
* (`@wesence/agent-core`) refuses to use `Intl` at all on the model-facing
|
|
5946
|
+
* side.
|
|
5947
|
+
*
|
|
5948
|
+
* Never throws: an unrecognised currency code or locale must not take out a
|
|
5949
|
+
* product card, so it falls back to a plain, still-comprehensible rendering
|
|
5950
|
+
* with the same digit count.
|
|
5951
|
+
*/
|
|
5952
|
+
function formatMoney$1(priceMinor, currency, locale) {
|
|
5953
|
+
const code = typeof currency === "string" ? currency : String(currency);
|
|
5954
|
+
const decimals = minorUnitDecimals(code);
|
|
5955
|
+
const major = priceMinor / 10 ** decimals;
|
|
5778
5956
|
try {
|
|
5779
5957
|
return new Intl.NumberFormat(locale, {
|
|
5780
5958
|
style: "currency",
|
|
5781
|
-
currency
|
|
5959
|
+
currency: code,
|
|
5960
|
+
minimumFractionDigits: decimals,
|
|
5961
|
+
maximumFractionDigits: decimals
|
|
5782
5962
|
}).format(major);
|
|
5783
5963
|
} catch {
|
|
5784
|
-
return `${major.toFixed(
|
|
5964
|
+
return `${major.toFixed(decimals)} ${code}`;
|
|
5785
5965
|
}
|
|
5786
5966
|
}
|
|
5787
5967
|
//#endregion
|
|
5968
|
+
//#region src/format-money.ts
|
|
5969
|
+
/**
|
|
5970
|
+
* Money on a card, a cart line and a checkout summary — the shared formatter
|
|
5971
|
+
* from `@saar-ai/widget-protocol/money`, which owns it.
|
|
5972
|
+
*
|
|
5973
|
+
* ## Why this stopped being a copy
|
|
5974
|
+
*
|
|
5975
|
+
* It used to be a hand-kept duplicate of `apps/web/src/lib/money.ts`, on the
|
|
5976
|
+
* documented grounds that both were "small, pure, `Intl`-only" functions with
|
|
5977
|
+
* nothing to keep in sync — the same reasoning `cn` and `text-direction.ts`
|
|
5978
|
+
* still carry, and still correctly. That held only while the function had no
|
|
5979
|
+
* DOMAIN KNOWLEDGE in it. It had one all along, stated in its own doc comment
|
|
5980
|
+
* as a "SIMPLIFICATION, stated rather than hidden": it divided `priceMinor` by
|
|
5981
|
+
* a hardcoded 100.
|
|
5982
|
+
*
|
|
5983
|
+
* That simplification became a bug the moment the server side of the same
|
|
5984
|
+
* question was fixed. `@wesence/agent-core`'s `commerce/money.ts` now carries
|
|
5985
|
+
* the complete ISO 4217 zero-decimal and three-decimal sets, so the concierge
|
|
5986
|
+
* says "9900 JPY" in prose while this function drew "¥99" on the card beside
|
|
5987
|
+
* it — two answers to one question, inside one conversation, which is the
|
|
5988
|
+
* exact failure that table exists to prevent.
|
|
5989
|
+
*
|
|
5990
|
+
* Three copies of a currency table is not a tradeoff, it is a scheduled
|
|
5991
|
+
* outage: a code gets added on one side and not the others. This package's
|
|
5992
|
+
* own `AGENTS.md` already says what to do about it — "a third copy anywhere
|
|
5993
|
+
* is the signal to extract a shared package instead of copying again" — so
|
|
5994
|
+
* the table and the formatter moved into `@saar-ai/widget-protocol/money`,
|
|
5995
|
+
* which this package already bundles, and `@wesence/agent-core` and
|
|
5996
|
+
* `apps/web/src/lib/money.ts` re-export the same one.
|
|
5997
|
+
*
|
|
5998
|
+
* `@saar-ai/widget-protocol`, not `@wesence/agent-core`, because no
|
|
5999
|
+
* `@wesence/*` specifier may survive into this package's published tarball
|
|
6000
|
+
* (`docs/PACKAGE_DISTRIBUTION.md`, enforced with an empty allowlist by
|
|
6001
|
+
* `scripts/check-npm-bundle-provenance.mjs`). The `/money` subpath is
|
|
6002
|
+
* zod-free and zero-dependency for the same reason `/desk-typing` is: this is
|
|
6003
|
+
* a STATIC import into the chat bundle a shopper downloads.
|
|
6004
|
+
*
|
|
6005
|
+
* ## Why a typed `const`, and not `export { formatMoney } from '…'`
|
|
6006
|
+
*
|
|
6007
|
+
* Because `formatMoney` is part of this package's PUBLIC npm surface
|
|
6008
|
+
* (`index.ts` re-exports it) and `@saar-ai/widget-protocol` is `private: true`
|
|
6009
|
+
* — bundled into `dist/` at build time, never published. A re-export
|
|
6010
|
+
* statement makes `tsc --emitDeclarationOnly` write that specifier into
|
|
6011
|
+
* `dist/format-money.d.ts` verbatim, and an installer resolving types under
|
|
6012
|
+
* `node16`/`bundler` cannot resolve it: the runtime import is inlined by the
|
|
6013
|
+
* bundler, but the DECLARATION names a package that does not exist on npm.
|
|
6014
|
+
* That is the same declaration leak `@saar-ai/widget-protocol/tuning` was
|
|
6015
|
+
* created to close, in the other direction.
|
|
6016
|
+
*
|
|
6017
|
+
* An explicitly annotated `const` erases the specifier: every type in the
|
|
6018
|
+
* signature is a primitive, so the emitted declaration is a self-contained
|
|
6019
|
+
* `export declare const formatMoney: (...) => string` with no import at all.
|
|
6020
|
+
* The binding is still the SAME function object, which is what
|
|
6021
|
+
* `__tests__/format-money.test.ts` asserts by identity — a local
|
|
6022
|
+
* reimplementation fails that test whatever it happens to compute.
|
|
6023
|
+
*/
|
|
6024
|
+
var formatMoney = formatMoney$1;
|
|
6025
|
+
//#endregion
|
|
5788
6026
|
//#region src/widget-cards.tsx
|
|
5789
6027
|
/**
|
|
5790
6028
|
* Is this click a plain, unmodified left click — the only kind that should
|
|
@@ -5974,7 +6212,7 @@ function WidgetCardList({ cards, onAddToCart, curationHref, productHref, navigat
|
|
|
5974
6212
|
children: [/* @__PURE__ */ jsx("ul", {
|
|
5975
6213
|
"data-testid": "widget-card-list",
|
|
5976
6214
|
"data-layout": roomy ? "grid" : "carousel",
|
|
5977
|
-
className: roomy ? "grid grid-cols-[repeat(auto-fit,minmax(15rem,1fr))] gap-2" : "
|
|
6215
|
+
className: roomy ? "grid grid-cols-[repeat(auto-fit,minmax(15rem,1fr))] gap-2" : "card-carousel flex snap-x snap-mandatory gap-2 overflow-x-auto overscroll-x-contain",
|
|
5978
6216
|
children: visibleItems.map((item) => {
|
|
5979
6217
|
const href = item.handle && productHref ? productHref(item.handle) : void 0;
|
|
5980
6218
|
return /* @__PURE__ */ jsxs("li", {
|
|
@@ -6401,6 +6639,13 @@ var SUGGESTION_KEYS = [
|
|
|
6401
6639
|
"suggestion_3"
|
|
6402
6640
|
];
|
|
6403
6641
|
/**
|
|
6642
|
+
* The settled agent bubble's look, shared by the turn renderer and the
|
|
6643
|
+
* human-typing indicator — one constant, so "the typing bubble looks exactly
|
|
6644
|
+
* like the reply it precedes" is enforced by reference, not by a copied
|
|
6645
|
+
* class string that drifts on the next restyle.
|
|
6646
|
+
*/
|
|
6647
|
+
var AGENT_BUBBLE_CLASS = "ring-brand-plum/10 rounded-2xl rounded-es-md bg-[var(--widget-bubble)] text-[var(--widget-foreground)] ring-1";
|
|
6648
|
+
/**
|
|
6404
6649
|
* Does this line read as "I want to pay now"?
|
|
6405
6650
|
*
|
|
6406
6651
|
* Deliberately a plain phrase match on the SHOPPER's own words rather than a
|
|
@@ -6429,26 +6674,69 @@ function readsAsCheckoutIntent(text) {
|
|
|
6429
6674
|
].some((phrase) => t.includes(phrase));
|
|
6430
6675
|
}
|
|
6431
6676
|
/**
|
|
6432
|
-
* Does this
|
|
6677
|
+
* Does this line ask to SEE the basket — "show me my cart", "what's my
|
|
6678
|
+
* total"?
|
|
6679
|
+
*
|
|
6680
|
+
* A separate read from {@link readsAsCheckoutIntent} because it is a
|
|
6681
|
+
* different question with the same answer: the basket itself. Asking what is
|
|
6682
|
+
* in the cart, or what it comes to, is answered by lines, prices and a
|
|
6683
|
+
* running total — not by prose. Without this the concierge answered "show me
|
|
6684
|
+
* my cart" as an ordinary question and TYPED the basket back as a bullet list
|
|
6685
|
+
* with no prices at all, then refused the total, because the server's
|
|
6686
|
+
* guardrails (rightly) forbid it from stating a price no tool grounded.
|
|
6687
|
+
* Observed on the KH storefront.
|
|
6688
|
+
*
|
|
6689
|
+
* Wider than the checkout list on purpose: a false positive here shows a
|
|
6690
|
+
* basket the shopper is already looking at the contents of, which costs
|
|
6691
|
+
* nothing. Bare "how much" is deliberately absent — "how much is delivery?"
|
|
6692
|
+
* is a question about a policy, not about the basket.
|
|
6693
|
+
*/
|
|
6694
|
+
function readsAsCartViewIntent(text) {
|
|
6695
|
+
const t = text.toLowerCase();
|
|
6696
|
+
return [
|
|
6697
|
+
"my cart",
|
|
6698
|
+
"my basket",
|
|
6699
|
+
"my bag",
|
|
6700
|
+
"view cart",
|
|
6701
|
+
"see cart",
|
|
6702
|
+
"show cart",
|
|
6703
|
+
"open cart",
|
|
6704
|
+
"cart total",
|
|
6705
|
+
"basket total",
|
|
6706
|
+
"order total",
|
|
6707
|
+
"grand total",
|
|
6708
|
+
"total amount",
|
|
6709
|
+
"total cost",
|
|
6710
|
+
"the total"
|
|
6711
|
+
].some((phrase) => t.includes(phrase));
|
|
6712
|
+
}
|
|
6713
|
+
/**
|
|
6714
|
+
* Does this thread, as it stands, want the basket on screen?
|
|
6433
6715
|
*
|
|
6434
6716
|
* The shopper's MOST RECENT line, not "any line ever": once they carry on
|
|
6435
6717
|
* shopping past the summary the basket should get out of the way again, and a
|
|
6436
6718
|
* sticky flag would leave it wedged at the bottom of every later answer.
|
|
6437
6719
|
*
|
|
6720
|
+
* TWO intents, ONE answer. Asking to pay ({@link readsAsCheckoutIntent}) and
|
|
6721
|
+
* asking to see the cart ({@link readsAsCartViewIntent}) are different
|
|
6722
|
+
* questions that are both answered by rendering the basket, so they share a
|
|
6723
|
+
* single read rather than two flags that could disagree about the same line.
|
|
6724
|
+
*
|
|
6438
6725
|
* There is exactly ONE of these because two consumers ask the same question
|
|
6439
6726
|
* of the same transcript and must never disagree about the answer:
|
|
6440
6727
|
* `VoiceWidget` below draws the basket from it, and `ConciergeWidget`
|
|
6441
6728
|
* (`host-widget.tsx`) re-reads the HOST's cart from it, so the basket the
|
|
6442
|
-
* shopper is
|
|
6443
|
-
*
|
|
6729
|
+
* shopper is looking at is the one that exists now. Two copies of the same
|
|
6730
|
+
* `reverse().find()` is how those two quietly drift apart.
|
|
6444
6731
|
*
|
|
6445
6732
|
* Takes only what it reads, so a caller with its own merged turn shape (which
|
|
6446
6733
|
* `ConciergeWidget` has — typed turns plus spoken lines plus rendered cards)
|
|
6447
6734
|
* can pass it without conversion.
|
|
6448
6735
|
*/
|
|
6449
|
-
function
|
|
6736
|
+
function basketIntentFromTurns(turns) {
|
|
6450
6737
|
const lastCallerLine = [...turns].reverse().find((turn) => turn.speaker === "caller");
|
|
6451
|
-
|
|
6738
|
+
if (lastCallerLine === void 0) return false;
|
|
6739
|
+
return readsAsCheckoutIntent(lastCallerLine.text) || readsAsCartViewIntent(lastCallerLine.text);
|
|
6452
6740
|
}
|
|
6453
6741
|
/**
|
|
6454
6742
|
* The end-user agent widget: a launcher bubble that expands into a conversation
|
|
@@ -6478,7 +6766,7 @@ function checkoutIntentFromTurns(turns) {
|
|
|
6478
6766
|
* `dir`, resolved from that line's locale rather than inherited from the page —
|
|
6479
6767
|
* inheriting is what renders Arabic punctuation on the wrong end of a sentence.
|
|
6480
6768
|
*/
|
|
6481
|
-
function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, open, onOpenChange, status, mode = "voice", escalated = false, onAddToCart, curationHref, productHref, onAttachFile, launcherLabel, position, onPositionChange, cart, messages = defaultWidgetMessages, navigate, locale = "en", skinStyle, avatar, attribution }) {
|
|
6769
|
+
function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle", onSendText, micOpen, open, onOpenChange, status, mode = "voice", escalated = false, humanTyping = false, onTyping, onAddToCart, curationHref, productHref, onAttachFile, launcherLabel, position, onPositionChange, cart, messages = defaultWidgetMessages, navigate, locale = "en", skinStyle, avatar, attribution }) {
|
|
6482
6770
|
const [draft, setDraft] = useState("");
|
|
6483
6771
|
const [sending, setSending] = useState(false);
|
|
6484
6772
|
/** Roomy mode — see the expand control in the header. Collapses back on close, so a reopened widget starts small. */
|
|
@@ -6513,8 +6801,8 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6513
6801
|
* line only when the host left it empty, which is the ordinary case.
|
|
6514
6802
|
*/
|
|
6515
6803
|
const statusLine = status ?? voiceUnavailable;
|
|
6516
|
-
/** Whether the shopper's MOST RECENT line asked
|
|
6517
|
-
const
|
|
6804
|
+
/** Whether the shopper's MOST RECENT line asked for the basket — to pay, or just to see it. Same read `ConciergeWidget` makes; see `basketIntentFromTurns`. */
|
|
6805
|
+
const showBasket = basketIntentFromTurns(turns);
|
|
6518
6806
|
const onFileSelected = async (event) => {
|
|
6519
6807
|
const file = event.target.files?.[0];
|
|
6520
6808
|
event.target.value = "";
|
|
@@ -6562,9 +6850,12 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6562
6850
|
...attribution !== void 0 ? { attribution } : {},
|
|
6563
6851
|
messageArrived: lastTurn?.speaker === "caller",
|
|
6564
6852
|
idPrefix: "widget",
|
|
6565
|
-
scrollKey: turns.length,
|
|
6853
|
+
scrollKey: turns.length + (humanTyping ? 1 : 0),
|
|
6566
6854
|
draft,
|
|
6567
|
-
onDraftChange:
|
|
6855
|
+
onDraftChange: (value) => {
|
|
6856
|
+
setDraft(value);
|
|
6857
|
+
if (value.trim() !== "") onTyping?.();
|
|
6858
|
+
},
|
|
6568
6859
|
onSubmit: () => void submit(),
|
|
6569
6860
|
...position !== void 0 ? { position } : {},
|
|
6570
6861
|
...onPositionChange !== void 0 ? { onPositionChange } : {},
|
|
@@ -6667,7 +6958,7 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6667
6958
|
dir: textDirectionFor(turn.locale),
|
|
6668
6959
|
lang: turn.locale,
|
|
6669
6960
|
"data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
|
|
6670
|
-
className: `max-w-[85%] px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${turn.speaker === "caller" ? "from-brand-plum to-brand-plum/90 text-[var(--widget-accent-foreground)] rounded-2xl rounded-ee-md bg-gradient-to-br" : turn.filler === true ? "rounded-2xl rounded-es-md border border-dashed border-[var(--widget-foreground-muted)]/50 bg-transparent text-[var(--widget-foreground-muted)] shadow-none" :
|
|
6961
|
+
className: `max-w-[85%] px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${turn.speaker === "caller" ? "from-brand-plum to-brand-plum/90 text-[var(--widget-accent-foreground)] rounded-2xl rounded-ee-md bg-gradient-to-br" : turn.filler === true ? "rounded-2xl rounded-es-md border border-dashed border-[var(--widget-foreground-muted)]/50 bg-transparent text-[var(--widget-foreground-muted)] shadow-none" : AGENT_BUBBLE_CLASS}`,
|
|
6671
6962
|
children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
|
|
6672
6963
|
className: "flex items-center gap-2 italic",
|
|
6673
6964
|
children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
|
|
@@ -6702,6 +6993,14 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6702
6993
|
}) : null
|
|
6703
6994
|
]
|
|
6704
6995
|
}, `${turn.speaker}-${i}`)),
|
|
6996
|
+
humanTyping ? /* @__PURE__ */ jsx("div", {
|
|
6997
|
+
"data-testid": "widget-human-typing",
|
|
6998
|
+
className: "flex flex-col items-start",
|
|
6999
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
7000
|
+
className: `px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${AGENT_BUBBLE_CLASS}`,
|
|
7001
|
+
children: /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })
|
|
7002
|
+
})
|
|
7003
|
+
}) : null,
|
|
6705
7004
|
!escalated && turns.every((turn) => turn.speaker !== "caller") ? /* @__PURE__ */ jsx("ul", {
|
|
6706
7005
|
"aria-label": messages.suggestions_label,
|
|
6707
7006
|
"data-testid": "widget-suggestions",
|
|
@@ -6715,7 +7014,7 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
|
|
|
6715
7014
|
children: messages[key]
|
|
6716
7015
|
}) }, key))
|
|
6717
7016
|
}) : null,
|
|
6718
|
-
cart && cart.lines.length > 0 &&
|
|
7017
|
+
cart && cart.lines.length > 0 && showBasket ? /* @__PURE__ */ jsx(WidgetCartSummary, {
|
|
6719
7018
|
lines: cart.lines,
|
|
6720
7019
|
subtotalMinor: cart.subtotalMinor,
|
|
6721
7020
|
currency: cart.currency,
|
|
@@ -7074,6 +7373,19 @@ new RegExp(`^${LOCALE_PREFIX}/checkouts/`, "i");
|
|
|
7074
7373
|
new RegExp(`^${LOCALE_PREFIX}/search/?$`, "i");
|
|
7075
7374
|
new RegExp(`^${LOCALE_PREFIX}/cart(?:/.*)?$`, "i");
|
|
7076
7375
|
//#endregion
|
|
7376
|
+
//#region ../widget-protocol/dist/desk-typing.js
|
|
7377
|
+
/**
|
|
7378
|
+
* How long one received `desk:typing` ping keeps the widget's indicator up.
|
|
7379
|
+
*
|
|
7380
|
+
* MUST stay at least twice {@link DESK_TYPING_PING_INTERVAL_MS}: while the
|
|
7381
|
+
* operator keeps typing, pings arrive one interval apart, and a TTL under two
|
|
7382
|
+
* intervals turns a single dropped ping into the indicator flickering off
|
|
7383
|
+
* mid-sentence. `desk-typing.test.ts` pins the ratio — retune either side and
|
|
7384
|
+
* that test is the contract to satisfy, in this package, before either bundle
|
|
7385
|
+
* ships.
|
|
7386
|
+
*/
|
|
7387
|
+
var DESK_TYPING_INDICATOR_TTL_MS = 6e3;
|
|
7388
|
+
//#endregion
|
|
7077
7389
|
//#region src/use-chat-session.ts
|
|
7078
7390
|
/**
|
|
7079
7391
|
* `''` = same-origin — every fetch/socket URL this hook builds is relative to
|
|
@@ -7098,6 +7410,8 @@ var DEFAULT_SOCKET_PATH = "/socket.io";
|
|
|
7098
7410
|
var HANDOFF_EVENT_TURN_ID = "event-handoff";
|
|
7099
7411
|
/** Must equal `WIDGET_DESK_MESSAGE_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
|
|
7100
7412
|
var DESK_MESSAGE_EVENT = "desk:message";
|
|
7413
|
+
/** Must equal `WIDGET_DESK_TYPING_EVENT` in `apps/api/src/realtime/widget-room.ts`. */
|
|
7414
|
+
var DESK_TYPING_EVENT = "desk:typing";
|
|
7101
7415
|
/** Must equal the namespace `WidgetGateway` (`apps/api/src/realtime/widget.gateway.ts`) is mounted on. */
|
|
7102
7416
|
var SOCKET_NAMESPACE = "/widget";
|
|
7103
7417
|
/**
|
|
@@ -7291,11 +7605,28 @@ function useChatSession(options) {
|
|
|
7291
7605
|
const [chatToken, setChatToken] = useState(void 0);
|
|
7292
7606
|
const [cards, setCards] = useState([]);
|
|
7293
7607
|
const [checkoutHandoffs, setCheckoutHandoffs] = useState([]);
|
|
7608
|
+
/**
|
|
7609
|
+
* Append-only, and deliberately UNCAPPED unlike the voice leg's own
|
|
7610
|
+
* `widgetEvents` (`MAX_WIDGET_EVENTS`): one entry per agent-requested add in
|
|
7611
|
+
* a single typed conversation is a handful at most, and the cap on that side
|
|
7612
|
+
* exists because a call's data channel also carries transcript revisions.
|
|
7613
|
+
* Either way the consumer never reads this by index or by length — see the
|
|
7614
|
+
* field's doc comment on `UseChatSessionResult`.
|
|
7615
|
+
*/
|
|
7616
|
+
const [cartAdds, setCartAdds] = useState([]);
|
|
7617
|
+
/**
|
|
7618
|
+
* The basket the caller last told us about — see
|
|
7619
|
+
* {@link UseChatSessionResult.setCart}. A ref because nothing renders from
|
|
7620
|
+
* it and every cart read would otherwise repaint the transcript.
|
|
7621
|
+
*/
|
|
7622
|
+
const cartRef = useRef(null);
|
|
7294
7623
|
const [cartAttributionToken, setCartAttributionToken] = useState(null);
|
|
7295
7624
|
const [status, setStatus] = useState("idle");
|
|
7296
7625
|
const [error, setError] = useState(void 0);
|
|
7297
7626
|
const [ready, setReady] = useState(false);
|
|
7298
7627
|
const [connection, setConnection] = useState("idle");
|
|
7628
|
+
/** See `UseChatSessionResult.deskTyping`. Expiry timer lives in `deskTypingTimerRef`. */
|
|
7629
|
+
const [deskTyping, setDeskTyping] = useState(false);
|
|
7299
7630
|
/**
|
|
7300
7631
|
* Counts SESSIONS, not renders — bumped once per successful `bootSession`,
|
|
7301
7632
|
* and by nothing else. A token ROTATION deliberately does not bump it.
|
|
@@ -7320,6 +7651,7 @@ function useChatSession(options) {
|
|
|
7320
7651
|
const pollIntervalRef = useRef(pollIntervalMs);
|
|
7321
7652
|
const mountedRef = useRef(true);
|
|
7322
7653
|
const socketRef = useRef(null);
|
|
7654
|
+
const deskTypingTimerRef = useRef(null);
|
|
7323
7655
|
/**
|
|
7324
7656
|
* `StartWidgetSessionResult.visitorSessionId` — same value `collector`
|
|
7325
7657
|
* (when supplied) receives via `setSession`, stored here too because the
|
|
@@ -7458,6 +7790,19 @@ function useChatSession(options) {
|
|
|
7458
7790
|
};
|
|
7459
7791
|
}, []);
|
|
7460
7792
|
/**
|
|
7793
|
+
* The ONE way the typing indicator goes out — timer expiry, a delivered
|
|
7794
|
+
* reply, and socket teardown all call this rather than each keeping its own
|
|
7795
|
+
* copy of the "cancel timer, null the ref, drop the flag" sequence (the
|
|
7796
|
+
* next clear site inherits the mounted guard instead of forgetting it).
|
|
7797
|
+
* `clearTimeout` on an already-fired timer id is a defined no-op, so the
|
|
7798
|
+
* TTL callback may call this about itself.
|
|
7799
|
+
*/
|
|
7800
|
+
const clearDeskTyping = useCallback(() => {
|
|
7801
|
+
if (deskTypingTimerRef.current !== null) clearTimeout(deskTypingTimerRef.current);
|
|
7802
|
+
deskTypingTimerRef.current = null;
|
|
7803
|
+
if (mountedRef.current) setDeskTyping(false);
|
|
7804
|
+
}, []);
|
|
7805
|
+
/**
|
|
7461
7806
|
* The ONE place turns from push OR poll become `ChatTurn`s. Dedupes by
|
|
7462
7807
|
* `seq` (never renders the same turn twice, whichever path delivers it
|
|
7463
7808
|
* first) and advances `lastSeqRef` to the highest seq seen so far (the
|
|
@@ -7467,6 +7812,7 @@ function useChatSession(options) {
|
|
|
7467
7812
|
if (!mountedRef.current || !Array.isArray(incoming) || incoming.length === 0) return;
|
|
7468
7813
|
const fresh = incoming.filter((t) => !seenSeqRef.current.has(t.seq)).slice().sort((a, b) => a.seq - b.seq);
|
|
7469
7814
|
if (fresh.length === 0) return;
|
|
7815
|
+
if (fresh.some((t) => speakerFor(t.role) === "agent")) clearDeskTyping();
|
|
7470
7816
|
for (const t of fresh) seenSeqRef.current.add(t.seq);
|
|
7471
7817
|
lastSeqRef.current = fresh.reduce((max, t) => Math.max(max, t.seq), lastSeqRef.current);
|
|
7472
7818
|
setTurns((prev) => {
|
|
@@ -7482,10 +7828,11 @@ function useChatSession(options) {
|
|
|
7482
7828
|
speaker: speakerFor(t.role),
|
|
7483
7829
|
text: t.text ?? "",
|
|
7484
7830
|
final: true,
|
|
7485
|
-
...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {}
|
|
7831
|
+
...t.attachments && t.attachments.length > 0 ? { attachments: t.attachments } : {},
|
|
7832
|
+
...t.cards && Array.isArray(t.cards.items) && t.cards.items.length > 0 ? { cards: t.cards } : {}
|
|
7486
7833
|
}))];
|
|
7487
7834
|
});
|
|
7488
|
-
}, []);
|
|
7835
|
+
}, [clearDeskTyping]);
|
|
7489
7836
|
/**
|
|
7490
7837
|
* Records the handoff to a human AS AN EVENT IN THE TRANSCRIPT, at the
|
|
7491
7838
|
* point in the thread where it happened, and flips `status`.
|
|
@@ -7692,8 +8039,57 @@ function useChatSession(options) {
|
|
|
7692
8039
|
visitorSessionId: body.visitorSessionId,
|
|
7693
8040
|
expiresAt: receivedAt + ttlMs
|
|
7694
8041
|
});
|
|
8042
|
+
/**
|
|
8043
|
+
* Paint the greeting the server just STORED — never a greeting this
|
|
8044
|
+
* client invented.
|
|
8045
|
+
*
|
|
8046
|
+
* ## What this used to be, and why it was the bug
|
|
8047
|
+
*
|
|
8048
|
+
* `setTurns([{ id: 'greeting', … }])`. A pseudo-turn: `'greeting'` is
|
|
8049
|
+
* not a turn id, nothing on the server had ever heard of it, and the
|
|
8050
|
+
* text existed only in this browser's memory. So a refresh — which
|
|
8051
|
+
* RESUMES the session and re-reads the transcript — came back without
|
|
8052
|
+
* it, the operator console (which reads `turns`) never saw the agent's
|
|
8053
|
+
* opening line at all, and a shopper's own conversation appeared to
|
|
8054
|
+
* start with their first question. That is "on refresh the greeting
|
|
8055
|
+
* disappears", reported from production.
|
|
8056
|
+
*
|
|
8057
|
+
* The server now writes the greeting as a `turns` row before it answers
|
|
8058
|
+
* this call, so this seed's whole job is to RENDER WHAT THE SERVER
|
|
8059
|
+
* SENT — same bytes, same identity — rather than to be a second,
|
|
8060
|
+
* client-side source of the greeting. `${greetingTurnId}:out` is
|
|
8061
|
+
* precisely the id `GET /widget/messages` will hand back for that row
|
|
8062
|
+
* (`WidgetChatService.listMessagesAfter` splits an exchange into
|
|
8063
|
+
* `:in`/`:out`), which is what makes `mergeIncoming`'s base-id dedupe
|
|
8064
|
+
* recognise the replayed copy as one already on screen.
|
|
8065
|
+
*
|
|
8066
|
+
* ## Why the seed was kept at all
|
|
8067
|
+
*
|
|
8068
|
+
* The alternative considered — delete the seed outright and always
|
|
8069
|
+
* `poll()` on mount, so the transcript has exactly one source — is
|
|
8070
|
+
* simpler and was rejected on the shopper's experience: it puts a
|
|
8071
|
+
* second round trip in front of the FIRST thing the widget ever shows,
|
|
8072
|
+
* so a concierge that is supposed to feel like someone already there
|
|
8073
|
+
* opens on an empty pane for the length of a network hop. It would also
|
|
8074
|
+
* make "the tenant wrote no greeting" and "the fetch failed" render
|
|
8075
|
+
* identically. The seed is cheap and, now that it carries the server's
|
|
8076
|
+
* own id and text, it cannot drift from or duplicate the stored row.
|
|
8077
|
+
*
|
|
8078
|
+
* `id` falls back to the local `'greeting'` when the server sent no
|
|
8079
|
+
* `greetingTurnId` — an older api build, or a greeting whose write
|
|
8080
|
+
* failed. In both of those cases there IS no stored row to collide
|
|
8081
|
+
* with, so a local id is exactly right.
|
|
8082
|
+
*
|
|
8083
|
+
* The skew in the OTHER direction is a real, accepted cost: a bundle
|
|
8084
|
+
* that predates this field seeds `'greeting'` against an api that now
|
|
8085
|
+
* stores the row, so an escalation poll (the only path that refetches a
|
|
8086
|
+
* seeded transcript) appends a second copy under the first. Bounded to
|
|
8087
|
+
* a pre-update bundle in a session that escalated, and cosmetic — and
|
|
8088
|
+
* unclosable from the server, which cannot know the id an old bundle
|
|
8089
|
+
* chose. See `AGENTS.md`.
|
|
8090
|
+
*/
|
|
7695
8091
|
if (isMount && body.greeting) setTurns([{
|
|
7696
|
-
id: "greeting",
|
|
8092
|
+
id: body.greetingTurnId ? `${body.greetingTurnId}:out` : "greeting",
|
|
7697
8093
|
speaker: "agent",
|
|
7698
8094
|
text: body.greeting,
|
|
7699
8095
|
final: true
|
|
@@ -7950,11 +8346,18 @@ function useChatSession(options) {
|
|
|
7950
8346
|
socket.on(DESK_MESSAGE_EVENT, (message) => {
|
|
7951
8347
|
mergeIncoming([message]);
|
|
7952
8348
|
});
|
|
8349
|
+
socket.on(DESK_TYPING_EVENT, () => {
|
|
8350
|
+
if (!mountedRef.current) return;
|
|
8351
|
+
setDeskTyping(true);
|
|
8352
|
+
if (deskTypingTimerRef.current !== null) clearTimeout(deskTypingTimerRef.current);
|
|
8353
|
+
deskTypingTimerRef.current = setTimeout(clearDeskTyping, DESK_TYPING_INDICATOR_TTL_MS);
|
|
8354
|
+
});
|
|
7953
8355
|
})();
|
|
7954
8356
|
return () => {
|
|
7955
8357
|
cancelled = true;
|
|
7956
8358
|
socketRef.current?.disconnect();
|
|
7957
8359
|
socketRef.current = null;
|
|
8360
|
+
clearDeskTyping();
|
|
7958
8361
|
};
|
|
7959
8362
|
}, [
|
|
7960
8363
|
socketUrl,
|
|
@@ -7963,6 +8366,7 @@ function useChatSession(options) {
|
|
|
7963
8366
|
status,
|
|
7964
8367
|
socketFactory,
|
|
7965
8368
|
mergeIncoming,
|
|
8369
|
+
clearDeskTyping,
|
|
7966
8370
|
bootGeneration
|
|
7967
8371
|
]);
|
|
7968
8372
|
useEffect(() => {
|
|
@@ -8021,7 +8425,10 @@ function useChatSession(options) {
|
|
|
8021
8425
|
"content-type": "application/json",
|
|
8022
8426
|
authorization: `Bearer ${chatToken}`
|
|
8023
8427
|
},
|
|
8024
|
-
body: JSON.stringify(
|
|
8428
|
+
body: JSON.stringify({
|
|
8429
|
+
...payload,
|
|
8430
|
+
...cartRef.current ? { cart: cartRef.current } : {}
|
|
8431
|
+
})
|
|
8025
8432
|
});
|
|
8026
8433
|
} catch {
|
|
8027
8434
|
rollBack();
|
|
@@ -8049,6 +8456,9 @@ function useChatSession(options) {
|
|
|
8049
8456
|
onCheckoutEvent: (evt) => {
|
|
8050
8457
|
if (mountedRef.current) setCheckoutHandoffs((prev) => [...prev, evt]);
|
|
8051
8458
|
},
|
|
8459
|
+
onCartAddEvent: (evt) => {
|
|
8460
|
+
if (mountedRef.current) setCartAdds((prev) => [...prev, evt]);
|
|
8461
|
+
},
|
|
8052
8462
|
onEscalated: () => {
|
|
8053
8463
|
markHandoffToHuman();
|
|
8054
8464
|
},
|
|
@@ -8082,6 +8492,36 @@ function useChatSession(options) {
|
|
|
8082
8492
|
]);
|
|
8083
8493
|
const send = useCallback(async (text, options) => postTurn({ message: text }, options), [postTurn]);
|
|
8084
8494
|
const sendReport = useCallback(async (report) => postTurn({ report }), [postTurn]);
|
|
8495
|
+
/**
|
|
8496
|
+
* See {@link UseChatSessionResult.setCart}. A plain ref write, with a
|
|
8497
|
+
* stable identity — callers put this in an effect's dependency array, and
|
|
8498
|
+
* an identity that changed per render would make that effect run on every
|
|
8499
|
+
* one of them.
|
|
8500
|
+
*/
|
|
8501
|
+
const setCart = useCallback((cart) => {
|
|
8502
|
+
cartRef.current = cart;
|
|
8503
|
+
}, []);
|
|
8504
|
+
/** See {@link UseChatSessionResult.pushCart}. */
|
|
8505
|
+
const pushCart = useCallback(async (cart) => {
|
|
8506
|
+
const chatToken = chatTokenRef.current;
|
|
8507
|
+
if (chatToken === void 0) return false;
|
|
8508
|
+
try {
|
|
8509
|
+
return (await fetchImpl(withEmbedKeyParam(`${apiBase}/cart`, embedKey), {
|
|
8510
|
+
method: "POST",
|
|
8511
|
+
headers: {
|
|
8512
|
+
"content-type": "application/json",
|
|
8513
|
+
authorization: `Bearer ${chatToken}`
|
|
8514
|
+
},
|
|
8515
|
+
body: JSON.stringify({ cart })
|
|
8516
|
+
})).ok;
|
|
8517
|
+
} catch {
|
|
8518
|
+
return false;
|
|
8519
|
+
}
|
|
8520
|
+
}, [
|
|
8521
|
+
apiBase,
|
|
8522
|
+
embedKey,
|
|
8523
|
+
fetchImpl
|
|
8524
|
+
]);
|
|
8085
8525
|
const sendEvent = useCallback(async (events) => {
|
|
8086
8526
|
const chatToken = chatTokenRef.current;
|
|
8087
8527
|
if (chatToken === void 0 || events.length === 0) return false;
|
|
@@ -8108,6 +8548,46 @@ function useChatSession(options) {
|
|
|
8108
8548
|
fetchImpl
|
|
8109
8549
|
]);
|
|
8110
8550
|
/**
|
|
8551
|
+
* See `UseChatSessionResult.notifyTyping`.
|
|
8552
|
+
*
|
|
8553
|
+
* ## Why a ref-held timestamp rather than a `setTimeout` throttle
|
|
8554
|
+
*
|
|
8555
|
+
* A timer-based throttle would need arming on the first keystroke,
|
|
8556
|
+
* disarming on unmount, and re-arming across a token rotation — three
|
|
8557
|
+
* chances to leak a timer for a signal whose entire value is being too
|
|
8558
|
+
* cheap to think about. Comparing "now" against the last accepted ping is
|
|
8559
|
+
* the same behaviour with no timer to own: leading-edge (the first
|
|
8560
|
+
* keystroke pings immediately, so the operator sees the dots when the
|
|
8561
|
+
* shopper starts typing rather than three seconds in), no trailing request
|
|
8562
|
+
* after they stop, and nothing to clean up.
|
|
8563
|
+
*
|
|
8564
|
+
* The stamp is recorded BEFORE the request, not after it resolves: a slow
|
|
8565
|
+
* or failing network must not let the next 40 keystrokes each start their
|
|
8566
|
+
* own request, and a failed ping must not latch the throttle shut either.
|
|
8567
|
+
* `void`-returning and fully caught, for the reason the public doc comment
|
|
8568
|
+
* gives.
|
|
8569
|
+
*/
|
|
8570
|
+
const lastTypingPingRef = useRef(0);
|
|
8571
|
+
const notifyTyping = useCallback(() => {
|
|
8572
|
+
const chatToken = chatTokenRef.current;
|
|
8573
|
+
if (chatToken === void 0) return;
|
|
8574
|
+
const now = Date.now();
|
|
8575
|
+
if (now - lastTypingPingRef.current < 3e3) return;
|
|
8576
|
+
lastTypingPingRef.current = now;
|
|
8577
|
+
(async () => {
|
|
8578
|
+
try {
|
|
8579
|
+
await fetchImpl(withEmbedKeyParam(`${apiBase}/typing`, embedKey), {
|
|
8580
|
+
method: "POST",
|
|
8581
|
+
headers: { authorization: `Bearer ${chatToken}` }
|
|
8582
|
+
});
|
|
8583
|
+
} catch {}
|
|
8584
|
+
})();
|
|
8585
|
+
}, [
|
|
8586
|
+
apiBase,
|
|
8587
|
+
embedKey,
|
|
8588
|
+
fetchImpl
|
|
8589
|
+
]);
|
|
8590
|
+
/**
|
|
8111
8591
|
* `POST /widget/ingest` with one event per receipt kind that just became
|
|
8112
8592
|
* true — the two receipts behind the console's ticks on an outbound
|
|
8113
8593
|
* bubble: `client.messages_delivered` (it reached this browser) and
|
|
@@ -8264,9 +8744,14 @@ function useChatSession(options) {
|
|
|
8264
8744
|
error,
|
|
8265
8745
|
ready,
|
|
8266
8746
|
connection,
|
|
8747
|
+
deskTyping,
|
|
8748
|
+
cartAdds,
|
|
8267
8749
|
send,
|
|
8268
8750
|
sendReport,
|
|
8751
|
+
setCart,
|
|
8752
|
+
pushCart,
|
|
8269
8753
|
sendEvent,
|
|
8754
|
+
notifyTyping,
|
|
8270
8755
|
checkout: useCallback(async (items, curationId, cartAttributionToken) => {
|
|
8271
8756
|
const chatToken = chatTokenRef.current;
|
|
8272
8757
|
if (chatToken === void 0 || items.length === 0) return null;
|
|
@@ -8371,7 +8856,7 @@ function useChatSession(options) {
|
|
|
8371
8856
|
* promise and is trivially unit-testable with a synthetic `ReadableStream`.
|
|
8372
8857
|
*/
|
|
8373
8858
|
async function streamReply(args) {
|
|
8374
|
-
const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onEscalated, onDone, onError, isMounted } = args;
|
|
8859
|
+
const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onEscalated, onDone, onError, isMounted } = args;
|
|
8375
8860
|
const reader = body.getReader();
|
|
8376
8861
|
const decoder = new TextDecoder();
|
|
8377
8862
|
const parser = new SseFrameParser();
|
|
@@ -8423,6 +8908,14 @@ async function streamReply(args) {
|
|
|
8423
8908
|
});
|
|
8424
8909
|
break;
|
|
8425
8910
|
}
|
|
8911
|
+
case "add-to-cart": {
|
|
8912
|
+
const item = evt.data?.item;
|
|
8913
|
+
if (!item || typeof item !== "object") break;
|
|
8914
|
+
if (typeof item.title !== "string" || item.title.length === 0) break;
|
|
8915
|
+
if (item.variantId === void 0 && item.platformVariantId === void 0) break;
|
|
8916
|
+
onCartAddEvent({ item });
|
|
8917
|
+
break;
|
|
8918
|
+
}
|
|
8426
8919
|
case "escalated":
|
|
8427
8920
|
onEscalated();
|
|
8428
8921
|
break;
|
|
@@ -8448,7 +8941,7 @@ async function streamReply(args) {
|
|
|
8448
8941
|
* cache makes a second `start()` after `stop()` free).
|
|
8449
8942
|
*/
|
|
8450
8943
|
async function loadVoiceProtocol() {
|
|
8451
|
-
const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-
|
|
8944
|
+
const [telemetry, chat] = await Promise.all([import("./telemetry-Bw-3F_Zk.js"), import("./chat-tMKkYmTC.js")]);
|
|
8452
8945
|
return {
|
|
8453
8946
|
decodeTelemetry: telemetry.decodeTelemetry,
|
|
8454
8947
|
encodeCallerText: telemetry.encodeCallerText,
|
|
@@ -8865,6 +9358,7 @@ function useVoiceSession(options = {}) {
|
|
|
8865
9358
|
setTurns([]);
|
|
8866
9359
|
setTranscript([]);
|
|
8867
9360
|
setCosts([]);
|
|
9361
|
+
setWidgetEvents([]);
|
|
8868
9362
|
setConfig(null);
|
|
8869
9363
|
record("token_requested");
|
|
8870
9364
|
let room;
|
|
@@ -8975,7 +9469,11 @@ function useVoiceSession(options = {}) {
|
|
|
8975
9469
|
record("widget_event_invalid", String(message.event["type"]));
|
|
8976
9470
|
return;
|
|
8977
9471
|
}
|
|
8978
|
-
|
|
9472
|
+
const withTurn = message.turnId === void 0 ? parsed.data : {
|
|
9473
|
+
...parsed.data,
|
|
9474
|
+
turnId: message.turnId
|
|
9475
|
+
};
|
|
9476
|
+
setWidgetEvents((all) => [...all, withTurn].slice(-20));
|
|
8979
9477
|
record("widget_event", parsed.data.type);
|
|
8980
9478
|
return;
|
|
8981
9479
|
}
|
|
@@ -9131,6 +9629,117 @@ function useVoiceSession(options = {}) {
|
|
|
9131
9629
|
};
|
|
9132
9630
|
}
|
|
9133
9631
|
//#endregion
|
|
9632
|
+
//#region src/turn-order.ts
|
|
9633
|
+
/**
|
|
9634
|
+
* The widget's arrival clock. One instance per mounted widget (`useRef`), fed
|
|
9635
|
+
* the CURRENT source lists on every render; every call is idempotent for
|
|
9636
|
+
* unchanged input, so React StrictMode's double-invoked render (and any memo
|
|
9637
|
+
* re-run) hands back identical stamps.
|
|
9638
|
+
*/
|
|
9639
|
+
var TurnOrderClock = class {
|
|
9640
|
+
counter = 0;
|
|
9641
|
+
typedPrev = [];
|
|
9642
|
+
typedStamps = [];
|
|
9643
|
+
spokenPrev = [];
|
|
9644
|
+
spokenStamps = [];
|
|
9645
|
+
eventStamps = /* @__PURE__ */ new WeakMap();
|
|
9646
|
+
fresh() {
|
|
9647
|
+
this.counter += 1;
|
|
9648
|
+
return this.counter;
|
|
9649
|
+
}
|
|
9650
|
+
/**
|
|
9651
|
+
* Stamps for the typed session's turns, parallel to `turns`.
|
|
9652
|
+
*
|
|
9653
|
+
* Per row, in order of precedence:
|
|
9654
|
+
*
|
|
9655
|
+
* 1. **Positional rewrite** — the row at this INDEX last render had a
|
|
9656
|
+
* different id that no longer exists anywhere in the list, and the same
|
|
9657
|
+
* speaker: that is `send`/`onDone`'s in-place id swap, so the stamp
|
|
9658
|
+
* carries over. Checked BEFORE the id lookup because of the one race
|
|
9659
|
+
* where both would match: the poll can backfill the streaming turn's
|
|
9660
|
+
* server row before `onDone` renames the streamed bubble to that same
|
|
9661
|
+
* id and drops the duplicate — the id lookup alone would hand the
|
|
9662
|
+
* bubble the DUPLICATE's later stamp and orphan every row between.
|
|
9663
|
+
* 2. **Id match** — the row was here last render; same stamp.
|
|
9664
|
+
* 3. **Fresh** — a genuinely new row, which sorts after everything already
|
|
9665
|
+
* on screen. This is where a row lands when a failed `send`'s rollback
|
|
9666
|
+
* and a new append batch into one render: the newcomer stands at a
|
|
9667
|
+
* removed OPTIMISTIC row's index, but the speaker gate in rule 1 (and
|
|
9668
|
+
* the dead id in rule 2) keep it from inheriting the dead row's past.
|
|
9669
|
+
*/
|
|
9670
|
+
stampTyped(turns) {
|
|
9671
|
+
const prevStampById = /* @__PURE__ */ new Map();
|
|
9672
|
+
for (let i = 0; i < this.typedPrev.length; i += 1) prevStampById.set(this.typedPrev[i].id, this.typedStamps[i]);
|
|
9673
|
+
const nextIds = new Set(turns.map((turn) => turn.id));
|
|
9674
|
+
const stamps = turns.map((turn, i) => {
|
|
9675
|
+
const positional = this.typedPrev[i];
|
|
9676
|
+
if (positional !== void 0 && positional.id !== turn.id && !nextIds.has(positional.id) && positional.speaker === turn.speaker) return this.typedStamps[i];
|
|
9677
|
+
return prevStampById.get(turn.id) ?? this.fresh();
|
|
9678
|
+
});
|
|
9679
|
+
this.typedPrev = turns;
|
|
9680
|
+
this.typedStamps = stamps;
|
|
9681
|
+
return stamps;
|
|
9682
|
+
}
|
|
9683
|
+
/**
|
|
9684
|
+
* Stamps for the voice transcript, parallel to `lines` — the FULL list as
|
|
9685
|
+
* `useVoiceSession` publishes it, before any render-side filtering, so the
|
|
9686
|
+
* caller can filter lines and stamps together.
|
|
9687
|
+
*
|
|
9688
|
+
* Rows are matched by object IDENTITY, scanning forward only — which is
|
|
9689
|
+
* what lets the cap trim (the whole list shifted left one) keep every
|
|
9690
|
+
* surviving stamp. An unmatched row standing where an unmatched PROVISIONAL
|
|
9691
|
+
* line of the same speaker stood is `coalesceTranscript`'s in-place
|
|
9692
|
+
* revision and inherits that line's stamp; anything else is new and stamps
|
|
9693
|
+
* fresh, after everything already seen.
|
|
9694
|
+
*
|
|
9695
|
+
* Inheritance is disabled outright on a render where the list SHRANK:
|
|
9696
|
+
* appends and revisions never shrink it and the cap trim keeps the length
|
|
9697
|
+
* constant, so a shorter list means rows were dropped (`start()`'s reset to
|
|
9698
|
+
* `[]` for a new call, or any future producer change) — and a dropped
|
|
9699
|
+
* line's stamp must never be donated to a newcomer that merely stands where
|
|
9700
|
+
* it stood. Surviving identical rows still keep their stamps; everything
|
|
9701
|
+
* else restamps fresh, i.e. the new call's lines sort after everything
|
|
9702
|
+
* already said. (`start()`'s clear commits as its own render before any
|
|
9703
|
+
* frame from the new room can arrive, so in practice the reset is observed
|
|
9704
|
+
* as `[]` and this guard is belt and braces.)
|
|
9705
|
+
*/
|
|
9706
|
+
stampSpoken(lines) {
|
|
9707
|
+
const mayInherit = lines.length >= this.spokenPrev.length;
|
|
9708
|
+
const stamps = [];
|
|
9709
|
+
let pi = 0;
|
|
9710
|
+
for (const line of lines) {
|
|
9711
|
+
let found = -1;
|
|
9712
|
+
for (let j = pi; j < this.spokenPrev.length; j += 1) if (this.spokenPrev[j] === line) {
|
|
9713
|
+
found = j;
|
|
9714
|
+
break;
|
|
9715
|
+
}
|
|
9716
|
+
if (found >= 0) {
|
|
9717
|
+
stamps.push(this.spokenStamps[found]);
|
|
9718
|
+
pi = found + 1;
|
|
9719
|
+
continue;
|
|
9720
|
+
}
|
|
9721
|
+
const replaced = this.spokenPrev[pi];
|
|
9722
|
+
if (mayInherit && replaced !== void 0 && !replaced.final && replaced.speaker === line.speaker && !lines.includes(replaced)) {
|
|
9723
|
+
stamps.push(this.spokenStamps[pi]);
|
|
9724
|
+
pi += 1;
|
|
9725
|
+
continue;
|
|
9726
|
+
}
|
|
9727
|
+
stamps.push(this.fresh());
|
|
9728
|
+
}
|
|
9729
|
+
this.spokenPrev = lines;
|
|
9730
|
+
this.spokenStamps = stamps;
|
|
9731
|
+
return stamps;
|
|
9732
|
+
}
|
|
9733
|
+
/** Stamp for one voice tool event — append-only distinct objects, so plain first-sight identity. */
|
|
9734
|
+
stampEvent(event) {
|
|
9735
|
+
const existing = this.eventStamps.get(event);
|
|
9736
|
+
if (existing !== void 0) return existing;
|
|
9737
|
+
const stamp = this.fresh();
|
|
9738
|
+
this.eventStamps.set(event, stamp);
|
|
9739
|
+
return stamp;
|
|
9740
|
+
}
|
|
9741
|
+
};
|
|
9742
|
+
//#endregion
|
|
9134
9743
|
//#region src/host-widget.tsx
|
|
9135
9744
|
/**
|
|
9136
9745
|
* Resolves the widget's "add to cart" handler from the bridge's OWN degraded
|
|
@@ -9258,6 +9867,85 @@ function cartLinesFromSnapshot(snapshot, currency) {
|
|
|
9258
9867
|
}));
|
|
9259
9868
|
}
|
|
9260
9869
|
/**
|
|
9870
|
+
* The largest basket this widget will describe to the concierge. Mirrors
|
|
9871
|
+
* `MAX_CART_LINES` (`@saar-ai/widget-protocol`), which is the server's own
|
|
9872
|
+
* bound — duplicated as a number rather than imported so this package does
|
|
9873
|
+
* not pull the protocol's zod runtime into every shopper's bundle (see the
|
|
9874
|
+
* type-only import at the top of `use-chat-session.ts` for the same
|
|
9875
|
+
* discipline). The two are pinned together by a test.
|
|
9876
|
+
*/
|
|
9877
|
+
var MAX_REPORTED_CART_LINES = 50;
|
|
9878
|
+
/** Mirrors the schema's own per-line ceiling — a press, not a basket. */
|
|
9879
|
+
var MAX_REPORTED_LINE_QUANTITY = 999;
|
|
9880
|
+
/** Mirrors the schema's own amount ceiling, in minor units. */
|
|
9881
|
+
var MAX_REPORTED_AMOUNT_MINOR = 1e9;
|
|
9882
|
+
/**
|
|
9883
|
+
* Build the cart snapshot the widget sends with every chat turn, from the
|
|
9884
|
+
* basket it is already rendering.
|
|
9885
|
+
*
|
|
9886
|
+
* ## It reads the SAME resolution the summary renders, never a second one
|
|
9887
|
+
*
|
|
9888
|
+
* `lines`, the currency and the subtotal are all handed in exactly as
|
|
9889
|
+
* `ConciergeWidget` resolved them for `WidgetCartSummary` — the ownership
|
|
9890
|
+
* table in this package's `AGENTS.md` ("Whose numbers win") is the one rule,
|
|
9891
|
+
* applied once. A concierge whose answer disagreed with the basket drawn
|
|
9892
|
+
* under it would be worse than one that could not answer at all.
|
|
9893
|
+
*
|
|
9894
|
+
* ## `hostReported` is the `'host'` / `'widget'` split, and it is load-bearing
|
|
9895
|
+
*
|
|
9896
|
+
* `true` when the host's own `readCart()` reported a `lines` array — the
|
|
9897
|
+
* WHOLE basket, including whatever was in it before the conversation started.
|
|
9898
|
+
* `false` when it reported none and these are only this widget's own adds,
|
|
9899
|
+
* which is a LOWER BOUND; the server says so in the prompt, so the concierge
|
|
9900
|
+
* never tells a shopper a partial basket is everything they have.
|
|
9901
|
+
*
|
|
9902
|
+
* ## `hostSubtotalMinor` is passed only when the HOST supplied one
|
|
9903
|
+
*
|
|
9904
|
+
* A total the host states survives discounts and bundle pricing; one derived
|
|
9905
|
+
* by multiplying out unit prices does not. Passing a derived figure here
|
|
9906
|
+
* would present it to the model as the storefront's own, so it is omitted
|
|
9907
|
+
* instead and the server derives (and labels) it. Same rule, same direction,
|
|
9908
|
+
* as the summary's own.
|
|
9909
|
+
*
|
|
9910
|
+
* ## Everything is clamped, because a 400 here would break the chat
|
|
9911
|
+
*
|
|
9912
|
+
* The server validates this against `WidgetChatCartSchema` and REJECTS a
|
|
9913
|
+
* malformed cart with a 400 — deliberately, so a drifted client is not
|
|
9914
|
+
* silently ignored. That makes it this function's job to never emit one: a
|
|
9915
|
+
* host bridge's cart lines are host-authored data (every field optional, any
|
|
9916
|
+
* value), so titles are trimmed and capped, quantities and prices are floored
|
|
9917
|
+
* to sane integers, untitled rows are dropped, and the list is truncated. A
|
|
9918
|
+
* cart question answered from a slightly truncated basket is a small loss; a
|
|
9919
|
+
* shopper whose every message 400s is a total one.
|
|
9920
|
+
*
|
|
9921
|
+
* Returns `null` when there is nothing honest to say — no host `lines` and no
|
|
9922
|
+
* adds of our own. That is a DIFFERENT statement from an empty cart: the
|
|
9923
|
+
* server renders no cart section at all, and the guardrail's degraded branch
|
|
9924
|
+
* ("you can open the cart on the page") is written for exactly that case,
|
|
9925
|
+
* whereas an empty `lines` array is "the storefront says the cart is empty"
|
|
9926
|
+
* and may be stated plainly.
|
|
9927
|
+
*/
|
|
9928
|
+
function toChatCart(input) {
|
|
9929
|
+
if (!input.hostReported && input.lines.length === 0) return null;
|
|
9930
|
+
if (input.currency.length !== 3) return null;
|
|
9931
|
+
const lines = input.lines.map((line) => ({
|
|
9932
|
+
title: line.title.replace(/\s+/gu, " ").trim().slice(0, 200),
|
|
9933
|
+
quantity: clampInteger(line.quantity, 1, MAX_REPORTED_LINE_QUANTITY),
|
|
9934
|
+
priceMinor: clampInteger(line.priceMinor, 0, MAX_REPORTED_AMOUNT_MINOR)
|
|
9935
|
+
})).filter((line) => line.title !== "").slice(0, 50);
|
|
9936
|
+
return {
|
|
9937
|
+
source: input.hostReported ? "host" : "widget",
|
|
9938
|
+
currency: input.currency,
|
|
9939
|
+
lines,
|
|
9940
|
+
...input.hostSubtotalMinor !== void 0 ? { subtotalMinor: clampInteger(input.hostSubtotalMinor, 0, MAX_REPORTED_AMOUNT_MINOR) } : {}
|
|
9941
|
+
};
|
|
9942
|
+
}
|
|
9943
|
+
/** Floor to an integer inside `[min, max]`; anything unusable (NaN, Infinity) becomes `min`. */
|
|
9944
|
+
function clampInteger(value, min, max) {
|
|
9945
|
+
if (!Number.isFinite(value)) return min;
|
|
9946
|
+
return Math.min(max, Math.max(min, Math.floor(value)));
|
|
9947
|
+
}
|
|
9948
|
+
/**
|
|
9261
9949
|
* Where "Checkout" sends the shopper, and the order the two answers are
|
|
9262
9950
|
* tried in.
|
|
9263
9951
|
*
|
|
@@ -9449,7 +10137,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9449
10137
|
* shopper is waiting on.
|
|
9450
10138
|
*
|
|
9451
10139
|
* **Only the LATEST-ISSUED read may set the snapshot.** Two triggers fire
|
|
9452
|
-
* this — a successful add, and a
|
|
10140
|
+
* this — a successful add, and a basket intent — so overlapping reads are
|
|
9453
10141
|
* ordinary, not a corner case, and `readCart` promises nothing about the
|
|
9454
10142
|
* order they RESOLVE in (a host answering one from the network and the next
|
|
9455
10143
|
* from a warm cache resolves them backwards). Without this guard the winner
|
|
@@ -9466,9 +10154,59 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9466
10154
|
if (mountedRef.current && seq === cartReadSeqRef.current) setHostCart(snapshot);
|
|
9467
10155
|
} catch {}
|
|
9468
10156
|
}, [bridge]);
|
|
9469
|
-
|
|
10157
|
+
/**
|
|
10158
|
+
* The half of a successful add that is a LOCAL FACT: this widget added a
|
|
10159
|
+
* thing, so its own basket grows and the host's cart is re-read.
|
|
10160
|
+
*
|
|
10161
|
+
* Split out from `onAddedToCart` below when the concierge gained the ability
|
|
10162
|
+
* to add something ITSELF (`add_to_cart`), because the two adds want the
|
|
10163
|
+
* same local bookkeeping and different conversational consequences — see
|
|
10164
|
+
* `performAgentCartAdd` for why an agent-requested add sends no report.
|
|
10165
|
+
* Nothing here is conditional on a session existing: a widget with no
|
|
10166
|
+
* conversation that somehow performed an add still has an item in a basket.
|
|
10167
|
+
*/
|
|
10168
|
+
const recordAddedLine = useCallback((item) => {
|
|
9470
10169
|
setAddedLines((prev) => mergeAddedCartLine(prev, item));
|
|
9471
10170
|
refreshHostCart();
|
|
10171
|
+
}, [refreshHostCart]);
|
|
10172
|
+
/**
|
|
10173
|
+
* What a successful add through a CARD BUTTON means to the rest of the
|
|
10174
|
+
* conversation, and the two halves are independent.
|
|
10175
|
+
*
|
|
10176
|
+
* **The basket** always grows: that is a local fact about what this widget
|
|
10177
|
+
* did, true whether or not a session exists.
|
|
10178
|
+
*
|
|
10179
|
+
* **The nudge** is a REPORT, and it is conditional. A typed
|
|
10180
|
+
* `{ kind: 'cart_add', … }` goes to the server via
|
|
10181
|
+
* `UseChatSessionResult.sendReport` — silently (no shopper bubble), so the
|
|
10182
|
+
* concierge answers with something that goes WITH the item.
|
|
10183
|
+
*
|
|
10184
|
+
* It used to be the sentence `Added <title> to cart`, sent as a silent
|
|
10185
|
+
* shopper MESSAGE, which the server matched on its exact wording. Three
|
|
10186
|
+
* things were wrong with that and are structurally impossible now: a
|
|
10187
|
+
* shopper who typed those words was answered as though they had added
|
|
10188
|
+
* something; the sentence persisted as shopper prose in the operator's
|
|
10189
|
+
* transcript; and any change to how a card renders a title broke the match
|
|
10190
|
+
* with nothing failing. The sentence the model reads is now composed
|
|
10191
|
+
* server-side from these fields
|
|
10192
|
+
* (`WidgetChatService.composeStorefrontReportText`).
|
|
10193
|
+
*
|
|
10194
|
+
* Two conditions gate it, both deliberately conservative:
|
|
10195
|
+
*
|
|
10196
|
+
* - **A session must already exist** (`chatToken`). A nudge is a reply
|
|
10197
|
+
* inside a conversation, never the thing that STARTS one — a shopper
|
|
10198
|
+
* who has not spoken to the concierge has not asked it for anything.
|
|
10199
|
+
* - **No voice call may be live.** A typed turn during a call produces a
|
|
10200
|
+
* spoken answer over whatever the caller is in the middle of saying. The
|
|
10201
|
+
* add is still recorded locally; only the message is skipped.
|
|
10202
|
+
*
|
|
10203
|
+
* Both gates are unchanged by the arrival of `add_to_cart`, and neither is
|
|
10204
|
+
* weakened: this hook still fires only for an add the SHOPPER initiated by
|
|
10205
|
+
* pressing a card's button, which is the only kind of add the server does
|
|
10206
|
+
* not already know about.
|
|
10207
|
+
*/
|
|
10208
|
+
const onAddedToCart = useCallback((item) => {
|
|
10209
|
+
recordAddedLine(item);
|
|
9472
10210
|
if (chatToken === void 0 || inCall) return;
|
|
9473
10211
|
session.sendReport({
|
|
9474
10212
|
kind: "cart_add",
|
|
@@ -9481,8 +10219,256 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9481
10219
|
chatToken,
|
|
9482
10220
|
inCall,
|
|
9483
10221
|
session,
|
|
9484
|
-
|
|
9485
|
-
])
|
|
10222
|
+
recordAddedLine
|
|
10223
|
+
]);
|
|
10224
|
+
/**
|
|
10225
|
+
* Whether the LAST agent-requested add failed to reach any cart — see
|
|
10226
|
+
* `performAgentCartAdd`. Rendered on the host status line, and cleared by
|
|
10227
|
+
* the next agent-requested add that succeeds.
|
|
10228
|
+
*/
|
|
10229
|
+
const [agentAddFailed, setAgentAddFailed] = useState(false);
|
|
10230
|
+
/**
|
|
10231
|
+
* Failure reports this widget could not send yet because a CALL was live —
|
|
10232
|
+
* see `performAgentCartAdd`'s "A FAILURE, though, is news nobody else has".
|
|
10233
|
+
*
|
|
10234
|
+
* A REF, not state: nothing renders from it, and holding it in state would
|
|
10235
|
+
* re-render the whole panel for a queue only an effect ever reads. The
|
|
10236
|
+
* queue is drained by the effect below the moment the call ends, and each
|
|
10237
|
+
* entry is removed BEFORE it is sent — a flush that overlapped a re-render
|
|
10238
|
+
* would otherwise send the same correction twice, and two apologies for one
|
|
10239
|
+
* item read as two failed adds.
|
|
10240
|
+
*/
|
|
10241
|
+
const heldFailureReportsRef = useRef([]);
|
|
10242
|
+
/**
|
|
10243
|
+
* Tell the concierge that an add it asked for did NOT reach the cart.
|
|
10244
|
+
*
|
|
10245
|
+
* The ids are the CATALOG's (`productId`/`variantId`), never
|
|
10246
|
+
* `platformVariantId` — the storefront's own id space means nothing on the
|
|
10247
|
+
* server — which is the same choice `onAddedToCart` makes for the success
|
|
10248
|
+
* report. There is no `quantity`: nothing was added, and the schema is
|
|
10249
|
+
* `.strict()` about it precisely so a failure can never carry a number a
|
|
10250
|
+
* model might read as units that went in.
|
|
10251
|
+
*/
|
|
10252
|
+
const reportFailedAgentCartAdd = useCallback((item) => {
|
|
10253
|
+
if (chatToken === void 0) return;
|
|
10254
|
+
const report = {
|
|
10255
|
+
kind: "cart_add_failed",
|
|
10256
|
+
title: item.title,
|
|
10257
|
+
productId: item.productId,
|
|
10258
|
+
...item.variantId !== void 0 ? { variantId: item.variantId } : {}
|
|
10259
|
+
};
|
|
10260
|
+
if (inCall) {
|
|
10261
|
+
heldFailureReportsRef.current = [...heldFailureReportsRef.current, report];
|
|
10262
|
+
return;
|
|
10263
|
+
}
|
|
10264
|
+
session.sendReport(report).catch(() => void 0);
|
|
10265
|
+
}, [
|
|
10266
|
+
chatToken,
|
|
10267
|
+
inCall,
|
|
10268
|
+
session
|
|
10269
|
+
]);
|
|
10270
|
+
/**
|
|
10271
|
+
* Flush the corrections a live call held back, the moment it ends.
|
|
10272
|
+
*
|
|
10273
|
+
* SEQUENTIALLY, for the same reason the adds themselves run in sequence:
|
|
10274
|
+
* `sendReport` resolves `false` while a turn is already streaming, so two
|
|
10275
|
+
* concurrent reports would race and lose one — and a lost correction is a
|
|
10276
|
+
* shopper who never hears that an item is missing.
|
|
10277
|
+
*
|
|
10278
|
+
* The empty-queue early return is what makes this safe to re-run on every
|
|
10279
|
+
* `session` identity change, which is every render of the real hook.
|
|
10280
|
+
*/
|
|
10281
|
+
useEffect(() => {
|
|
10282
|
+
if (inCall || chatToken === void 0) return;
|
|
10283
|
+
const held = heldFailureReportsRef.current;
|
|
10284
|
+
if (held.length === 0) return;
|
|
10285
|
+
heldFailureReportsRef.current = [];
|
|
10286
|
+
(async () => {
|
|
10287
|
+
for (const report of held) try {
|
|
10288
|
+
await session.sendReport(report);
|
|
10289
|
+
} catch {}
|
|
10290
|
+
})();
|
|
10291
|
+
}, [
|
|
10292
|
+
inCall,
|
|
10293
|
+
chatToken,
|
|
10294
|
+
session
|
|
10295
|
+
]);
|
|
10296
|
+
/**
|
|
10297
|
+
* Perform an add the CONCIERGE asked for (`add_to_cart`), rather than one
|
|
10298
|
+
* the shopper pressed a button for.
|
|
10299
|
+
*
|
|
10300
|
+
* ## The same add path, deliberately — not a second one
|
|
10301
|
+
*
|
|
10302
|
+
* It goes through `resolveAddToCartHandler`, the exact function the card
|
|
10303
|
+
* button uses, so a spoken add and a pressed add agree on everything that
|
|
10304
|
+
* has ever been argued about here: which id space this bridge wants, the
|
|
10305
|
+
* `CartLineContext` a `'catalog'`-space bridge is handed, and the rule that
|
|
10306
|
+
* `onAdded` fires only AFTER the bridge's own promise resolves. A parallel
|
|
10307
|
+
* implementation would be free to drift from all three.
|
|
10308
|
+
*
|
|
10309
|
+
* ## No PDP navigation DURING A CALL
|
|
10310
|
+
*
|
|
10311
|
+
* `productHref` is withheld while a call is live, which is what disables the
|
|
10312
|
+
* handler's PDP-navigation fallback. On the typed leg the fallback is right
|
|
10313
|
+
* and is kept: the shopper asked for this item, so landing on its page is a
|
|
10314
|
+
* reasonable second-best, and it is what pressing the button would have
|
|
10315
|
+
* done. Mid-call it is not second-best but destructive — `bridge.navigate`
|
|
10316
|
+
* unloads the host page, which tears down the LiveKit room and ends the call
|
|
10317
|
+
* the shopper is talking on. Losing the call is a worse answer to "add the
|
|
10318
|
+
* cushion" than not adding the cushion.
|
|
10319
|
+
*
|
|
10320
|
+
* ## No SUCCESS report, on either leg — and that is not the in-call gate
|
|
10321
|
+
*
|
|
10322
|
+
* `recordAddedLine` runs (the basket grows, the host cart is re-read), but
|
|
10323
|
+
* a `session.sendReport({ kind: 'cart_add', … })` for an add that WORKED
|
|
10324
|
+
* deliberately does not, and the reason is different from the in-call gate
|
|
10325
|
+
* `onAddedToCart` keeps.
|
|
10326
|
+
*
|
|
10327
|
+
* A report exists to tell the concierge about an add it did not know about —
|
|
10328
|
+
* a shopper pressing a button on a card. A SUCCESSFUL add here is one the
|
|
10329
|
+
* concierge ASKED FOR: it is mid-turn, holding the tool result that produced
|
|
10330
|
+
* it, already composing the sentence that confirms it. Reporting it back
|
|
10331
|
+
* would be the conversation telling itself its own news, and the
|
|
10332
|
+
* consequences are concrete rather than stylistic. On the typed leg the
|
|
10333
|
+
* report opens a SECOND turn, so the shopper gets the confirmation twice and
|
|
10334
|
+
* a second complementary curation on top of it (`WIDGET_CHAT_GUARDRAILS`
|
|
10335
|
+
* instructs both). On the voice leg it is exactly the turn the in-call gate
|
|
10336
|
+
* exists to prevent — an answer spoken over the caller mid-sentence. So this
|
|
10337
|
+
* is not "the in-call gate, extended": a success report is wrong here
|
|
10338
|
+
* whether or not a call is running, and it stays skipped when the panel is
|
|
10339
|
+
* purely typed.
|
|
10340
|
+
*
|
|
10341
|
+
* The attribution that report does NOT carry is not lost with it. Cart
|
|
10342
|
+
* attribution is minted from the `cart.changed` VISITOR event
|
|
10343
|
+
* (`CheckoutHandoffService.recordCartAdd`), which the host's own collector
|
|
10344
|
+
* emits when the cart really changes — a separate, consent-gated path this
|
|
10345
|
+
* has never been part of.
|
|
10346
|
+
*
|
|
10347
|
+
* ## A FAILURE, though, is news nobody else has — and it is reported
|
|
10348
|
+
*
|
|
10349
|
+
* The paragraph above used to end "no storefront report, on either leg",
|
|
10350
|
+
* and every word of its reasoning still holds for an add that WORKED. It
|
|
10351
|
+
* was wrong about the other half, and the asymmetry is the whole point:
|
|
10352
|
+
* the concierge knows it asked for the add, and does not and cannot know
|
|
10353
|
+
* whether it landed. `add_to_cart` returns `status: 'requested'` — the
|
|
10354
|
+
* server has no handle on a cart that lives in this browser behind the
|
|
10355
|
+
* shopper's own session cookie — so a rejected add is the one thing in this
|
|
10356
|
+
* exchange the conversation has no other way to learn.
|
|
10357
|
+
*
|
|
10358
|
+
* Left unreported it was invisible in exactly the case that matters most.
|
|
10359
|
+
* The status line below closes the gap for a shopper who is READING; a
|
|
10360
|
+
* CALLER is not looking at the panel, and by then the concierge has said
|
|
10361
|
+
* something about the add out loud. So a failure goes back as a typed
|
|
10362
|
+
* `{ kind: 'cart_add_failed', … }` report — the repo's existing storefront-
|
|
10363
|
+
* report vocabulary, not a parallel mechanism — and the guardrails tell the
|
|
10364
|
+
* model to correct itself in one line and NOT to curate anything
|
|
10365
|
+
* complementary (`apps/api/src/widget/widget-chat.service.ts`).
|
|
10366
|
+
*
|
|
10367
|
+
* Two gates, both narrower than they look:
|
|
10368
|
+
*
|
|
10369
|
+
* - **A session must exist** (`chatToken`), the same gate
|
|
10370
|
+
* `onAddedToCart` keeps. There is no concierge holding a claim to correct
|
|
10371
|
+
* if no conversation was ever booted.
|
|
10372
|
+
* - **Not DURING a call.** A chat request mid-call is answered out loud
|
|
10373
|
+
* over whatever the caller is saying — the harm the in-call gate exists
|
|
10374
|
+
* for, and it does not stop being that harm because the news is bad. So
|
|
10375
|
+
* the report is HELD and flushed when the call ends (see
|
|
10376
|
+
* `heldFailureReportsRef`), never dropped. The caller is not left with a
|
|
10377
|
+
* false claim in the meantime: `add_to_cart`'s `description()` no longer
|
|
10378
|
+
* instructs a completed-add confirmation at all, so what is outstanding
|
|
10379
|
+
* is a request under way, not a fact to retract.
|
|
10380
|
+
*
|
|
10381
|
+
* Fire-and-forget in both cases — a shopper's next message must never wait
|
|
10382
|
+
* on a correction, and `sendReport` resolves `false` rather than throwing
|
|
10383
|
+
* for every failure it has, including the 400 an OLD API answers a report
|
|
10384
|
+
* kind it has never heard of with.
|
|
10385
|
+
*
|
|
10386
|
+
* ## Telling the shopper when it did not work
|
|
10387
|
+
*
|
|
10388
|
+
* The outcome is captured from the `onAdded` hook rather than inferred from
|
|
10389
|
+
* the promise: `resolveAddToCartHandler` resolves quietly on the paths where
|
|
10390
|
+
* it could not act at all (no `addToCart`, no id in this bridge's space),
|
|
10391
|
+
* so "it did not throw" is not "it added". When nothing was added, the
|
|
10392
|
+
* status line says so — and it still does, independently of the report:
|
|
10393
|
+
* that line is the only thing left standing when the API is too old to
|
|
10394
|
+
* accept the report, and it costs the shopper nothing to have both.
|
|
10395
|
+
*/
|
|
10396
|
+
const performAgentCartAdd = useCallback(async (item) => {
|
|
10397
|
+
let added = false;
|
|
10398
|
+
const perform = resolveAddToCartHandler(bridge, inCall ? void 0 : productHref, (addedItem) => {
|
|
10399
|
+
added = true;
|
|
10400
|
+
recordAddedLine(addedItem);
|
|
10401
|
+
});
|
|
10402
|
+
try {
|
|
10403
|
+
await perform?.(item);
|
|
10404
|
+
} catch {}
|
|
10405
|
+
setAgentAddFailed(!added);
|
|
10406
|
+
if (!added) reportFailedAgentCartAdd(item);
|
|
10407
|
+
}, [
|
|
10408
|
+
bridge,
|
|
10409
|
+
productHref,
|
|
10410
|
+
inCall,
|
|
10411
|
+
recordAddedLine,
|
|
10412
|
+
reportFailedAgentCartAdd
|
|
10413
|
+
]);
|
|
10414
|
+
/**
|
|
10415
|
+
* The adds the CONCIERGE asked for, from both legs, performed exactly once
|
|
10416
|
+
* each.
|
|
10417
|
+
*
|
|
10418
|
+
* Two sources, one consumption record. The typed leg delivers an
|
|
10419
|
+
* `add-to-cart` SSE frame, which `useChatSession` collects into
|
|
10420
|
+
* `session.cartAdds`; the spoken leg delivers the same event over the
|
|
10421
|
+
* LiveKit data channel, which `useVoiceSession` parses into
|
|
10422
|
+
* `voice.widgetEvents`. Both are append-only lists of distinct objects, so
|
|
10423
|
+
* one `WeakSet` serves both and nothing has to know which transport an add
|
|
10424
|
+
* arrived on.
|
|
10425
|
+
*
|
|
10426
|
+
* **Consumed by IDENTITY, never by an index or a count.** This is the same
|
|
10427
|
+
* rule the escalation effect above follows, and it is not merely stylistic:
|
|
10428
|
+
* `useVoiceSession` caps its list with a sliding `slice(-20)`, so a
|
|
10429
|
+
* "how many have I handled" counter silently drifts past new entries the
|
|
10430
|
+
* moment the cap is reached — and here that means adds that never happen or,
|
|
10431
|
+
* worse, adds performed twice. See `AGENTS.md` → "Consuming an
|
|
10432
|
+
* agent-requested add".
|
|
10433
|
+
*
|
|
10434
|
+
* **Marked consumed BEFORE the add is attempted, deliberately.** The add is
|
|
10435
|
+
* asynchronous and this effect re-runs on any dependency change (a new
|
|
10436
|
+
* `bridge` identity, a call starting), so marking afterwards would let a
|
|
10437
|
+
* re-run pick up an event whose add is still in flight and charge the
|
|
10438
|
+
* shopper twice. At-most-once is the property worth having: a missed add
|
|
10439
|
+
* leaves a shopper without an item they can still add, a double add takes
|
|
10440
|
+
* their money for one they did not want.
|
|
10441
|
+
*
|
|
10442
|
+
* The adds run in SEQUENCE, not in parallel: `ShopifyBridge` posts to
|
|
10443
|
+
* `/cart/add.js`, and a storefront cart is one resource — two concurrent
|
|
10444
|
+
* posts against it is exactly the shape that loses one of them.
|
|
10445
|
+
*/
|
|
10446
|
+
const consumedCartAddsRef = useRef(/* @__PURE__ */ new WeakSet());
|
|
10447
|
+
const voiceWidgetEvents = voice.widgetEvents;
|
|
10448
|
+
const sessionCartAdds = session.cartAdds;
|
|
10449
|
+
useEffect(() => {
|
|
10450
|
+
const pending = [];
|
|
10451
|
+
for (const event of voiceWidgetEvents) {
|
|
10452
|
+
if (event.type !== "add-to-cart") continue;
|
|
10453
|
+
if (consumedCartAddsRef.current.has(event)) continue;
|
|
10454
|
+
consumedCartAddsRef.current.add(event);
|
|
10455
|
+
pending.push(event.item);
|
|
10456
|
+
}
|
|
10457
|
+
for (const request of sessionCartAdds) {
|
|
10458
|
+
if (consumedCartAddsRef.current.has(request)) continue;
|
|
10459
|
+
consumedCartAddsRef.current.add(request);
|
|
10460
|
+
pending.push(request.item);
|
|
10461
|
+
}
|
|
10462
|
+
if (pending.length === 0) return;
|
|
10463
|
+
(async () => {
|
|
10464
|
+
for (const item of pending) await performAgentCartAdd(item);
|
|
10465
|
+
})();
|
|
10466
|
+
}, [
|
|
10467
|
+
voiceWidgetEvents,
|
|
10468
|
+
sessionCartAdds,
|
|
10469
|
+
performAgentCartAdd
|
|
10470
|
+
]);
|
|
10471
|
+
const onAddToCart = resolveAddToCartHandler(bridge, productHref, onAddedToCart);
|
|
9486
10472
|
const navigate = useMemo(() => bridge?.navigate?.bind(bridge), [bridge]);
|
|
9487
10473
|
const onSendText = useCallback(async (text) => session.send(text), [session]);
|
|
9488
10474
|
/**
|
|
@@ -9493,26 +10479,52 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9493
10479
|
* future caller of this prop cannot accidentally start a call the tenant
|
|
9494
10480
|
* never enabled.
|
|
9495
10481
|
*
|
|
9496
|
-
* **
|
|
9497
|
-
*
|
|
9498
|
-
*
|
|
9499
|
-
*
|
|
9500
|
-
*
|
|
9501
|
-
*
|
|
9502
|
-
*
|
|
9503
|
-
*
|
|
9504
|
-
*
|
|
9505
|
-
*
|
|
9506
|
-
*
|
|
9507
|
-
*
|
|
9508
|
-
*
|
|
9509
|
-
*
|
|
9510
|
-
*
|
|
9511
|
-
*
|
|
9512
|
-
*
|
|
9513
|
-
*
|
|
9514
|
-
*
|
|
9515
|
-
*
|
|
10482
|
+
* **A call opens with the agent greeting unless the SHOPPER has already
|
|
10483
|
+
* spoken in this session** — `greet: !session.turns.some((t) => t.speaker
|
|
10484
|
+
* === 'caller')`.
|
|
10485
|
+
*
|
|
10486
|
+
* ## The rule, and the two ways of getting it wrong
|
|
10487
|
+
*
|
|
10488
|
+
* This condition used to be `!turns.some((t) => t.speaker === 'agent')` —
|
|
10489
|
+
* "greet only if the caller has not already been greeted in writing, so
|
|
10490
|
+
* nobody is welcomed twice in two different sets of words." The reasoning
|
|
10491
|
+
* was sound and the effect was not: the panel puts the tenant's written
|
|
10492
|
+
* greeting on screen as an agent turn the moment it OPENS, and the panel
|
|
10493
|
+
* has to be open before the microphone exists to press. So an agent turn was
|
|
10494
|
+
* always present, `greet` was always `false`, and the worker skipped
|
|
10495
|
+
* greeting synthesis on every single call — confirmed on three real calls,
|
|
10496
|
+
* which logged `agent_ready greetingChars: 56` and never issued a synthesis
|
|
10497
|
+
* request. No error anywhere, just a call that opened in dead silence and
|
|
10498
|
+
* read as broken. It was then hard-coded to `true` to stop the bleeding.
|
|
10499
|
+
*
|
|
10500
|
+
* Neither extreme is the rule. `true` always is a caller who reads the
|
|
10501
|
+
* written greeting, presses the mic, and is welcomed again a second later;
|
|
10502
|
+
* keying on ANY agent turn is silence on every call. **The honest question
|
|
10503
|
+
* is whether this conversation is already under way, and only the SHOPPER
|
|
10504
|
+
* can answer it.** A caller-authored turn is the one signal that cannot be
|
|
10505
|
+
* produced by the widget merely being open:
|
|
10506
|
+
*
|
|
10507
|
+
* - **Fresh panel, mic pressed** — no caller turn, so the call greets. The
|
|
10508
|
+
* silent-call regression cannot come back through this line, because the
|
|
10509
|
+
* condition it depends on is false at exactly the moment the old one was
|
|
10510
|
+
* true.
|
|
10511
|
+
* - **Mid-conversation, mic pressed** — the shopper has typed, been
|
|
10512
|
+
* answered, and now wants to talk instead. Welcoming them to a
|
|
10513
|
+
* conversation already on screen is the double greeting, and it is worse
|
|
10514
|
+
* than the written/spoken pair ever was: it interrupts something in
|
|
10515
|
+
* progress. Here `greet: false` costs nothing, because the shopper has
|
|
10516
|
+
* visible evidence the line is live.
|
|
10517
|
+
*
|
|
10518
|
+
* The written-then-spoken pair on a FRESH panel is still accepted, and
|
|
10519
|
+
* deliberately: the two greetings belong to two modalities, the caller has
|
|
10520
|
+
* heard neither of them spoken, and a call that connects into silence is
|
|
10521
|
+
* indistinguishable from one that did not connect. One greeting per
|
|
10522
|
+
* modality, at most one per session per leg, and never a re-greet into a
|
|
10523
|
+
* conversation that has started — that is the whole rule.
|
|
10524
|
+
*
|
|
10525
|
+
* `SessionTuningSchema.greet` itself is unchanged and still a real knob for
|
|
10526
|
+
* a host that has genuinely greeted the caller on the voice channel
|
|
10527
|
+
* already; what moved is only this widget's answer to it.
|
|
9516
10528
|
*/
|
|
9517
10529
|
const onToggleMic = useCallback(() => {
|
|
9518
10530
|
if (!voiceEnabled) return;
|
|
@@ -9521,12 +10533,13 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9521
10533
|
voice.toggleMic();
|
|
9522
10534
|
return;
|
|
9523
10535
|
}
|
|
9524
|
-
voice.start({ greet:
|
|
10536
|
+
voice.start({ greet: !session.turns.some((t) => t.speaker === "caller") });
|
|
9525
10537
|
}, [
|
|
9526
10538
|
voiceEnabled,
|
|
9527
10539
|
escalated,
|
|
9528
10540
|
inCall,
|
|
9529
|
-
voice
|
|
10541
|
+
voice,
|
|
10542
|
+
session.turns
|
|
9530
10543
|
]);
|
|
9531
10544
|
/**
|
|
9532
10545
|
* A call that outlives the handoff is a shopper talking to an AI leg the
|
|
@@ -9610,17 +10623,81 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9610
10623
|
state: voice.state
|
|
9611
10624
|
});
|
|
9612
10625
|
/**
|
|
9613
|
-
* One conversation
|
|
9614
|
-
*
|
|
9615
|
-
*
|
|
9616
|
-
*
|
|
9617
|
-
*
|
|
9618
|
-
*
|
|
9619
|
-
*
|
|
9620
|
-
*
|
|
10626
|
+
* One conversation, in the order the shopper watched it happen.
|
|
10627
|
+
*
|
|
10628
|
+
* Typed turns, spoken lines and voice card events are three lists with no
|
|
10629
|
+
* shared clock, so this used to concatenate them as blocks — typed, then
|
|
10630
|
+
* spoken, then cards. Two reported bugs came straight from that: cards
|
|
10631
|
+
* rendered as a pile after the WHOLE transcript instead of beside the
|
|
10632
|
+
* answer that produced them, and a shopper who talked first and then typed
|
|
10633
|
+
* saw their new typed line sort ABOVE the older spoken transcript.
|
|
10634
|
+
*
|
|
10635
|
+
* `TurnOrderClock` replaces the block order with ARRIVAL order: every row
|
|
10636
|
+
* is stamped the first render it appears in and keeps that stamp for the
|
|
10637
|
+
* life of the widget (through in-place revisions, the transcript cap, the
|
|
10638
|
+
* optimistic→server id rewrite and a new call's transcript reset — see
|
|
10639
|
+
* `turn-order.ts`), and the merge simply sorts by stamp. Rows that appear
|
|
10640
|
+
* in the same render keep source order (typed, spoken, cards), which is
|
|
10641
|
+
* exactly the old behaviour for a conversation restored in one go.
|
|
10642
|
+
*
|
|
10643
|
+
* ## Arrival order was not enough for CARDS — they bind to their turn
|
|
10644
|
+
*
|
|
10645
|
+
* Arrival order was the mitigation for the first of those two bugs, and it
|
|
10646
|
+
* only half-worked: it put a curation NEAR the answer instead of after the
|
|
10647
|
+
* whole transcript, but the cards were still their own turn-less row. On the
|
|
10648
|
+
* live storefront that read as a floating block which the agent's own line —
|
|
10649
|
+
* a separate frame, published a beat later — then rendered BELOW, shoving
|
|
10650
|
+
* the products off the top of the panel while the concierge was describing
|
|
10651
|
+
* them. The typed leg never had this: `use-chat-session.ts` attaches its
|
|
10652
|
+
* `cards` SSE event onto the live agent turn, and `VoiceWidget` draws
|
|
10653
|
+
* `turn.cards` under that turn's bubble.
|
|
10654
|
+
*
|
|
10655
|
+
* The voice leg now carries the same join key — `session-host.ts` stamps the
|
|
10656
|
+
* in-flight turn on the `widget.event` envelope, `useVoiceSession` keeps it
|
|
10657
|
+
* as `VoiceWidgetEvent.turnId` — and a stamped curation is folded into the
|
|
10658
|
+
* matching agent line's `cards` instead of standing as a row of its own.
|
|
10659
|
+
*
|
|
10660
|
+
* ### The ordering rule: the CARDS move, the transcript does not
|
|
10661
|
+
*
|
|
10662
|
+
* There is no sequencing contract between a `widget.event` frame and the
|
|
10663
|
+
* transcript frames on the data channel, and deliberately so: a curation is
|
|
10664
|
+
* sent the instant its tool resolves, never held to end-of-turn, so it
|
|
10665
|
+
* routinely lands before any line carrying that turn exists.
|
|
10666
|
+
*
|
|
10667
|
+
* The bound row keeps the LINE's own arrival stamp, and the cards come to
|
|
10668
|
+
* it. Nothing already on screen is reordered — not the filler that covered
|
|
10669
|
+
* the wait, not a question the shopper asked while the tool was resolving.
|
|
10670
|
+
* The cards are drawn inside that row, under its bubble, so at worst they
|
|
10671
|
+
* sit one row lower than they did a moment ago, which is exactly what the
|
|
10672
|
+
* report asked for: the message above and its cards below, in view together.
|
|
10673
|
+
* Pulling the bubble back to the cards instead is the natural-looking
|
|
10674
|
+
* alternative and it is a trap — see the long note on the `spoken` mapping
|
|
10675
|
+
* below for why it is wrong unclamped and provably pointless clamped.
|
|
10676
|
+
*
|
|
10677
|
+
* Buffering the cards until their line appears was the other alternative,
|
|
10678
|
+
* and it is worse in exactly the way the bug was: it hides a curation the
|
|
10679
|
+
* concierge is already talking about, and loses it outright when the line
|
|
10680
|
+
* never comes. Stamps stay unique throughout — the cards' own row ceases to
|
|
10681
|
+
* exist the moment it is absorbed.
|
|
10682
|
+
*
|
|
10683
|
+
* ### Nothing is ever buffered, so nothing can be lost
|
|
10684
|
+
*
|
|
10685
|
+
* A cards event that never finds a line — an unstamped one from an older
|
|
10686
|
+
* agent or a curation raised outside a turn, a turn that fails, a call that
|
|
10687
|
+
* ends mid-answer — renders exactly as it did before, as its own row in
|
|
10688
|
+
* arrival order. That is the fallback, and it is the reason the binding can
|
|
10689
|
+
* be attempted at all: the worst case is the behaviour we already shipped.
|
|
10690
|
+
*
|
|
10691
|
+
* Fillers are skipped when choosing the line to bind to. Dead-air cover
|
|
10692
|
+
* speech ("One moment.") is drawn as deliberately transient, and hanging a
|
|
10693
|
+
* curation off it would put the products under a bubble that reads as
|
|
10694
|
+
* nothing at all; the cards wait for the turn's real answer and stay in
|
|
10695
|
+
* arrival order until it arrives.
|
|
9621
10696
|
*/
|
|
10697
|
+
const orderRef = useRef(null);
|
|
10698
|
+
orderRef.current ??= new TurnOrderClock();
|
|
9622
10699
|
const widgetTurns = useMemo(() => {
|
|
9623
|
-
const
|
|
10700
|
+
const mapTypedTurn = (turn) => ({
|
|
9624
10701
|
speaker: turn.speaker,
|
|
9625
10702
|
text: turn.text,
|
|
9626
10703
|
locale,
|
|
@@ -9629,31 +10706,155 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9629
10706
|
...turn.delivery ? { delivery: turn.delivery } : {},
|
|
9630
10707
|
...turn.cards ? { cards: turn.cards } : {},
|
|
9631
10708
|
...turn.attachments ? { attachments: turn.attachments } : {}
|
|
10709
|
+
});
|
|
10710
|
+
if (!voiceEnabled) return session.turns.map(mapTypedTurn);
|
|
10711
|
+
const order = orderRef.current;
|
|
10712
|
+
const typedStamps = order.stampTyped(session.turns);
|
|
10713
|
+
const typed = session.turns.map((turn, i) => ({
|
|
10714
|
+
stamp: typedStamps[i],
|
|
10715
|
+
turn: mapTypedTurn(turn)
|
|
9632
10716
|
}));
|
|
9633
|
-
if (!voiceEnabled) return typed;
|
|
9634
10717
|
const lines = voice.transcript;
|
|
9635
|
-
const
|
|
9636
|
-
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
|
|
9640
|
-
|
|
9641
|
-
}));
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
|
|
9645
|
-
|
|
9646
|
-
|
|
9647
|
-
|
|
10718
|
+
const spokenStamps = order.stampSpoken(lines);
|
|
10719
|
+
const lastIndexBySpeaker = /* @__PURE__ */ new Map();
|
|
10720
|
+
lines.forEach((l, i) => lastIndexBySpeaker.set(l.speaker, i));
|
|
10721
|
+
const visible = lines.map((line, i) => ({
|
|
10722
|
+
line,
|
|
10723
|
+
i
|
|
10724
|
+
})).filter(({ line, i }) => line.final || lastIndexBySpeaker.get(line.speaker) === i);
|
|
10725
|
+
/**
|
|
10726
|
+
* Every stamped curation, gathered by the turn that raised it. Stamping
|
|
10727
|
+
* happens HERE, over the whole list and on every render, because
|
|
10728
|
+
* `stampEvent` is first-sight-wins by identity: an event that is about to
|
|
10729
|
+
* be absorbed into a bubble must still hold the stamp it earned on the
|
|
10730
|
+
* render it arrived in, which is the position the bound row inherits.
|
|
10731
|
+
*
|
|
10732
|
+
* Two curations from one turn accumulate into one `cards` block rather
|
|
10733
|
+
* than replacing each other — a second tool call in the same answer is an
|
|
10734
|
+
* addition to it, and dropping the first would lose products the shopper
|
|
10735
|
+
* was just shown. The block keeps the FIRST stamp, so it stays where the
|
|
10736
|
+
* shopper first saw it.
|
|
10737
|
+
*
|
|
10738
|
+
* It does NOT keep the first `curationId`. `WidgetCardList` truncates to
|
|
10739
|
+
* `INLINE_CARD_LIMIT` and offers "see all N" pointing at
|
|
10740
|
+
* `curationHref(cards.curationId)` — ONE curation's landing page. After a
|
|
10741
|
+
* merge the count covers every contributing event while the link names
|
|
10742
|
+
* only one of them, so the shopper clicks through to a page missing
|
|
10743
|
+
* everything the other tool calls found, with nothing to tell them they
|
|
10744
|
+
* were shown a subset. An id therefore survives only while every
|
|
10745
|
+
* contributing event agrees on it; the moment one disagrees (an id-less
|
|
10746
|
+
* event included — its items are in the block too) the block goes
|
|
10747
|
+
* id-less and the overflow link is withheld rather than pointed somewhere
|
|
10748
|
+
* wrong. Withholding is recoverable — the shopper can ask — and a link
|
|
10749
|
+
* that quietly under-delivers is not.
|
|
10750
|
+
*/
|
|
10751
|
+
const byTurn = /* @__PURE__ */ new Map();
|
|
10752
|
+
const unbound = [];
|
|
10753
|
+
for (const event of voice.widgetEvents) {
|
|
10754
|
+
if (event.type !== "cards") continue;
|
|
10755
|
+
const stamp = order.stampEvent(event);
|
|
10756
|
+
const curation = {
|
|
9648
10757
|
...event.curationId !== void 0 ? { curationId: event.curationId } : {},
|
|
9649
10758
|
items: event.items
|
|
10759
|
+
};
|
|
10760
|
+
if (event.turnId === void 0) {
|
|
10761
|
+
unbound.push({
|
|
10762
|
+
stamp,
|
|
10763
|
+
...curation
|
|
10764
|
+
});
|
|
10765
|
+
continue;
|
|
10766
|
+
}
|
|
10767
|
+
const existing = byTurn.get(event.turnId);
|
|
10768
|
+
if (existing === void 0) {
|
|
10769
|
+
byTurn.set(event.turnId, {
|
|
10770
|
+
stamp,
|
|
10771
|
+
...curation,
|
|
10772
|
+
items: [...event.items]
|
|
10773
|
+
});
|
|
10774
|
+
continue;
|
|
10775
|
+
}
|
|
10776
|
+
existing.items.push(...event.items);
|
|
10777
|
+
if (existing.curationId !== event.curationId) delete existing.curationId;
|
|
10778
|
+
}
|
|
10779
|
+
const anchors = /* @__PURE__ */ new Map();
|
|
10780
|
+
for (const { line, i } of visible) {
|
|
10781
|
+
const turnId = line.turnId;
|
|
10782
|
+
if (line.speaker !== "agent" || line.filler === true || turnId === void 0) continue;
|
|
10783
|
+
if (!byTurn.has(turnId) || anchors.has(turnId)) continue;
|
|
10784
|
+
anchors.set(turnId, i);
|
|
10785
|
+
}
|
|
10786
|
+
const orphaned = [...unbound, ...[...byTurn].filter(([turnId]) => !anchors.has(turnId)).map(([, cards]) => cards)];
|
|
10787
|
+
/**
|
|
10788
|
+
* ── Why the bound row simply keeps the LINE's stamp ───────────────────
|
|
10789
|
+
*
|
|
10790
|
+
* The obvious move here is `Math.min(stamp, bound.stamp)`: pull the bubble
|
|
10791
|
+
* back to where its cards already sit so the products never move. Do not
|
|
10792
|
+
* reintroduce it. It is wrong unclamped and pointless clamped, and the
|
|
10793
|
+
* reasoning is worth keeping because the idea is a natural one to have
|
|
10794
|
+
* twice.
|
|
10795
|
+
*
|
|
10796
|
+
* UNCLAMPED it leapfrogs. A row stamped between the cards and the line is
|
|
10797
|
+
* one the shopper already watched appear, and lifting the answer over it
|
|
10798
|
+
* rewrites the order they saw the conversation happen in. It is not
|
|
10799
|
+
* hypothetical, and this change makes it likelier rather than rarer: a
|
|
10800
|
+
* `widget.event` is not a `say.*` frame, so a curation does not disarm the
|
|
10801
|
+
* dead-air watchdog, and a slow turn covers the gap between the cards
|
|
10802
|
+
* landing and the answer arriving with a spoken filler — an unclamped lift
|
|
10803
|
+
* prints that stall message AFTER the answer it was stalling for. A caller
|
|
10804
|
+
* line in the same window is worse: the concierge appears to answer a
|
|
10805
|
+
* question before it was asked.
|
|
10806
|
+
*
|
|
10807
|
+
* CLAMPED — "reach back only while nothing stands in between" — it becomes
|
|
10808
|
+
* a no-op, provably. The clamp fires exactly when the interval between the
|
|
10809
|
+
* two stamps holds no rendered row, and moving a row within an interval
|
|
10810
|
+
* that contains nothing cannot change its position in the sort. Nor can
|
|
10811
|
+
* that interval fill up later: stamps are handed out by a rising counter,
|
|
10812
|
+
* so a row appearing after this render lands ABOVE both ends of it, never
|
|
10813
|
+
* inside. So the clamped version and this line produce the same
|
|
10814
|
+
* transcript, and this one needs no occupancy set to say so.
|
|
10815
|
+
*
|
|
10816
|
+
* The cards move instead, and that is the whole fix: they are drawn INSIDE
|
|
10817
|
+
* this row, under the bubble, so they arrive wherever the sentence that
|
|
10818
|
+
* introduced them arrives. At worst that is one row lower than where they
|
|
10819
|
+
* were sitting a moment ago — which is the property the report actually
|
|
10820
|
+
* asked for, the message above and its cards below, in view together.
|
|
10821
|
+
*/
|
|
10822
|
+
const spoken = visible.map(({ line, i }) => {
|
|
10823
|
+
const turnId = line.turnId;
|
|
10824
|
+
const bound = turnId !== void 0 && anchors.get(turnId) === i ? byTurn.get(turnId) : void 0;
|
|
10825
|
+
return {
|
|
10826
|
+
stamp: spokenStamps[i],
|
|
10827
|
+
turn: {
|
|
10828
|
+
speaker: line.speaker,
|
|
10829
|
+
text: line.text,
|
|
10830
|
+
locale: line.locale,
|
|
10831
|
+
final: line.final,
|
|
10832
|
+
...line.filler ? { filler: true } : {},
|
|
10833
|
+
...bound === void 0 ? {} : { cards: {
|
|
10834
|
+
...bound.curationId !== void 0 ? { curationId: bound.curationId } : {},
|
|
10835
|
+
items: bound.items
|
|
10836
|
+
} }
|
|
10837
|
+
}
|
|
10838
|
+
};
|
|
10839
|
+
});
|
|
10840
|
+
const rendered = orphaned.map(({ stamp, curationId, items }) => ({
|
|
10841
|
+
stamp,
|
|
10842
|
+
turn: {
|
|
10843
|
+
speaker: "agent",
|
|
10844
|
+
text: "",
|
|
10845
|
+
locale,
|
|
10846
|
+
final: true,
|
|
10847
|
+
cards: {
|
|
10848
|
+
...curationId !== void 0 ? { curationId } : {},
|
|
10849
|
+
items
|
|
10850
|
+
}
|
|
9650
10851
|
}
|
|
9651
10852
|
}));
|
|
9652
10853
|
return [
|
|
9653
10854
|
...typed,
|
|
9654
10855
|
...spoken,
|
|
9655
10856
|
...rendered
|
|
9656
|
-
];
|
|
10857
|
+
].sort((a, b) => a.stamp - b.stamp).map((entry) => entry.turn);
|
|
9657
10858
|
}, [
|
|
9658
10859
|
session.turns,
|
|
9659
10860
|
voice.transcript,
|
|
@@ -9663,17 +10864,39 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9663
10864
|
]);
|
|
9664
10865
|
/**
|
|
9665
10866
|
* The SAME read `VoiceWidget` makes to decide whether to draw the summary —
|
|
9666
|
-
* literally the same function (`
|
|
9667
|
-
*
|
|
9668
|
-
*
|
|
9669
|
-
*
|
|
9670
|
-
*
|
|
9671
|
-
* a
|
|
10867
|
+
* literally the same function (`basketIntentFromTurns`), not a second copy
|
|
10868
|
+
* of it — put to a different use here: this is the moment to re-read the
|
|
10869
|
+
* host's cart, so the basket the shopper is looking at is the one that
|
|
10870
|
+
* exists NOW and not the one that existed at the last add. It answers to
|
|
10871
|
+
* "show me my cart" as well as "let's check out", because a stale basket is
|
|
10872
|
+
* a wrong answer to both. Reading the merged turns rather than
|
|
10873
|
+
* `session.turns` alone is what makes a SPOKEN line refresh too.
|
|
10874
|
+
*/
|
|
10875
|
+
const wantsBasket = useMemo(() => basketIntentFromTurns(widgetTurns), [widgetTurns]);
|
|
10876
|
+
useEffect(() => {
|
|
10877
|
+
if (wantsBasket) refreshHostCart();
|
|
10878
|
+
}, [wantsBasket, refreshHostCart]);
|
|
10879
|
+
/**
|
|
10880
|
+
* The THIRD trigger for a host cart read, and the one that makes "the cart
|
|
10881
|
+
* is always present" true for a shopper's FIRST message rather than only
|
|
10882
|
+
* after they have added something.
|
|
10883
|
+
*
|
|
10884
|
+
* A page reload leaves the widget knowing nothing about a basket built
|
|
10885
|
+
* before it: `addedLines` starts empty and `hostCart` is `null` until
|
|
10886
|
+
* something asks. Opening the panel is the moment the shopper engages, and
|
|
10887
|
+
* it is early enough that the read has resolved long before they finish
|
|
10888
|
+
* typing — so the first turn of a resumed conversation carries the real
|
|
10889
|
+
* basket instead of nothing.
|
|
10890
|
+
*
|
|
10891
|
+
* Gated on `open` rather than run on mount, deliberately. The widget mounts
|
|
10892
|
+
* on every page load, including for the large majority of visitors who
|
|
10893
|
+
* never talk to it; firing a storefront cart request for each of them would
|
|
10894
|
+
* be a real cost on the merchant's own store, and an observation of a
|
|
10895
|
+
* shopper who has done nothing. Opening the panel is an action they took.
|
|
9672
10896
|
*/
|
|
9673
|
-
const wantsCheckout = useMemo(() => checkoutIntentFromTurns(widgetTurns), [widgetTurns]);
|
|
9674
10897
|
useEffect(() => {
|
|
9675
|
-
if (
|
|
9676
|
-
}, [
|
|
10898
|
+
if (open) refreshHostCart();
|
|
10899
|
+
}, [open, refreshHostCart]);
|
|
9677
10900
|
/**
|
|
9678
10901
|
* The host's answer wins wherever it HAS one, and the widget's own
|
|
9679
10902
|
* accumulation covers the rest:
|
|
@@ -9688,7 +10911,8 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9688
10911
|
* themselves were priced in.
|
|
9689
10912
|
*/
|
|
9690
10913
|
const cartCurrency = hostCart?.currency ?? addedLines[0]?.currency ?? "USD";
|
|
9691
|
-
const
|
|
10914
|
+
const hostLines = useMemo(() => cartLinesFromSnapshot(hostCart, cartCurrency), [hostCart, cartCurrency]);
|
|
10915
|
+
const cartLines = hostLines ?? addedLines;
|
|
9692
10916
|
const cartSubtotalMinor = hostCart?.subtotalCents ?? cartLines.reduce((total, line) => total + line.priceMinor * line.quantity, 0);
|
|
9693
10917
|
/**
|
|
9694
10918
|
* Fire the checkout. `undefined` (rather than an `onCheckout` that always
|
|
@@ -9706,12 +10930,133 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9706
10930
|
bridge,
|
|
9707
10931
|
session
|
|
9708
10932
|
]);
|
|
10933
|
+
/**
|
|
10934
|
+
* The one line under the header, and the order the three claimants take it
|
|
10935
|
+
* in — extracted from the prop so the precedence is stated once, in reading
|
|
10936
|
+
* order, rather than as a nested ternary.
|
|
10937
|
+
*
|
|
10938
|
+
* 1. A **session error** — the conversation itself is broken, which nothing
|
|
10939
|
+
* else the widget could say matters more than.
|
|
10940
|
+
* 2. A **voice error** — a refused microphone or a dead speech vendor is the
|
|
10941
|
+
* only place either of those reaches the caller at all.
|
|
10942
|
+
* 3. A **failed agent-requested add** — last, because it is the least
|
|
10943
|
+
* urgent of the three and the only one that is about a single item. It
|
|
10944
|
+
* still has to be said: the concierge has already told the shopper the
|
|
10945
|
+
* item is going in their basket, and this side is the only one that knows
|
|
10946
|
+
* it did not (see `performAgentCartAdd`).
|
|
10947
|
+
*
|
|
10948
|
+
* `VoiceWidget` fills an empty line with its own escalation reason, exactly
|
|
10949
|
+
* as before — this only decides what the HOST has to say.
|
|
10950
|
+
*/
|
|
10951
|
+
const voiceStatus = voiceEnabled ? voice.error ?? void 0 : void 0;
|
|
10952
|
+
const cartAddStatus = agentAddFailed ? messages.cart_add_failed ?? defaultWidgetMessages.cart_add_failed : void 0;
|
|
10953
|
+
const statusLine = session.status === "error" ? session.error ?? "error" : voiceStatus ?? cartAddStatus;
|
|
9709
10954
|
const cart = cartLines.length > 0 ? {
|
|
9710
10955
|
lines: cartLines,
|
|
9711
10956
|
subtotalMinor: cartSubtotalMinor,
|
|
9712
10957
|
currency: cartCurrency,
|
|
9713
10958
|
onCheckout
|
|
9714
10959
|
} : void 0;
|
|
10960
|
+
/**
|
|
10961
|
+
* THE CART IS ALWAYS PRESENT — the concierge's half of the basket the
|
|
10962
|
+
* shopper is looking at.
|
|
10963
|
+
*
|
|
10964
|
+
* Before this, the model learned about a basket only from `cart_add`
|
|
10965
|
+
* reports: one per press, only for adds made through a widget card, and
|
|
10966
|
+
* gone the moment the page reloaded. So it could not answer "what is in my
|
|
10967
|
+
* cart" (the storefront's own basket, built before the conversation
|
|
10968
|
+
* started, was invisible to it) and a resumed session knew nothing about a
|
|
10969
|
+
* basket built before the reload. Every turn now carries the basket THIS
|
|
10970
|
+
* component already resolved, so the answer and the summary drawn under it
|
|
10971
|
+
* come from one set of numbers.
|
|
10972
|
+
*
|
|
10973
|
+
* Pushed into `useChatSession` rather than passed to it: this component
|
|
10974
|
+
* both calls the hook and owns the cart, so the value does not exist yet
|
|
10975
|
+
* when the hook is constructed. The hook stores it in a ref (no re-render)
|
|
10976
|
+
* and attaches it to the next chat request — see `setCart`'s doc comment.
|
|
10977
|
+
*
|
|
10978
|
+
* Recomputed from the SAME `cartLines`/`cartCurrency`/`hostCart` the
|
|
10979
|
+
* summary renders, so there is exactly one resolution of "whose numbers
|
|
10980
|
+
* win" (`AGENTS.md`) in this file. `hostSubtotalMinor` is passed ONLY when
|
|
10981
|
+
* the host itself stated a total — a figure derived by multiplying out unit
|
|
10982
|
+
* prices must not reach the model as the storefront's own, because it
|
|
10983
|
+
* cannot carry a discount.
|
|
10984
|
+
*/
|
|
10985
|
+
const chatCart = useMemo(() => toChatCart({
|
|
10986
|
+
lines: cartLines,
|
|
10987
|
+
currency: cartCurrency,
|
|
10988
|
+
hostReported: hostLines !== void 0,
|
|
10989
|
+
...hostCart?.subtotalCents !== void 0 ? { hostSubtotalMinor: hostCart.subtotalCents } : {}
|
|
10990
|
+
}), [
|
|
10991
|
+
cartLines,
|
|
10992
|
+
cartCurrency,
|
|
10993
|
+
hostLines,
|
|
10994
|
+
hostCart
|
|
10995
|
+
]);
|
|
10996
|
+
useEffect(() => {
|
|
10997
|
+
session.setCart(chatCart);
|
|
10998
|
+
}, [chatCart, session.setCart]);
|
|
10999
|
+
/**
|
|
11000
|
+
* The last basket this widget PUSHED to the server, serialised.
|
|
11001
|
+
*
|
|
11002
|
+
* A ref, not state: nothing renders from it, and it exists only so the push
|
|
11003
|
+
* effect below can tell "the basket changed" from "React ran the effect
|
|
11004
|
+
* again". `chatCart` is a fresh object on every recompute even when the
|
|
11005
|
+
* numbers are identical, so without this every re-render of a live call
|
|
11006
|
+
* would be a request.
|
|
11007
|
+
*/
|
|
11008
|
+
const pushedCartRef = useRef(null);
|
|
11009
|
+
/**
|
|
11010
|
+
* Keep a LIVE CALL's basket current.
|
|
11011
|
+
*
|
|
11012
|
+
* ## Why a push at all, when every typed turn already carries the cart
|
|
11013
|
+
*
|
|
11014
|
+
* A typed turn carries it as a field on the request the model is about to
|
|
11015
|
+
* answer, which is atomic with the question by construction. A spoken turn
|
|
11016
|
+
* has no such request: the caller asks out loud, `apps/agent` assembles the
|
|
11017
|
+
* turn, and nothing on that path has ever been near this browser. So for
|
|
11018
|
+
* the duration of a call the basket has to be pushed to somewhere the turn
|
|
11019
|
+
* tier can read (`POST /widget/cart`), and it re-reads that on every turn.
|
|
11020
|
+
*
|
|
11021
|
+
* ## Why on CHANGE, and why that is the whole freshness story
|
|
11022
|
+
*
|
|
11023
|
+
* A basket pushed once when the call connects is wrong the moment anything
|
|
11024
|
+
* moves — and on a call the concierge itself can add
|
|
11025
|
+
* (`performAgentCartAdd`, from the `add_to_cart` event), so the very
|
|
11026
|
+
* feature that lets a caller fill a basket is what would make a call-start
|
|
11027
|
+
* snapshot lie. `chatCart` is recomputed from the same `cartLines` /
|
|
11028
|
+
* `cartCurrency` / `hostCart` the summary renders, so EVERY route into the
|
|
11029
|
+
* basket — a card button, a host cart re-read, an add the concierge asked
|
|
11030
|
+
* for — lands here as a changed value, with no second list of triggers to
|
|
11031
|
+
* keep in step.
|
|
11032
|
+
*
|
|
11033
|
+
* ## Bounded on this side too
|
|
11034
|
+
*
|
|
11035
|
+
* Only while a call is live (a typed conversation needs none of this), and
|
|
11036
|
+
* only when the SERIALISED snapshot actually differs from the last one
|
|
11037
|
+
* pushed. That is a courtesy rather than a guarantee, which is why the
|
|
11038
|
+
* server carries its own per-embed-key ceiling on the route — but it is
|
|
11039
|
+
* what keeps the ordinary call at a handful of requests rather than one per
|
|
11040
|
+
* render.
|
|
11041
|
+
*
|
|
11042
|
+
* `null` — no host lines and no adds of our own — is deliberately NOT
|
|
11043
|
+
* pushed. It means "I know of no cart", which is a different statement from
|
|
11044
|
+
* an empty one, and overwriting a real snapshot with silence would have the
|
|
11045
|
+
* concierge lose a basket it was correctly describing a second ago. The
|
|
11046
|
+
* stale snapshot expires on its own.
|
|
11047
|
+
*/
|
|
11048
|
+
const pushCart = session.pushCart;
|
|
11049
|
+
useEffect(() => {
|
|
11050
|
+
if (!inCall || chatCart === null) return;
|
|
11051
|
+
const serialised = JSON.stringify(chatCart);
|
|
11052
|
+
if (serialised === pushedCartRef.current) return;
|
|
11053
|
+
pushedCartRef.current = serialised;
|
|
11054
|
+
pushCart(chatCart);
|
|
11055
|
+
}, [
|
|
11056
|
+
chatCart,
|
|
11057
|
+
inCall,
|
|
11058
|
+
pushCart
|
|
11059
|
+
]);
|
|
9715
11060
|
return /* @__PURE__ */ jsx(VoiceWidget, {
|
|
9716
11061
|
state: inCall ? voice.state : "idle",
|
|
9717
11062
|
turns: widgetTurns,
|
|
@@ -9726,7 +11071,9 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9726
11071
|
open,
|
|
9727
11072
|
onOpenChange: setOpen,
|
|
9728
11073
|
escalated,
|
|
9729
|
-
|
|
11074
|
+
humanTyping: session.deskTyping,
|
|
11075
|
+
onTyping: session.notifyTyping,
|
|
11076
|
+
status: statusLine,
|
|
9730
11077
|
...onAddToCart ? { onAddToCart } : {},
|
|
9731
11078
|
...cart ? { cart } : {},
|
|
9732
11079
|
...curationHref ? { curationHref } : {},
|
|
@@ -9742,4 +11089,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
|
|
|
9742
11089
|
});
|
|
9743
11090
|
}
|
|
9744
11091
|
//#endregion
|
|
9745
|
-
export {
|
|
11092
|
+
export { latencyBetween as A, alignOf as B, parseBlocks as C, SESSION_EVENTS as D, SseFrameParser as E, resolveWidgetMessages as F, positionForArrow as G, nearestPosition as H, widgetMessagesFromCopy as I, isWidgetAvatar as J, DEFAULT_WIDGET_AVATAR as K, ConciergeLauncher as L, MorphingLoader as M, defaultWidgetMessages as N, SessionLog as O, formatMessage as P, cn as Q, CONCIERGE_POSITIONS as R, WidgetMarkdown as S, botStateFor as T, panelClasses as U, edgeOf as V, positionClasses as W, BotFace as X, RopeKnot as Y, labelProps as Z, readsAsCheckoutIntent as _, mergeAddedCartLine as a, WidgetCardList as b, toChatCart as c, useVoiceSession as d, useChatSession as f, readsAsCartViewIntent as g, basketIntentFromTurns as h, deriveCallPhase as i, ConciergeShell as j, formatMs as k, ROOM_EVENTS as l, VoiceWidget as m, MAX_REPORTED_CART_LINES as n, resolveAddToCartHandler as o, detectPage as p, WIDGET_AVATARS as q, cartLinesFromSnapshot as r, resolveCheckoutUrl as s, ConciergeWidget as t, createWidgetVoiceTokenFetcher as u, textDirectionFor as v, IDLE_SNAPSHOT as w, formatMoney as x, WidgetCartSummary as y, DEFAULT_CONCIERGE_POSITION as z };
|