@saar-ai/web-widget 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/chunks/{chat-tMKkYmTC.js → chat-e1afSRBr.js} +188 -3
  2. package/dist/chunks/{host-widget-CAPud_Jz.js → host-widget-Ce-l1xu1.js} +1760 -116
  3. package/dist/chunks/{schemas-Bl_6mxe4.js → schemas-D-uDc-9q.js} +164 -1
  4. package/dist/chunks/{telemetry-BI_SEWTb.js → telemetry-CBblNC6C.js} +1 -1
  5. package/dist/dock/dock-drag.d.ts +81 -0
  6. package/dist/dock/dock-drag.d.ts.map +1 -0
  7. package/dist/dock/dock-motion.d.ts +14 -0
  8. package/dist/dock/dock-motion.d.ts.map +1 -1
  9. package/dist/dock/dock-pill.d.ts +7 -2
  10. package/dist/dock/dock-pill.d.ts.map +1 -1
  11. package/dist/dock/dock-row.d.ts +13 -2
  12. package/dist/dock/dock-row.d.ts.map +1 -1
  13. package/dist/dock/dock-sheet.d.ts +11 -1
  14. package/dist/dock/dock-sheet.d.ts.map +1 -1
  15. package/dist/dock/dock-state.d.ts +41 -0
  16. package/dist/dock/dock-state.d.ts.map +1 -1
  17. package/dist/dock/dock.d.ts +64 -0
  18. package/dist/dock/dock.d.ts.map +1 -1
  19. package/dist/dock/geometry.d.ts +74 -2
  20. package/dist/dock/geometry.d.ts.map +1 -1
  21. package/dist/generated/widget-css.d.ts.map +1 -1
  22. package/dist/host-widget.d.ts +14 -2
  23. package/dist/host-widget.d.ts.map +1 -1
  24. package/dist/index.js +3 -3
  25. package/dist/messages.d.ts +14 -0
  26. package/dist/messages.d.ts.map +1 -1
  27. package/dist/next/index.js +1 -1
  28. package/dist/styles.d.ts +3 -3
  29. package/dist/theme/derive.d.ts +1 -1
  30. package/dist/theme/derive.d.ts.map +1 -1
  31. package/dist/use-chat-session.d.ts +45 -1
  32. package/dist/use-chat-session.d.ts.map +1 -1
  33. package/dist/use-voice-session.d.ts +35 -0
  34. package/dist/use-voice-session.d.ts.map +1 -1
  35. package/dist/voice-widget.d.ts.map +1 -1
  36. package/dist/widget.css +1 -1
  37. package/package.json +3 -3
  38. package/src/styles/concierge.css +160 -7
  39. package/src/styles/tokens.css +6 -0
@@ -462,8 +462,8 @@ function createScrollRecede(options) {
462
462
  enabled = next;
463
463
  if (next) anchor = last;
464
464
  },
465
- markProgrammatic() {
466
- programmaticUntil = Date.now() + PROGRAMMATIC_WINDOW_MS;
465
+ markProgrammatic(ms) {
466
+ programmaticUntil = Date.now() + (ms ?? PROGRAMMATIC_WINDOW_MS);
467
467
  if (timer !== void 0) {
468
468
  clearTimeout(timer);
469
469
  timer = void 0;
@@ -524,6 +524,7 @@ var defaultWidgetMessages = {
524
524
  dock_cards: "{count} picks — see",
525
525
  dock_voice_failed: "Couldn’t start the call — type instead",
526
526
  dock_show_transcript: "Show what was said",
527
+ dock_show_conversation: "Show conversation",
527
528
  dock_earbuds: "Earbuds in — talk freely",
528
529
  handoff_event: "Handed to a human teammate",
529
530
  escalated_banner: "A human teammate will pick this up shortly.",
@@ -840,11 +841,14 @@ var WIDGET_THEME_TOKENS = [
840
841
  "--wgt-accent",
841
842
  "--wgt-surface",
842
843
  "--wgt-surface-2",
844
+ "--wgt-surface-glass",
845
+ "--wgt-surface-glass-blurred",
843
846
  "--wgt-text",
844
847
  "--wgt-text-muted",
845
848
  "--wgt-border",
846
849
  "--wgt-ring",
847
850
  "--wgt-radius",
851
+ "--wgt-row-radius",
848
852
  "--wgt-sheet-radius",
849
853
  "--wgt-card-radius",
850
854
  "--wgt-font",
@@ -895,6 +899,60 @@ var MUTED_ALPHA = .62;
895
899
  var BORDER_ALPHA = .12;
896
900
  /** §9.2: `color-mix(in oklch, surface 94%, text)`, computed rather than emitted. */
897
901
  var SURFACE_2_MIX = .06;
902
+ /**
903
+ * §3.3 (revised 2026-09-11) — the sheet is translucent, at one of TWO alphas.
904
+ *
905
+ * The sheet overlays the merchant's page and has to read as something the
906
+ * concierge raised over it rather than as a second page pasted on top. How
907
+ * much of the page can show through before it stops being texture and starts
908
+ * being competing content depends entirely on whether a blur is standing
909
+ * between the two, so there are two tokens rather than one:
910
+ *
911
+ * - `--wgt-surface-glass` (97 %) is the DEFAULT, and the one the sheet uses
912
+ * unless something else is established. No blur is helping it, so it faces
913
+ * the merchant's page at full detail. Photographed against a product grid,
914
+ * 92 % left the card titles and prices plainly READABLE through the
915
+ * greeting and the chips; 95 % and 96 % still did; 97 % is the first step
916
+ * where the backdrop stops competing with the text and stays a tint.
917
+ * - `--wgt-surface-glass-blurred` (92 %) is for the one case where a
918
+ * `backdrop-filter` is behind the surface — `pointer: fine`, and only
919
+ * where the browser actually supports the filter (§3.3). A 16 px blur
920
+ * destroys exactly the high-frequency detail that made 92 % illegible, so
921
+ * the extra five per cent buys depth at no cost to the reading surface.
922
+ *
923
+ * The default being the SAFE one is deliberate: every way the blur can fail
924
+ * to apply — an unsupported browser, a stripped declaration, a coarse
925
+ * pointer, a future refactor that moves the rule — lands on the alpha that is
926
+ * legible without it. The pairing is asserted in `concierge-css.test.ts`
927
+ * against the COMPILED bundle, because a `backdrop-filter` that survives the
928
+ * source and not the minifier is exactly how this shipped wrong once.
929
+ *
930
+ * Tokens rather than an `opacity` on the element, because `opacity` on the
931
+ * sheet would fade its contents — the shopper's own words, the prices — and
932
+ * because §7.1 rule 1 wants nothing on that box that a transition could later
933
+ * be attached to. The BUBBLES inside stay opaque (`--wgt-surface-2`) either
934
+ * way: the reading surface is solid and it is the sheet's margins that show
935
+ * the page.
936
+ *
937
+ * The ROW is deliberately not glass at all. It is a control surface: the
938
+ * caption is a field somebody types into and the four slots have to stay
939
+ * legible over whatever the merchant's page happens to be scrolled to.
940
+ */
941
+ var SURFACE_GLASS_ALPHA = .97;
942
+ /** §3.3 — the alpha that is only safe with a blur behind it. See above. */
943
+ var SURFACE_GLASS_BLURRED_ALPHA = .92;
944
+ /**
945
+ * §2 (revised 2026-09-11) — the row and the pill are ALWAYS a full pill.
946
+ *
947
+ * A constant rather than a derivation, and emitted as a token rather than
948
+ * hard-coded in the two stylesheets, for the reason every other length here
949
+ * is: the dock is drawn twice and the two renderers must not each carry their
950
+ * own 9999. `type.radius` keeps shaping the sheet (`--wgt-sheet-radius`), the
951
+ * cards (`--wgt-card-radius`) and the buttons (`--wgt-radius`) — it stopped
952
+ * shaping the row on 2026-09-11, because a 48 px bar with 12 px corners
953
+ * reads as a dialog that lost its title bar, and the row is not a dialog.
954
+ */
955
+ var ROW_RADIUS_CSS = "9999px";
898
956
  /** §9.3's floor for derived text on the surface. */
899
957
  var TEXT_CONTRAST_MIN = 4.5;
900
958
  /** §11's floor for the focus ring against the surface it is drawn on. */
@@ -1037,11 +1095,14 @@ function deriveVars(color, type, surfaceHex) {
1037
1095
  "--wgt-accent": accent,
1038
1096
  "--wgt-surface": surface,
1039
1097
  "--wgt-surface-2": mixToward(surface, text, SURFACE_2_MIX),
1098
+ "--wgt-surface-glass": withAlpha(surface, SURFACE_GLASS_ALPHA),
1099
+ "--wgt-surface-glass-blurred": withAlpha(surface, SURFACE_GLASS_BLURRED_ALPHA),
1040
1100
  "--wgt-text": text,
1041
1101
  "--wgt-text-muted": withAlpha(text, MUTED_ALPHA),
1042
1102
  "--wgt-border": withAlpha(text, BORDER_ALPHA),
1043
1103
  "--wgt-ring": deriveRing(primary, surface),
1044
1104
  "--wgt-radius": `${radiusPx}px`,
1105
+ "--wgt-row-radius": ROW_RADIUS_CSS,
1045
1106
  "--wgt-sheet-radius": `${Math.min(radiusPx, 20)}px`,
1046
1107
  "--wgt-card-radius": `${Math.min(radiusPx, 12)}px`,
1047
1108
  "--wgt-font": lookup({
@@ -1147,8 +1208,18 @@ var DESKTOP_GUTTER = 16;
1147
1208
  var BOTTOM_FLOOR = 10;
1148
1209
  /** Desktop bottom inset (§3.1). */
1149
1210
  var DESKTOP_BOTTOM = 16;
1150
- /** Gap between the sheet's floor and the row above it (§3.3). */
1151
- var SHEET_GAP = 8;
1211
+ /**
1212
+ * Gap between the sheet's floor and the row above it (§3.3).
1213
+ *
1214
+ * ZERO since 2026-09-11. The 8 px gap read as two unrelated boxes stacked on
1215
+ * a merchant's page rather than as one surface the concierge grew, which is
1216
+ * what §3.3's "a bottom sheet whose floor is the row" was always describing.
1217
+ * The constant stays rather than being deleted: it is the number the sheet's
1218
+ * `bottom` is written from, both renderers have to agree about it, and a
1219
+ * reader who finds `bottom: var(--wgt-row-h)` in the stylesheet needs
1220
+ * somewhere that says why there is nothing added to it.
1221
+ */
1222
+ var SHEET_GAP = 0;
1152
1223
  /** The one breakpoint. Below it the dock is full-width and thumb-anchored. */
1153
1224
  var DESKTOP_BREAKPOINT = 768;
1154
1225
  /**
@@ -1199,6 +1270,88 @@ var SHEET_TOP_CLEARANCE = 24;
1199
1270
  * storage key is two ways for one preference to be lost.
1200
1271
  */
1201
1272
  var DOCK_MINIMISED_STORAGE_KEY = "wgt_dock_minimised";
1273
+ /**
1274
+ * §9.1's `layout.draggable` — where a shopper's own horizontal position is
1275
+ * remembered, per visitor and per origin.
1276
+ *
1277
+ * Beside {@link DOCK_MINIMISED_STORAGE_KEY} and for the same reason: the core
1278
+ * dock reads it BEFORE first paint (so a returning shopper never watches the
1279
+ * dock slide across the page to where they left it) and the React dock writes
1280
+ * it when a drag settles. Two copies of a storage key is two ways for one
1281
+ * preference to be lost.
1282
+ */
1283
+ var DOCK_ALIGN_STORAGE_KEY = "wgt_dock_align";
1284
+ /**
1285
+ * Under this many pixels of travel, a press-and-release is a TAP (§9.1).
1286
+ *
1287
+ * Six rather than the sheet drag's four: the sheet's handle does nothing but
1288
+ * drag, so a hair-trigger costs nothing, while the pill and the mark are the
1289
+ * dock's two most-pressed controls and a mouse that travels three pixels
1290
+ * between press and release is a click in every other piece of software the
1291
+ * shopper uses. Below it the gesture never became a drag at all — no
1292
+ * alignment is written and the press's own click is left to run.
1293
+ */
1294
+ var DRAG_TAP_SLOP_PX = 6;
1295
+ /**
1296
+ * Where a released drag lands (§9.1): the third of the viewport the dock's
1297
+ * CENTRE finished in.
1298
+ *
1299
+ * Thirds rather than nearest-edge, because `center` is one of the three
1300
+ * answers and an edge-distance rule can never return it. Pure, and shared by
1301
+ * both renderers — the pill's drag is `cdn/dock-dom.ts`'s and the row's is
1302
+ * `dock/dock-drag.ts`'s, and a dock that snapped differently depending on
1303
+ * which one the shopper grabbed would be a bug nobody could describe.
1304
+ *
1305
+ * A degenerate viewport (0 wide, or a `NaN` centre from a `pointercancel`
1306
+ * that carried no coordinates) resolves to `center`: the tenant's own default,
1307
+ * and the only answer that cannot put the dock off the edge of the screen.
1308
+ */
1309
+ function snapAlign(centreX, viewportWidth) {
1310
+ if (!(viewportWidth > 0)) return "center";
1311
+ if (centreX < viewportWidth / 3) return "left";
1312
+ if (centreX > viewportWidth * 2 / 3) return "right";
1313
+ return "center";
1314
+ }
1315
+ /**
1316
+ * `localStorage`, wrapped once for the whole dock.
1317
+ *
1318
+ * Both preferences the dock remembers (§5.4's minimise, §9.1's alignment) are
1319
+ * read by `cdn/dock-dom.ts` before first paint and written by the React dock,
1320
+ * so four near-identical `try`/`catch` blocks were four copies of the same
1321
+ * three lines in an artefact every visitor to every merchant page downloads.
1322
+ *
1323
+ * The `try` is the load-bearing part and is not optional: `localStorage`
1324
+ * THROWS on access — not on use — in a third-party frame with storage access
1325
+ * blocked, in Safari's private mode past its quota, and behind a merchant's
1326
+ * own cookie wall. A dock that took the storefront's script down over a
1327
+ * remembered position is worse than a dock that forgets one.
1328
+ */
1329
+ function readStored(win, key) {
1330
+ try {
1331
+ return win.localStorage?.getItem(key) ?? void 0;
1332
+ } catch {
1333
+ return;
1334
+ }
1335
+ }
1336
+ function writeStored(win, key, value) {
1337
+ try {
1338
+ win.localStorage?.setItem(key, value);
1339
+ } catch {}
1340
+ }
1341
+ /**
1342
+ * The shopper's remembered alignment, or `undefined` where there is none.
1343
+ *
1344
+ * Anything that is not one of §9.1's three values is `undefined` rather than
1345
+ * a default: the key is on the MERCHANT's origin, shared with whatever else
1346
+ * their page stores, and a value we did not write is not a preference.
1347
+ */
1348
+ function readStoredAlign(win) {
1349
+ const raw = readStored(win, DOCK_ALIGN_STORAGE_KEY);
1350
+ return raw === "left" || raw === "center" || raw === "right" ? raw : void 0;
1351
+ }
1352
+ function persistAlign(win, align) {
1353
+ writeStored(win, DOCK_ALIGN_STORAGE_KEY, align);
1354
+ }
1202
1355
  /** §5.6 — how long a proactive nudge holds the row open before it recedes. */
1203
1356
  var PROACTIVE_NUDGE_MS = 8e3;
1204
1357
  /**
@@ -1467,6 +1620,20 @@ var SWAP_EASING = "cubic-bezier(0.2, 0, 0, 1)";
1467
1620
  /** §7.2 — the waveform's per-frame smoothing. */
1468
1621
  var LEVEL_LERP = .25;
1469
1622
  /**
1623
+ * §5.3/§5.5's concierge-scroll exception — how long a flagged scroll stays
1624
+ * ours.
1625
+ *
1626
+ * Longer than `recede.ts`'s own default window, deliberately: that one is
1627
+ * sized for the few frames a bridge `navigate` emits before the document goes
1628
+ * away, and a `spotlight` is a SMOOTH scroll across an arbitrary distance —
1629
+ * the length of a collection page, on a slow phone. The cost of being generous
1630
+ * is asymmetric and that is why it is generous: too long and the dock ignores
1631
+ * one deliberate shopper scroll a second after the concierge acted; too short
1632
+ * and it recedes and ducks in the middle of its own gesture, which is the
1633
+ * failure the exception exists for.
1634
+ */
1635
+ var CONCIERGE_SCROLL_WINDOW_MS = 1200;
1636
+ /**
1470
1637
  * `prefers-reduced-motion`, as a subscription rather than a one-shot read.
1471
1638
  *
1472
1639
  * A shopper can turn it on mid-session (iOS has it in Control Center), and a
@@ -1878,6 +2045,199 @@ function useDockDurations(motionOff) {
1878
2045
  }, [motionOff]);
1879
2046
  }
1880
2047
  //#endregion
2048
+ //#region src/dock/dock-drag.ts
2049
+ /** The one custom property a drag writes (§7.1 rule 5). */
2050
+ var DRAG_VAR = "--wgt-drag-x";
2051
+ function useDockDrag(containerRef, { enabled, published, win, durationMs, pillRef }) {
2052
+ const [stored, setStored] = useState(void 0);
2053
+ const align = (enabled ? stored : void 0) ?? published;
2054
+ /**
2055
+ * The stored alignment is read AFTER MOUNT, in a layout effect, and never
2056
+ * in a `useState` initialiser.
2057
+ *
2058
+ * The initialiser was gated on `enabled`, and `enabled` is false on the
2059
+ * HYDRATION render of every server-rendered host: `useViewport`'s
2060
+ * `useSyncExternalStore` server snapshots are hard-coded `false` (§1 rule 8
2061
+ * — a hydration mismatch on those booleans throws the dock's whole subtree
2062
+ * away), so `isDesktop` and `finePointer` are both false on the render the
2063
+ * initialiser runs in. Nothing re-read it afterwards, so the marketing
2064
+ * preview, the console preview and every npm consumer pinned the shopper's
2065
+ * remembered position `undefined` for the life of the mount — while still
2066
+ * happily WRITING to the same key on every drop. The same hole swallowed
2067
+ * the CDN path whenever the window started under 768 px and was widened
2068
+ * mid-session.
2069
+ *
2070
+ * A LAYOUT effect rather than an ordinary one, because `cdn/dock-dom.ts`
2071
+ * applies this value before its first paint (see that file's `storedAlign`)
2072
+ * and §4.2 gives the handover one frame to disagree in: read after the
2073
+ * paint, the React dock would start at the tenant's alignment and slide to
2074
+ * the shopper's in front of them. `flipFrom` is null on this path, so the
2075
+ * adoption commits the anchor with no settle animation, which is what an
2076
+ * alignment that was never dragged should look like.
2077
+ *
2078
+ * `enabled` still gates the READ as well as the gesture. A tenant who
2079
+ * turned dragging off may have turned it off BECAUSE of where a shopper
2080
+ * could put it, and a remembered position that outlives the setting which
2081
+ * allowed it is a setting that does not work.
2082
+ */
2083
+ useLayoutEffect(() => {
2084
+ if (!enabled || !win) return;
2085
+ const remembered = readStoredAlign(win);
2086
+ if (remembered !== void 0) setStored(remembered);
2087
+ }, [enabled, win]);
2088
+ const drag = useRef(null);
2089
+ const movedLast = useRef(false);
2090
+ /** Where the container's left edge was at the instant of release — rule 4's FLIP. */
2091
+ const flipFrom = useRef(null);
2092
+ /** Where the PILL's left edge was at the same instant — rule 4's other half. */
2093
+ const pillFlipFrom = useRef(null);
2094
+ const write = useCallback((value) => containerRef.current?.style.setProperty(DRAG_VAR, value), [containerRef]);
2095
+ /**
2096
+ * Rule 4, in the commit that moved the anchor.
2097
+ *
2098
+ * `useLayoutEffect` rather than an effect: this runs BEFORE the browser
2099
+ * paints the new anchor, so the shopper never sees the frame where the dock
2100
+ * has jumped. One frame later the transform is animated away, and the
2101
+ * `data-settling` attribute is what turns the transition on — the container
2102
+ * cannot simply carry one, because `--wgt-kb` rides on the same `transform`
2103
+ * and §7.2 gives the keyboard offset "continuous, no easing".
2104
+ */
2105
+ useLayoutEffect(() => {
2106
+ const el = containerRef.current;
2107
+ const from = flipFrom.current;
2108
+ const pillFrom = pillFlipFrom.current;
2109
+ flipFrom.current = null;
2110
+ pillFlipFrom.current = null;
2111
+ if (!el || from === null) return;
2112
+ const applied = Number.parseFloat(el.style.getPropertyValue("--wgt-drag-x")) || 0;
2113
+ const dx = from - (el.getBoundingClientRect().left - applied);
2114
+ const pill = pillRef?.current ?? null;
2115
+ const pillDx = pill && pillFrom !== null ? pillFrom - (pill.getBoundingClientRect().left - applied + dx) : 0;
2116
+ if (pill && Math.abs(pillDx) >= .5 && durationMs > 0) pill.animate?.([{ transform: `translateX(${pillDx}px)` }, { transform: "none" }], {
2117
+ duration: durationMs,
2118
+ easing: SWAP_EASING,
2119
+ fill: "none"
2120
+ });
2121
+ if (dx === 0 || durationMs === 0) {
2122
+ write("0px");
2123
+ return;
2124
+ }
2125
+ write(`${dx}px`);
2126
+ el.setAttribute("data-settling", "true");
2127
+ const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => write("0px")) : (write("0px"), 0);
2128
+ const timer = setTimeout(() => {
2129
+ el.removeAttribute("data-settling");
2130
+ write("0px");
2131
+ }, durationMs + 100);
2132
+ return () => {
2133
+ if (raf) cancelAnimationFrame(raf);
2134
+ clearTimeout(timer);
2135
+ el.removeAttribute("data-settling");
2136
+ };
2137
+ }, [
2138
+ align,
2139
+ containerRef,
2140
+ durationMs,
2141
+ pillRef,
2142
+ write
2143
+ ]);
2144
+ const settle = useCallback((endX) => {
2145
+ const state = drag.current;
2146
+ drag.current = null;
2147
+ const el = containerRef.current;
2148
+ if (!state || !el || !win) return;
2149
+ el.removeAttribute("data-dragging");
2150
+ movedLast.current = state.moved;
2151
+ if (!state.moved) {
2152
+ write("0px");
2153
+ return;
2154
+ }
2155
+ const rect = el.getBoundingClientRect();
2156
+ const next = snapAlign(rect.left + rect.width / 2, win.innerWidth || 0);
2157
+ flipFrom.current = rect.left;
2158
+ pillFlipFrom.current = pillRef?.current?.getBoundingClientRect().left ?? null;
2159
+ persistAlign(win, next);
2160
+ setStored(next);
2161
+ if (next === align) {
2162
+ flipFrom.current = null;
2163
+ pillFlipFrom.current = null;
2164
+ write("0px");
2165
+ }
2166
+ }, [
2167
+ align,
2168
+ containerRef,
2169
+ pillRef,
2170
+ win,
2171
+ write
2172
+ ]);
2173
+ /**
2174
+ * The three listeners the press in flight has armed, so an UNMOUNT can take
2175
+ * them off.
2176
+ *
2177
+ * `onEnd` disarms them itself on `pointerup`/`pointercancel`, which is every
2178
+ * way a gesture ends — but not every way this hook ends. A dock unmounted
2179
+ * mid-drag (the host swaps routes, the merchant's SPA tears the mount point
2180
+ * down, a test unmounts between cases) left three listeners on the WINDOW
2181
+ * closed over a detached container, for the life of the page.
2182
+ */
2183
+ const armed = useRef(null);
2184
+ useEffect(() => () => {
2185
+ armed.current?.();
2186
+ armed.current = null;
2187
+ }, []);
2188
+ const onPointerDown = useCallback((event) => {
2189
+ const el = containerRef.current;
2190
+ if (!el || !win || event.button > 0 || drag.current !== null) return;
2191
+ movedLast.current = false;
2192
+ drag.current = {
2193
+ startX: event.clientX,
2194
+ lastX: event.clientX,
2195
+ moved: false
2196
+ };
2197
+ const onMove = (native) => {
2198
+ const state = drag.current;
2199
+ const x = native.clientX;
2200
+ if (!state || !Number.isFinite(x)) return;
2201
+ state.lastX = x;
2202
+ const dx = x - state.startX;
2203
+ if (Math.abs(dx) >= 6) {
2204
+ state.moved = true;
2205
+ el.setAttribute("data-dragging", "true");
2206
+ }
2207
+ if (state.moved) write(`${dx}px`);
2208
+ };
2209
+ const disarm = () => {
2210
+ armed.current = null;
2211
+ win.removeEventListener("pointermove", onMove);
2212
+ win.removeEventListener("pointerup", onEnd);
2213
+ win.removeEventListener("pointercancel", onEnd);
2214
+ };
2215
+ const onEnd = (native) => {
2216
+ disarm();
2217
+ settle(native.clientX ?? NaN);
2218
+ };
2219
+ armed.current?.();
2220
+ win.addEventListener("pointermove", onMove, { passive: true });
2221
+ win.addEventListener("pointerup", onEnd, { passive: true });
2222
+ win.addEventListener("pointercancel", onEnd, { passive: true });
2223
+ armed.current = disarm;
2224
+ }, [
2225
+ containerRef,
2226
+ settle,
2227
+ win,
2228
+ write
2229
+ ]);
2230
+ return {
2231
+ align,
2232
+ consumeClick: useCallback(() => {
2233
+ if (!movedLast.current) return false;
2234
+ movedLast.current = false;
2235
+ return true;
2236
+ }, []),
2237
+ handleProps: enabled ? { onPointerDown } : {}
2238
+ };
2239
+ }
2240
+ //#endregion
1881
2241
  //#region src/dock/dock-row.tsx
1882
2242
  /** Same path data as `rope-knot.tsx`'s `KNOT_PATH` and `cdn/dock-dom.ts`'s copy. */
1883
2243
  var KNOT_PATH = "M2 54 C15 54 24 55 31 53 C40 50 44 40 54 41 C64 42 67 51 60 57 C52 64 38 64 33 57 C29 51 34 45 42 46 C50 47 58 52 68 53.5 C80 55 90 54 98 54";
@@ -1949,7 +2309,7 @@ function DockActivitySlot({ activity }) {
1949
2309
  }, i)) : activity === "progress" ? /* @__PURE__ */ jsx("span", { className: "wgt-progress" }) : null
1950
2310
  });
1951
2311
  }
1952
- function DockRow({ view, identity, form, messages, captionLine, captionSwapKey, captionTestId, draft, onDraftChange, onSubmit, placeholder, composerDisabled, onControl, onMicDown, onMicUp, interruptLabelled, micOpen, micDisabled, micUnavailableReason, attachBusy, rowRef, inputRef, captionDurationMs, markStateLabel, onMarkPress }) {
2312
+ function DockRow({ view, identity, form, messages, captionLine, captionSwapKey, captionTestId, draft, onDraftChange, onSubmit, placeholder, composerDisabled, onControl, onMicDown, onMicUp, interruptLabelled, micOpen, micDisabled, micUnavailableReason, attachBusy, rowRef, inputRef, captionDurationMs, markStateLabel, onMarkPress, sheetOpen, draggable, dragHandleProps }) {
1953
2313
  const msg = (key, vars) => formatMessage(messages[key] ?? defaultWidgetMessages[key], vars);
1954
2314
  /**
1955
2315
  * §5.1 — tap anywhere on the row during `speaking` is an interrupt. A press
@@ -1968,6 +2328,8 @@ function DockRow({ view, identity, form, messages, captionLine, captionSwapKey,
1968
2328
  "data-state": view.state,
1969
2329
  "data-border": view.border,
1970
2330
  "data-form": form,
2331
+ "data-sheet": sheetOpen ? "open" : "closed",
2332
+ "data-draggable": draggable ? "true" : void 0,
1971
2333
  "data-testid": "widget-dock-row",
1972
2334
  onClick: onRowClick,
1973
2335
  children: [
@@ -1976,6 +2338,7 @@ function DockRow({ view, identity, form, messages, captionLine, captionSwapKey,
1976
2338
  className: "wgt-mark",
1977
2339
  "data-dock-slot": "mark",
1978
2340
  "aria-label": markStateLabel,
2341
+ ...draggable ? dragHandleProps : {},
1979
2342
  onClick: onMarkPress,
1980
2343
  children: /* @__PURE__ */ jsx(DockMarkFace, {
1981
2344
  identity,
@@ -2229,7 +2592,7 @@ function ClipGlyph() {
2229
2592
  }
2230
2593
  //#endregion
2231
2594
  //#region src/dock/dock-pill.tsx
2232
- function DockPill({ identity, mark, label, line, expandLabel, form, onPress, pillRef }) {
2595
+ function DockPill({ identity, mark, label, line, expandLabel, form, onPress, draggable, dragHandleProps, pillRef }) {
2233
2596
  const text = line !== void 0 && line !== "" ? line : label;
2234
2597
  return /* @__PURE__ */ jsxs("button", {
2235
2598
  ref: pillRef,
@@ -2239,7 +2602,9 @@ function DockPill({ identity, mark, label, line, expandLabel, form, onPress, pil
2239
2602
  "data-concierge-open": "",
2240
2603
  "data-form": form,
2241
2604
  "data-testid": "widget-dock-pill",
2605
+ "data-draggable": draggable ? "true" : void 0,
2242
2606
  "aria-label": `${label} — ${expandLabel}`,
2607
+ ...draggable ? dragHandleProps : {},
2243
2608
  onClick: onPress,
2244
2609
  children: [/* @__PURE__ */ jsx(DockMarkFace, {
2245
2610
  identity,
@@ -2257,7 +2622,7 @@ function DockPill({ identity, mark, label, line, expandLabel, form, onPress, pil
2257
2622
  var EXPAND_DRAG_PX = 40;
2258
2623
  /** Below this, the pointer never left the tap — a thumb resting, not a drag. */
2259
2624
  var DRAG_SLOP_PX = 4;
2260
- function DockSheet({ snap, onSnapChange, label, peekOnly, header, children, onDismiss, followKey, sheetRef, durationMs, dragHandleLabel }) {
2625
+ function DockSheet({ snap, onSnapChange, label, peekOnly, header, children, onDismiss, followKey, historyRevealed = false, sheetRef, durationMs, dragHandleLabel }) {
2261
2626
  const localRef = useRef(null);
2262
2627
  const ref = sheetRef ?? localRef;
2263
2628
  const bodyRef = useRef(null);
@@ -2287,6 +2652,11 @@ function DockSheet({ snap, onSnapChange, label, peekOnly, header, children, onDi
2287
2652
  * precisely when a reader who has scrolled away must be left alone.
2288
2653
  */
2289
2654
  const rowCount = useRef(-1);
2655
+ /**
2656
+ * Whether the last follow ran on the WHOLE transcript — see
2657
+ * {@link DockSheetProps.historyRevealed}.
2658
+ */
2659
+ const revealed = useRef(historyRevealed);
2290
2660
  const onScroll = useCallback(() => {
2291
2661
  const el = bodyRef.current;
2292
2662
  if (!el) return;
@@ -2296,16 +2666,18 @@ function DockSheet({ snap, onSnapChange, label, peekOnly, header, children, onDi
2296
2666
  const el = bodyRef.current;
2297
2667
  if (!el || snap === "closed") return;
2298
2668
  const anchorCount = el.querySelectorAll("[data-dock-follow]").length;
2299
- const grew = anchorCount > rowCount.current && rowCount.current >= 0;
2669
+ const justRevealed = historyRevealed && !revealed.current;
2670
+ revealed.current = historyRevealed;
2671
+ const grew = anchorCount !== rowCount.current && rowCount.current >= 0;
2300
2672
  rowCount.current = anchorCount;
2301
- if (grew) following.current = true;
2673
+ if (grew || justRevealed) following.current = true;
2302
2674
  if (!following.current) return;
2303
2675
  const settle = () => {
2304
2676
  const anchors = el.querySelectorAll("[data-dock-follow]");
2305
2677
  const newest = anchors[anchors.length - 1];
2306
2678
  const end = Math.max(0, el.scrollHeight - el.clientHeight);
2307
2679
  const before = el.scrollTop;
2308
- el.scrollTop = newest === void 0 ? end : Math.max(0, Math.min(end, el.scrollTop + (newest.getBoundingClientRect().top - el.getBoundingClientRect().top)));
2680
+ el.scrollTop = newest === void 0 || justRevealed ? end : Math.max(0, Math.min(end, el.scrollTop + (newest.getBoundingClientRect().top - el.getBoundingClientRect().top)));
2309
2681
  return Math.abs(el.scrollTop - before);
2310
2682
  };
2311
2683
  settle();
@@ -2316,7 +2688,11 @@ function DockSheet({ snap, onSnapChange, label, peekOnly, header, children, onDi
2316
2688
  if (settle() > .5 && passes < 4) raf = requestAnimationFrame(again);
2317
2689
  });
2318
2690
  return () => cancelAnimationFrame(raf);
2319
- }, [followKey, snap]);
2691
+ }, [
2692
+ followKey,
2693
+ snap,
2694
+ historyRevealed
2695
+ ]);
2320
2696
  const lastSnap = useRef(snap);
2321
2697
  const firstSnap = useRef(true);
2322
2698
  useEffect(() => {
@@ -3125,6 +3501,43 @@ function deriveView(input) {
3125
3501
  }
3126
3502
  }
3127
3503
  }
3504
+ /**
3505
+ * §3.4 (revised 2026-09-11) — where the LATEST EXCHANGE begins.
3506
+ *
3507
+ * An exchange is the shopper's line and the reply to it. The latest one
3508
+ * therefore starts at the LAST caller turn and runs to the end, so a reply
3509
+ * that arrived as three turns (a filler, the answer, the cards) stays whole.
3510
+ *
3511
+ * Two cases are not that shape and both are real:
3512
+ *
3513
+ * - the shopper has not spoken yet. The concierge opens with a greeting of
3514
+ * its own, and a proactive nudge can add a second line before anybody has
3515
+ * typed; the latest exchange is then the LAST agent turn alone, because
3516
+ * two unanswered agent lines are two things said, not one exchange.
3517
+ * - a `speaker: 'event'` row — §3.4's handoff marker. It is something that
3518
+ * happened TO an exchange rather than a turn in one, so it never starts a
3519
+ * new one and never ends the search for the caller line above it.
3520
+ */
3521
+ function latestExchangeStart(speakers) {
3522
+ for (let i = speakers.length - 1; i >= 0; i--) if (speakers[i] === "caller") return i;
3523
+ return Math.max(0, speakers.length - 1);
3524
+ }
3525
+ /**
3526
+ * How many exchanges the transcript holds — the number "Show conversation"
3527
+ * is offered on (§3.4: the control exists only when there is more than one).
3528
+ *
3529
+ * A caller line opens an exchange; anything said BEFORE the first one (the
3530
+ * greeting, a proactive nudge) is an exchange of its own, because it is
3531
+ * something the shopper can scroll back to and would otherwise be counted as
3532
+ * nothing at all — leaving a dock that shows a greeting, then an answer, and
3533
+ * claims there is nothing more to see.
3534
+ */
3535
+ function exchangeCount(speakers) {
3536
+ if (speakers.length === 0) return 0;
3537
+ const opened = speakers.findIndex((s) => s === "caller");
3538
+ if (opened === -1) return speakers.length;
3539
+ return speakers.filter((s) => s === "caller").length + (opened === 0 ? 0 : 1);
3540
+ }
3128
3541
  //#endregion
3129
3542
  //#region src/dock/dock.tsx
3130
3543
  var DEFAULT_COLOR = {
@@ -3143,7 +3556,7 @@ var DEFAULT_LAYOUT = {
3143
3556
  };
3144
3557
  var INTERRUPT_SEEN_STORAGE_KEY = "wgt_dock_interrupt_seen";
3145
3558
  function Dock(props) {
3146
- const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
3559
+ const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, latestExchange, exchangeCount, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, conciergeScrollRef, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
3147
3560
  const scopeId = useId().replace(/[^a-zA-Z0-9_-]/g, "");
3148
3561
  const rootRef = useRef(null);
3149
3562
  const rowRef = useRef(null);
@@ -3152,7 +3565,24 @@ function Dock(props) {
3152
3565
  const setVar = useCssVars(rootRef);
3153
3566
  const motionOff = useMotionOff();
3154
3567
  const durations = useDockDurations(motionOff);
3155
- const { isDesktop, shortViewport } = useViewport(rootRef);
3568
+ const { isDesktop, shortViewport, finePointer, win } = useViewport(rootRef);
3569
+ /**
3570
+ * §9.1's `layout.draggable` — desktop only, a real pointer only, and the
3571
+ * tenant's own switch on top.
3572
+ *
3573
+ * Defaulted `true` rather than required, because the config field is
3574
+ * younger than this component: a host still passing a `layout` without it
3575
+ * (the marketing preview, a Next.js embed pinned to an older config) gets
3576
+ * §9.1's default rather than a dock that refuses to move.
3577
+ */
3578
+ const draggable = isDesktop && finePointer && layout.draggable !== false;
3579
+ const dragging = useDockDrag(rootRef, {
3580
+ enabled: draggable,
3581
+ published: layout.desktopAlign,
3582
+ win,
3583
+ durationMs: durations.swap,
3584
+ pillRef
3585
+ });
3156
3586
  const msg = useCallback((key, vars) => formatMessage(messages[key] ?? defaultWidgetMessages[key], vars), [messages]);
3157
3587
  const name = identity.name?.trim() || "Concierge";
3158
3588
  const [form, setForm] = useState(() => layout.minimised === "never" ? "row" : initialMinimised ?? layout.minimised === "startMinimised" ? "pill" : "row");
@@ -3175,6 +3605,16 @@ function Dock(props) {
3175
3605
  const [sheetEverOpened, setSheetEverOpened] = useState(false);
3176
3606
  const [ducked, setDucked] = useState(false);
3177
3607
  const [showTranscript, setShowTranscript] = useState(false);
3608
+ /**
3609
+ * §3.4 — the shopper asked for the whole conversation, so the sheet holds
3610
+ * the transcript rather than the latest exchange.
3611
+ *
3612
+ * Reset when the sheet CLOSES (see `dismissSheet`) rather than kept for the
3613
+ * session: the sheet's job at `peek` is to show the concierge's answer, and
3614
+ * a shopper who opened the history once should not find every later reply
3615
+ * buried under it.
3616
+ */
3617
+ const [showConversation, setShowConversation] = useState(false);
3178
3618
  const [nudge, setNudge] = useState(void 0);
3179
3619
  const [interruptsSeen, setInterruptsSeen] = useState(readInterruptsSeen);
3180
3620
  const [engaged, setEngaged] = useState(() => initialFocus !== null && initialFocus !== void 0);
@@ -3642,6 +4082,10 @@ function Dock(props) {
3642
4082
  anchor = offset;
3643
4083
  return;
3644
4084
  }
4085
+ if (Date.now() < conciergeScrollUntilRef.current) {
4086
+ anchor = offset;
4087
+ return;
4088
+ }
3645
4089
  if (Math.abs(offset - anchor) <= 24) return;
3646
4090
  anchor = offset;
3647
4091
  duckRef.current();
@@ -3678,6 +4122,32 @@ function Dock(props) {
3678
4122
  speaking,
3679
4123
  ownScroller
3680
4124
  ]);
4125
+ /**
4126
+ * Until when the page's own scroll is the CONCIERGE's, not the shopper's —
4127
+ * see {@link DockProps.conciergeScrollRef}. A timestamp rather than a
4128
+ * boolean so it lapses on its own: a `spotlight` whose smooth scroll never
4129
+ * arrives (the card was removed, the host cancelled it) must not deafen the
4130
+ * dock to the shopper for the rest of the session.
4131
+ */
4132
+ const conciergeScrollUntilRef = useRef(0);
4133
+ /**
4134
+ * Publish the flag-raiser. Both halves of the exception are raised together
4135
+ * and by the SAME call — §5.5's duck guard (this component's own scroll
4136
+ * listener) and §5.3's recede (`cdn/recede.ts`, which keeps its own window)
4137
+ * — because a spotlight that ducked the sheet but not the row, or the other
4138
+ * way round, is half a bug rather than none.
4139
+ */
4140
+ useEffect(() => {
4141
+ const ref = conciergeScrollRef;
4142
+ if (!ref) return;
4143
+ ref.current = (ms = CONCIERGE_SCROLL_WINDOW_MS) => {
4144
+ conciergeScrollUntilRef.current = ms > 0 ? Date.now() + ms : 0;
4145
+ recedeRef.current?.markProgrammatic(ms);
4146
+ };
4147
+ return () => {
4148
+ ref.current = null;
4149
+ };
4150
+ }, [conciergeScrollRef]);
3681
4151
  const firstPage = useRef(true);
3682
4152
  useEffect(() => {
3683
4153
  if (firstPage.current) {
@@ -3887,10 +4357,14 @@ function Dock(props) {
3887
4357
  setSheet("closed");
3888
4358
  inputRef.current?.focus();
3889
4359
  }, []);
4360
+ useEffect(() => {
4361
+ if (sheet === "closed") setShowConversation(false);
4362
+ }, [sheet]);
4363
+ const align = dragging.align;
3890
4364
  const rootStyle = useMemo(() => {
3891
4365
  const style = { ...geometryVars(isDesktop, layout) };
3892
4366
  style["--wgt-row-margin"] = isDesktop ? "0px" : `10px`;
3893
- const anchor = pillAnchor(direction, isDesktop, layout.desktopAlign);
4367
+ const anchor = pillAnchor(direction, isDesktop, align);
3894
4368
  style["--wgt-pill-left"] = anchor.side === "left" ? `${anchor.inset}px` : "auto";
3895
4369
  style["--wgt-pill-right"] = anchor.side === "right" ? `${anchor.inset}px` : "auto";
3896
4370
  style["--wgt-sheet-peek"] = `260px`;
@@ -3907,8 +4381,8 @@ function Dock(props) {
3907
4381
  } else {
3908
4382
  const width = rowWidthLen(true, layout.desktopWidth);
3909
4383
  style.width = width;
3910
- if (layout.desktopAlign === "left") style.left = `16px`;
3911
- else if (layout.desktopAlign === "right") style.right = `16px`;
4384
+ if (align === "left") style.left = `16px`;
4385
+ else if (align === "right") style.right = `16px`;
3912
4386
  else {
3913
4387
  style.left = "50%";
3914
4388
  style.marginLeft = `calc(${width} / -2)`;
@@ -3921,6 +4395,7 @@ function Dock(props) {
3921
4395
  }, [
3922
4396
  isDesktop,
3923
4397
  layout,
4398
+ align,
3924
4399
  durations,
3925
4400
  direction,
3926
4401
  skinStyle,
@@ -3973,6 +4448,16 @@ function Dock(props) {
3973
4448
  const greeting = copy.greeting?.trim();
3974
4449
  const typedPlaceholder = copy.placeholder?.trim() || msg("type_placeholder");
3975
4450
  const placeholder = greeting !== void 0 && greeting !== "" && !hasContent && !sheetEverOpened && view.state === "dormant" ? greeting : typedPlaceholder;
4451
+ /**
4452
+ * §3.4 — is this the one-answer view?
4453
+ *
4454
+ * A TEXT session, a host that supplied the latest view at all, the shopper
4455
+ * has not asked for the history, and the sheet is not already expanded —
4456
+ * because a sheet dragged open by its handle is a shopper asking for room,
4457
+ * and answering that with one exchange and a lot of white space is worse
4458
+ * than answering it with the conversation.
4459
+ */
4460
+ const showLatestOnly = channel === "text" && latestExchange !== void 0 && !showConversation && sheet !== "expanded";
3976
4461
  const sheetHeader = /* @__PURE__ */ jsxs(Fragment, { children: [
3977
4462
  onEndCall !== void 0 && view.callActive ? /* @__PURE__ */ jsx("button", {
3978
4463
  type: "button",
@@ -3988,15 +4473,29 @@ function Dock(props) {
3988
4473
  onClick: () => setShowTranscript(true),
3989
4474
  children: msg("dock_show_transcript")
3990
4475
  }) : null,
4476
+ showLatestOnly && (exchangeCount ?? 0) > 1 ? /* @__PURE__ */ jsx("button", {
4477
+ type: "button",
4478
+ className: "wgt-sheet-action",
4479
+ "data-testid": "widget-dock-show-conversation",
4480
+ onClick: (event) => {
4481
+ const handle = event.currentTarget.closest(".wgt-sheet")?.querySelector(".wgt-sheet-handle");
4482
+ setShowConversation(true);
4483
+ if (!shortViewport) setSheet("expanded");
4484
+ handle?.focus();
4485
+ },
4486
+ children: msg("dock_show_conversation")
4487
+ }) : null,
3991
4488
  layout.minimised !== "never" ? /* @__PURE__ */ jsx("button", {
3992
4489
  type: "button",
3993
4490
  className: "wgt-sheet-action",
3994
4491
  "data-testid": "widget-dock-minimise",
4492
+ "aria-label": msg("minimize"),
4493
+ title: msg("minimize"),
3995
4494
  onClick: () => {
3996
4495
  setSheet("closed");
3997
4496
  setFormPersisting("pill");
3998
4497
  },
3999
- children: msg("minimize")
4498
+ children: /* @__PURE__ */ jsx(ChevronDownGlyph, {})
4000
4499
  }) : null
4001
4500
  ] });
4002
4501
  return /* @__PURE__ */ jsxs("div", {
@@ -4005,6 +4504,8 @@ function Dock(props) {
4005
4504
  "data-concierge-dock": "",
4006
4505
  "data-wgt-scope": scopeId,
4007
4506
  "data-viewport": isDesktop ? "desktop" : "mobile",
4507
+ "data-align": align,
4508
+ "data-draggable": draggable ? "true" : void 0,
4008
4509
  "data-state": view.state,
4009
4510
  ...skin !== void 0 ? { "data-skin": skin } : {},
4010
4511
  role: "region",
@@ -4034,6 +4535,7 @@ function Dock(props) {
4034
4535
  header: sheetHeader,
4035
4536
  onDismiss: dismissSheet,
4036
4537
  ...followKey !== void 0 ? { followKey } : {},
4538
+ historyRevealed: latestExchange !== void 0 && !showLatestOnly,
4037
4539
  durationMs: sheet === "closed" ? durations.sheetClose : durations.sheetOpen,
4038
4540
  dragHandleLabel: msg("conversation"),
4039
4541
  children: [
@@ -4046,7 +4548,7 @@ function Dock(props) {
4046
4548
  ...productHref ? { productHref } : {},
4047
4549
  ...navigate ? { navigate } : {}
4048
4550
  }) : null,
4049
- channel === "text" || showTranscript ? transcript : null,
4551
+ channel === "text" || showTranscript ? showLatestOnly ? latestExchange : transcript : null,
4050
4552
  sheetExtra,
4051
4553
  attribution !== void 0 ? /* @__PURE__ */ jsx("a", {
4052
4554
  className: "wgt-shelf-more",
@@ -4066,9 +4568,12 @@ function Dock(props) {
4066
4568
  expandLabel: msg("open"),
4067
4569
  form,
4068
4570
  onPress: () => {
4571
+ if (dragging.consumeClick()) return;
4069
4572
  setEngaged(true);
4070
4573
  setFormPersisting("row");
4071
4574
  },
4575
+ draggable,
4576
+ dragHandleProps: dragging.handleProps,
4072
4577
  pillRef
4073
4578
  }),
4074
4579
  /* @__PURE__ */ jsx(DockRow, {
@@ -4100,14 +4605,41 @@ function Dock(props) {
4100
4605
  captionDurationMs: durations.caption,
4101
4606
  markStateLabel: msg(view.border === "primary" ? "state_listening" : "state_idle", { product: name }),
4102
4607
  onMarkPress: () => {
4608
+ if (dragging.consumeClick()) return;
4103
4609
  setEngaged(true);
4104
4610
  setSheet((current) => current === "closed" ? "peek" : "closed");
4105
- }
4611
+ },
4612
+ sheetOpen: sheet !== "closed",
4613
+ draggable,
4614
+ dragHandleProps: dragging.handleProps
4106
4615
  }),
4107
4616
  attachSlot
4108
4617
  ]
4109
4618
  });
4110
4619
  }
4620
+ /**
4621
+ * §5.4's minimise glyph — a chevron pointing at the row the sheet collapses
4622
+ * onto.
4623
+ *
4624
+ * Inline SVG at 18 px on `currentColor`, exactly like `dock-row.tsx`'s five:
4625
+ * a webfont is a network request on a merchant's page for one shape, and an
4626
+ * `aria-hidden` glyph inside a button that already carries its accessible
4627
+ * name is never read out.
4628
+ */
4629
+ function ChevronDownGlyph() {
4630
+ return /* @__PURE__ */ jsx("svg", {
4631
+ width: 18,
4632
+ height: 18,
4633
+ viewBox: "0 0 24 24",
4634
+ "aria-hidden": "true",
4635
+ fill: "none",
4636
+ stroke: "currentColor",
4637
+ strokeWidth: 1.8,
4638
+ strokeLinecap: "round",
4639
+ strokeLinejoin: "round",
4640
+ children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
4641
+ });
4642
+ }
4111
4643
  /** Turns §5.1's caption spec into the string this locale renders. */
4112
4644
  function resolveCaption(view, msg) {
4113
4645
  if (view.caption.kind === "field") return void 0;
@@ -4225,7 +4757,15 @@ function useViewport(rootRef) {
4225
4757
  const subscribe = useCallback((onChange) => win === null ? () => void 0 : subscribeToViewport(win, onChange), [win]);
4226
4758
  return {
4227
4759
  isDesktop: useSyncExternalStore(subscribe, () => win !== null && win.innerWidth >= 768, () => false),
4228
- shortViewport: useSyncExternalStore(subscribe, () => win !== null && win.innerHeight < 500, () => false)
4760
+ shortViewport: useSyncExternalStore(subscribe, () => win !== null && win.innerHeight < 500, () => false),
4761
+ finePointer: useSyncExternalStore(subscribe, () => {
4762
+ try {
4763
+ return win?.matchMedia?.("(pointer: fine)").matches === true;
4764
+ } catch {
4765
+ return false;
4766
+ }
4767
+ }, () => false),
4768
+ win
4229
4769
  };
4230
4770
  }
4231
4771
  //#endregion
@@ -5441,6 +5981,103 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5441
5981
  onStart: onToggleMic,
5442
5982
  onToggleMute: onToggleMic
5443
5983
  };
5984
+ /**
5985
+ * §3.4 — the transcript, rendered from whichever slice of the turns it is
5986
+ * given.
5987
+ *
5988
+ * A local function rather than a component, and deliberately: it closes
5989
+ * over the dozen things a turn is drawn from (the messages, the locale, the
5990
+ * card handlers, `escalated`, `sending`) and lifting those into props would
5991
+ * be a component with fifteen of them and no second caller. The two slices
5992
+ * it is called with are §3.4's two views.
5993
+ */
5994
+ const renderLog = (shown, view = "all", offset = 0) => /* @__PURE__ */ jsxs("div", {
5995
+ role: "log",
5996
+ "aria-live": "polite",
5997
+ "aria-relevant": "additions text",
5998
+ className: "flex flex-col gap-1",
5999
+ children: [
6000
+ shown.length === 0 ? /* @__PURE__ */ jsx("p", {
6001
+ className: "py-8 text-center text-sm text-[var(--widget-foreground-muted)]",
6002
+ children: messages.empty
6003
+ }) : shown.map((turn, i) => turn.speaker === "event" ? /* @__PURE__ */ jsx(TranscriptEvent, {
6004
+ event: turn.event,
6005
+ messages,
6006
+ awaitingReply: !shown.slice(i + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "")
6007
+ }, `event-${offset + i}`) : /* @__PURE__ */ jsxs("div", {
6008
+ "data-dock-follow": "",
6009
+ className: turn.speaker === "caller" ? "wgt-turn-row flex flex-col items-end" : "wgt-turn-row flex flex-col items-start",
6010
+ children: [
6011
+ turn.text !== "" || turn.speaker === "agent" && turn.final === false ? /* @__PURE__ */ jsx("div", {
6012
+ dir: textDirectionFor(turn.locale),
6013
+ lang: turn.locale,
6014
+ "data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
6015
+ 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}`,
6016
+ children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
6017
+ className: "flex items-center gap-2 italic",
6018
+ children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
6019
+ }) : turn.speaker === "agent" ? /* @__PURE__ */ jsx(WidgetMarkdown, { text: turn.text }) : /* @__PURE__ */ jsx("span", {
6020
+ className: `whitespace-pre-wrap ${turn.final === false ? "italic opacity-70" : ""}`,
6021
+ children: turn.text
6022
+ })
6023
+ }) : null,
6024
+ turn.attachments && turn.attachments.length > 0 ? /* @__PURE__ */ jsx("div", {
6025
+ className: "w-full max-w-[85%]",
6026
+ children: /* @__PURE__ */ jsx(WidgetAttachmentList, {
6027
+ attachments: turn.attachments,
6028
+ messages
6029
+ })
6030
+ }) : null,
6031
+ turn.cards && turn.cards.items.length > 0 ? /* @__PURE__ */ jsx("div", {
6032
+ className: "w-full",
6033
+ children: /* @__PURE__ */ jsx(WidgetCardList, {
6034
+ cards: turn.cards,
6035
+ onAddToCart,
6036
+ curationHref,
6037
+ productHref,
6038
+ navigate,
6039
+ locale,
6040
+ messages,
6041
+ roomy: false,
6042
+ ...dock?.showPrice !== void 0 ? { showPrice: dock.showPrice } : {},
6043
+ ...dock?.cardImageAspect !== void 0 ? { imageAspect: dock.cardImageAspect } : {}
6044
+ })
6045
+ }) : null,
6046
+ turn.delivery !== void 0 ? /* @__PURE__ */ jsx(TurnDeliveryStatus, {
6047
+ delivery: turn.delivery,
6048
+ messages
6049
+ }) : null
6050
+ ]
6051
+ }, `${turn.speaker}-${offset + i}`)),
6052
+ humanTyping ? /* @__PURE__ */ jsx("div", {
6053
+ "data-testid": "widget-human-typing",
6054
+ "data-dock-follow": "",
6055
+ className: "wgt-turn-row flex flex-col items-start",
6056
+ children: /* @__PURE__ */ jsx("div", {
6057
+ className: `px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${AGENT_BUBBLE_CLASS}`,
6058
+ children: /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })
6059
+ })
6060
+ }) : null,
6061
+ !escalated && turns.every((turn) => turn.speaker !== "caller") ? /* @__PURE__ */ jsx("ul", {
6062
+ "aria-label": messages.suggestions_label,
6063
+ "data-testid": "widget-suggestions",
6064
+ className: "flex flex-wrap gap-2 pt-1",
6065
+ children: SUGGESTION_KEYS.map((key) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("button", {
6066
+ type: "button",
6067
+ "data-testid": "widget-suggestion",
6068
+ disabled: sending,
6069
+ onClick: () => void sendSuggestion(messages[key]),
6070
+ className: "cursor-pointer rounded-full bg-[var(--widget-chip)] px-3 py-1.5 text-xs font-medium text-[var(--widget-foreground)] ring-1 ring-black/10 transition-colors hover:bg-[var(--widget-accent)] hover:text-[var(--widget-accent-foreground)] disabled:cursor-default disabled:opacity-50 focus-visible:ring-2 focus-visible:ring-[var(--widget-accent-ring)] focus-visible:outline-none",
6071
+ children: messages[key]
6072
+ }) }, key))
6073
+ }) : null
6074
+ ]
6075
+ }, `log-${view}`);
6076
+ /**
6077
+ * The turns' SPEAKERS, which is all §3.4's split looks at
6078
+ * (`dock-state.ts`'s `latestExchangeStart` / `exchangeCount`).
6079
+ */
6080
+ const speakers = turns.map((turn) => turn.speaker);
5444
6081
  return /* @__PURE__ */ jsx(Dock, {
5445
6082
  identity: {
5446
6083
  name: "",
@@ -5498,98 +6135,324 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
5498
6135
  className: `text-xs ${attaching.failed ? "text-destructive" : "text-[var(--widget-foreground-muted)]"}`,
5499
6136
  children: attaching.failed ? formatMessage(messages.attach_error, { filename: attaching.filename }) : formatMessage(messages.attach_uploading, { filename: attaching.filename })
5500
6137
  }) : null] }),
5501
- transcript: /* @__PURE__ */ jsxs("div", {
5502
- role: "log",
5503
- "aria-live": "polite",
5504
- "aria-relevant": "additions text",
5505
- className: "flex flex-col gap-1",
5506
- children: [
5507
- turns.length === 0 ? /* @__PURE__ */ jsx("p", {
5508
- className: "py-8 text-center text-sm text-[var(--widget-foreground-muted)]",
5509
- children: messages.empty
5510
- }) : turns.map((turn, i) => turn.speaker === "event" ? /* @__PURE__ */ jsx(TranscriptEvent, {
5511
- event: turn.event,
5512
- messages,
5513
- awaitingReply: !turns.slice(i + 1).some((t) => t.speaker === "agent" && t.text.trim() !== "")
5514
- }, `event-${i}`) : /* @__PURE__ */ jsxs("div", {
5515
- "data-dock-follow": "",
5516
- className: turn.speaker === "caller" ? "wgt-turn-row flex flex-col items-end" : "wgt-turn-row flex flex-col items-start",
5517
- children: [
5518
- turn.text !== "" || turn.speaker === "agent" && turn.final === false ? /* @__PURE__ */ jsx("div", {
5519
- dir: textDirectionFor(turn.locale),
5520
- lang: turn.locale,
5521
- "data-testid": turn.speaker === "caller" ? "widget-turn-caller" : turn.filler === true ? "widget-turn-agent-filler" : "widget-turn-agent",
5522
- 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}`,
5523
- children: turn.speaker === "agent" && turn.text === "" && turn.final === false ? /* @__PURE__ */ jsx(TypingDots, { label: messages.typing }) : turn.speaker === "agent" && turn.filler === true ? /* @__PURE__ */ jsxs("span", {
5524
- className: "flex items-center gap-2 italic",
5525
- children: [/* @__PURE__ */ jsx("span", { children: turn.text }), /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })]
5526
- }) : turn.speaker === "agent" ? /* @__PURE__ */ jsx(WidgetMarkdown, { text: turn.text }) : /* @__PURE__ */ jsx("span", {
5527
- className: `whitespace-pre-wrap ${turn.final === false ? "italic opacity-70" : ""}`,
5528
- children: turn.text
5529
- })
5530
- }) : null,
5531
- turn.attachments && turn.attachments.length > 0 ? /* @__PURE__ */ jsx("div", {
5532
- className: "w-full max-w-[85%]",
5533
- children: /* @__PURE__ */ jsx(WidgetAttachmentList, {
5534
- attachments: turn.attachments,
5535
- messages
5536
- })
5537
- }) : null,
5538
- turn.cards && turn.cards.items.length > 0 ? /* @__PURE__ */ jsx("div", {
5539
- className: "w-full",
5540
- children: /* @__PURE__ */ jsx(WidgetCardList, {
5541
- cards: turn.cards,
5542
- onAddToCart,
5543
- curationHref,
5544
- productHref,
5545
- navigate,
5546
- locale,
5547
- messages,
5548
- roomy: false,
5549
- ...dock?.showPrice !== void 0 ? { showPrice: dock.showPrice } : {},
5550
- ...dock?.cardImageAspect !== void 0 ? { imageAspect: dock.cardImageAspect } : {}
5551
- })
5552
- }) : null,
5553
- turn.delivery !== void 0 ? /* @__PURE__ */ jsx(TurnDeliveryStatus, {
5554
- delivery: turn.delivery,
5555
- messages
5556
- }) : null
5557
- ]
5558
- }, `${turn.speaker}-${i}`)),
5559
- humanTyping ? /* @__PURE__ */ jsx("div", {
5560
- "data-testid": "widget-human-typing",
5561
- "data-dock-follow": "",
5562
- className: "wgt-turn-row flex flex-col items-start",
5563
- children: /* @__PURE__ */ jsx("div", {
5564
- className: `px-3.5 py-2 text-[14px] leading-[1.55] shadow-sm ${AGENT_BUBBLE_CLASS}`,
5565
- children: /* @__PURE__ */ jsx(TypingDots, { label: messages.typing })
5566
- })
5567
- }) : null,
5568
- !escalated && turns.every((turn) => turn.speaker !== "caller") ? /* @__PURE__ */ jsx("ul", {
5569
- "aria-label": messages.suggestions_label,
5570
- "data-testid": "widget-suggestions",
5571
- className: "flex flex-wrap gap-2 pt-1",
5572
- children: SUGGESTION_KEYS.map((key) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("button", {
5573
- type: "button",
5574
- "data-testid": "widget-suggestion",
5575
- disabled: sending,
5576
- onClick: () => void sendSuggestion(messages[key]),
5577
- className: "cursor-pointer rounded-full bg-[var(--widget-chip)] px-3 py-1.5 text-xs font-medium text-[var(--widget-foreground)] ring-1 ring-black/10 transition-colors hover:bg-[var(--widget-accent)] hover:text-[var(--widget-accent-foreground)] disabled:cursor-default disabled:opacity-50 focus-visible:ring-2 focus-visible:ring-[var(--widget-accent-ring)] focus-visible:outline-none",
5578
- children: messages[key]
5579
- }) }, key))
5580
- }) : null
5581
- ]
5582
- })
6138
+ transcript: renderLog(turns),
6139
+ latestExchange: renderLog(turns.slice(latestExchangeStart(speakers)), "latest", latestExchangeStart(speakers)),
6140
+ exchangeCount: exchangeCount(speakers)
5583
6141
  });
5584
6142
  }
5585
- new Set([
6143
+ //#endregion
6144
+ //#region ../widget-bridge/dist/index.js
6145
+ /**
6146
+ * The subset of {@link VISITOR_EVENT_KIND_NAMES} that is BEHAVIOURAL tracking
6147
+ * — a record of what a shopper looked at or did while merely browsing — and
6148
+ * therefore requires consent before it ships. Single source of truth for
6149
+ * BOTH sides of the wire: `apps/api/src/widget/widget-chat.service.ts`'s
6150
+ * `CONSENT_REQUIRED_WIDGET_EVENT_KINDS` imports this directly (replacing a
6151
+ * hand-duplicated literal that had drifted from `packages/widget-bridge`'s
6152
+ * own client-side gate — the client was gating everything except
6153
+ * `checkout.handoff`, which silently dropped `session.started`/
6154
+ * `session.ended` forever since they were never queued in the first place),
6155
+ * and `packages/widget-bridge`'s `VisitorEventCollector` imports it too (via
6156
+ * the zod-free `/constants` subpath, same as every other constant here).
6157
+ *
6158
+ * `checkout.handoff` is deliberately EXCLUDED — it records a transaction the
6159
+ * shopper themselves just initiated, not a browsing observation (GDPR Art.
6160
+ * 6(1)(b) contract necessity), so it ships regardless of consent on both
6161
+ * sides. `session.started`/`session.ended`, `scroll.depth`, `exit.intent`
6162
+ * and `search.performed` are also excluded: a session's start/end and a
6163
+ * scroll/exit-intent signal carry no identifying browsing content on their
6164
+ * own, and a shopper's own search text is the one allowlisted content field
6165
+ * in the registry (`payloads.ts`) — none of the five is the kind of
6166
+ * behavioural profiling a consent banner is asking permission for. See
6167
+ * `widget-chat.service.ts`'s doc comment on `recordEvents` for the full
6168
+ * reasoning on the server side.
6169
+ */
6170
+ var CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1 = [
5586
6171
  "page.viewed",
5587
6172
  "product.viewed",
5588
6173
  "collection.viewed",
5589
6174
  "cart.viewed",
5590
6175
  "cart.changed",
5591
6176
  "product.hovered"
5592
- ]);
6177
+ ];
6178
+ /** How long the ring stays on screen. Long enough to be seen, short enough not to become furniture. */
6179
+ var SPOTLIGHT_RING_MS = 2e3;
6180
+ /**
6181
+ * Above every storefront's own stacking context, below the widget's dock.
6182
+ * `2147483647` is the maximum, and taking it outright would put a decorative
6183
+ * ring above a merchant's cookie banner and their own modals.
6184
+ */
6185
+ var RING_Z_INDEX = 2147483e3;
6186
+ /** How far outside the card's own box the ring is drawn, so it reads as around the card rather than as a border on it. */
6187
+ var RING_INSET_PX = 4;
6188
+ /** The same defaults `page-tracker.ts` uses — one answer to "which element is a product card". */
6189
+ var DEFAULT_PRODUCT_CARD$1 = {
6190
+ selector: ".product-card, [data-product-id]",
6191
+ idFrom: "data-attr",
6192
+ idAttr: "data-product-id"
6193
+ };
6194
+ /**
6195
+ * CSS-escape a value that is about to be spliced into an attribute selector.
6196
+ *
6197
+ * These ids come from OUR server (a catalogue uuid, a parsed Shopify GID), not
6198
+ * from the page — but a selector built by concatenation is a selector
6199
+ * injection waiting for the day one of them contains a quote, and
6200
+ * `querySelector` throws on a malformed selector rather than returning null,
6201
+ * which would take a live call down over a highlight. `CSS.escape` where the
6202
+ * browser has it (every browser above this package's floor), a conservative
6203
+ * manual escape where it does not.
6204
+ */
6205
+ function escapeAttrValue(win, value) {
6206
+ const css = win.CSS;
6207
+ if (typeof css?.escape === "function") return css.escape(value);
6208
+ return value.replace(/["\\]/g, "\\$&");
6209
+ }
6210
+ /**
6211
+ * Does `href` contain `needle` (`/products/<handle>`) as a whole path SEGMENT
6212
+ * — followed by the end of the string, a `/` (a collection-scoped url
6213
+ * continues past it), a `?` or a `#`?
6214
+ *
6215
+ * Plain string scanning rather than a constructed `RegExp`, and that is not a
6216
+ * style choice: a regex built by concatenation from a catalogue field is a
6217
+ * ReDoS surface a security scanner is right to refuse, and this needs no
6218
+ * backtracking at all. Every occurrence is checked, because a url may name the
6219
+ * handle twice (`/collections/rug/products/rug`).
6220
+ */
6221
+ function endsHandleSegment(href, needle) {
6222
+ for (let at = href.indexOf(needle); at !== -1; at = href.indexOf(needle, at + 1)) {
6223
+ const after = href.charAt(at + needle.length);
6224
+ if (after === "" || after === "/" || after === "?" || after === "#") return true;
6225
+ }
6226
+ return false;
6227
+ }
6228
+ /**
6229
+ * Find the element for `target`, or `null`.
6230
+ *
6231
+ * The ladder, in order of how reliably a storefront actually carries each:
6232
+ *
6233
+ * 1. **The id attribute** the site profile names (`data-product-id` by
6234
+ * default) — tried with the PLATFORM id first, because that is what a
6235
+ * theme emits, then with our internal uuid, because a host that built its
6236
+ * grid from our catalogue would emit that one instead.
6237
+ * 2. **A PDP link** — `a[href*="/products/<handle>"]`, then the nearest
6238
+ * enclosing card. A link is what exists on a theme that carries no id
6239
+ * attribute at all, and the enclosing card is what the shopper sees as
6240
+ * "the product", so the ring goes round the card and not round the anchor.
6241
+ *
6242
+ * Never throws: a malformed profile selector, a document mid-teardown, an
6243
+ * element without `closest` — all answer `null`, and a highlight that did not
6244
+ * happen is reported honestly rather than crashing a merchant's page.
6245
+ */
6246
+ function findProductCard(win, doc, target, profile) {
6247
+ const config = profile?.productCard ?? DEFAULT_PRODUCT_CARD$1;
6248
+ const idAttr = config.idAttr ?? DEFAULT_PRODUCT_CARD$1.idAttr ?? "data-product-id";
6249
+ try {
6250
+ for (const id of [target.platformProductId, target.productId]) {
6251
+ if (!id) continue;
6252
+ const byAttr = doc.querySelector(`[${idAttr}="${escapeAttrValue(win, id)}"]`);
6253
+ if (byAttr) return byAttr.closest(config.selector) ?? byAttr;
6254
+ }
6255
+ if (target.handle) {
6256
+ const escaped = escapeAttrValue(win, target.handle);
6257
+ const needle = `/products/${target.handle}`;
6258
+ for (const link of Array.from(doc.querySelectorAll(`a[href*="/products/${escaped}"]`))) {
6259
+ if (!endsHandleSegment(link.getAttribute("href") ?? "", needle)) continue;
6260
+ return link.closest(config.selector) ?? link;
6261
+ }
6262
+ }
6263
+ } catch {}
6264
+ return null;
6265
+ }
6266
+ /**
6267
+ * Scroll `target`'s card into view and ring it. `false` when the card is not
6268
+ * on this page — see the module doc comment on why that is ordinary.
6269
+ *
6270
+ * The scroll is `block: 'center'` so the card lands where a shopper looks, and
6271
+ * it is `behavior: 'smooth'` ONLY when the shopper has not asked for less
6272
+ * motion. `prefers-reduced-motion: reduce` gets an instant jump: the point of
6273
+ * the setting is that nothing slides, and this is the one scroll on the page
6274
+ * the shopper did not start themselves.
6275
+ *
6276
+ * The CALLER is responsible for telling the dock that this scroll was ours
6277
+ * (§5.3/§5.5 — otherwise the row recedes and the sheet ducks at the exact
6278
+ * moment the concierge acted). That flag lives in `@saar-ai/web-widget`'s
6279
+ * dock, which this package deliberately knows nothing about.
6280
+ */
6281
+ function spotlightProductCard(win, doc, target, options = {}) {
6282
+ const card = findProductCard(win, doc, target, options.siteProfile);
6283
+ if (!card) return false;
6284
+ try {
6285
+ let smooth = true;
6286
+ try {
6287
+ smooth = win.matchMedia?.("(prefers-reduced-motion: reduce)").matches !== true;
6288
+ } catch {}
6289
+ card.scrollIntoView({
6290
+ block: "center",
6291
+ behavior: smooth ? "smooth" : "auto"
6292
+ });
6293
+ drawRing(win, doc, card, options.setTimeoutImpl ?? win.setTimeout.bind(win));
6294
+ } catch {}
6295
+ return true;
6296
+ }
6297
+ /**
6298
+ * One FIXED element over the card's box, re-placed on scroll, removed on a
6299
+ * timer.
6300
+ *
6301
+ * The double `box-shadow` is what makes this legible on a storefront whose
6302
+ * colours we do not know: a dark inner ring reads on a light theme, the light
6303
+ * outer one reads on a dark theme, and together they read on a photograph.
6304
+ * Static — no transition, no keyframes, nothing for §7.1 rule 1 to object to.
6305
+ *
6306
+ * The element sits at the viewport origin and is moved by `transform` alone,
6307
+ * so tracking the card through the smooth scroll costs a compositor property
6308
+ * per event and never a `top`/`left` write. The listener is PASSIVE and
6309
+ * capturing (a card inside the merchant's own scroll container emits its
6310
+ * scroll there, not on `window`), and it is removed with the ring — a stray
6311
+ * listener outliving a two-second decoration would be our bytes running on a
6312
+ * merchant's page for the rest of the session.
6313
+ */
6314
+ function drawRing(win, doc, card, schedule) {
6315
+ const body = doc.body;
6316
+ if (!body) return;
6317
+ const ring = doc.createElement("div");
6318
+ ring.setAttribute("aria-hidden", "true");
6319
+ ring.setAttribute("data-concierge-spotlight", "");
6320
+ const px = (value) => `${Math.round(value)}px`;
6321
+ const place = () => {
6322
+ const rect = card.getBoundingClientRect();
6323
+ ring.style.width = px(rect.width + RING_INSET_PX * 2);
6324
+ ring.style.height = px(rect.height + RING_INSET_PX * 2);
6325
+ ring.style.transform = `translate(${px(rect.left - RING_INSET_PX)},${px(rect.top - RING_INSET_PX)})`;
6326
+ };
6327
+ ring.style.cssText = `position:fixed;top:0;left:0;border-radius:10px;pointer-events:none;z-index:${RING_Z_INDEX};box-shadow:0 0 0 2px rgba(17,17,17,.85),0 0 0 5px rgba(255,255,255,.9)`;
6328
+ place();
6329
+ body.appendChild(ring);
6330
+ const onMove = () => {
6331
+ try {
6332
+ place();
6333
+ } catch {}
6334
+ };
6335
+ const listen = (add) => {
6336
+ try {
6337
+ if (add) {
6338
+ win.addEventListener("scroll", onMove, {
6339
+ passive: true,
6340
+ capture: true
6341
+ });
6342
+ win.addEventListener("resize", onMove, { passive: true });
6343
+ } else {
6344
+ win.removeEventListener("scroll", onMove, { capture: true });
6345
+ win.removeEventListener("resize", onMove);
6346
+ }
6347
+ } catch {}
6348
+ };
6349
+ listen(true);
6350
+ schedule(() => {
6351
+ listen(false);
6352
+ try {
6353
+ ring.remove();
6354
+ } catch {}
6355
+ }, SPOTLIGHT_RING_MS);
6356
+ }
6357
+ /**
6358
+ * STOREFRONT PATHS — the two things every act event's destination has to be
6359
+ * rewritten for before a browser is sent to it.
6360
+ *
6361
+ * Both are facts about the SHOPPER'S storefront that the server cannot know,
6362
+ * which is why neither belongs in `apps/api`'s `act-destinations.ts`:
6363
+ *
6364
+ * 1. **The locale prefix.** Shopify Markets puts a locale/market code on the
6365
+ * front of every path — `/en-gb/collections/rugs`, `/fr-ca/cart`. The
6366
+ * catalogue holds handles, not markets, so a resolved path is always
6367
+ * spelt without one. Sending a shopper who is browsing `/en-gb/...` to a
6368
+ * bare `/collections/rugs` drops them out of their own market: a different
6369
+ * currency, a different language, and on some storefronts a redirect that
6370
+ * loses the path entirely. {@link storefrontLocalePrefix} reads the prefix
6371
+ * off the page they are actually on and {@link withStorefrontLocale} puts
6372
+ * it back.
6373
+ * 2. **The facet query.** A filter for a collection the shopper is NOT on
6374
+ * cannot go through `applyFilter` — that method narrows the CURRENT page
6375
+ * by construction — so the facets have to travel in the destination's own
6376
+ * query string instead. {@link withStorefrontFacets} builds it, and
6377
+ * `ShopifyBridge.applyFilter` uses the same function so the scheme exists
6378
+ * in one place.
6379
+ *
6380
+ * Pure string functions, no `window`, no DOM: everything here is testable
6381
+ * against a literal and is shared by the bridge and by `@saar-ai/web-widget`.
6382
+ */
6383
+ /**
6384
+ * Shopify's own facet query-param scheme — `filter.<key>=<value>`, one param
6385
+ * per value (repeated for a multi-select facet).
6386
+ *
6387
+ * The KEY is the exact suffix after `filter.` in Shopify's URL scheme
6388
+ * (`v.option.color`, `p.vendor`, `p.product_type`), which is what the
6389
+ * `apply_filter` tool emits and what `ShopifyBridge.applyFilter` documents
6390
+ * itself as taking. Neither this module nor that method invents a mapping.
6391
+ *
6392
+ * Exported because `ShopifyBridge` READS the same params back for the page
6393
+ * context it hands the model (`pageContextExtras`) — one reader, one writer,
6394
+ * one spelling of the convention.
6395
+ */
6396
+ var FILTER_PARAM_PREFIX = "filter.";
6397
+ /**
6398
+ * The leading locale/market segment of a storefront path, WITH its slash
6399
+ * (`/en-gb`), or `''` when there is none.
6400
+ *
6401
+ * `[a-z]{2}` language, optional `-[a-z]{2}` region — the same shape
6402
+ * `shopify-bridge.ts`'s own `LOCALE_PREFIX` matches, and deliberately no
6403
+ * wider: every storefront route this concierge can name (`/products`,
6404
+ * `/collections`, `/search`, `/cart`, `/pages`, `/policies`) is longer than
6405
+ * two characters, so a two-letter first segment on a storefront is a market
6406
+ * code and not a page.
6407
+ */
6408
+ function storefrontLocalePrefix(path) {
6409
+ const match = /^\/([a-z]{2}(?:-[a-z]{2})?)(?=\/|$)/i.exec(path);
6410
+ return match ? `/${match[1]}` : "";
6411
+ }
6412
+ /**
6413
+ * Put `prefix` (from {@link storefrontLocalePrefix}) on the front of a
6414
+ * resolved path — unless that path already carries one of its own.
6415
+ *
6416
+ * The "already carries one" case is real rather than defensive: `navigate`'s
6417
+ * `target: 'url'` accepts a locale-prefixed storefront path, so a model
6418
+ * echoing the URL it was shown produces `/en-gb/collections/rugs` and
6419
+ * prefixing it again would produce `/en-gb/en-gb/...`.
6420
+ */
6421
+ function withStorefrontLocale(prefix, path) {
6422
+ if (prefix === "" || storefrontLocalePrefix(path) !== "") return path;
6423
+ return `${prefix}${path}`;
6424
+ }
6425
+ /**
6426
+ * `path` with `filters` applied as Shopify's own facet query params, REPLACING
6427
+ * any `filter.*` params it already carried.
6428
+ *
6429
+ * Replacing rather than accumulating is the documented contract of
6430
+ * `apply_filter` ("applying a filter replaces the previous one rather than
6431
+ * adding to it") and of `ShopifyBridge.applyFilter`; anything else turns a
6432
+ * shopper's second thought into an intersection that matches nothing. Every
6433
+ * other query param on the path is kept: a collection url may legitimately
6434
+ * carry `?sort_by=`, and dropping it would undo a choice the shopper made.
6435
+ *
6436
+ * Never throws — a path this cannot parse comes back unchanged, which is a
6437
+ * destination without a filter rather than a navigation that did not happen.
6438
+ */
6439
+ function withStorefrontFacets(path, filters) {
6440
+ try {
6441
+ const hash = path.indexOf("#");
6442
+ const withoutHash = hash === -1 ? path : path.slice(0, hash);
6443
+ const fragment = hash === -1 ? "" : path.slice(hash);
6444
+ const split = withoutHash.indexOf("?");
6445
+ const base = split === -1 ? withoutHash : withoutHash.slice(0, split);
6446
+ const params = new URLSearchParams(split === -1 ? "" : withoutHash.slice(split + 1));
6447
+ for (const key of Array.from(params.keys())) if (key.startsWith("filter.")) params.delete(key);
6448
+ for (const [key, values] of Object.entries(filters)) for (const value of values) params.append(`${FILTER_PARAM_PREFIX}${key}`, value);
6449
+ const query = params.toString();
6450
+ return `${base}${query ? `?${query}` : ""}${fragment}`;
6451
+ } catch {
6452
+ return path;
6453
+ }
6454
+ }
6455
+ new Set(CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1);
5593
6456
  /**
5594
6457
  * Append `embedKey` as a query param, preserving whatever query string `url`
5595
6458
  * already carries — a CORS preflight for `/widget/*` has neither the
@@ -5840,7 +6703,7 @@ var DEFAULT_PATTERNS = {
5840
6703
  search: ["/search"],
5841
6704
  cart: ["/cart"]
5842
6705
  };
5843
- var DEFAULT_SEARCH_QUERY_PARAMS$1 = [
6706
+ var DEFAULT_SEARCH_QUERY_PARAMS = [
5844
6707
  "q",
5845
6708
  "s",
5846
6709
  "search"
@@ -5868,7 +6731,7 @@ function detectFromUrlAndDom(doc, location, profile) {
5868
6731
  cart: profile?.cart ?? DEFAULT_PATTERNS.cart
5869
6732
  };
5870
6733
  const path = location.pathname;
5871
- const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS$1.some((p) => new URLSearchParams(location.search).has(p));
6734
+ const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS.some((p) => new URLSearchParams(location.search).has(p));
5872
6735
  if (matchesAny(path, patterns.cart)) return {
5873
6736
  pageKind: "cart",
5874
6737
  source: "heuristic"
@@ -5938,6 +6801,30 @@ var DESK_TYPING_INDICATOR_TTL_MS = 6e3;
5938
6801
  //#endregion
5939
6802
  //#region src/use-chat-session.ts
5940
6803
  /**
6804
+ * The RUNTIME twin of `@saar-ai/widget-protocol`'s `SameOriginPathSchema`,
6805
+ * kept as a bare regex because that module is zod-backed and `ui` is a
6806
+ * `forbidZod` CDN artefact (`tools/check-config.json`).
6807
+ *
6808
+ * Two copies of one predicate is a drift risk and is worth naming: the SERVER
6809
+ * is the boundary, this is defence in depth, and `act.ts`'s own doc comment
6810
+ * carries the reasoning for every character of it. Kept byte-identical
6811
+ * deliberately — a looser copy would be worse than no copy, because it would
6812
+ * read as a check.
6813
+ */
6814
+ var SAME_ORIGIN_PATH_RE = /^\/(?![/\\])[^\s\\]*$/;
6815
+ /**
6816
+ * Is `value` a root-relative, same-origin storefront path?
6817
+ *
6818
+ * Exported so `host-widget.tsx` re-checks at the POINT OF USE as well — the
6819
+ * two act events that carry a navigable field arrive on two different
6820
+ * transports (this hook's SSE stream, and `use-voice-session.ts`'s data
6821
+ * channel), and a check that lived only here would cover one of them. The
6822
+ * bytes are one regex either way.
6823
+ */
6824
+ function isSameOriginPath(value) {
6825
+ return typeof value === "string" && SAME_ORIGIN_PATH_RE.test(value);
6826
+ }
6827
+ /**
5941
6828
  * `''` = same-origin — every fetch/socket URL this hook builds is relative to
5942
6829
  * whatever origin the browser loaded the widget from (docs/WIDGET_EMBED_PLAN.md
5943
6830
  * §4 Phase 3, coupling (4)). `apps/web` overrides this to its own same-origin
@@ -6160,6 +7047,7 @@ function useChatSession(options) {
6160
7047
  * field's doc comment on `UseChatSessionResult`.
6161
7048
  */
6162
7049
  const [cartAdds, setCartAdds] = useState([]);
7050
+ const [actEvents, setActEvents] = useState([]);
6163
7051
  /**
6164
7052
  * The basket the caller last told us about — see
6165
7053
  * {@link UseChatSessionResult.setCart}. A ref because nothing renders from
@@ -6995,6 +7883,9 @@ function useChatSession(options) {
6995
7883
  onCartAddEvent: (evt) => {
6996
7884
  if (mountedRef.current) setCartAdds((prev) => [...prev, evt]);
6997
7885
  },
7886
+ onActEvent: (evt) => {
7887
+ if (mountedRef.current) setActEvents((prev) => [...prev, evt]);
7888
+ },
6998
7889
  onEscalated: () => {
6999
7890
  markHandoffToHuman();
7000
7891
  },
@@ -7037,19 +7928,30 @@ function useChatSession(options) {
7037
7928
  const setCart = useCallback((cart) => {
7038
7929
  cartRef.current = cart;
7039
7930
  }, []);
7040
- /** See {@link UseChatSessionResult.pushCart}. */
7041
- const pushCart = useCallback(async (cart) => {
7931
+ /**
7932
+ * The shape `pushCart` and `pushPageContext` share: a tokened POST of one
7933
+ * JSON body, with every failure reported as `false` and none of them ever
7934
+ * thrown at the shopper.
7935
+ *
7936
+ * Both are STATEMENTS INSIDE a conversation and never the thing that starts
7937
+ * one, so both refuse before there is a token — the same gate the
7938
+ * add-to-cart nudge applies. And both treat a 204 as a refusal rather than a
7939
+ * success: `POST /widget/context` answers one when the server's own consent
7940
+ * and tracking gates decline the push, and `Response.ok` is `true` for it.
7941
+ */
7942
+ const postSessionState = useCallback(async (path, body) => {
7042
7943
  const chatToken = chatTokenRef.current;
7043
7944
  if (chatToken === void 0) return false;
7044
7945
  try {
7045
- return (await fetchImpl(withEmbedKeyParam(`${apiBase}/cart`, embedKey), {
7946
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}${path}`, embedKey), {
7046
7947
  method: "POST",
7047
7948
  headers: {
7048
7949
  "content-type": "application/json",
7049
7950
  authorization: `Bearer ${chatToken}`
7050
7951
  },
7051
- body: JSON.stringify({ cart })
7052
- })).ok;
7952
+ body: JSON.stringify(body)
7953
+ });
7954
+ return res.ok && res.status !== 204;
7053
7955
  } catch {
7054
7956
  return false;
7055
7957
  }
@@ -7058,6 +7960,10 @@ function useChatSession(options) {
7058
7960
  embedKey,
7059
7961
  fetchImpl
7060
7962
  ]);
7963
+ /** See {@link UseChatSessionResult.pushCart}. */
7964
+ const pushCart = useCallback(async (cart) => postSessionState("/cart", { cart }), [postSessionState]);
7965
+ /** See {@link UseChatSessionResult.pushPageContext}. */
7966
+ const pushPageContext = useCallback(async (context) => postSessionState("/context", { context }), [postSessionState]);
7061
7967
  const sendEvent = useCallback(async (events) => {
7062
7968
  const chatToken = chatTokenRef.current;
7063
7969
  if (chatToken === void 0 || events.length === 0) return false;
@@ -7387,8 +8293,10 @@ function useChatSession(options) {
7387
8293
  cartAdds,
7388
8294
  send,
7389
8295
  sendReport,
8296
+ actEvents,
7390
8297
  setCart,
7391
8298
  pushCart,
8299
+ pushPageContext,
7392
8300
  sendEvent,
7393
8301
  notifyTyping,
7394
8302
  checkout,
@@ -7402,7 +8310,7 @@ function useChatSession(options) {
7402
8310
  * promise and is trivially unit-testable with a synthetic `ReadableStream`.
7403
8311
  */
7404
8312
  async function streamReply(args) {
7405
- const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onEscalated, onDone, onError, isMounted } = args;
8313
+ const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onActEvent, onEscalated, onDone, onError, isMounted } = args;
7406
8314
  const reader = body.getReader();
7407
8315
  const decoder = new TextDecoder();
7408
8316
  const parser = new SseFrameParser();
@@ -7520,6 +8428,21 @@ async function streamReply(args) {
7520
8428
  onCartAddEvent({ item });
7521
8429
  break;
7522
8430
  }
8431
+ case "navigate": {
8432
+ const data = evt.data;
8433
+ if (!isSameOriginPath(data?.url)) break;
8434
+ onActEvent(evt.data);
8435
+ break;
8436
+ }
8437
+ case "filter": {
8438
+ const data = evt.data;
8439
+ if (data?.collectionUrl !== void 0 && !isSameOriginPath(data.collectionUrl)) break;
8440
+ onActEvent(evt.data);
8441
+ break;
8442
+ }
8443
+ case "spotlight":
8444
+ onActEvent(evt.data);
8445
+ break;
7523
8446
  case "escalated":
7524
8447
  onEscalated();
7525
8448
  break;
@@ -7545,7 +8468,7 @@ async function streamReply(args) {
7545
8468
  * cache makes a second `start()` after `stop()` free).
7546
8469
  */
7547
8470
  async function loadVoiceProtocol() {
7548
- const [telemetry, chat] = await Promise.all([import("./telemetry-BI_SEWTb.js"), import("./chat-tMKkYmTC.js")]);
8471
+ const [telemetry, chat] = await Promise.all([import("./telemetry-CBblNC6C.js"), import("./chat-e1afSRBr.js")]);
7549
8472
  return {
7550
8473
  decodeTelemetry: telemetry.decodeTelemetry,
7551
8474
  encodeCallerText: telemetry.encodeCallerText,
@@ -8209,6 +9132,23 @@ function useVoiceSession(options = {}) {
8209
9132
  reason
8210
9133
  }), [publishControl]);
8211
9134
  /**
9135
+ * §8.6's hint, sent DELIBERATELY rather than from `pagehide` — the
9136
+ * concierge's own `navigate` is about to move the page.
9137
+ *
9138
+ * `pagehide` already covers a shopper's click and a full-document
9139
+ * `location.assign`, and it still does. It does not cover the case this
9140
+ * exists for: a SOFT navigation (a `NextBridge` host, any bridge with a
9141
+ * router) fires no `pagehide` at all, so a concierge-driven move on a
9142
+ * headless storefront would look, at the transport layer, exactly like a
9143
+ * caller who said nothing for a while. Sending it explicitly means the
9144
+ * session gets its bounded hold either way — and on a hard navigation the
9145
+ * duplicate is free: the worker reads the hint as a flag, not a counter.
9146
+ *
9147
+ * Resolves `false` and sends nothing when there is no room, so a typed-only
9148
+ * panel calling this pays one function call.
9149
+ */
9150
+ const notifyNavigating = useCallback(async () => publishControl({ type: "navigating" }), [publishControl]);
9151
+ /**
8212
9152
  * §8.6 — `navigating`, sent from `pagehide` while a call is live.
8213
9153
  *
8214
9154
  * The caller's participant disconnects on EVERY click of a conventionally
@@ -8304,10 +9244,350 @@ function useVoiceSession(options = {}) {
8304
9244
  sendText,
8305
9245
  sendEouHint,
8306
9246
  sendResume,
8307
- interrupt
9247
+ interrupt,
9248
+ notifyNavigating
8308
9249
  };
8309
9250
  }
8310
9251
  //#endregion
9252
+ //#region ../widget-bridge/dist/page-context.js
9253
+ function clampId(value, max) {
9254
+ if (typeof value !== "string") return void 0;
9255
+ const trimmed = value.replace(/\s+/gu, " ").trim();
9256
+ if (trimmed === "") return void 0;
9257
+ return trimmed.slice(0, max);
9258
+ }
9259
+ /**
9260
+ * A pathname, or `undefined`.
9261
+ *
9262
+ * Deliberately NOT a URL parser. Every caller hands this `location.pathname`
9263
+ * (or an adapter's own classification of it), so the `new URL()` branch this
9264
+ * used to carry was defensive code for a caller that does not exist — and
9265
+ * this module is bundled into `ui.mjs`, which has a few hundred bytes of
9266
+ * headroom. What survives is the rule that actually matters: anything
9267
+ * carrying a `?`, a `#`, whitespace, or no leading `/` is REFUSED rather than
9268
+ * repaired, because a query string is where storefronts put session ids and
9269
+ * email addresses and this field must never carry one.
9270
+ */
9271
+ function clampPath(value) {
9272
+ if (typeof value !== "string") return void 0;
9273
+ const path = value.trim();
9274
+ if (!path.startsWith("/") || /[?#\s]/u.test(path)) return void 0;
9275
+ return path.slice(0, 512);
9276
+ }
9277
+ function clampFilters(filters) {
9278
+ if (!filters) return void 0;
9279
+ const out = {};
9280
+ for (const [rawKey, rawValue] of Object.entries(filters)) {
9281
+ if (Object.keys(out).length >= 8) break;
9282
+ const key = clampId(rawKey, 64);
9283
+ const value = clampId(rawValue, 64);
9284
+ if (key === void 0 || value === void 0) continue;
9285
+ out[key] = value;
9286
+ }
9287
+ return Object.keys(out).length > 0 ? out : void 0;
9288
+ }
9289
+ function byteLength(context) {
9290
+ return new TextEncoder().encode(JSON.stringify(context)).byteLength;
9291
+ }
9292
+ /**
9293
+ * Build a bounded, wire-legal `PageContext`, or `undefined` when there is not
9294
+ * even a path to report.
9295
+ *
9296
+ * ## Degrade, never fabricate — and never drop the whole thing
9297
+ *
9298
+ * Every optional field is omitted rather than defaulted: no `cartCount: 0` for
9299
+ * a host that does not report one (zero is a real answer, "the cart is
9300
+ * empty"), no handle substituted for a missing id. `pageType` and `path` are
9301
+ * the only things this needs, and a page that cannot supply a path supplies no
9302
+ * context at all.
9303
+ *
9304
+ * ## Trimming to the byte ceiling
9305
+ *
9306
+ * `PAGE_CONTEXT_MAX_BYTES` is a hard ceiling on both wires, and a payload over
9307
+ * it is dropped WHOLE by the decoder on the other side. Rather than let a
9308
+ * merchant with very long handles lose their context entirely, this trims in
9309
+ * increasing order of usefulness to the model: the facets go first, then the
9310
+ * search text and the ids together. The page type and the path always
9311
+ * survive, and they are together far below the ceiling by construction.
9312
+ *
9313
+ * @param draft the raw values, from whichever `HostBridge` resolved them
9314
+ */
9315
+ /**
9316
+ * The locale shape `PageContextSchema` accepts, mirrored here rather than
9317
+ * imported.
9318
+ *
9319
+ * This package deliberately does not depend on `@saar-ai/widget-protocol` —
9320
+ * zod would land in `core.mjs` — so the contract is written down on both
9321
+ * sides with a pointer between them, the same way the bridge's other
9322
+ * cross-package literals are. `page-context-contract.test.ts` in
9323
+ * `@saar-ai/web-widget` pins the two together.
9324
+ *
9325
+ * It is applied as a DROP rather than a repair, and that is the whole point.
9326
+ * `<html lang>` is whatever the merchant's theme wrote, and themes write
9327
+ * `EN`, `en_US` and `en-us` as readily as `en-US`. Passing one of those
9328
+ * through is not a cosmetic problem: the wire schema is strict, so the server
9329
+ * refuses the entire body with a 400 and the shopper loses their page context
9330
+ * because of one optional field. Dropping it costs a locale the model barely
9331
+ * uses and keeps the page. A platform adapter that knows the real locale
9332
+ * supplies it through `pageContextExtras()` and is unaffected — Shopify's
9333
+ * does, from `Shopify.locale`.
9334
+ *
9335
+ * Normalising the case instead was measured at ~115 bytes of `ui.mjs` against
9336
+ * 77 bytes of headroom, and buys only the generic fallback path on badly
9337
+ * written themes. Not worth the budget; revisit if `ui` ever has room.
9338
+ */
9339
+ var WIRE_LOCALE_PATTERN = /^[a-z]{2,3}(-[A-Za-z]{2,4})?(-[A-Z]{2}|-\d{3})?$/u;
9340
+ function buildPageContext(draft) {
9341
+ const path = clampPath(draft.path);
9342
+ if (path === void 0) return void 0;
9343
+ const capturedAt = new Date(draft.capturedAt ?? Date.now()).toISOString();
9344
+ const cartCount = typeof draft.cartCount === "number" && Number.isFinite(draft.cartCount) && draft.cartCount >= 0 ? Math.min(9999, Math.floor(draft.cartCount)) : void 0;
9345
+ let filters = clampFilters(draft.filters);
9346
+ let searchQuery = clampId(draft.searchQuery, 128);
9347
+ let productId = clampId(draft.productId, 128);
9348
+ let variantId = clampId(draft.variantId, 128);
9349
+ let collectionHandle = clampId(draft.collectionHandle, 128);
9350
+ const clampedLocale = clampId(draft.locale, 35);
9351
+ const locale = clampedLocale !== void 0 && WIRE_LOCALE_PATTERN.test(clampedLocale) ? clampedLocale : void 0;
9352
+ const assemble = () => ({
9353
+ pageType: draft.pageType,
9354
+ path,
9355
+ ...productId !== void 0 ? { productId } : {},
9356
+ ...variantId !== void 0 ? { variantId } : {},
9357
+ ...collectionHandle !== void 0 ? { collectionHandle } : {},
9358
+ ...filters !== void 0 ? { filters } : {},
9359
+ ...searchQuery !== void 0 ? { searchQuery } : {},
9360
+ ...cartCount !== void 0 ? { cartCount } : {},
9361
+ ...locale !== void 0 ? { locale } : {},
9362
+ capturedAt
9363
+ });
9364
+ let context = assemble();
9365
+ if (byteLength(context) > 2048) {
9366
+ filters = void 0;
9367
+ context = assemble();
9368
+ }
9369
+ if (byteLength(context) > 2048) {
9370
+ searchQuery = void 0;
9371
+ productId = void 0;
9372
+ variantId = void 0;
9373
+ collectionHandle = void 0;
9374
+ context = assemble();
9375
+ }
9376
+ return context;
9377
+ }
9378
+ /**
9379
+ * Are these two contexts the same PLACE?
9380
+ *
9381
+ * `capturedAt` is excluded deliberately — it moves on every capture and is
9382
+ * descriptive, never the thing that makes a context new. Used by
9383
+ * `PageContextTracker` to avoid re-pushing an identical context when a host's
9384
+ * router fires `onPageChange` twice for one navigation, which several
9385
+ * storefront themes do.
9386
+ *
9387
+ * Compares the JSON up to `capturedAt`, which {@link buildPageContext} always
9388
+ * emits LAST — cheaper than rebuilding both objects without it, on a module
9389
+ * that ships inside a budgeted bundle. A hand-written field-by-field compare
9390
+ * would be cheaper still and is exactly the thing that silently stops
9391
+ * comparing a field somebody adds later.
9392
+ *
9393
+ * @param a one context, or nothing
9394
+ * @param b the other, or nothing
9395
+ */
9396
+ function samePageContext(a, b) {
9397
+ if (a === void 0 || b === void 0) return a === b;
9398
+ return place(a) === place(b);
9399
+ }
9400
+ function place(context) {
9401
+ const json = JSON.stringify(context);
9402
+ return json.slice(0, json.lastIndexOf("\"capturedAt\""));
9403
+ }
9404
+ /**
9405
+ * The query-string parameter names a storefront's search box puts its text
9406
+ * in, in the order they are tried.
9407
+ *
9408
+ * ONE list, read by both callers: `PageTracker` builds `search.performed`
9409
+ * from it and `GenericBridge.pageContextExtras` builds the page context's
9410
+ * `searchQuery` from it. A second spelling would let the visitor timeline and
9411
+ * the model's prompt disagree about what the shopper searched for — and, on a
9412
+ * bundle with a few hundred bytes of headroom, a second copy of the loop is
9413
+ * not free either.
9414
+ */
9415
+ var SEARCH_QUERY_PARAMS = [
9416
+ "q",
9417
+ "s",
9418
+ "search"
9419
+ ];
9420
+ /**
9421
+ * The shopper's own search text out of a query string, or `undefined`.
9422
+ *
9423
+ * @param search `location.search`, with or without its leading `?`
9424
+ */
9425
+ function readSearchQueryParam(search) {
9426
+ try {
9427
+ const params = new URLSearchParams(search);
9428
+ for (const name of SEARCH_QUERY_PARAMS) {
9429
+ const value = params.get(name);
9430
+ if (value && value.trim()) return value.trim();
9431
+ }
9432
+ return;
9433
+ } catch {
9434
+ return;
9435
+ }
9436
+ }
9437
+ /** The real `location.search` and `<html lang>`, or nothing outside a browser. */
9438
+ function browserPageContextGlobals() {
9439
+ if (typeof window === "undefined") return {};
9440
+ return {
9441
+ search: window.location?.search ?? "",
9442
+ ...typeof document !== "undefined" && typeof document.documentElement?.lang === "string" ? { documentLang: document.documentElement.lang } : {}
9443
+ };
9444
+ }
9445
+ /**
9446
+ * `HostPageKind` → `PageContextType`.
9447
+ *
9448
+ * The one mapping that is not the identity is `'other'` at the site root,
9449
+ * which becomes `'home'`. The bridge's kind list never needed a name for the
9450
+ * front page because a home page is a `page.viewed` like any other; the model
9451
+ * does need one, because "they are on the front page" and "they are on some
9452
+ * page we could not classify" call for different opening sentences.
9453
+ *
9454
+ * @param kind the classified page kind
9455
+ * @param path the page's pathname
9456
+ */
9457
+ function pageContextTypeFor(kind, path) {
9458
+ if (kind === "other") return /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/?)?$/iu.test(path) ? "home" : "other";
9459
+ return kind;
9460
+ }
9461
+ /**
9462
+ * Where the shopper is standing, as `PageContextSchema` wants it — or `null`
9463
+ * when there is no usable page to describe.
9464
+ *
9465
+ * Never throws: an adapter that explodes costs the concierge a grounded
9466
+ * phrase, never the merchant's page. Everything is CLAMPED rather than
9467
+ * rejected (`buildPageContext`), so a storefront with unusually long handles
9468
+ * loses a facet rather than its whole context.
9469
+ *
9470
+ * @param bridge the host adapter to ask
9471
+ */
9472
+ function currentPageContext(bridge, globals) {
9473
+ try {
9474
+ const page = bridge.currentPage();
9475
+ const { search, documentLang } = globals ?? browserPageContextGlobals();
9476
+ const extras = bridge.pageContextExtras?.() ?? {};
9477
+ return buildPageContext({
9478
+ pageType: pageContextTypeFor(page.kind, page.path),
9479
+ path: page.path,
9480
+ searchQuery: readSearchQueryParam(search ?? ""),
9481
+ locale: documentLang,
9482
+ ...page.kind === "product" ? { productId: page.entityId } : {},
9483
+ ...page.kind === "collection" ? { collectionHandle: page.handle ?? page.entityId } : {},
9484
+ ...extras
9485
+ }) ?? null;
9486
+ } catch {
9487
+ return null;
9488
+ }
9489
+ }
9490
+ /**
9491
+ * The default timer, declared here rather than imported from `coalescer.ts`.
9492
+ *
9493
+ * `realTimer` there is identical, and importing it would be the obvious
9494
+ * thing — but `coalescer.ts` also holds `ScrollDepthCoalescer`,
9495
+ * `ProductHoverTracker` and `PageViewDeduper`, none of which this module
9496
+ * uses, and this module is bundled into `ui.mjs` (which carries none of them
9497
+ * either) through the `@saar-ai/widget-bridge/page-context` entry. Two lines
9498
+ * of duplication against several hundred bytes on an artefact with under a
9499
+ * kilobyte of headroom. The TYPE is still imported, so the two cannot drift.
9500
+ */
9501
+ var defaultTimer = {
9502
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
9503
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
9504
+ };
9505
+ /** The visitor-event kind whose gates this tracker borrows. See the class doc comment. */
9506
+ var GATED_AS = "page.viewed";
9507
+ var PageContextTracker = class {
9508
+ bridge;
9509
+ consent;
9510
+ trackingEnabled;
9511
+ send;
9512
+ timer;
9513
+ debounceMs;
9514
+ started = false;
9515
+ destroyed = false;
9516
+ unsubscribePageChange;
9517
+ pending;
9518
+ /** The last context that actually went out — see {@link samePageContext}. */
9519
+ lastSent;
9520
+ pageChangeListener = () => {
9521
+ try {
9522
+ this.schedule();
9523
+ } catch {}
9524
+ };
9525
+ constructor(options) {
9526
+ this.bridge = options.bridge;
9527
+ this.consent = options.consent;
9528
+ this.trackingEnabled = options.trackingEnabled ?? (() => true);
9529
+ this.send = options.send;
9530
+ this.timer = options.timer ?? defaultTimer;
9531
+ this.debounceMs = options.debounceMs ?? 250;
9532
+ }
9533
+ /**
9534
+ * Boot the tracker: capture the page the shopper opened on, then follow
9535
+ * every navigation.
9536
+ *
9537
+ * The FIRST capture is not debounced — it is the context the model needs
9538
+ * before the first turn, and a quarter-second of deliberate lateness on a
9539
+ * page that has only just loaded buys nothing. Every later capture is.
9540
+ *
9541
+ * Calling twice is a no-op. Never throws.
9542
+ */
9543
+ start() {
9544
+ try {
9545
+ if (this.started || this.destroyed) return;
9546
+ this.started = true;
9547
+ this.capture();
9548
+ this.unsubscribePageChange = this.bridge.onPageChange(this.pageChangeListener);
9549
+ } catch {}
9550
+ }
9551
+ destroy() {
9552
+ try {
9553
+ this.destroyed = true;
9554
+ this.unsubscribePageChange?.();
9555
+ if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
9556
+ this.pending = void 0;
9557
+ } catch {}
9558
+ }
9559
+ /** `true` when both gates allow a push right now. Exposed for the caller's own diagnostics. */
9560
+ mayPush() {
9561
+ return this.consent.mayTrack(GATED_AS) && this.trackingEnabled();
9562
+ }
9563
+ schedule() {
9564
+ if (this.destroyed) return;
9565
+ if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
9566
+ this.pending = this.timer.setTimeout(() => {
9567
+ this.pending = void 0;
9568
+ this.capture();
9569
+ }, this.debounceMs);
9570
+ }
9571
+ /**
9572
+ * The whole decision, in order: gates first, then the bridge.
9573
+ *
9574
+ * Gates BEFORE `currentPageContext()` is deliberate. Reading the page is
9575
+ * cheap but not free (a `querySelectorAll` on some adapters), and more to
9576
+ * the point a visitor who denied consent should have nothing about their
9577
+ * page read at all — not read, then discarded.
9578
+ */
9579
+ capture() {
9580
+ try {
9581
+ if (this.destroyed || !this.mayPush()) return;
9582
+ const context = currentPageContext(this.bridge) ?? void 0;
9583
+ if (context === void 0 || samePageContext(context, this.lastSent)) return;
9584
+ this.lastSent = context;
9585
+ const result = this.send(context);
9586
+ if (typeof result?.catch === "function") result.catch(() => {});
9587
+ } catch {}
9588
+ }
9589
+ };
9590
+ //#endregion
8311
9591
  //#region src/turn-order.ts
8312
9592
  /**
8313
9593
  * The widget's arrival clock. One instance per mounted widget (`useRef`), fed
@@ -8421,6 +9701,51 @@ var TurnOrderClock = class {
8421
9701
  //#endregion
8422
9702
  //#region src/host-widget.tsx
8423
9703
  /**
9704
+ * DOCK_SPEC §6 — how long the TYPED leg waits before performing a
9705
+ * concierge-driven `navigate` or `filter`.
9706
+ *
9707
+ * "Agent-initiated navigation is scheduled, not immediate. Finish the clause,
9708
+ * then navigate." On a call the realtime tier does the scheduling
9709
+ * (`apps/voice/src/session/scheduled-widget-events.ts` holds the event until
9710
+ * the utterance ends), so by the time the event reaches this widget the
9711
+ * concierge has stopped speaking. A typed reply has no utterance to finish and
9712
+ * the event arrives mid-stream — the shopper would read half a sentence and
9713
+ * watch the page take the rest of it away. One beat is what lets the sentence
9714
+ * land, and it is short on purpose: a navigation the shopper asked for should
9715
+ * feel like a click, not like a wait.
9716
+ */
9717
+ var NAVIGATE_BEAT_MS = 300;
9718
+ /**
9719
+ * Is this widget event one the concierge wants PERFORMED on the host page?
9720
+ *
9721
+ * Hand-written rather than imported from `@saar-ai/widget-protocol`'s
9722
+ * `ACT_EVENT_TYPES`, and that is a build constraint rather than a preference:
9723
+ * that module is zod-backed, and `ui` is a `forbidZod` CDN artefact
9724
+ * (`tools/check-config.json`) — a VALUE import from it would pull zod into an
9725
+ * artefact a shopper downloads the moment they open the concierge. The type
9726
+ * still comes from there, so a fourth act event is a compile error here rather
9727
+ * than a silent no-op.
9728
+ */
9729
+ function isActEvent(event) {
9730
+ return event.type === "navigate" || event.type === "filter" || event.type === "spotlight";
9731
+ }
9732
+ /**
9733
+ * Do two storefront paths name the same PAGE — ignoring the query, the
9734
+ * fragment and a trailing slash?
9735
+ *
9736
+ * It decides one thing: whether a `filter`'s `collectionUrl` is the page the
9737
+ * shopper is already on (narrow it in place) or a different one (walk them
9738
+ * there with the facets in the url). Deliberately a string comparison rather
9739
+ * than a `URL` parse: both sides are root-relative by construction — the
9740
+ * server's schema and `isSameOriginPath` have both refused anything else — so
9741
+ * there is no origin to resolve against and nothing a parser would add except
9742
+ * a second place for the two to disagree.
9743
+ */
9744
+ function isSamePagePath(a, b) {
9745
+ const bare = (value) => (value.split("#")[0] ?? "").split("?")[0]?.replace(/\/+$/, "") ?? "";
9746
+ return bare(a) === bare(b);
9747
+ }
9748
+ /**
8424
9749
  * Resolves the widget's "add to cart" handler from the bridge's OWN degraded
8425
9750
  * path — docs/WIDGET_EMBED_PLAN.md §3, rule 1 ("every optional method is
8426
9751
  * genuinely optional... the widget has a working degraded path for each —
@@ -8726,7 +10051,7 @@ function deriveCallPhase(voice) {
8726
10051
  * about offering voice here costs a byte until a caller actually presses
8727
10052
  * the microphone.
8728
10053
  */
8729
- function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
10054
+ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, siteProfile, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
8730
10055
  /**
8731
10056
  * Maps the tenant's semantic config fields onto the widget's historical
8732
10057
  * CSS custom properties — this is the "one becomes the other" site
@@ -8785,6 +10110,66 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
8785
10110
  */
8786
10111
  const escalated = session.status === "escalated";
8787
10112
  /**
10113
+ * Page context — where the shopper is standing, pushed to both legs
10114
+ * (ADR 0014).
10115
+ *
10116
+ * ## Why it is wired HERE and not in `core.ts`
10117
+ *
10118
+ * `core.ts` is where `PageTracker` starts, and this tracker's sibling
10119
+ * naturally belongs beside it — the ENTRY page is the one that says which
10120
+ * campaign or product brought the shopper, and by the time this component
10121
+ * mounts they may have navigated twice. It is here anyway, for one reason
10122
+ * that is not a preference: `core.mjs` has a hard min+gz budget
10123
+ * (`tools/check-config.json`, `bundle-budget.artefacts.core`) with under
10124
+ * 250 bytes of headroom at the time of writing, and a tracker plus a POST
10125
+ * does not fit in it. `ui.mjs` has room and is where the chat token already
10126
+ * lives.
10127
+ *
10128
+ * What that costs, stated plainly rather than hidden: no page context
10129
+ * exists until the shopper OPENS the concierge, because `ui.mjs` is not
10130
+ * requested until intent (§4.1). A context still arrives before the first
10131
+ * TURN, which is what the feature needs — the concierge grounds its first
10132
+ * reply — but a proactive opener cannot be grounded on the page, and a
10133
+ * visitor who never opens the widget pushes nothing at all. Moving this to
10134
+ * `core` is the follow-up, and it is gated on the theme derivation coming
10135
+ * out of `core` (option 2 of `packages/web-widget/AGENTS.md`'s "Measured
10136
+ * sizes" table), which returns eight times what this would spend.
10137
+ *
10138
+ * ## ONE push, and both legs read what it stored
10139
+ *
10140
+ * The tracker decides WHETHER; this decides WHERE, and the answer is the
10141
+ * one gated endpoint. `POST /widget/context` re-checks the visitor's
10142
+ * consent and the tenant's tracking toggle server-side and stores the
10143
+ * context against the session; the typed leg renders it from there, and the
10144
+ * turn tier reads the SAME key per turn (`PageContextStore`, `apps/agent`).
10145
+ *
10146
+ * There is deliberately no second push down the call's data channel. A
10147
+ * frame like that reaches a model without passing any server gate, so a
10148
+ * merchant who switched behavioural tracking off would still have their
10149
+ * shoppers' browsing narrated into a prompt on every call — and no check
10150
+ * running in the merchant's own page could prevent it. One gated write, two
10151
+ * readers. See ADR 0014.
10152
+ */
10153
+ const pushPageContext = session.pushPageContext;
10154
+ const sendPageContextRef = useRef(() => {});
10155
+ sendPageContextRef.current = (context) => {
10156
+ pushPageContext(context);
10157
+ };
10158
+ useEffect(() => {
10159
+ if (!bridge || !collector || chatToken === void 0) return;
10160
+ const tracker = new PageContextTracker({
10161
+ bridge,
10162
+ consent: collector,
10163
+ send: (context) => sendPageContextRef.current(context)
10164
+ });
10165
+ tracker.start();
10166
+ return () => tracker.destroy();
10167
+ }, [
10168
+ bridge,
10169
+ collector,
10170
+ chatToken
10171
+ ]);
10172
+ /**
8788
10173
  * The basket this widget built from its OWN adds — see `AddedCartLine`.
8789
10174
  * Always accumulated, even when the host has a `readCart` that reports
8790
10175
  * lines: the host read is asynchronous and can fail, and this is what the
@@ -9121,6 +10506,264 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9121
10506
  * `/cart/add.js`, and a storefront cart is one resource — two concurrent
9122
10507
  * posts against it is exactly the shape that loses one of them.
9123
10508
  */
10509
+ /**
10510
+ * §5.3/§5.5's concierge-scroll flag, as a function the DOCK publishes.
10511
+ *
10512
+ * Called immediately BEFORE a spotlight scroll and synchronously, which is
10513
+ * the whole point of it being a callback rather than the state nonce it
10514
+ * started as: the dock's scroll listener is a capture listener on
10515
+ * `document`, so the first `scroll` event of a smooth scroll can arrive in
10516
+ * the same task — before React has re-rendered — and a flag raised by a
10517
+ * `setState` would be raised one event too late. The row receding and the
10518
+ * sheet ducking at the exact moment the concierge pointed at something is
10519
+ * precisely the failure §5.3's exception exists to prevent.
10520
+ *
10521
+ * `null` until the dock mounts (a harness with no dock at all), and calling
10522
+ * it with `0` DISARMS — see `performAct`'s spotlight branch.
10523
+ */
10524
+ const conciergeScrollRef = useRef(null);
10525
+ /**
10526
+ * The facts an act reads at the moment it RUNS, rather than at the moment
10527
+ * its callback was built.
10528
+ *
10529
+ * An act is asynchronous by construction — `navigate` waits a beat, a bridge
10530
+ * returns a promise — so a call that starts during that window changes the
10531
+ * right answer after the closure was made. `inCall` decides whether a
10532
+ * failure report is sent now or held (`heldFailureReportsRef`), and a stale
10533
+ * `false` there is a chat request answered out loud over whatever the caller
10534
+ * is saying. `actLive` is the unmount latch: nothing may assign
10535
+ * `location`, and nothing may send a report, after this widget is gone.
10536
+ */
10537
+ const inCallRef = useRef(inCall);
10538
+ const actLiveRef = useRef(true);
10539
+ useEffect(() => {
10540
+ inCallRef.current = inCall;
10541
+ }, [inCall]);
10542
+ useEffect(() => () => {
10543
+ actLiveRef.current = false;
10544
+ actQueueRef.current = [];
10545
+ }, []);
10546
+ /**
10547
+ * Send a storefront report about an act that did not happen, or hold it
10548
+ * until the call ends.
10549
+ *
10550
+ * The exact gates `reportFailedAgentCartAdd` keeps, and for the identical
10551
+ * reasons: no conversation ⇒ nothing to correct; mid-call ⇒ a chat request
10552
+ * is answered OUT LOUD over whatever the caller is saying, so it is held and
10553
+ * flushed when the call ends, never dropped. `inCall` is read from the ref
10554
+ * because this is called at the END of an asynchronous act.
10555
+ */
10556
+ const sendActReport = useCallback((report) => {
10557
+ if (chatToken === void 0 || !actLiveRef.current) return;
10558
+ if (inCallRef.current) {
10559
+ heldFailureReportsRef.current = [...heldFailureReportsRef.current, report];
10560
+ return;
10561
+ }
10562
+ session.sendReport(report).catch(() => void 0);
10563
+ }, [chatToken, session]);
10564
+ /**
10565
+ * Tell the concierge that a `spotlight` it asked for found NOTHING.
10566
+ *
10567
+ * The exact mirror of `reportFailedAgentCartAdd`: the server said
10568
+ * `status: 'requested'` because the card lives in a DOM it cannot see, so
10569
+ * this widget is the only party that learns the answer. A caller is not
10570
+ * looking at the panel at all, and by then the concierge has said "that's
10571
+ * the one, highlighted on your screen" out loud.
10572
+ */
10573
+ const reportFailedSpotlight = useCallback((event) => {
10574
+ sendActReport({
10575
+ kind: "spotlight_failed",
10576
+ title: event.title ?? event.productId,
10577
+ productId: event.productId
10578
+ });
10579
+ }, [sendActReport]);
10580
+ /**
10581
+ * Tell the concierge the page did NOT move.
10582
+ *
10583
+ * This used to be a comment explaining that there was no correction channel
10584
+ * for a navigation the way there is for a cart add. There is now
10585
+ * (`navigate_failed`), and it is needed more than the cart one: a bridge
10586
+ * with no `navigate` is §3's ordinary case rather than an exotic one, and
10587
+ * "taking you to the cushions" is the most concrete claim the concierge
10588
+ * makes. A caller cannot see that the page stayed put.
10589
+ *
10590
+ * It deliberately carries no path — the guardrails forbid the concierge to
10591
+ * say one out loud, and a report holding a url puts it in the model's
10592
+ * context with nothing but an instruction in the way.
10593
+ */
10594
+ const reportFailedNavigate = useCallback((target) => {
10595
+ sendActReport({
10596
+ kind: "navigate_failed",
10597
+ ...target !== void 0 ? { target } : {}
10598
+ });
10599
+ }, [sendActReport]);
10600
+ /**
10601
+ * The path prefix of the storefront the shopper is ACTUALLY on.
10602
+ *
10603
+ * Shopify Markets puts a locale/market code on the front of every path
10604
+ * (`/en-gb/collections/rugs`). The catalogue holds handles, not markets, so
10605
+ * every path the server resolves is spelt without one — and sending a
10606
+ * shopper browsing `/en-gb/...` to a bare `/collections/rugs` drops them out
10607
+ * of their own market: another currency, another language, and on some
10608
+ * storefronts a redirect that loses the path entirely. The bridge already
10609
+ * classifies these prefixes; this reads the one it is looking at.
10610
+ */
10611
+ const bridgePath = useCallback(() => {
10612
+ try {
10613
+ return bridge?.currentPage?.().path ?? "";
10614
+ } catch {
10615
+ return "";
10616
+ }
10617
+ }, [bridge]);
10618
+ /**
10619
+ * Walk the shopper to another page — `navigate` (§6).
10620
+ *
10621
+ * The §6 beat is NOT here — `performAct` waits it once per page-moving
10622
+ * event, so the `filter` fallback below does not wait it twice.
10623
+ *
10624
+ * ## Same-origin, re-checked HERE
10625
+ *
10626
+ * The server's schema is the boundary and `useChatSession` re-checks the
10627
+ * SSE frame, but the spoken leg does not come through that hook at all, and
10628
+ * a `filter`'s `collectionUrl` reaches this function by the same route a
10629
+ * `navigate`'s url does. This is the one place both legs and both fields
10630
+ * meet, so the predicate lives here too. A path that fails it is not
10631
+ * repaired: it is a page nobody meant to open.
10632
+ *
10633
+ * ## The `navigating` hint goes FIRST
10634
+ *
10635
+ * §8.6 — a caller's participant disconnects on every navigation, and at the
10636
+ * transport layer that is indistinguishable from a hangup. The hint is what
10637
+ * buys the session its bounded hold so the next page REJOINS the same
10638
+ * conversation. Awaited, not fired and forgotten: `location.assign` can tear
10639
+ * the page down before an unawaited publish reaches the wire.
10640
+ */
10641
+ const notifyNavigating = voice.notifyNavigating;
10642
+ const performNavigate = useCallback(async (url, target) => {
10643
+ if (!isSameOriginPath(url) || !bridge?.navigate) {
10644
+ reportFailedNavigate(target);
10645
+ return;
10646
+ }
10647
+ const path = withStorefrontLocale(storefrontLocalePrefix(bridgePath()), url);
10648
+ if (!actLiveRef.current) return;
10649
+ if (voiceEnabled) await notifyNavigating().catch(() => false);
10650
+ if (!actLiveRef.current) return;
10651
+ try {
10652
+ await bridge.navigate(path);
10653
+ } catch {
10654
+ reportFailedNavigate(target);
10655
+ }
10656
+ }, [
10657
+ bridge,
10658
+ bridgePath,
10659
+ voiceEnabled,
10660
+ notifyNavigating,
10661
+ reportFailedNavigate
10662
+ ]);
10663
+ /**
10664
+ * Perform ONE act event. Never throws — every branch is a host-facing call.
10665
+ */
10666
+ const performAct = useCallback(async (event) => {
10667
+ if (event.type !== "spotlight") {
10668
+ if (!inCallRef.current) await new Promise((resolve) => setTimeout(resolve, NAVIGATE_BEAT_MS));
10669
+ if (!actLiveRef.current) return;
10670
+ }
10671
+ if (event.type === "navigate") {
10672
+ await performNavigate(event.url, event.target);
10673
+ return;
10674
+ }
10675
+ if (event.type === "filter") {
10676
+ if (event.collectionUrl !== void 0 && !isSameOriginPath(event.collectionUrl)) return;
10677
+ const prefix = storefrontLocalePrefix(bridgePath());
10678
+ const collectionUrl = event.collectionUrl === void 0 ? void 0 : withStorefrontLocale(prefix, event.collectionUrl);
10679
+ if (!(collectionUrl !== void 0 && !isSamePagePath(collectionUrl, bridgePath())) && bridge?.applyFilter) try {
10680
+ if (await bridge.applyFilter(event.filters) !== false) return;
10681
+ } catch {}
10682
+ if (collectionUrl !== void 0) await performNavigate(withStorefrontFacets(collectionUrl, event.filters), "collection");
10683
+ return;
10684
+ }
10685
+ conciergeScrollRef.current?.();
10686
+ const target = event;
10687
+ let found = false;
10688
+ try {
10689
+ found = bridge?.spotlight?.(target) ?? (typeof window === "undefined" ? false : spotlightProductCard(window, window.document, target, { ...siteProfile ? { siteProfile } : {} }));
10690
+ } catch {}
10691
+ if (!found) {
10692
+ conciergeScrollRef.current?.(0);
10693
+ reportFailedSpotlight(event);
10694
+ }
10695
+ }, [
10696
+ bridge,
10697
+ bridgePath,
10698
+ siteProfile,
10699
+ performNavigate,
10700
+ reportFailedSpotlight
10701
+ ]);
10702
+ /**
10703
+ * The acts the concierge asked for, from both legs, performed exactly once
10704
+ * each and one at a time.
10705
+ *
10706
+ * Two sources (`session.actEvents` for the typed leg, `voice.widgetEvents`
10707
+ * for the spoken one), one consumption record, **consumed by object
10708
+ * IDENTITY**, marked consumed BEFORE they are performed — all of that is the
10709
+ * agent-cart-add effect's discipline and the reasons are the same there.
10710
+ * Identity matters MORE here: a shopper who says "that one again" produces a
10711
+ * second `spotlight` for the SAME product, and a consumer keyed on the
10712
+ * payload would silently swallow the repeat.
10713
+ *
10714
+ * ## Why a queue and a ref, rather than an async loop per run
10715
+ *
10716
+ * The effect used to depend on `performAct`, whose identity churns on every
10717
+ * render (`useChatSession` returns a fresh object, so every callback built
10718
+ * from `session` is new every frame). So the effect re-ran constantly, and
10719
+ * an event arriving while a previous act was still in flight started a
10720
+ * SECOND async loop beside the first: a `filter` and a `navigate` racing to
10721
+ * assign `location`, or two beats elapsing concurrently. The events were
10722
+ * still performed once each — identity saw to that — but "sequential" was
10723
+ * never true.
10724
+ *
10725
+ * Now the effect only ENQUEUES, and depends on nothing but the two lists. A
10726
+ * single drain runs at a time (`actDrainingRef`), reads the latest
10727
+ * `performAct` out of a ref at the moment it runs each event (so nothing is
10728
+ * performed with a stale `bridge` or a stale call state), and stops on
10729
+ * unmount — no `location.assign` and no `sendReport` after teardown.
10730
+ */
10731
+ const consumedActsRef = useRef(/* @__PURE__ */ new WeakSet());
10732
+ const actQueueRef = useRef([]);
10733
+ const actDrainingRef = useRef(false);
10734
+ const performActRef = useRef(performAct);
10735
+ useEffect(() => {
10736
+ performActRef.current = performAct;
10737
+ }, [performAct]);
10738
+ const voiceWidgetEventsForActs = voice.widgetEvents;
10739
+ const sessionActEvents = session.actEvents;
10740
+ useEffect(() => {
10741
+ for (const event of voiceWidgetEventsForActs) {
10742
+ if (!isActEvent(event)) continue;
10743
+ if (consumedActsRef.current.has(event)) continue;
10744
+ consumedActsRef.current.add(event);
10745
+ actQueueRef.current.push(event);
10746
+ }
10747
+ for (const event of sessionActEvents) {
10748
+ if (consumedActsRef.current.has(event)) continue;
10749
+ consumedActsRef.current.add(event);
10750
+ actQueueRef.current.push(event);
10751
+ }
10752
+ if (actDrainingRef.current || actQueueRef.current.length === 0) return;
10753
+ actDrainingRef.current = true;
10754
+ (async () => {
10755
+ try {
10756
+ for (;;) {
10757
+ if (!actLiveRef.current) break;
10758
+ const next = actQueueRef.current.shift();
10759
+ if (next === void 0) break;
10760
+ await performActRef.current(next);
10761
+ }
10762
+ } finally {
10763
+ actDrainingRef.current = false;
10764
+ }
10765
+ })();
10766
+ }, [voiceWidgetEventsForActs, sessionActEvents]);
9124
10767
  const consumedCartAddsRef = useRef(/* @__PURE__ */ new WeakSet());
9125
10768
  const voiceWidgetEvents = voice.widgetEvents;
9126
10769
  const sessionCartAdds = session.cartAdds;
@@ -9882,6 +11525,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9882
11525
  roomDropped: voiceEnabled && voice.phase === "disconnected",
9883
11526
  ...latestCuration ? { shelf: latestCuration } : {},
9884
11527
  pageKey,
11528
+ conciergeScrollRef,
9885
11529
  ...initialDraft !== void 0 ? { initialDraft } : {},
9886
11530
  ...initialSelection !== void 0 ? { initialSelection } : {},
9887
11531
  ...initialFocus !== void 0 ? { initialFocus } : {},
@@ -9922,4 +11566,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9922
11566
  });
9923
11567
  }
9924
11568
  //#endregion
9925
- export { SHEET_PEEK_MAX as $, Dock as A, srgbToLinear as At, DESKTOP_GUTTER as B, IDLE_SNAPSHOT as C, oklabToLinearRgb as Ct, SessionLog as D, parseHex as Dt, SESSION_EVENTS as E, oklchToOklab as Et, ACTIVITY_W as F, widgetMessagesFromCopy as Ft, PILL_H as G, DOCK_MINIMISED_STORAGE_KEY as H, BOTTOM_FLOOR as I, RADII as J, PILL_MARK as K, CONTROL as L, deriveDockState as M, defaultWidgetMessages as Mt, idleDockInput as N, formatMessage as Nt, formatMs as O, relativeLuminance as Ot, formatMoney as P, resolveWidgetMessages as Pt, SHEET_GAP as Q, DESKTOP_BOTTOM as R, parseBlocks as S, oklabToHex as St, SseFrameParser as T, oklchToHex as Tt, MARK as U, DESKTOP_WIDTHS as V, MOBILE_MARGIN as W, SHEET_EXPANDED_DESKTOP_MAX as X, ROW_H as Y, SHEET_EXPANDED_VH as Z, readsAsCheckoutIntent as _, hexToOklab as _t, mergeAddedCartLine as a, pillAnchor as at, WidgetCardList as b, linearToSrgb as bt, toChatCart as c, CARD_RADIUS_MAX_PX as ct, useVoiceSession as d, WIDGET_THEME_TOKENS as dt, SHEET_TOP_CLEARANCE as et, useChatSession as f, deriveTheme as ft, readsAsCartViewIntent as g, formatHex as gt, basketIntentFromTurns as h, contrastRatio as ht, deriveCallPhase as i, geometryVars as it, DOCK_STATES as j, withAlpha as jt, latencyBetween as k, rotateHue as kt, ROOM_EVENTS as l, SHEET_RADIUS_MAX_PX as lt, VoiceWidget as m, themeToInlineStyle as mt, MAX_REPORTED_CART_LINES as n, Z_INDEX as nt, resolveAddToCartHandler as o, rowWidthLen as ot, detectPage as p, themeToCss as pt, PROACTIVE_NUDGE_MS as q, cartLinesFromSnapshot as r, bottomLen as rt, resolveCheckoutUrl as s, sheetMaxHeightLen as st, ConciergeWidget as t, SHORT_VIEWPORT as tt, createWidgetVoiceTokenFetcher as u, SYSTEM_FONT_STACK as ut, textDirectionFor as v, hexToOklch as vt, botStateFor as w, oklabToOklch as wt, WidgetMarkdown as x, mixToward as xt, WidgetCartSummary as y, linearRgbToOklab as yt, DESKTOP_BREAKPOINT as z };
11569
+ export { RADII as $, latencyBetween as A, linearToSrgb as At, CONTROL as B, srgbToLinear as Bt, parseBlocks as C, themeToCss as Ct, SESSION_EVENTS as D, hexToOklab as Dt, SseFrameParser as E, formatHex as Et, idleDockInput as F, oklchToHex as Ft, DOCK_ALIGN_STORAGE_KEY as G, widgetMessagesFromCopy as Gt, DESKTOP_BREAKPOINT as H, defaultWidgetMessages as Ht, latestExchangeStart as I, oklchToOklab as It, MARK as J, DOCK_MINIMISED_STORAGE_KEY as K, formatMoney as L, parseHex as Lt, DOCK_STATES as M, oklabToHex as Mt, deriveDockState as N, oklabToLinearRgb as Nt, SessionLog as O, hexToOklch as Ot, exchangeCount as P, oklabToOklch as Pt, PROACTIVE_NUDGE_MS as Q, ACTIVITY_W as R, relativeLuminance as Rt, WidgetMarkdown as S, deriveTheme as St, botStateFor as T, contrastRatio as Tt, DESKTOP_GUTTER as U, formatMessage as Ut, DESKTOP_BOTTOM as V, withAlpha as Vt, DESKTOP_WIDTHS as W, resolveWidgetMessages as Wt, PILL_H as X, MOBILE_MARGIN as Y, PILL_MARK as Z, readsAsCartViewIntent as _, writeStored as _t, mergeAddedCartLine as a, SHEET_TOP_CLEARANCE as at, WidgetCartSummary as b, SYSTEM_FONT_STACK as bt, toChatCart as c, bottomLen as ct, useVoiceSession as d, pillAnchor as dt, ROW_H as et, isSameOriginPath as f, readStored as ft, basketIntentFromTurns as g, snapAlign as gt, VoiceWidget as h, sheetMaxHeightLen as ht, deriveCallPhase as i, SHEET_PEEK_MAX as it, Dock as j, mixToward as jt, formatMs as k, linearRgbToOklab as kt, ROOM_EVENTS as l, geometryVars as lt, detectPage as m, rowWidthLen as mt, MAX_REPORTED_CART_LINES as n, SHEET_EXPANDED_VH as nt, resolveAddToCartHandler as o, SHORT_VIEWPORT as ot, useChatSession as p, readStoredAlign as pt, DRAG_TAP_SLOP_PX as q, cartLinesFromSnapshot as r, SHEET_GAP as rt, resolveCheckoutUrl as s, Z_INDEX as st, ConciergeWidget as t, SHEET_EXPANDED_DESKTOP_MAX as tt, createWidgetVoiceTokenFetcher as u, persistAlign as ut, readsAsCheckoutIntent as v, CARD_RADIUS_MAX_PX as vt, IDLE_SNAPSHOT as w, themeToInlineStyle as wt, WidgetCardList as x, WIDGET_THEME_TOKENS as xt, textDirectionFor as y, SHEET_RADIUS_MAX_PX as yt, BOTTOM_FLOOR as z, rotateHue as zt };