@flamingo-stack/openframe-frontend-core 0.0.609 → 0.0.610-2115.5924.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/dist/chat-protocol/card-marker.d.ts +31 -0
  2. package/dist/chat-protocol/card-marker.d.ts.map +1 -0
  3. package/dist/chat-protocol/events.d.ts +21 -2
  4. package/dist/chat-protocol/events.d.ts.map +1 -1
  5. package/dist/chat-protocol/index.cjs +211 -9
  6. package/dist/chat-protocol/index.cjs.map +1 -1
  7. package/dist/chat-protocol/index.js +211 -9
  8. package/dist/chat-protocol/index.js.map +1 -1
  9. package/dist/chat-protocol/nats-decoder.d.ts.map +1 -1
  10. package/dist/chat-protocol/source-metadata.d.ts +56 -0
  11. package/dist/chat-protocol/source-metadata.d.ts.map +1 -0
  12. package/dist/{chunk-LA2W5L6K.js → chunk-25YIHMZ6.js} +2 -2
  13. package/dist/{chunk-6MLRFM3T.js → chunk-2QBXG74C.js} +5 -5
  14. package/dist/{chunk-3N4FXBVJ.cjs → chunk-2YMDDD5V.cjs} +3 -3
  15. package/dist/{chunk-3N4FXBVJ.cjs.map → chunk-2YMDDD5V.cjs.map} +1 -1
  16. package/dist/{chunk-JOCVQZGT.js → chunk-37CAZTLP.js} +5 -5
  17. package/dist/{chunk-D3DTC7SZ.cjs → chunk-C4KQ2XPK.cjs} +15 -15
  18. package/dist/{chunk-D3DTC7SZ.cjs.map → chunk-C4KQ2XPK.cjs.map} +1 -1
  19. package/dist/{chunk-CZTOSG7Q.cjs → chunk-EANAFFAD.cjs} +22 -22
  20. package/dist/{chunk-CZTOSG7Q.cjs.map → chunk-EANAFFAD.cjs.map} +1 -1
  21. package/dist/{chunk-BSMPCPOZ.js → chunk-F2C2U7CP.js} +590 -299
  22. package/dist/chunk-F2C2U7CP.js.map +1 -0
  23. package/dist/{chunk-O2M4T34Q.cjs → chunk-FASOANK7.cjs} +4 -4
  24. package/dist/{chunk-O2M4T34Q.cjs.map → chunk-FASOANK7.cjs.map} +1 -1
  25. package/dist/{chunk-JKM5FH63.js → chunk-FS3CTGIR.js} +3 -3
  26. package/dist/{chunk-45XXK2VU.cjs → chunk-GFAHCXIL.cjs} +10 -10
  27. package/dist/{chunk-45XXK2VU.cjs.map → chunk-GFAHCXIL.cjs.map} +1 -1
  28. package/dist/{chunk-SEW25Y2W.cjs → chunk-GNLV326I.cjs} +10 -10
  29. package/dist/{chunk-SEW25Y2W.cjs.map → chunk-GNLV326I.cjs.map} +1 -1
  30. package/dist/{chunk-DKNXAJMP.cjs → chunk-HKJ3WKGW.cjs} +159 -159
  31. package/dist/{chunk-DKNXAJMP.cjs.map → chunk-HKJ3WKGW.cjs.map} +1 -1
  32. package/dist/{chunk-HGVW7OHI.js → chunk-HQSCJYCF.js} +2 -2
  33. package/dist/{chunk-QX4ANESW.js → chunk-HZS4TV34.js} +6 -6
  34. package/dist/{chunk-B3UXNGVM.js → chunk-IBMHEOBV.js} +3 -3
  35. package/dist/{chunk-BUXGWBTF.js → chunk-MGXSJI23.js} +2 -2
  36. package/dist/{chunk-B7LYKBCD.js → chunk-O6PO5BHE.js} +5 -5
  37. package/dist/{chunk-C7CTEUU7.js → chunk-OIKZDXNW.js} +2 -2
  38. package/dist/{chunk-TJ3GFULR.js → chunk-OJZW3GE2.js} +3 -3
  39. package/dist/{chunk-L2JWC5VS.cjs → chunk-OVVKVIMH.cjs} +43 -43
  40. package/dist/{chunk-L2JWC5VS.cjs.map → chunk-OVVKVIMH.cjs.map} +1 -1
  41. package/dist/{chunk-VCYRJY7J.js → chunk-Q2CNCBMK.js} +4 -4
  42. package/dist/{chunk-NJUSDREV.cjs → chunk-Q3APHZK5.cjs} +22 -22
  43. package/dist/{chunk-NJUSDREV.cjs.map → chunk-Q3APHZK5.cjs.map} +1 -1
  44. package/dist/{chunk-TCEALWE3.cjs → chunk-QE2Z6WME.cjs} +33 -33
  45. package/dist/{chunk-TCEALWE3.cjs.map → chunk-QE2Z6WME.cjs.map} +1 -1
  46. package/dist/{chunk-OTYV6SDN.js → chunk-R2UDEMKK.js} +3 -3
  47. package/dist/{chunk-JR7I2AGL.js → chunk-ROOIHDLS.js} +3 -3
  48. package/dist/{chunk-3XNMDLGB.cjs → chunk-THCB7NHV.cjs} +9 -9
  49. package/dist/{chunk-3XNMDLGB.cjs.map → chunk-THCB7NHV.cjs.map} +1 -1
  50. package/dist/{chunk-GMOBT5NP.cjs → chunk-THCSSPXU.cjs} +70 -70
  51. package/dist/{chunk-GMOBT5NP.cjs.map → chunk-THCSSPXU.cjs.map} +1 -1
  52. package/dist/{chunk-FYG7QNAO.cjs → chunk-UFFVMZDL.cjs} +5 -5
  53. package/dist/{chunk-FYG7QNAO.cjs.map → chunk-UFFVMZDL.cjs.map} +1 -1
  54. package/dist/{chunk-MVBRMQGU.js → chunk-V6TINNLD.js} +2 -2
  55. package/dist/{chunk-ZRLFBLME.cjs → chunk-WJQOYSR3.cjs} +3 -3
  56. package/dist/{chunk-ZRLFBLME.cjs.map → chunk-WJQOYSR3.cjs.map} +1 -1
  57. package/dist/{chunk-XNDTYTVT.cjs → chunk-YXTAV2E3.cjs} +974 -683
  58. package/dist/chunk-YXTAV2E3.cjs.map +1 -0
  59. package/dist/{chunk-RZM6FPOT.cjs → chunk-ZDLCWNM6.cjs} +25 -25
  60. package/dist/{chunk-RZM6FPOT.cjs.map → chunk-ZDLCWNM6.cjs.map} +1 -1
  61. package/dist/components/case-studies/index.cjs +9 -9
  62. package/dist/components/case-studies/index.js +3 -3
  63. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  64. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  65. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  66. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +5 -28
  67. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  68. package/dist/components/chat/index.cjs +2 -2
  69. package/dist/components/chat/index.js +1 -1
  70. package/dist/components/chat/remark-card-links.d.ts +5 -4
  71. package/dist/components/chat/remark-card-links.d.ts.map +1 -1
  72. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +1 -1
  73. package/dist/components/chat/tool-execution-display.d.ts.map +1 -1
  74. package/dist/components/chat/types/component.types.d.ts +27 -0
  75. package/dist/components/chat/types/component.types.d.ts.map +1 -1
  76. package/dist/components/chat/types/message.types.d.ts +81 -1
  77. package/dist/components/chat/types/message.types.d.ts.map +1 -1
  78. package/dist/components/chat/types/unified-chat-state.types.d.ts +12 -3
  79. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  80. package/dist/components/chat/utils/cited-sources.d.ts +24 -0
  81. package/dist/components/chat/utils/cited-sources.d.ts.map +1 -0
  82. package/dist/components/chat/utils/host-message.d.ts +41 -0
  83. package/dist/components/chat/utils/host-message.d.ts.map +1 -0
  84. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  85. package/dist/components/contact/index.cjs +4 -4
  86. package/dist/components/contact/index.js +3 -3
  87. package/dist/components/docs/index.cjs +7 -7
  88. package/dist/components/docs/index.js +6 -6
  89. package/dist/components/embeds/index.cjs +4 -4
  90. package/dist/components/embeds/index.js +3 -3
  91. package/dist/components/faq/index.cjs +4 -4
  92. package/dist/components/faq/index.js +3 -3
  93. package/dist/components/features/index.cjs +3 -3
  94. package/dist/components/features/index.js +2 -2
  95. package/dist/components/help-center-pages/index.cjs +23 -23
  96. package/dist/components/help-center-pages/index.js +14 -14
  97. package/dist/components/index.cjs +38 -38
  98. package/dist/components/index.js +13 -13
  99. package/dist/components/meeting-scheduler/index.cjs +24 -24
  100. package/dist/components/meeting-scheduler/index.js +2 -2
  101. package/dist/components/navigation/index.cjs +6 -6
  102. package/dist/components/navigation/index.js +5 -5
  103. package/dist/components/onboarding-guides/index.cjs +6 -6
  104. package/dist/components/onboarding-guides/index.js +5 -5
  105. package/dist/components/tickets/index.cjs +7 -7
  106. package/dist/components/tickets/index.js +6 -6
  107. package/dist/components/ui/index.cjs +3 -3
  108. package/dist/components/ui/index.js +2 -2
  109. package/dist/index.cjs +7 -7
  110. package/dist/index.js +6 -6
  111. package/dist/utils/index.cjs.map +1 -1
  112. package/dist/utils/index.js.map +1 -1
  113. package/package.json +1 -1
  114. package/src/chat-protocol/__tests__/card-marker.test.ts +63 -0
  115. package/src/chat-protocol/__tests__/source-metadata.test.ts +243 -0
  116. package/src/chat-protocol/card-marker.ts +40 -0
  117. package/src/chat-protocol/events.ts +22 -1
  118. package/src/chat-protocol/nats-decoder.ts +12 -0
  119. package/src/chat-protocol/source-metadata.ts +336 -0
  120. package/src/components/chat/__tests__/tool-execution-display.test.tsx +70 -0
  121. package/src/components/chat/chat-message-enhanced.tsx +37 -12
  122. package/src/components/chat/chat-message-list.tsx +14 -1
  123. package/src/components/chat/embeddable-chat.tsx +47 -87
  124. package/src/components/chat/hooks/use-sse-chat-adapter.ts +5 -28
  125. package/src/components/chat/remark-card-links.ts +14 -12
  126. package/src/components/chat/stream/chat-stream-reducer.ts +48 -3
  127. package/src/components/chat/tool-execution-display.tsx +18 -4
  128. package/src/components/chat/types/component.types.ts +27 -0
  129. package/src/components/chat/types/message.types.ts +83 -0
  130. package/src/components/chat/types/unified-chat-state.types.ts +12 -3
  131. package/src/components/chat/utils/__tests__/cited-sources.test.ts +80 -0
  132. package/src/components/chat/utils/__tests__/host-message.test.ts +92 -0
  133. package/src/components/chat/utils/__tests__/process-historical-messages-sources.test.ts +138 -0
  134. package/src/components/chat/utils/cited-sources.ts +61 -0
  135. package/src/components/chat/utils/host-message.ts +87 -0
  136. package/src/components/chat/utils/process-historical-messages.ts +25 -0
  137. package/dist/chunk-BSMPCPOZ.js.map +0 -1
  138. package/dist/chunk-XNDTYTVT.cjs.map +0 -1
  139. /package/dist/{chunk-LA2W5L6K.js.map → chunk-25YIHMZ6.js.map} +0 -0
  140. /package/dist/{chunk-6MLRFM3T.js.map → chunk-2QBXG74C.js.map} +0 -0
  141. /package/dist/{chunk-JOCVQZGT.js.map → chunk-37CAZTLP.js.map} +0 -0
  142. /package/dist/{chunk-JKM5FH63.js.map → chunk-FS3CTGIR.js.map} +0 -0
  143. /package/dist/{chunk-HGVW7OHI.js.map → chunk-HQSCJYCF.js.map} +0 -0
  144. /package/dist/{chunk-QX4ANESW.js.map → chunk-HZS4TV34.js.map} +0 -0
  145. /package/dist/{chunk-B3UXNGVM.js.map → chunk-IBMHEOBV.js.map} +0 -0
  146. /package/dist/{chunk-BUXGWBTF.js.map → chunk-MGXSJI23.js.map} +0 -0
  147. /package/dist/{chunk-B7LYKBCD.js.map → chunk-O6PO5BHE.js.map} +0 -0
  148. /package/dist/{chunk-C7CTEUU7.js.map → chunk-OIKZDXNW.js.map} +0 -0
  149. /package/dist/{chunk-TJ3GFULR.js.map → chunk-OJZW3GE2.js.map} +0 -0
  150. /package/dist/{chunk-VCYRJY7J.js.map → chunk-Q2CNCBMK.js.map} +0 -0
  151. /package/dist/{chunk-OTYV6SDN.js.map → chunk-R2UDEMKK.js.map} +0 -0
  152. /package/dist/{chunk-JR7I2AGL.js.map → chunk-ROOIHDLS.js.map} +0 -0
  153. /package/dist/{chunk-MVBRMQGU.js.map → chunk-V6TINNLD.js.map} +0 -0
@@ -247,16 +247,16 @@ import {
247
247
  } from "@floating-ui/react";
248
248
  import { useMemo, useState } from "react";
249
249
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
250
- function parseColoredText(text) {
251
- if (typeof text !== "string") return text;
250
+ function parseColoredText(text2) {
251
+ if (typeof text2 !== "string") return text2;
252
252
  const parts = [];
253
253
  let lastIndex = 0;
254
254
  const colorRegex = /\[([A-Z]+)\](.*?)\[\/\1\]/g;
255
255
  let match;
256
256
  let keyIndex = 0;
257
- while ((match = colorRegex.exec(text)) !== null) {
257
+ while ((match = colorRegex.exec(text2)) !== null) {
258
258
  if (match.index > lastIndex) {
259
- const beforeText = text.slice(lastIndex, match.index);
259
+ const beforeText = text2.slice(lastIndex, match.index);
260
260
  parts.push(/* @__PURE__ */ jsx("span", { children: beforeText }, `text-${keyIndex++}`));
261
261
  }
262
262
  const color = match[1].toLowerCase();
@@ -267,11 +267,11 @@ function parseColoredText(text) {
267
267
  );
268
268
  lastIndex = match.index + match[0].length;
269
269
  }
270
- if (lastIndex < text.length) {
271
- const remainingText = text.slice(lastIndex);
270
+ if (lastIndex < text2.length) {
271
+ const remainingText = text2.slice(lastIndex);
272
272
  parts.push(/* @__PURE__ */ jsx("span", { children: remainingText }, `text-${keyIndex++}`));
273
273
  }
274
- return parts.length > 0 ? /* @__PURE__ */ jsx(Fragment, { children: parts }) : text;
274
+ return parts.length > 0 ? /* @__PURE__ */ jsx(Fragment, { children: parts }) : text2;
275
275
  }
276
276
  function FloatingTooltip({
277
277
  content,
@@ -1163,6 +1163,15 @@ var MESSAGE_TYPE = {
1163
1163
  TEXT: "TEXT",
1164
1164
  THINKING: "THINKING",
1165
1165
  ASK: "ASK",
1166
+ /** Per-answer source metadata (documents, videos, entity cards).
1167
+ *
1168
+ * TWO names for ONE payload, on purpose. `SOURCES` is the contract the
1169
+ * backend is moving to; `GUIDE` is the envelope it ships in today, reused
1170
+ * from Guide Mode v2 so a released frontend keeps working during the v2→v3
1171
+ * rollout. Both decode through the same path, so dropping `GUIDE` later is a
1172
+ * deletion here and nothing else. */
1173
+ GUIDE: "GUIDE",
1174
+ SOURCES: "SOURCES",
1166
1175
  EXECUTING_TOOL: "EXECUTING_TOOL",
1167
1176
  EXECUTED_TOOL: "EXECUTED_TOOL",
1168
1177
  APPROVAL_REQUEST: "APPROVAL_REQUEST",
@@ -1301,16 +1310,16 @@ function buildHeadingIdMap(content, sectionIds) {
1301
1310
  let sectionOrdinal = 0;
1302
1311
  let headingOrdinal = 0;
1303
1312
  for (const { line, level, text: rawText } of scanHeadings(content)) {
1304
- const text = stripInlineMarkdown(rawText).trim();
1313
+ const text2 = stripInlineMarkdown(rawText).trim();
1305
1314
  headingOrdinal++;
1306
1315
  if (level <= EXTRACTOR_MAX_LEVEL) sectionOrdinal++;
1307
1316
  let assigned;
1308
1317
  if (sectionIds && level <= EXTRACTOR_MAX_LEVEL) {
1309
1318
  for (const variation of [
1310
- text,
1311
- text.toLowerCase(),
1312
- stripHeadingEmojis(text),
1313
- stripHeadingEmojis(text).toLowerCase()
1319
+ text2,
1320
+ text2.toLowerCase(),
1321
+ stripHeadingEmojis(text2),
1322
+ stripHeadingEmojis(text2).toLowerCase()
1314
1323
  ]) {
1315
1324
  const id = sectionIdMap.get(variation);
1316
1325
  if (id) {
@@ -1320,7 +1329,7 @@ function buildHeadingIdMap(content, sectionIds) {
1320
1329
  }
1321
1330
  }
1322
1331
  if (assigned === void 0) {
1323
- const baseId = slugifyHeadingText(text);
1332
+ const baseId = slugifyHeadingText(text2);
1324
1333
  assigned = dedupe(
1325
1334
  baseId || (level <= EXTRACTOR_MAX_LEVEL ? `section-${sectionOrdinal}` : `heading-${headingOrdinal}`)
1326
1335
  );
@@ -2311,8 +2320,8 @@ function findInlineCodeRanges(source) {
2311
2320
  }
2312
2321
  return ranges;
2313
2322
  }
2314
- function foldAsciiCase(text) {
2315
- return text.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
2323
+ function foldAsciiCase(text2) {
2324
+ return text2.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
2316
2325
  }
2317
2326
  function blankRanges(masked, ranges) {
2318
2327
  if (ranges.length === 0) return masked;
@@ -2554,13 +2563,13 @@ function footnoteLabelEnd(c, open) {
2554
2563
  }
2555
2564
  function blankUnreferencedFootnotes(masked, lines, folded) {
2556
2565
  if (masked.indexOf("[^") === -1) return masked;
2557
- const text = (line) => stripCr(masked.slice(line.contentStart, line.contentStart + line.content.length));
2566
+ const text2 = (line) => stripCr(masked.slice(line.contentStart, line.contentStart + line.content.length));
2558
2567
  const refMask = footnoteReferenceMask(masked, folded);
2559
2568
  const refText = (line) => stripCr(refMask.slice(line.contentStart, line.contentStart + line.content.length));
2560
2569
  const referenced = /* @__PURE__ */ new Set();
2561
2570
  const defAt = [];
2562
2571
  for (const line of lines) {
2563
- const c = text(line);
2572
+ const c = text2(line);
2564
2573
  let isDef = null;
2565
2574
  if (c.indexOf("[^") !== -1) {
2566
2575
  const open = FOOTNOTE_DEF_OPEN_RE.exec(c);
@@ -2589,13 +2598,13 @@ function blankUnreferencedFootnotes(masked, lines, folded) {
2589
2598
  for (let i = 0; i < lines.length; i++) {
2590
2599
  const at = defAt[i];
2591
2600
  if (at === null) continue;
2592
- const head = text(lines[i]);
2601
+ const head = text2(lines[i]);
2593
2602
  const end = footnoteLabelEnd(head, at);
2594
2603
  if (referenced.has(normalizeFootnoteLabel(head.slice(at + 2, end)))) continue;
2595
2604
  let j = i;
2596
2605
  let sawBlank = false;
2597
2606
  for (let k = i + 1; k < lines.length; k++) {
2598
- const c = text(lines[k]);
2607
+ const c = text2(lines[k]);
2599
2608
  if (isBlankLine(c)) {
2600
2609
  sawBlank = true;
2601
2610
  continue;
@@ -2778,9 +2787,9 @@ function spliceWindows(masked, edits) {
2778
2787
  if (edits.length === 0) return masked;
2779
2788
  const parts = [];
2780
2789
  let cursor = 0;
2781
- for (const [from, to, text] of edits) {
2790
+ for (const [from, to, text2] of edits) {
2782
2791
  if (from > cursor) parts.push(masked.slice(cursor, from));
2783
- parts.push(text);
2792
+ parts.push(text2);
2784
2793
  cursor = to;
2785
2794
  }
2786
2795
  parts.push(masked.slice(cursor));
@@ -2884,8 +2893,8 @@ function blankListItemCode(masked, lines, depth = 0) {
2884
2893
  flush();
2885
2894
  return spliceWindows(masked, edits);
2886
2895
  }
2887
- function buildCloserHaystack(text) {
2888
- const folded = foldAsciiCase(text);
2896
+ function buildCloserHaystack(text2) {
2897
+ const folded = foldAsciiCase(text2);
2889
2898
  const lines = toMaskLines(folded);
2890
2899
  let masked = blankRanges(folded, findInlineCodeRanges(folded));
2891
2900
  masked = blankFencedRegions(masked, lines);
@@ -3072,8 +3081,8 @@ function htmlBlockStartKind(line, inParagraph) {
3072
3081
  if (!inParagraph && HTML_BLOCK_START_7.test(line)) return 7;
3073
3082
  return null;
3074
3083
  }
3075
- function computeHtmlBlockRanges(text) {
3076
- if (text.indexOf("<") === -1) return [];
3084
+ function computeHtmlBlockRanges(text2) {
3085
+ if (text2.indexOf("<") === -1) return [];
3077
3086
  const ranges = [];
3078
3087
  const fences = createFenceTracker();
3079
3088
  let kind = null;
@@ -3083,7 +3092,7 @@ function computeHtmlBlockRanges(text) {
3083
3092
  let offset2 = 0;
3084
3093
  let listContentCol = 0;
3085
3094
  let openPrefixLen = 0;
3086
- for (const line of text.split("\n")) {
3095
+ for (const line of text2.split("\n")) {
3087
3096
  const lineStart = offset2;
3088
3097
  const lineEnd = offset2 + line.length;
3089
3098
  offset2 = lineEnd + 1;
@@ -3145,21 +3154,21 @@ function escapeLeftoverTagStarts(gap, lowerSource, gapOffset) {
3145
3154
  (m, slash, tag, at) => isMaskedBlank(lowerSource, gapOffset + at, gapOffset + at + m.length) ? m : `&lt;${slash}${tag}`
3146
3155
  );
3147
3156
  }
3148
- function escapeUnknownHtmlTags(text, allowedTags = SAFE_HTML_TAGS) {
3149
- if (!text || text.indexOf("<") === -1) return text;
3150
- const lowerSource = buildCloserHaystack(text);
3157
+ function escapeUnknownHtmlTags(text2, allowedTags = SAFE_HTML_TAGS) {
3158
+ if (!text2 || text2.indexOf("<") === -1) return text2;
3159
+ const lowerSource = buildCloserHaystack(text2);
3151
3160
  let htmlBlocks = null;
3152
3161
  const spanInsideHtmlBlock = (from, to) => {
3153
- htmlBlocks ?? (htmlBlocks = computeHtmlBlockRanges(text));
3162
+ htmlBlocks ?? (htmlBlocks = computeHtmlBlockRanges(text2));
3154
3163
  return htmlBlocks.some((r) => r.start < to && r.end > from);
3155
3164
  };
3156
3165
  const parts = [];
3157
3166
  let cursor = 0;
3158
3167
  PROTECTED_SPAN_RE.lastIndex = 0;
3159
3168
  let span;
3160
- while ((span = PROTECTED_SPAN_RE.exec(text)) !== null) {
3169
+ while ((span = PROTECTED_SPAN_RE.exec(text2)) !== null) {
3161
3170
  if (span.index > cursor) {
3162
- parts.push(escapeOutsideFences(text.slice(cursor, span.index), allowedTags, lowerSource, cursor));
3171
+ parts.push(escapeOutsideFences(text2.slice(cursor, span.index), allowedTags, lowerSource, cursor));
3163
3172
  }
3164
3173
  const isFence = span[1] !== void 0;
3165
3174
  const spanEnd = span.index + span[0].length;
@@ -3168,8 +3177,8 @@ function escapeUnknownHtmlTags(text, allowedTags = SAFE_HTML_TAGS) {
3168
3177
  );
3169
3178
  cursor = span.index + span[0].length;
3170
3179
  }
3171
- if (cursor < text.length) {
3172
- parts.push(escapeOutsideFences(text.slice(cursor), allowedTags, lowerSource, cursor));
3180
+ if (cursor < text2.length) {
3181
+ parts.push(escapeOutsideFences(text2.slice(cursor), allowedTags, lowerSource, cursor));
3173
3182
  }
3174
3183
  return parts.join("");
3175
3184
  }
@@ -3352,12 +3361,12 @@ function splitStreamingBlocks(content) {
3352
3361
  }
3353
3362
  let cursorLine = 1;
3354
3363
  return units.map((unitLines, idx) => {
3355
- const text = unitLines.join("\n");
3364
+ const text2 = unitLines.join("\n");
3356
3365
  const isTail = idx === units.length - 1;
3357
3366
  const startLine = cursorLine;
3358
3367
  cursorLine += unitLines.length;
3359
3368
  return {
3360
- text,
3369
+ text: text2,
3361
3370
  index: idx,
3362
3371
  startLine,
3363
3372
  // Units carrying UNBALANCED raw HTML are never cached: an open
@@ -3367,7 +3376,7 @@ function splitStreamingBlocks(content) {
3367
3376
  // opens AND closes within the unit (`<div>x</div>`) leaves the
3368
3377
  // scanner's depth unchanged, so it stays memoizable — correctly: its
3369
3378
  // parse cannot be invalidated by later tokens.
3370
- memoizable: !isTail && !unitTouchedHtml[idx] && !NON_MEMOIZABLE_RE.test(text)
3379
+ memoizable: !isTail && !unitTouchedHtml[idx] && !NON_MEMOIZABLE_RE.test(text2)
3371
3380
  };
3372
3381
  });
3373
3382
  }
@@ -3456,7 +3465,7 @@ function resolveTextSizeConfig(config) {
3456
3465
  import { jsx as jsx14 } from "react/jsx-runtime";
3457
3466
  var NO_BROKEN_LINKS = [];
3458
3467
  var StreamingBlockRenderer = memo(function StreamingBlockRendererImpl({
3459
- text,
3468
+ text: text2,
3460
3469
  remarkPlugins,
3461
3470
  rehypePlugins,
3462
3471
  components
@@ -3468,7 +3477,7 @@ var StreamingBlockRenderer = memo(function StreamingBlockRendererImpl({
3468
3477
  rehypePlugins,
3469
3478
  urlTransform: cardAwareUrlTransform,
3470
3479
  components,
3471
- children: text
3480
+ children: text2
3472
3481
  }
3473
3482
  );
3474
3483
  });
@@ -3616,7 +3625,7 @@ var thoughtMdClasses = [
3616
3625
  "[&_.code-block-container_>div:last-child]:!p-3"
3617
3626
  ].join(" ");
3618
3627
  var ThinkingDisplay = forwardRef8(
3619
- ({ className, text, isStreaming = false, ...props }, ref) => {
3628
+ ({ className, text: text2, isStreaming = false, ...props }, ref) => {
3620
3629
  const [expanded, setExpanded] = useState7(false);
3621
3630
  const { innerRef, isOverflowing, containerStyle } = useCollapsible({
3622
3631
  expanded,
@@ -3650,7 +3659,7 @@ var ThinkingDisplay = forwardRef8(
3650
3659
  ] }),
3651
3660
  isStreaming && /* @__PURE__ */ jsx15(DotsLoaderIcon, { size: 16, className: "text-ods-text-secondary" })
3652
3661
  ] }),
3653
- /* @__PURE__ */ jsx15("div", { className: "min-w-0 flex-1", style: containerStyle, children: /* @__PURE__ */ jsx15("div", { ref: innerRef, className: cn("text-sm leading-snug text-ods-text-secondary", thoughtMdClasses), children: /* @__PURE__ */ jsx15(SimpleMarkdownRenderer, { content: text, textSize: "compact" }) }) }),
3662
+ /* @__PURE__ */ jsx15("div", { className: "min-w-0 flex-1", style: containerStyle, children: /* @__PURE__ */ jsx15("div", { ref: innerRef, className: cn("text-sm leading-snug text-ods-text-secondary", thoughtMdClasses), children: /* @__PURE__ */ jsx15(SimpleMarkdownRenderer, { content: text2, textSize: "compact" }) }) }),
3654
3663
  canToggle && /* @__PURE__ */ jsx15("div", { className: "flex h-[19px] shrink-0 items-center", children: /* @__PURE__ */ jsx15(ExpandChevron, { expanded }) })
3655
3664
  ]
3656
3665
  }
@@ -3663,15 +3672,15 @@ ThinkingDisplay.displayName = "ThinkingDisplay";
3663
3672
  import { forwardRef as forwardRef9, useEffect as useEffect2, useId, useState as useState8 } from "react";
3664
3673
  import { Fragment as Fragment3, jsx as jsx16, jsxs as jsxs11 } from "react/jsx-runtime";
3665
3674
  var LOCKED_HINT = "This question was already answered";
3666
- var AskDisplay = forwardRef9(({ className, cards, onSelect, ...props }, ref) => {
3675
+ var AskDisplay = forwardRef9(({ className, cards: cards2, onSelect, ...props }, ref) => {
3667
3676
  const [index, setIndex] = useState8(0);
3668
3677
  const lockedHintId = useId();
3669
3678
  useEffect2(() => {
3670
- setIndex((current) => current < cards.length ? current : Math.max(0, cards.length - 1));
3671
- }, [cards.length]);
3672
- const active = cards[Math.min(index, cards.length - 1)];
3679
+ setIndex((current) => current < cards2.length ? current : Math.max(0, cards2.length - 1));
3680
+ }, [cards2.length]);
3681
+ const active = cards2[Math.min(index, cards2.length - 1)];
3673
3682
  if (!active) return null;
3674
- const showPager = cards.length > 1;
3683
+ const showPager = cards2.length > 1;
3675
3684
  const isInteractive = !!onSelect;
3676
3685
  return /* @__PURE__ */ jsxs11(
3677
3686
  "div",
@@ -3703,15 +3712,15 @@ var AskDisplay = forwardRef9(({ className, cards, onSelect, ...props }, ref) =>
3703
3712
  /* @__PURE__ */ jsxs11("span", { className: "whitespace-nowrap text-ods-text-secondary text-h6", children: [
3704
3713
  index + 1,
3705
3714
  " of ",
3706
- cards.length
3715
+ cards2.length
3707
3716
  ] }),
3708
3717
  /* @__PURE__ */ jsx16(
3709
3718
  "button",
3710
3719
  {
3711
3720
  type: "button",
3712
3721
  "aria-label": "Next question",
3713
- disabled: index === cards.length - 1,
3714
- onClick: () => setIndex((current) => Math.min(cards.length - 1, current + 1)),
3722
+ disabled: index === cards2.length - 1,
3723
+ onClick: () => setIndex((current) => Math.min(cards2.length - 1, current + 1)),
3715
3724
  className: "text-ods-text-secondary transition-colors hover:text-ods-text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:text-ods-text-secondary",
3716
3725
  children: /* @__PURE__ */ jsx16(Chevron02RightIcon, { size: 16 })
3717
3726
  }
@@ -5778,12 +5787,12 @@ function placeCaretAtOffset(el, offset2) {
5778
5787
  sel.removeAllRanges();
5779
5788
  sel.addRange(range);
5780
5789
  }
5781
- function insertTextAtCaret(text) {
5790
+ function insertTextAtCaret(text2) {
5782
5791
  const sel = typeof window !== "undefined" ? window.getSelection() : null;
5783
5792
  if (!sel || sel.rangeCount === 0) return;
5784
5793
  const range = sel.getRangeAt(0);
5785
5794
  range.deleteContents();
5786
- const tn = document.createTextNode(text);
5795
+ const tn = document.createTextNode(text2);
5787
5796
  range.insertNode(tn);
5788
5797
  range.setStartAfter(tn);
5789
5798
  range.collapse(true);
@@ -5985,9 +5994,9 @@ var ChatInput = forwardRef14((allProps, ref) => {
5985
5994
  const handlePaste = useCallback2(
5986
5995
  (e) => {
5987
5996
  e.preventDefault();
5988
- const text = e.clipboardData.getData("text/plain");
5989
- if (!text) return;
5990
- insertTextAtCaret(text);
5997
+ const text2 = e.clipboardData.getData("text/plain");
5998
+ if (!text2) return;
5999
+ insertTextAtCaret(text2);
5991
6000
  syncFromDom();
5992
6001
  },
5993
6002
  [syncFromDom]
@@ -6244,6 +6253,14 @@ ChatInput.displayName = "ChatInput";
6244
6253
  // src/components/chat/chat-message-enhanced.tsx
6245
6254
  import React2, { forwardRef as forwardRef16, memo as memo2, useEffect as useEffect6, useMemo as useMemo8, useRef as useRef4 } from "react";
6246
6255
 
6256
+ // src/chat-protocol/card-marker.ts
6257
+ var CARD_TYPE = "[a-zA-Z0-9_-]+";
6258
+ var CARD_ID = "[^\\]\\r\\n)]+";
6259
+ var CARD_REFERENCE = new RegExp(`^\\[card://(${CARD_TYPE}):(${CARD_ID})\\]$`);
6260
+ function createCardMarkerScanner() {
6261
+ return new RegExp(`\\[card://(${CARD_TYPE}):(${CARD_ID})[\\])]`, "g");
6262
+ }
6263
+
6247
6264
  // src/utils/date-utils.ts
6248
6265
  function formatTicketRelativeTime(iso) {
6249
6266
  const now = /* @__PURE__ */ new Date();
@@ -6797,21 +6814,21 @@ function BlockCard(_props) {
6797
6814
 
6798
6815
  // src/components/chat/remark-card-links.ts
6799
6816
  import { visit, SKIP } from "unist-util-visit";
6800
- var CARD_REGEX = /\[card:\/\/([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)[\])]/g;
6817
+ var CARD_REGEX = createCardMarkerScanner();
6801
6818
  var remarkCardLinks = () => {
6802
6819
  return (tree) => {
6803
6820
  visit(tree, "text", (node, index, parent) => {
6804
6821
  if (!parent || typeof index !== "number") return void 0;
6805
- const text = node.value;
6806
- if (!text || !text.includes("[card://")) return void 0;
6822
+ const text2 = node.value;
6823
+ if (!text2 || !text2.includes("[card://")) return void 0;
6807
6824
  const parts = [];
6808
6825
  let lastIndex = 0;
6809
6826
  CARD_REGEX.lastIndex = 0;
6810
6827
  let match;
6811
- while ((match = CARD_REGEX.exec(text)) !== null) {
6828
+ while ((match = CARD_REGEX.exec(text2)) !== null) {
6812
6829
  const matchStart = match.index;
6813
6830
  if (matchStart > lastIndex) {
6814
- parts.push({ type: "text", value: text.slice(lastIndex, matchStart) });
6831
+ parts.push({ type: "text", value: text2.slice(lastIndex, matchStart) });
6815
6832
  }
6816
6833
  const cardType = match[1];
6817
6834
  const cardId = match[2];
@@ -6826,8 +6843,8 @@ var remarkCardLinks = () => {
6826
6843
  lastIndex = matchStart + match[0].length;
6827
6844
  }
6828
6845
  if (lastIndex === 0) return void 0;
6829
- if (lastIndex < text.length) {
6830
- parts.push({ type: "text", value: text.slice(lastIndex) });
6846
+ if (lastIndex < text2.length) {
6847
+ parts.push({ type: "text", value: text2.slice(lastIndex) });
6831
6848
  }
6832
6849
  parent.children.splice(index, 1, ...parts);
6833
6850
  return [SKIP, index + parts.length];
@@ -6842,19 +6859,19 @@ var remarkMentionChips = () => {
6842
6859
  return (tree) => {
6843
6860
  visit2(tree, "text", (node, index, parent) => {
6844
6861
  if (!parent || typeof index !== "number") return void 0;
6845
- const text = node.value;
6846
- if (!text || !text.includes("@")) return void 0;
6862
+ const text2 = node.value;
6863
+ if (!text2 || !text2.includes("@")) return void 0;
6847
6864
  const parts = [];
6848
6865
  let lastIndex = 0;
6849
6866
  MENTION_REGEX.lastIndex = 0;
6850
6867
  let match;
6851
- while ((match = MENTION_REGEX.exec(text)) !== null) {
6868
+ while ((match = MENTION_REGEX.exec(text2)) !== null) {
6852
6869
  const lead = match[1];
6853
6870
  const marker = match[2];
6854
6871
  const id = match[3];
6855
6872
  const tokenStart = match.index + lead.length;
6856
6873
  if (tokenStart > lastIndex) {
6857
- parts.push({ type: "text", value: text.slice(lastIndex, tokenStart) });
6874
+ parts.push({ type: "text", value: text2.slice(lastIndex, tokenStart) });
6858
6875
  }
6859
6876
  parts.push({
6860
6877
  type: "link",
@@ -6866,8 +6883,8 @@ var remarkMentionChips = () => {
6866
6883
  lastIndex = match.index + match[0].length;
6867
6884
  }
6868
6885
  if (lastIndex === 0) return void 0;
6869
- if (lastIndex < text.length) {
6870
- parts.push({ type: "text", value: text.slice(lastIndex) });
6886
+ if (lastIndex < text2.length) {
6887
+ parts.push({ type: "text", value: text2.slice(lastIndex) });
6871
6888
  }
6872
6889
  parent.children.splice(index, 1, ...parts);
6873
6890
  return [SKIP2, index + parts.length];
@@ -6919,6 +6936,8 @@ var ToolExecutionDisplay = forwardRef15(
6919
6936
  return [...commandEntries, ...otherEntries];
6920
6937
  }, [message.parameters, variant]);
6921
6938
  const hasResult = isExecuted && typeof message.result === "string" && message.result.length > 0;
6939
+ const isConciseRemoteRead = !message.integratedToolType && !!previewText && argEntries.length === 0 && !hasResult;
6940
+ const isStaticRow = isClientView || isConciseRemoteRead;
6922
6941
  const hasBody = argEntries.length > 0 || hasResult || isExecuting;
6923
6942
  const renderStatusIcon = () => {
6924
6943
  if (isExecuting) return /* @__PURE__ */ jsx34(DotsLoaderIcon, { size: 16, className: "text-ods-text-secondary" });
@@ -6939,7 +6958,7 @@ var ToolExecutionDisplay = forwardRef15(
6939
6958
  }
6940
6959
  ),
6941
6960
  /* @__PURE__ */ jsx34("div", { className: "flex h-5 w-5 shrink-0 items-center justify-center", children: renderStatusIcon() }),
6942
- !isClientView && /* @__PURE__ */ jsx34("div", { className: "flex h-5 w-5 shrink-0 items-center justify-center", children: /* @__PURE__ */ jsx34(ExpandChevron, { expanded }) })
6961
+ !isStaticRow && /* @__PURE__ */ jsx34("div", { className: "flex h-5 w-5 shrink-0 items-center justify-center", children: /* @__PURE__ */ jsx34(ExpandChevron, { expanded }) })
6943
6962
  ] });
6944
6963
  return /* @__PURE__ */ jsx34(
6945
6964
  "div",
@@ -6952,9 +6971,10 @@ var ToolExecutionDisplay = forwardRef15(
6952
6971
  className
6953
6972
  ),
6954
6973
  ...props,
6955
- children: isClientView ? (
6956
- // Client (Fae end-user): static, non-expandable row — no chevron, no
6957
- // body. Just the explanation + status; command/args/result are hidden.
6974
+ children: isStaticRow ? (
6975
+ // Static, non-expandable row — no chevron, no body. Two cases reach
6976
+ // here: the Fae end-user view (command/args/result are admin-only
6977
+ // detail) and a remote read-only tool (there IS no detail).
6958
6978
  /* @__PURE__ */ jsx34("div", { className: "flex w-full items-start gap-[var(--spacing-system-xs)] p-[var(--spacing-system-s)] text-left", children: headerContent })
6959
6979
  ) : /* @__PURE__ */ jsxs24(Fragment9, { children: [
6960
6980
  /* @__PURE__ */ jsx34(
@@ -6999,7 +7019,7 @@ ToolExecutionDisplay.displayName = "ToolExecutionDisplay";
6999
7019
  // src/components/chat/chat-message-enhanced.tsx
7000
7020
  import { Fragment as Fragment10, jsx as jsx35, jsxs as jsxs25 } from "react/jsx-runtime";
7001
7021
  var MENTION_MARKER_REGEX = /(^|[^\w@])@[a-zA-Z]+:([A-Za-z0-9_.+/=-]*[A-Za-z0-9_+/=])/g;
7002
- var CARD_MARKER_REGEX = /\[card:\/\/([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)[\])]/g;
7022
+ var CARD_MARKER_REGEX = createCardMarkerScanner();
7003
7023
  function formatMessageTimestamp(timestamp) {
7004
7024
  const time = formatTime(timestamp);
7005
7025
  return isToday(timestamp) ? time : `${formatDate(timestamp)} ${time}`;
@@ -7046,6 +7066,7 @@ var ChatMessageEnhanced = forwardRef16(
7046
7066
  renderContextItem,
7047
7067
  renderMention,
7048
7068
  renderEntityCard,
7069
+ refs,
7049
7070
  onAskSelect,
7050
7071
  NavLinkAnchor,
7051
7072
  ...props
@@ -7080,6 +7101,11 @@ var ChatMessageEnhanced = forwardRef16(
7080
7101
  const renderedCardNodeCache = useRef4(
7081
7102
  /* @__PURE__ */ new Map()
7082
7103
  );
7104
+ const refByKey = useMemo8(() => {
7105
+ const byKey = /* @__PURE__ */ new Map();
7106
+ for (const described of refs ?? []) byKey.set(`${described.type}:${described.id}`, described);
7107
+ return byKey;
7108
+ }, [refs]);
7083
7109
  const renderingPlan = useMemo8(() => {
7084
7110
  if (!hasMarkerSupport) return null;
7085
7111
  const render = renderEntityCard;
@@ -7091,32 +7117,33 @@ var ChatMessageEnhanced = forwardRef16(
7091
7117
  const emittedBlockKeys = /* @__PURE__ */ new Set();
7092
7118
  segments.forEach((segment, segIdx) => {
7093
7119
  if (segment.type !== "text") return;
7094
- const text = segment.text;
7120
+ const text2 = segment.text;
7095
7121
  const parts = [];
7096
7122
  let cursor = 0;
7097
7123
  CARD_MARKER_REGEX.lastIndex = 0;
7098
7124
  let match;
7099
- while ((match = CARD_MARKER_REGEX.exec(text)) !== null) {
7125
+ while ((match = CARD_MARKER_REGEX.exec(text2)) !== null) {
7100
7126
  const cardType = match[1];
7101
7127
  const cardId = match[2];
7102
7128
  const key = `${cardType}:${cardId}`;
7103
7129
  usedKeys.add(key);
7130
+ const describedRef = refByKey.get(key);
7104
7131
  let entry = cache.get(key);
7105
- if (!entry || entry.render !== render) {
7106
- const refForRender = {
7132
+ if (!entry || entry.render !== render || entry.ref !== describedRef) {
7133
+ const refForRender = describedRef ?? {
7107
7134
  type: cardType,
7108
7135
  id: cardId,
7109
7136
  title: cardId,
7110
7137
  url: null
7111
7138
  };
7112
- entry = { render, node: render(refForRender) };
7139
+ entry = { render, ref: describedRef, node: render(refForRender) };
7113
7140
  cache.set(key, entry);
7114
7141
  }
7115
7142
  const rendered = entry.node;
7116
7143
  if (React2.isValidElement(rendered) && rendered.type === BlockCard) {
7117
7144
  const cardProps = rendered.props;
7118
7145
  const markerEnd = match.index + match[0].length;
7119
- parts.push({ kind: "text", text: text.slice(cursor, markerEnd) });
7146
+ parts.push({ kind: "text", text: text2.slice(cursor, markerEnd) });
7120
7147
  if (!emittedBlockKeys.has(key)) {
7121
7148
  emittedBlockKeys.add(key);
7122
7149
  parts.push({ kind: "block", key, node: cardProps.children });
@@ -7127,7 +7154,7 @@ var ChatMessageEnhanced = forwardRef16(
7127
7154
  cardProps.inline != null ? cardProps.inline : /* @__PURE__ */ jsx35("span", { className: "font-medium text-ods-text-primary", children: cardId })
7128
7155
  );
7129
7156
  } else if (rendered != null) {
7130
- parts.push({ kind: "text", text: text.slice(cursor, match.index) });
7157
+ parts.push({ kind: "text", text: text2.slice(cursor, match.index) });
7131
7158
  if (!emittedBlockKeys.has(key)) {
7132
7159
  emittedBlockKeys.add(key);
7133
7160
  parts.push({ kind: "block", key, node: rendered });
@@ -7135,15 +7162,15 @@ var ChatMessageEnhanced = forwardRef16(
7135
7162
  cursor = match.index + match[0].length;
7136
7163
  }
7137
7164
  }
7138
- if (cursor < text.length) {
7139
- parts.push({ kind: "text", text: text.slice(cursor) });
7165
+ if (cursor < text2.length) {
7166
+ parts.push({ kind: "text", text: text2.slice(cursor) });
7140
7167
  }
7141
7168
  if (parts.some((p) => p.kind === "block")) {
7142
7169
  partsBySegment.set(segIdx, parts);
7143
7170
  }
7144
7171
  });
7145
7172
  return { inlineByKey, partsBySegment, usedKeys };
7146
- }, [hasMarkerSupport, renderEntityCard, segments]);
7173
+ }, [hasMarkerSupport, renderEntityCard, refByKey, segments]);
7147
7174
  useEffect6(() => {
7148
7175
  const cache = renderedCardNodeCache.current;
7149
7176
  const usedKeys = renderingPlan?.usedKeys;
@@ -7192,13 +7219,13 @@ var ChatMessageEnhanced = forwardRef16(
7192
7219
  }
7193
7220
  };
7194
7221
  }, [hasMarkerSupport, hasMentionSupport, renderMention, NavLinkAnchor]);
7195
- const renderSegmentBody = (segIndex, text, isStreaming) => {
7222
+ const renderSegmentBody = (segIndex, text2, isStreaming) => {
7196
7223
  const parts = renderingPlan?.partsBySegment.get(segIndex);
7197
7224
  if (!parts || parts.length === 0) {
7198
7225
  return /* @__PURE__ */ jsx35(
7199
7226
  SimpleMarkdownRenderer,
7200
7227
  {
7201
- content: text,
7228
+ content: text2,
7202
7229
  textSize: "compact",
7203
7230
  additionalRemarkPlugins: cardRemarkPlugins,
7204
7231
  componentOverrides: cardComponentOverrides,
@@ -7370,7 +7397,9 @@ var MemoizedChatMessageEnhanced = memo2(ChatMessageEnhanced, (prevProps, nextPro
7370
7397
  // message (it's set once on the optimistic send and never mutated).
7371
7398
  prevProps.contextItems === nextProps.contextItems && prevProps.resolveContextIcon === nextProps.resolveContextIcon && prevProps.renderContextItem === nextProps.renderContextItem && // Host keeps this stable (module const / useCallback), so reference
7372
7399
  // equality holds across streaming chunks.
7373
- prevProps.renderMention === nextProps.renderMention && prevProps.renderEntityCard === nextProps.renderEntityCard && // Same stability contract as the renderers above: hosts pass a `useCallback`
7400
+ prevProps.renderMention === nextProps.renderMention && prevProps.renderEntityCard === nextProps.renderEntityCard && // Reference equality: the reducer sets this once per answer and the host
7401
+ // forwards the same array instance, so it holds across streaming chunks.
7402
+ prevProps.refs === nextProps.refs && // Same stability contract as the renderers above: hosts pass a `useCallback`
7374
7403
  // (EmbeddableChat passes its memoized `handleSend`), so this holds across
7375
7404
  // streaming chunks instead of re-rendering every ask card per chunk.
7376
7405
  prevProps.onAskSelect === nextProps.onAskSelect && prevProps.NavLinkAnchor === nextProps.NavLinkAnchor;
@@ -7467,11 +7496,11 @@ var BLINK_KEYFRAMES = `
7467
7496
  `;
7468
7497
  function CyclingPhrase({ words, className, charMs = 60, holdMs = 4500 }) {
7469
7498
  const [wordIndex, setWordIndex] = useState13(0);
7470
- const [text, setText] = useState13("");
7499
+ const [text2, setText] = useState13("");
7471
7500
  const [cursor, setCursor] = useState13(0);
7472
7501
  const target = words[wordIndex] ?? "";
7473
- const holding = words.length > 0 && cursor >= Math.max(text.length, target.length);
7474
- const shownText = holding ? target : text;
7502
+ const holding = words.length > 0 && cursor >= Math.max(text2.length, target.length);
7503
+ const shownText = holding ? target : text2;
7475
7504
  const placeholder = useMemo9(
7476
7505
  () => words.reduce((longest, w) => w.length > longest.length ? w : longest, ""),
7477
7506
  [words]
@@ -7497,7 +7526,7 @@ function CyclingPhrase({ words, className, charMs = 60, holdMs = 4500 }) {
7497
7526
  setCursor((c) => c + 1);
7498
7527
  }, charMs);
7499
7528
  return () => clearTimeout(timeoutId);
7500
- }, [wordIndex, cursor, text, holding, target, words, charMs, holdMs]);
7529
+ }, [wordIndex, cursor, text2, holding, target, words, charMs, holdMs]);
7501
7530
  if (words.length === 0) return null;
7502
7531
  const before = shownText.slice(0, cursor);
7503
7532
  const after = shownText.slice(cursor);
@@ -7581,6 +7610,7 @@ var ChatMessageList = forwardRef17(
7581
7610
  resolveContextIcon,
7582
7611
  renderContextItem,
7583
7612
  renderMention,
7613
+ renderAfterMessage,
7584
7614
  onAskSelect,
7585
7615
  NavLinkAnchor,
7586
7616
  ...props
@@ -7938,7 +7968,8 @@ var ChatMessageList = forwardRef17(
7938
7968
  if (message.hidden) return null;
7939
7969
  const isEmptyPendingTurn = index === messages.length - 1 && isTyping && message.role === "assistant" && !hasNonEmptyContent(message.content) && (!Array.isArray(message.content) || message.content.every((s) => s.type === "text"));
7940
7970
  if (isEmptyPendingTurn) return null;
7941
- return /* @__PURE__ */ jsx38(
7971
+ const ownedContent = renderAfterMessage?.(message, index);
7972
+ const row = /* @__PURE__ */ jsx38(
7942
7973
  MemoizedChatMessageEnhanced,
7943
7974
  {
7944
7975
  ref: getRegisterMessageEl(message.id),
@@ -7958,11 +7989,17 @@ var ChatMessageList = forwardRef17(
7958
7989
  renderContextItem,
7959
7990
  renderMention,
7960
7991
  renderEntityCard,
7992
+ refs: message.refs,
7961
7993
  onAskSelect: index > lastUserMessageIndex ? onAskSelect : void 0,
7962
7994
  NavLinkAnchor
7963
7995
  },
7964
7996
  message.id
7965
7997
  );
7998
+ if (!ownedContent) return row;
7999
+ return /* @__PURE__ */ jsxs28("div", { className: "flex w-full min-w-0 flex-col", children: [
8000
+ row,
8001
+ ownedContent
8002
+ ] }, message.id);
7966
8003
  })
7967
8004
  ]
7968
8005
  }
@@ -10557,8 +10594,8 @@ var ANTHROPIC_SUPPORTED_IMAGE_MIME = ["image/jpeg", "image/png", "image/webp", "
10557
10594
  function buildChatAttachmentViewUrl(viewUrlPrefix, storagePath, viewToken) {
10558
10595
  return `${viewUrlPrefix}${storagePath}?${CHAT_ATTACHMENT_VIEW_TOKEN_QUERY_PARAM}=${encodeURIComponent(viewToken)}`;
10559
10596
  }
10560
- function escapeMarkdownInline(text) {
10561
- return text.replace(/[[\]()\\\n\r<>"]/g, (ch) => {
10597
+ function escapeMarkdownInline(text2) {
10598
+ return text2.replace(/[[\]()\\\n\r<>"]/g, (ch) => {
10562
10599
  switch (ch) {
10563
10600
  case "\n":
10564
10601
  return " ";
@@ -10587,10 +10624,10 @@ var CHAT_ATTACHMENT_MARKDOWN_PATTERN = new RegExp(
10587
10624
  `^\\s*!?\\[[^\\]]*\\]\\(${CHAT_ATTACHMENT_VIEW_URL_PREFIX_REGEX_ESCAPED}[^)]+\\)\\s*$`,
10588
10625
  "gm"
10589
10626
  );
10590
- function stripChatAttachmentMarkdown(text) {
10627
+ function stripChatAttachmentMarkdown(text2) {
10591
10628
  const storagePaths = [];
10592
10629
  const pathExtract = new RegExp(`\\(${CHAT_ATTACHMENT_VIEW_URL_PREFIX_REGEX_ESCAPED}([^?)]+)`);
10593
- const stripped = text.replace(CHAT_ATTACHMENT_MARKDOWN_PATTERN, (match) => {
10630
+ const stripped = text2.replace(CHAT_ATTACHMENT_MARKDOWN_PATTERN, (match) => {
10594
10631
  const m = match.match(pathExtract);
10595
10632
  if (m && m[1]) storagePaths.push(m[1]);
10596
10633
  return "";
@@ -16065,11 +16102,11 @@ function makeSeqKey(messageType, chunkType, sequenceId) {
16065
16102
  function makeBatchDedupKey(item) {
16066
16103
  const seq = item.chunk.sequenceId ?? "na";
16067
16104
  const type = typeof item.chunk.type === "string" ? item.chunk.type : "na";
16068
- const text = typeof item.chunk.text === "string" ? item.chunk.text : "";
16105
+ const text2 = typeof item.chunk.text === "string" ? item.chunk.text : "";
16069
16106
  const integratedToolType = typeof item.chunk.integratedToolType === "string" ? item.chunk.integratedToolType : "";
16070
16107
  const toolFunction = typeof item.chunk.toolFunction === "string" ? item.chunk.toolFunction : "";
16071
16108
  const approvalRequestId = typeof item.chunk.approvalRequestId === "string" ? item.chunk.approvalRequestId : typeof item.chunk.approval_request_id === "string" ? item.chunk.approval_request_id : "";
16072
- return `${item.messageType}:${seq}:${type}:${text}:${integratedToolType}:${toolFunction}:${approvalRequestId}`;
16109
+ return `${item.messageType}:${seq}:${type}:${text2}:${integratedToolType}:${toolFunction}:${approvalRequestId}`;
16073
16110
  }
16074
16111
  function getChatTypeMessageType(chatType) {
16075
16112
  return chatType === CHAT_TYPE.ADMIN ? "admin-message" : "message";
@@ -17583,12 +17620,12 @@ function useChat({
17583
17620
  });
17584
17621
  }, []);
17585
17622
  const sendMessage = useCallback18(
17586
- async (text, extra, options) => {
17623
+ async (text2, extra, options) => {
17587
17624
  const userMessage = {
17588
17625
  id: `user-${Date.now()}`,
17589
17626
  role: "user",
17590
17627
  name: "You",
17591
- content: text,
17628
+ content: text2,
17592
17629
  timestamp: /* @__PURE__ */ new Date(),
17593
17630
  ...options?.hidden ? { hidden: true } : {}
17594
17631
  };
@@ -17607,7 +17644,7 @@ function useChat({
17607
17644
  try {
17608
17645
  let receivedFirstTextChunk = false;
17609
17646
  let currentTextSegment = "";
17610
- for await (const rawSegment of streamMessage(text, extra)) {
17647
+ for await (const rawSegment of streamMessage(text2, extra)) {
17611
17648
  const segment = asStreamFrame(rawSegment);
17612
17649
  if (!receivedFirstTextChunk && segment.type === "text") {
17613
17650
  setIsTyping(false);
@@ -17816,8 +17853,8 @@ var END_OF_LEADING = "";
17816
17853
  var TRAILER_SENTINEL = "";
17817
17854
 
17818
17855
  // src/chat-protocol/leading-frames.ts
17819
- function escapeThinkingTags(text) {
17820
- return text.replace(/</g, "&lt;");
17856
+ function escapeThinkingTags(text2) {
17857
+ return text2.replace(/</g, "&lt;");
17821
17858
  }
17822
17859
  function frameStr(value) {
17823
17860
  return typeof value === "string" ? value : void 0;
@@ -17928,11 +17965,11 @@ function isFrameObject(value) {
17928
17965
  }
17929
17966
  function frameTelemetry(value) {
17930
17967
  if (!isFrameObject(value)) return void 0;
17931
- const { cards, chips, sentences, answerLen } = value;
17932
- if (typeof cards !== "number" || typeof chips !== "number" || typeof sentences !== "number" || typeof answerLen !== "number") {
17968
+ const { cards: cards2, chips, sentences, answerLen } = value;
17969
+ if (typeof cards2 !== "number" || typeof chips !== "number" || typeof sentences !== "number" || typeof answerLen !== "number") {
17933
17970
  return void 0;
17934
17971
  }
17935
- return { cards, chips, sentences, answerLen };
17972
+ return { cards: cards2, chips, sentences, answerLen };
17936
17973
  }
17937
17974
  function createSseFrameDecoder() {
17938
17975
  const textDecoder = new TextDecoder();
@@ -18073,6 +18110,207 @@ function errorDetailsMessage(details) {
18073
18110
  }
18074
18111
  var CHAT_OWNER_ADMIN = "ADMIN";
18075
18112
 
18113
+ // src/chat-protocol/wire-narrow.ts
18114
+ function isRecord(value) {
18115
+ return typeof value === "object" && value !== null;
18116
+ }
18117
+ function unwrapEnvelope(payload) {
18118
+ return isRecord(payload) && "data" in payload ? payload.data : payload;
18119
+ }
18120
+
18121
+ // src/chat-protocol/source-metadata.ts
18122
+ var YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;
18123
+ var VIDEO_URL_KEYS = ["videoUrl", "highlightVideoUrl", "videoPoster", "highlightVideoPoster"];
18124
+ function text(value) {
18125
+ if (typeof value !== "string") return void 0;
18126
+ const trimmed = value.trim();
18127
+ return trimmed || void 0;
18128
+ }
18129
+ function nullableText(value) {
18130
+ return value === null ? null : text(value);
18131
+ }
18132
+ function httpsUrl(value) {
18133
+ const candidate = text(value);
18134
+ if (!candidate) return void 0;
18135
+ try {
18136
+ return new URL(candidate).protocol === "https:" ? candidate : void 0;
18137
+ } catch {
18138
+ return void 0;
18139
+ }
18140
+ }
18141
+ function youtubeVideoId(value) {
18142
+ const candidate = text(value);
18143
+ if (!candidate) return void 0;
18144
+ if (YOUTUBE_ID.test(candidate)) return candidate;
18145
+ const url = httpsUrl(candidate);
18146
+ if (!url) return void 0;
18147
+ const parsed = new URL(url);
18148
+ const hostname = parsed.hostname.toLowerCase();
18149
+ const isYoutubeHost = hostname === "youtu.be" || hostname === "youtube.com" || hostname.endsWith(".youtube.com");
18150
+ if (!isYoutubeHost) return void 0;
18151
+ const fromPath = hostname === "youtu.be" ? parsed.pathname.split("/").filter(Boolean)[0] : /^\/(?:embed|v|shorts)\/([A-Za-z0-9_-]{11})(?:\/|$)/.exec(parsed.pathname)?.[1];
18152
+ const id = fromPath ?? parsed.searchParams.get("v") ?? void 0;
18153
+ return id && YOUTUBE_ID.test(id) ? id : void 0;
18154
+ }
18155
+ function sourceItems(value) {
18156
+ if (!Array.isArray(value)) return void 0;
18157
+ const items = value.filter(isRecord).flatMap((item) => {
18158
+ const id = text(item.id);
18159
+ const documentType = text(item.documentType);
18160
+ const name = text(item.name);
18161
+ if (!id || !documentType || !name) return [];
18162
+ const externalUrl = httpsUrl(item.externalUrl);
18163
+ const targetPlatform = nullableText(item.targetPlatform);
18164
+ const path = nullableText(item.path);
18165
+ return [
18166
+ {
18167
+ id,
18168
+ documentType,
18169
+ name,
18170
+ ...externalUrl ? { externalUrl } : {},
18171
+ ...targetPlatform !== void 0 ? { targetPlatform } : {},
18172
+ ...path !== void 0 ? { path } : {}
18173
+ }
18174
+ ];
18175
+ });
18176
+ return items.length > 0 ? items : void 0;
18177
+ }
18178
+ function sources(value) {
18179
+ if (!Array.isArray(value)) return [];
18180
+ const claimed = /* @__PURE__ */ new Set();
18181
+ const decoded = [];
18182
+ for (const candidate of value) {
18183
+ if (!isRecord(candidate)) continue;
18184
+ const index = candidate.index;
18185
+ const name = text(candidate.name);
18186
+ const isUsableIndex = typeof index === "number" && Number.isInteger(index) && index > 0 && !claimed.has(index);
18187
+ if (!isUsableIndex || !name) continue;
18188
+ claimed.add(index);
18189
+ const path = text(candidate.path);
18190
+ const documentType = text(candidate.documentType);
18191
+ const externalUrl = httpsUrl(candidate.externalUrl);
18192
+ const targetPlatform = nullableText(candidate.targetPlatform);
18193
+ const id = text(candidate.id);
18194
+ const sourceRepo = text(candidate.sourceRepo);
18195
+ const label = text(candidate.label);
18196
+ const items = sourceItems(candidate.items);
18197
+ decoded.push({
18198
+ index,
18199
+ name,
18200
+ // Both are typed non-optional on `ChatSource` and predate this decoder;
18201
+ // '' is the established "no value" for them across the SSE path.
18202
+ path: path ?? "",
18203
+ documentType: documentType ?? "",
18204
+ ...externalUrl ? { externalUrl } : {},
18205
+ ...targetPlatform !== void 0 ? { targetPlatform } : {},
18206
+ ...id ? { id } : {},
18207
+ ...sourceRepo ? { sourceRepo } : {},
18208
+ ...label ? { label } : {},
18209
+ ...items ? { items } : {}
18210
+ });
18211
+ }
18212
+ return decoded;
18213
+ }
18214
+ function videoMetadata(value, url) {
18215
+ const metadata = {};
18216
+ if (isRecord(value)) {
18217
+ for (const key of VIDEO_URL_KEYS) {
18218
+ const validated = httpsUrl(value[key]);
18219
+ if (validated) metadata[key] = validated;
18220
+ }
18221
+ const declaredId = youtubeVideoId(value.youtubeUrl);
18222
+ if (declaredId) metadata.youtubeUrl = declaredId;
18223
+ }
18224
+ if (url) {
18225
+ const idFromUrl = youtubeVideoId(url);
18226
+ if (idFromUrl) {
18227
+ metadata.youtubeUrl = idFromUrl;
18228
+ delete metadata.videoUrl;
18229
+ } else {
18230
+ metadata.videoUrl = url;
18231
+ delete metadata.youtubeUrl;
18232
+ }
18233
+ }
18234
+ return metadata;
18235
+ }
18236
+ function videos(value) {
18237
+ if (!Array.isArray(value)) return [];
18238
+ return value.filter(isRecord).flatMap((video) => {
18239
+ const match = typeof video.ref === "string" ? CARD_REFERENCE.exec(video.ref) : null;
18240
+ if (!match || match[1] !== "video") return [];
18241
+ const id = match[2];
18242
+ const url = httpsUrl(video.url) ?? null;
18243
+ const sourceRepo = text(video.sourceRepo);
18244
+ const metadata = videoMetadata(video.metadata, url);
18245
+ return [
18246
+ {
18247
+ type: "video",
18248
+ id,
18249
+ title: text(video.title) ?? id,
18250
+ url,
18251
+ ...sourceRepo ? { sourceRepo } : {},
18252
+ ...Object.keys(metadata).length > 0 ? { metadata } : {}
18253
+ }
18254
+ ];
18255
+ });
18256
+ }
18257
+ function cards(value, decodedSources) {
18258
+ if (!Array.isArray(value)) return [];
18259
+ return value.filter(isRecord).flatMap((card) => {
18260
+ const match = typeof card.ref === "string" ? CARD_REFERENCE.exec(card.ref) : null;
18261
+ if (!match || match[1] === "video") return [];
18262
+ const type = text(card.entityType);
18263
+ const id = text(card.entityId);
18264
+ if (!type || !id || type !== match[1] || id !== match[2]) return [];
18265
+ const source = decodedSources.find((candidate) => candidate.id === id && candidate.documentType === type);
18266
+ return [
18267
+ {
18268
+ type,
18269
+ id,
18270
+ title: source?.name ?? id,
18271
+ url: source?.externalUrl ?? null,
18272
+ ...source?.sourceRepo ? { sourceRepo: source.sourceRepo } : {},
18273
+ ...source?.targetPlatform !== void 0 ? { targetPlatform: source.targetPlatform } : {},
18274
+ ...source?.path ? { metadata: { path: source.path } } : {}
18275
+ }
18276
+ ];
18277
+ });
18278
+ }
18279
+ function deduplicateRefs(refs) {
18280
+ const byIdentity = /* @__PURE__ */ new Map();
18281
+ for (const ref of refs) {
18282
+ const identity = `${ref.type}:${ref.id}`;
18283
+ if (!byIdentity.has(identity)) byIdentity.set(identity, ref);
18284
+ }
18285
+ return [...byIdentity.values()];
18286
+ }
18287
+ function sourceMetadataEvent(payload) {
18288
+ if (!isRecord(payload)) return null;
18289
+ const decodedSources = sources(payload.sources);
18290
+ const refs = deduplicateRefs([...videos(payload.videos), ...cards(payload.cards, decodedSources)]);
18291
+ if (decodedSources.length === 0 && refs.length === 0) return null;
18292
+ return {
18293
+ type: "sources",
18294
+ ...decodedSources.length > 0 ? { sources: decodedSources } : {},
18295
+ ...refs.length > 0 ? { refs } : {}
18296
+ };
18297
+ }
18298
+ function mergeSourceMetadata(previous, event) {
18299
+ const byIndex = /* @__PURE__ */ new Map();
18300
+ for (const source of [...previous?.sources ?? [], ...event.sources ?? []]) {
18301
+ if (!byIndex.has(source.index)) byIndex.set(source.index, source);
18302
+ }
18303
+ const byIdentity = /* @__PURE__ */ new Map();
18304
+ for (const ref of [...previous?.refs ?? [], ...event.refs ?? []]) {
18305
+ const identity = `${ref.type}:${ref.id}`;
18306
+ if (!byIdentity.has(identity)) byIdentity.set(identity, ref);
18307
+ }
18308
+ return {
18309
+ ...byIndex.size > 0 ? { sources: [...byIndex.values()] } : {},
18310
+ ...byIdentity.size > 0 ? { refs: [...byIdentity.values()] } : {}
18311
+ };
18312
+ }
18313
+
18076
18314
  // src/components/chat/utils/approval-display.ts
18077
18315
  function approvalDisplaysInline(approvalType, displayApprovalTypes) {
18078
18316
  return !displayApprovalTypes || displayApprovalTypes.includes(approvalType);
@@ -18374,12 +18612,12 @@ var MessageSegmentAccumulator = class {
18374
18612
  * Append text to the current message
18375
18613
  * If the last segment is text, append to it; otherwise create a new text segment
18376
18614
  */
18377
- appendText(text) {
18615
+ appendText(text2) {
18378
18616
  const lastSegment = this.segments[this.segments.length - 1];
18379
18617
  if (lastSegment && lastSegment.type === "text") {
18380
- this.segments[this.segments.length - 1] = { type: "text", text: lastSegment.text + text };
18618
+ this.segments[this.segments.length - 1] = { type: "text", text: lastSegment.text + text2 };
18381
18619
  } else {
18382
- this.segments.push({ type: "text", text });
18620
+ this.segments.push({ type: "text", text: text2 });
18383
18621
  }
18384
18622
  return this.getSegments();
18385
18623
  }
@@ -18387,12 +18625,12 @@ var MessageSegmentAccumulator = class {
18387
18625
  * Append thinking text to the current message.
18388
18626
  * If the last segment is thinking, append to it; otherwise start a new thinking segment.
18389
18627
  */
18390
- appendThinking(text) {
18628
+ appendThinking(text2) {
18391
18629
  const lastSegment = this.segments[this.segments.length - 1];
18392
18630
  if (lastSegment && lastSegment.type === "thinking") {
18393
- this.segments[this.segments.length - 1] = { type: "thinking", text: lastSegment.text + text };
18631
+ this.segments[this.segments.length - 1] = { type: "thinking", text: lastSegment.text + text2 };
18394
18632
  } else {
18395
- this.segments.push({ type: "thinking", text });
18633
+ this.segments.push({ type: "thinking", text: text2 });
18396
18634
  }
18397
18635
  return this.getSegments();
18398
18636
  }
@@ -18622,7 +18860,7 @@ var MessageSegmentAccumulator = class {
18622
18860
  * `[existing..., new...]` back through `replaySegments`, which would
18623
18861
  * otherwise yield two cards for one offer.
18624
18862
  */
18625
- addEscalationOffer(offerId, text, origin, status = "pending", resolvedByName) {
18863
+ addEscalationOffer(offerId, text2, origin, status = "pending", resolvedByName) {
18626
18864
  const existingIndex = this.segments.findIndex(
18627
18865
  (s) => s.type === "escalation_offer" && s.data.offerId === offerId
18628
18866
  );
@@ -18631,7 +18869,7 @@ var MessageSegmentAccumulator = class {
18631
18869
  type: "escalation_offer",
18632
18870
  // The resolved chunk carries no text/origin — a redelivered offer must
18633
18871
  // not blank the card the PENDING chunk already painted.
18634
- data: { offerId, text: text || existing?.data.text || "", origin: origin ?? existing?.data.origin },
18872
+ data: { offerId, text: text2 || existing?.data.text || "", origin: origin ?? existing?.data.origin },
18635
18873
  status,
18636
18874
  resolvedByName: resolvedByName ?? existing?.resolvedByName,
18637
18875
  onApprove: this.callbacks.onEscalationApprove,
@@ -18922,12 +19160,12 @@ function createChatStreamReducer(options = {}) {
18922
19160
  let lastAppliedSeq = Number.NEGATIVE_INFINITY;
18923
19161
  let pendingEchoTexts = [];
18924
19162
  let turnStartedAt = 0;
18925
- function consumeOwnEcho(text, authorMatched = false) {
19163
+ function consumeOwnEcho(text2, authorMatched = false) {
18926
19164
  if (pendingEchoTexts.length === 0) return false;
18927
19165
  const now = Date.now();
18928
19166
  pendingEchoTexts = pendingEchoTexts.filter((e) => now - e.at < OWN_ECHO_AUTHOR_TTL_MS);
18929
19167
  const ttl = authorMatched ? OWN_ECHO_AUTHOR_TTL_MS : OWN_ECHO_TTL_MS;
18930
- const idx = pendingEchoTexts.findIndex((e) => e.text === text && now - e.at < ttl);
19168
+ const idx = pendingEchoTexts.findIndex((e) => e.text === text2 && now - e.at < ttl);
18931
19169
  if (idx === -1) return false;
18932
19170
  pendingEchoTexts.splice(idx, 1);
18933
19171
  return true;
@@ -19004,17 +19242,29 @@ function createChatStreamReducer(options = {}) {
19004
19242
  if (typeof last.streamSeq === "number" && last.streamSeq >= seq) return next;
19005
19243
  return [...next.slice(0, -1), { ...last, streamSeq: seq }];
19006
19244
  }
19245
+ let turnSourceMetadata = null;
19246
+ function stampTrailingAssistantSourceMetadata(next) {
19247
+ const metadata = turnSourceMetadata;
19248
+ if (!metadata) return next;
19249
+ const last = next[next.length - 1];
19250
+ if (!last || last.role !== "assistant") return next;
19251
+ if (last.sources === metadata.sources && last.refs === metadata.refs) return next;
19252
+ return [...next.slice(0, -1), { ...last, ...metadata }];
19253
+ }
19254
+ function commitTrailingAssistant(next, seq) {
19255
+ return stampTrailingAssistantSourceMetadata(stampTrailingAssistantSeq(next, seq));
19256
+ }
19007
19257
  function applySegmentsToState(segments, meta) {
19008
19258
  const seq = meta?.streamSeq;
19009
19259
  if (meta?.append && meta.isCompacting) {
19010
- setMessagesInternal(stampTrailingAssistantSeq(upsertTrailingCompaction(messages, segments), seq));
19260
+ setMessagesInternal(commitTrailingAssistant(upsertTrailingCompaction(messages, segments), seq));
19011
19261
  return;
19012
19262
  }
19013
19263
  if (meta?.append) {
19014
- setMessagesInternal(stampTrailingAssistantSeq(appendToTrailingAssistant(messages, segments), seq));
19264
+ setMessagesInternal(commitTrailingAssistant(appendToTrailingAssistant(messages, segments), seq));
19015
19265
  return;
19016
19266
  }
19017
- setMessagesInternal(stampTrailingAssistantSeq(updateTrailingAssistant(messages, segments), seq));
19267
+ setMessagesInternal(commitTrailingAssistant(updateTrailingAssistant(messages, segments), seq));
19018
19268
  }
19019
19269
  function applyStreamStartToState() {
19020
19270
  setPhaseInternal("streaming");
@@ -19027,8 +19277,8 @@ function createChatStreamReducer(options = {}) {
19027
19277
  setMessagesInternal([...messages, { id: nextId("assistant"), role: "assistant", content: "", segments: [] }]);
19028
19278
  }
19029
19279
  function applyUserMessageToState(ev) {
19030
- const text = ev.text;
19031
- if (!text) return;
19280
+ const text2 = ev.text;
19281
+ if (!text2) return;
19032
19282
  const seq = ev.seq;
19033
19283
  const adminEchoAllowed = ev.ownerType !== CHAT_OWNER_ADMIN || options.ownEchoIncludesAdmin === true;
19034
19284
  const selfUserId = resolveSelfUserId();
@@ -19036,11 +19286,11 @@ function createChatStreamReducer(options = {}) {
19036
19286
  if (selfUserId !== void 0 && !authorDeclared) warnIdLessAuthor();
19037
19287
  const authorMatched = selfUserId !== void 0 && authorDeclared && ev.userId === selfUserId;
19038
19288
  const authorEchoAllowed = selfUserId === void 0 || !authorDeclared || authorMatched;
19039
- if (adminEchoAllowed && authorEchoAllowed && consumeOwnEcho(text, authorMatched)) return;
19289
+ if (adminEchoAllowed && authorEchoAllowed && consumeOwnEcho(text2, authorMatched)) return;
19040
19290
  const authorType = ev.ownerType === CHAT_OWNER_ADMIN ? "admin" : "user";
19041
19291
  if (typeof seq !== "number" && hasRecentMessage(
19042
19292
  messages,
19043
- (m) => m.role === "user" && (m.authorType ?? "user") === authorType && m.content === text,
19293
+ (m) => m.role === "user" && (m.authorType ?? "user") === authorType && m.content === text2,
19044
19294
  CONTENT_DEDUP_WINDOW
19045
19295
  )) {
19046
19296
  return;
@@ -19050,7 +19300,7 @@ function createChatStreamReducer(options = {}) {
19050
19300
  {
19051
19301
  id: nextId("user"),
19052
19302
  role: "user",
19053
- content: text,
19303
+ content: text2,
19054
19304
  // Coverage signal for the history merge — see `streamSeq` on
19055
19305
  // `UnifiedChatMessage`. For `user-` rows it is also what tells a
19056
19306
  // REPLAYED echo (history already has its row) apart from a genuine new
@@ -19063,12 +19313,12 @@ function createChatStreamReducer(options = {}) {
19063
19313
  ]);
19064
19314
  }
19065
19315
  function applyDirectMessageToState(ev) {
19066
- const text = ev.text;
19067
- if (!text) return;
19316
+ const text2 = ev.text;
19317
+ if (!text2) return;
19068
19318
  const seq = ev.seq;
19069
19319
  if (typeof seq !== "number" && hasRecentMessage(
19070
19320
  messages,
19071
- (m) => m.role === "user" && m.authorType === "admin" && m.content === text,
19321
+ (m) => m.role === "user" && m.authorType === "admin" && m.content === text2,
19072
19322
  CONTENT_DEDUP_WINDOW
19073
19323
  )) {
19074
19324
  return;
@@ -19078,7 +19328,7 @@ function createChatStreamReducer(options = {}) {
19078
19328
  {
19079
19329
  id: `direct-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
19080
19330
  role: "user",
19081
- content: text,
19331
+ content: text2,
19082
19332
  ...typeof seq === "number" ? { streamSeq: seq } : {},
19083
19333
  name: ev.displayName ?? "Admin",
19084
19334
  authorType: "admin"
@@ -19086,10 +19336,10 @@ function createChatStreamReducer(options = {}) {
19086
19336
  ]);
19087
19337
  }
19088
19338
  function applySystemMessageToState(ev) {
19089
- const text = ev.text;
19090
- if (!text) return;
19339
+ const text2 = ev.text;
19340
+ if (!text2) return;
19091
19341
  const seq = ev.seq;
19092
- if (typeof seq !== "number" && hasRecentMessage(messages, (m) => m.authorType === "system" && m.name === text, SYSTEM_DEDUP_WINDOW)) {
19342
+ if (typeof seq !== "number" && hasRecentMessage(messages, (m) => m.authorType === "system" && m.name === text2, SYSTEM_DEDUP_WINDOW)) {
19093
19343
  return;
19094
19344
  }
19095
19345
  setMessagesInternal([
@@ -19099,7 +19349,7 @@ function createChatStreamReducer(options = {}) {
19099
19349
  role: "user",
19100
19350
  content: "",
19101
19351
  ...typeof seq === "number" ? { streamSeq: seq } : {},
19102
- name: text,
19352
+ name: text2,
19103
19353
  authorType: "system"
19104
19354
  }
19105
19355
  ]);
@@ -19137,6 +19387,7 @@ function createChatStreamReducer(options = {}) {
19137
19387
  isInStream = true;
19138
19388
  hasEverStreamed = true;
19139
19389
  turnStartedAt = Date.now();
19390
+ turnSourceMetadata = null;
19140
19391
  emit("onStreamStart");
19141
19392
  applyStreamStartToState();
19142
19393
  accumulator.resetSegments();
@@ -19150,6 +19401,14 @@ function createChatStreamReducer(options = {}) {
19150
19401
  accumulator.resetSegments();
19151
19402
  break;
19152
19403
  }
19404
+ // Per-answer source metadata. Applied to the trailing assistant bubble
19405
+ // immediately when there is one, and held for the next write when the
19406
+ // chunk beat the answer text to the reducer.
19407
+ case "sources": {
19408
+ turnSourceMetadata = mergeSourceMetadata(turnSourceMetadata, event);
19409
+ setMessagesInternal(stampTrailingAssistantSourceMetadata(messages));
19410
+ break;
19411
+ }
19153
19412
  case "metadata": {
19154
19413
  emit("onMetadata", {
19155
19414
  action: "metadata",
@@ -19471,20 +19730,20 @@ function createChatStreamReducer(options = {}) {
19471
19730
  break;
19472
19731
  }
19473
19732
  }
19474
- function sseWriteTrailingText(text) {
19733
+ function sseWriteTrailingText(text2) {
19475
19734
  const last = messages[messages.length - 1];
19476
19735
  if (!last || last.role !== "assistant") return;
19477
19736
  const segments = [...last.segments ?? []];
19478
19737
  const tail = segments[segments.length - 1];
19479
19738
  if (tail && tail.type === "text") {
19480
- segments[segments.length - 1] = { type: "text", text };
19739
+ segments[segments.length - 1] = { type: "text", text: text2 };
19481
19740
  } else {
19482
- segments.push({ type: "text", text });
19741
+ segments.push({ type: "text", text: text2 });
19483
19742
  }
19484
19743
  setMessagesInternal([...messages.slice(0, -1), { ...last, segments }]);
19485
19744
  }
19486
- function sseAppendText(text) {
19487
- sseCurrentText += text;
19745
+ function sseAppendText(text2) {
19746
+ sseCurrentText += text2;
19488
19747
  sseWriteTrailingText(sseCurrentText);
19489
19748
  }
19490
19749
  function sseAppendThinking(escapedDelta) {
@@ -19777,19 +20036,19 @@ function createChatStreamReducer(options = {}) {
19777
20036
  messages = [...older, ...messages];
19778
20037
  invalidate();
19779
20038
  },
19780
- pushOptimisticSend(text, hidden = false) {
19781
- pendingEchoTexts.push({ text, at: Date.now() });
20039
+ pushOptimisticSend(text2, hidden = false) {
20040
+ pendingEchoTexts.push({ text: text2, at: Date.now() });
19782
20041
  if (pendingEchoTexts.length > MAX_PENDING_ECHOES) pendingEchoTexts.shift();
19783
20042
  messages = [
19784
20043
  ...messages,
19785
20044
  // An EMPTY-text send is out-of-band metadata (an approval decision),
19786
20045
  // not something the user said — see `beginSseSend` for the full
19787
20046
  // rationale. Never materialize a row for it.
19788
- ...text.length > 0 ? [
20047
+ ...text2.length > 0 ? [
19789
20048
  {
19790
20049
  id: nextId("user"),
19791
20050
  role: "user",
19792
- content: text,
20051
+ content: text2,
19793
20052
  ...hidden ? { hidden: true } : {}
19794
20053
  }
19795
20054
  ] : [],
@@ -19805,7 +20064,7 @@ function createChatStreamReducer(options = {}) {
19805
20064
  invalidate();
19806
20065
  },
19807
20066
  resetForDialogSwitch,
19808
- beginSseSend({ text, hidden, userName = "You", assistantName, assistantAvatar }) {
20067
+ beginSseSend({ text: text2, hidden, userName = "You", assistantName, assistantAvatar }) {
19809
20068
  const now = Date.now();
19810
20069
  messages = [
19811
20070
  ...messages,
@@ -19817,12 +20076,12 @@ function createChatStreamReducer(options = {}) {
19817
20076
  // label with no body). So we never mint it. Hidden sends that DO carry
19818
20077
  // text (e.g. an auto-continuation directive) still become real state:
19819
20078
  // the LLM must see them, `Message.hidden` keeps them off screen.
19820
- ...text.length > 0 ? [
20079
+ ...text2.length > 0 ? [
19821
20080
  {
19822
20081
  id: `user-${now}`,
19823
20082
  role: "user",
19824
20083
  name: userName,
19825
- content: text,
20084
+ content: text2,
19826
20085
  timestamp: new Date(now),
19827
20086
  ...hidden ? { hidden: true } : {}
19828
20087
  }
@@ -19865,8 +20124,8 @@ function createChatStreamReducer(options = {}) {
19865
20124
  streamingPhase = "idle";
19866
20125
  invalidate();
19867
20126
  },
19868
- seedSseMaps({ sources, sendCount: seedSendCount }) {
19869
- if (sources) for (const [k, v] of sources) sourcesMap.set(k, v);
20127
+ seedSseMaps({ sources: sources2, sendCount: seedSendCount }) {
20128
+ if (sources2) for (const [k, v] of sources2) sourcesMap.set(k, v);
19870
20129
  if (typeof seedSendCount === "number") sendCount = seedSendCount;
19871
20130
  invalidate();
19872
20131
  },
@@ -20278,14 +20537,6 @@ function pruneStaleChatConversationStorage(source) {
20278
20537
  }
20279
20538
  }
20280
20539
 
20281
- // src/chat-protocol/wire-narrow.ts
20282
- function isRecord(value) {
20283
- return typeof value === "object" && value !== null;
20284
- }
20285
- function unwrapEnvelope(payload) {
20286
- return isRecord(payload) && "data" in payload ? payload.data : payload;
20287
- }
20288
-
20289
20540
  // src/components/chat/utils/chat-conversations-api.ts
20290
20541
  function toDialogItem(row) {
20291
20542
  if (!isRecord(row)) return null;
@@ -20920,7 +21171,7 @@ function useSseChatAdapter(options, runtimeOptions = {}) {
20920
21171
  const sendMessage = useCallback21(
20921
21172
  // Resolves `true` on a clean turn, `false` when the request failed
20922
21173
  // (surfaced to batch approve-all loops via the card callbacks).
20923
- async (text, sendOptions) => {
21174
+ async (text2, sendOptions) => {
20924
21175
  const { hidden, attachments, commandOverride, approvalAction } = sendOptions ?? {};
20925
21176
  const echoedConversationId = conversationIdRef.current;
20926
21177
  const targetPath = approvalAction ? endpointsRef.current.approvalToolUrl : endpointsRef.current.chatStreamUrl;
@@ -20931,12 +21182,12 @@ function useSseChatAdapter(options, runtimeOptions = {}) {
20931
21182
  // established conversation (the proposal turn captured the id).
20932
21183
  buildConfirmToolBody({ ...approvalAction, conversationId: echoedConversationId })
20933
21184
  ) : {
20934
- messages: [{ role: "user", content: text }],
21185
+ messages: [{ role: "user", content: text2 }],
20935
21186
  ...commandOverride ? { commandOverride } : {},
20936
21187
  ...attachments && attachments.length > 0 ? { pendingAttachments: attachments } : {},
20937
21188
  ...echoedConversationId ? { conversationId: echoedConversationId } : {}
20938
21189
  };
20939
- mutate((r) => r.beginSseSend({ text, hidden, userName: "You", assistantName: "Mingo AI" }));
21190
+ mutate((r) => r.beginSseSend({ text: text2, hidden, userName: "You", assistantName: "Mingo AI" }));
20940
21191
  const ctrl = new AbortController();
20941
21192
  abortControllerRef.current = ctrl;
20942
21193
  let mintedThisTurn = false;
@@ -21052,14 +21303,14 @@ function useSseChatAdapter(options, runtimeOptions = {}) {
21052
21303
  return state.messages.map((m) => {
21053
21304
  const segments = m.segments;
21054
21305
  const content = typeof m.content === "string" && !segments ? m.content : segments?.filter((s) => s.type === "text").map((s) => s.text).join("") ?? "";
21055
- let sources;
21306
+ let sources2;
21056
21307
  let scrollAnchor;
21057
21308
  if (m.role === "user" && !m.hidden) {
21058
21309
  sendIdx++;
21059
21310
  }
21060
21311
  if (m.role === "assistant") {
21061
21312
  const lookupIdx = sendIdx >= 0 ? sendIdx : 0;
21062
- sources = sourcesMap.get(lookupIdx);
21313
+ sources2 = sourcesMap.get(lookupIdx);
21063
21314
  scrollAnchor = meta.get(lookupIdx)?.scrollAnchor ?? void 0;
21064
21315
  }
21065
21316
  return {
@@ -21067,7 +21318,7 @@ function useSseChatAdapter(options, runtimeOptions = {}) {
21067
21318
  role: m.role,
21068
21319
  content,
21069
21320
  ...segments ? { segments } : {},
21070
- ...sources ? { sources } : {},
21321
+ ...sources2 ? { sources: sources2 } : {},
21071
21322
  ...scrollAnchor ? { scrollAnchor } : {},
21072
21323
  ...m.hidden ? { hidden: true } : {}
21073
21324
  };
@@ -21090,8 +21341,8 @@ function useSseChatAdapter(options, runtimeOptions = {}) {
21090
21341
  const refSlug = typeof reference.metadata?.slug === "string" && reference.metadata.slug.length > 0 ? reference.metadata.slug : "";
21091
21342
  const queryValue = refSlug || sanitizeTitleForChat(reference.title) || reference.id;
21092
21343
  const escaped = queryValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
21093
- const text = `/${cmdId} display "${escaped}"`;
21094
- void sendMessage(text);
21344
+ const text2 = `/${cmdId} display "${escaped}"`;
21345
+ void sendMessage(text2);
21095
21346
  },
21096
21347
  [sendMessage, source, cmdIdByTableId, tableIdForDocumentType]
21097
21348
  );
@@ -21245,6 +21496,16 @@ function decodeNatsChunk(chunk) {
21245
21496
  return { type: "thinking-delta", text: data.text, ...seq };
21246
21497
  }
21247
21498
  return null;
21499
+ // Two chunk names, one payload and one decoder. `SOURCES` is the contract
21500
+ // the backend is moving to; `GUIDE` is the v2 envelope it ships in during
21501
+ // the rollout (see `MESSAGE_TYPE.GUIDE`). The chunk arrives BEFORE or
21502
+ // between the answer's text deltas, so the reducer — not this decoder —
21503
+ // owns attaching it to the right turn.
21504
+ case MESSAGE_TYPE.GUIDE:
21505
+ case MESSAGE_TYPE.SOURCES: {
21506
+ const event = sourceMetadataEvent(data.payload);
21507
+ return event ? { ...event, ...seq } : null;
21508
+ }
21248
21509
  // An ask card is only an ask card with something to pick: a question and at
21249
21510
  // least one option. Anything less is dropped rather than rendered as an
21250
21511
  // empty card the user can't answer — the backend already falls back to a
@@ -21596,6 +21857,12 @@ function decodeHistoricalMessageData(data) {
21596
21857
  return { type: "thinking-delta", text: data.text };
21597
21858
  }
21598
21859
  return null;
21860
+ // Persisted source metadata, through the SAME decoder the live chunk uses
21861
+ // (`sourceMetadataEvent`). That shared parse is the whole reason a reloaded
21862
+ // answer renders identically to the one the reader watched arrive.
21863
+ case MESSAGE_TYPE.GUIDE:
21864
+ case MESSAGE_TYPE.SOURCES:
21865
+ return "payload" in data ? sourceMetadataEvent(data.payload) : null;
21599
21866
  // Same completeness gate as the live decoder (`decodeNatsChunk`): a
21600
21867
  // persisted row without a question or without options is not a card the
21601
21868
  // user can answer, so it replays as nothing rather than as empty chrome.
@@ -21955,6 +22222,7 @@ function processHistoricalMessages(messages, options = {}) {
21955
22222
  let currentAssistantTimestamp = null;
21956
22223
  let lastAssistantId = null;
21957
22224
  let currentAssistantStreamSeq;
22225
+ let currentAssistantSourceMetadata = null;
21958
22226
  const flushAssistantMessage = () => {
21959
22227
  const idToUse = lastAssistantId || currentAssistantId;
21960
22228
  if (idToUse && accumulator.hasContent()) {
@@ -21967,7 +22235,8 @@ function processHistoricalMessages(messages, options = {}) {
21967
22235
  authorType: assistantType,
21968
22236
  timestamp: currentAssistantTimestamp || /* @__PURE__ */ new Date(),
21969
22237
  avatar: assistantAvatar,
21970
- ...currentAssistantStreamSeq !== void 0 ? { streamSeq: currentAssistantStreamSeq } : {}
22238
+ ...currentAssistantStreamSeq !== void 0 ? { streamSeq: currentAssistantStreamSeq } : {},
22239
+ ...currentAssistantSourceMetadata ?? {}
21971
22240
  });
21972
22241
  accumulator.resetSegments();
21973
22242
  }
@@ -21975,6 +22244,7 @@ function processHistoricalMessages(messages, options = {}) {
21975
22244
  currentAssistantTimestamp = null;
21976
22245
  lastAssistantId = null;
21977
22246
  currentAssistantStreamSeq = void 0;
22247
+ currentAssistantSourceMetadata = null;
21978
22248
  };
21979
22249
  messages.forEach((msg, index) => {
21980
22250
  if (chatTypeFilter && msg.chatType !== chatTypeFilter) return;
@@ -22018,6 +22288,10 @@ function processHistoricalMessages(messages, options = {}) {
22018
22288
  messageDataArray.forEach((data) => {
22019
22289
  const event = decodeHistoricalMessageData(data);
22020
22290
  if (!event) return;
22291
+ if (event.type === "sources") {
22292
+ currentAssistantSourceMetadata = mergeSourceMetadata(currentAssistantSourceMetadata, event);
22293
+ return;
22294
+ }
22021
22295
  applyHistoryEvent(
22022
22296
  event,
22023
22297
  accumulator,
@@ -22417,10 +22691,10 @@ function useNatsChatAdapter(config, options = {}) {
22417
22691
  });
22418
22692
  const connectionState = !active || !dialogId ? "connected" : connectedForDialog === dialogId ? "connected" : "connecting";
22419
22693
  const sendMessage = useCallback22(
22420
- async (text, sendOptions) => {
22694
+ async (text2, sendOptions) => {
22421
22695
  const hidden = sendOptions?.hidden ?? false;
22422
- mutate((r) => r.pushOptimisticSend(text, hidden));
22423
- await publishUserMessage(text, { hidden, dialogId });
22696
+ mutate((r) => r.pushOptimisticSend(text2, hidden));
22697
+ await publishUserMessage(text2, { hidden, dialogId });
22424
22698
  },
22425
22699
  [mutate, publishUserMessage, dialogId]
22426
22700
  );
@@ -22629,7 +22903,7 @@ function useUnifiedChat(options) {
22629
22903
  const stopMessage = useCallback23(() => activeStateRef.current.stopMessage(), []);
22630
22904
  const clearMessages = useCallback23(() => activeStateRef.current.clearMessages(), []);
22631
22905
  const sendMessage = useCallback23(
22632
- (text, opts) => activeStateRef.current.sendMessage(text, opts),
22906
+ (text2, opts) => activeStateRef.current.sendMessage(text2, opts),
22633
22907
  []
22634
22908
  );
22635
22909
  const discussRef = useCallback23(
@@ -22788,27 +23062,27 @@ function collectTwinSignals(rows) {
22788
23062
  for (const row of rows) {
22789
23063
  for (const key of turnRequestKeys(row.content)) signals.requestKeys.add(key);
22790
23064
  if (row.role === "assistant") {
22791
- const text2 = assistantAnswerText(row.content);
22792
- if (text2 !== "") signals.assistantTexts.set(text2, (signals.assistantTexts.get(text2) ?? 0) + 1);
23065
+ const text3 = assistantAnswerText(row.content);
23066
+ if (text3 !== "") signals.assistantTexts.set(text3, (signals.assistantTexts.get(text3) ?? 0) + 1);
22793
23067
  continue;
22794
23068
  }
22795
- const text = userText(row);
22796
- if (text !== "") signals.userContents.set(text, (signals.userContents.get(text) ?? 0) + 1);
23069
+ const text2 = userText(row);
23070
+ if (text2 !== "") signals.userContents.set(text2, (signals.userContents.get(text2) ?? 0) + 1);
22797
23071
  }
22798
23072
  return signals;
22799
23073
  }
22800
23074
  function twinVerdict(signals, m) {
22801
23075
  if (m.role !== "assistant") {
22802
- const text2 = userText(m);
22803
- if (text2 === "") return "unknown";
22804
- return signals.userContents.has(text2) ? "twin" : "distinct";
23076
+ const text3 = userText(m);
23077
+ if (text3 === "") return "unknown";
23078
+ return signals.userContents.has(text3) ? "twin" : "distinct";
22805
23079
  }
22806
23080
  const keys = turnRequestKeys(m.content);
22807
23081
  if (keys.size > 0) return sharesRequestKey(keys, signals.requestKeys) ? "twin" : "distinct";
22808
- const text = assistantAnswerText(m.content);
22809
- if (text === "") return "unknown";
23082
+ const text2 = assistantAnswerText(m.content);
23083
+ if (text2 === "") return "unknown";
22810
23084
  for (const other of signals.assistantTexts.keys()) {
22811
- if (other.startsWith(text) || text.startsWith(other)) return "twin";
23085
+ if (other.startsWith(text2) || text2.startsWith(other)) return "twin";
22812
23086
  }
22813
23087
  return "distinct";
22814
23088
  }
@@ -23001,10 +23275,10 @@ function computeHistoryPrepend(processedHistory, existingMessages) {
23001
23275
  for (let i = newEnd - 1; i >= 0; i--) {
23002
23276
  const pm = processedHistory[i];
23003
23277
  if (pm.role === "user") {
23004
- const text = userText(pm);
23005
- const left = text === "" ? 0 : userTwinsLeft.get(text) ?? 0;
23278
+ const text2 = userText(pm);
23279
+ const left = text2 === "" ? 0 : userTwinsLeft.get(text2) ?? 0;
23006
23280
  if (left === 0) continue;
23007
- userTwinsLeft.set(text, left - 1);
23281
+ userTwinsLeft.set(text2, left - 1);
23008
23282
  twinIndices.add(i);
23009
23283
  } else if (pm.role === "assistant") {
23010
23284
  const keys = turnRequestKeys(pm.content);
@@ -23012,10 +23286,10 @@ function computeHistoryPrepend(processedHistory, existingMessages) {
23012
23286
  if (sharesRequestKey(keys, liveSignals.requestKeys)) twinIndices.add(i);
23013
23287
  continue;
23014
23288
  }
23015
- const text = assistantAnswerText(pm.content);
23016
- if (text === "") continue;
23289
+ const text2 = assistantAnswerText(pm.content);
23290
+ if (text2 === "") continue;
23017
23291
  for (const [liveText, left] of assistantTwinsLeft) {
23018
- if (left === 0 || !text.startsWith(liveText)) continue;
23292
+ if (left === 0 || !text2.startsWith(liveText)) continue;
23019
23293
  assistantTwinsLeft.set(liveText, left - 1);
23020
23294
  twinIndices.add(i);
23021
23295
  break;
@@ -23079,8 +23353,8 @@ var TOKEN_MS = 55;
23079
23353
  var USER_MS = 480;
23080
23354
  var SEGMENT_MS = 340;
23081
23355
  var POST_MS = 240;
23082
- function tokenize(text) {
23083
- return text.match(/\s*\S+\s*/g) ?? (text ? [text] : []);
23356
+ function tokenize(text2) {
23357
+ return text2.match(/\s*\S+\s*/g) ?? (text2 ? [text2] : []);
23084
23358
  }
23085
23359
  function buildStreamFrames(messages) {
23086
23360
  const frames = [];
@@ -23758,6 +24032,70 @@ function useChatDialogManager({
23758
24032
  };
23759
24033
  }
23760
24034
 
24035
+ // src/components/chat/utils/cited-sources.ts
24036
+ var FALLBACK_TOP_RETRIEVED = 3;
24037
+ var CITATION = /\[(\d+)\]/g;
24038
+ var CODE = /```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`/g;
24039
+ function withoutCode(content) {
24040
+ return content.replace(CODE, (block) => " ".repeat(block.length));
24041
+ }
24042
+ function splitCitedSources(sources2, content) {
24043
+ if (!sources2 || sources2.length === 0) return { cited: [], uncited: [] };
24044
+ const firstMentionAt = /* @__PURE__ */ new Map();
24045
+ for (const match of withoutCode(content).matchAll(CITATION)) {
24046
+ const index = Number.parseInt(match[1], 10);
24047
+ if (!firstMentionAt.has(index)) firstMentionAt.set(index, firstMentionAt.size);
24048
+ }
24049
+ const cited = sources2.filter((source) => firstMentionAt.has(source.index)).sort((a, b) => (firstMentionAt.get(a.index) ?? 0) - (firstMentionAt.get(b.index) ?? 0));
24050
+ const uncited = sources2.filter((source) => !firstMentionAt.has(source.index));
24051
+ return { cited, uncited };
24052
+ }
24053
+
24054
+ // src/components/chat/utils/host-message.ts
24055
+ function mapHostMessage(m, options) {
24056
+ const { userName, userAvatar, timestampCache } = options;
24057
+ let timestamp;
24058
+ if (m.timestamp != null) {
24059
+ timestamp = new Date(m.timestamp);
24060
+ } else {
24061
+ const cached = timestampCache.get(m.id);
24062
+ timestamp = cached ?? /* @__PURE__ */ new Date();
24063
+ if (!cached) timestampCache.set(m.id, timestamp);
24064
+ }
24065
+ return {
24066
+ id: m.id,
24067
+ role: m.role,
24068
+ // Host-supplied per-message name/avatar win (e.g. the signed-in user's
24069
+ // full name + photo on a `user` bubble); fall back to the role default
24070
+ // when the host doesn't provide them.
24071
+ name: m.name ?? (m.role === "assistant" ? "Mingo" : userName ?? "You"),
24072
+ avatar: m.avatar ?? (m.role === "user" ? userAvatar ?? null : null),
24073
+ // Forward the host's authorType so user bubbles get the same accent
24074
+ // name color as the standalone /mingo page (user → 'admin').
24075
+ ...m.authorType ? { authorType: m.authorType } : {},
24076
+ content: m.segments && m.segments.length > 0 ? m.segments : m.content,
24077
+ timestamp,
24078
+ assistantType: m.role === "assistant" ? "mingo" : void 0,
24079
+ // `hidden` is load-bearing, NOT cosmetic: it carries synthetic rows
24080
+ // (e.g. an auto-continuation directive) that the LLM must see but the
24081
+ // reader must not. See the module note above.
24082
+ ...m.hidden ? { hidden: true } : {},
24083
+ ...m.scrollAnchor ? { scrollAnchor: m.scrollAnchor } : {},
24084
+ // Forward attached context items so the user bubble renders its chips.
24085
+ ...m.contextItems && m.contextItems.length > 0 ? { contextItems: m.contextItems } : {},
24086
+ // Per-answer source metadata: the citation strip under the answer, and the
24087
+ // descriptions the `[card://…]` markers in its body expand into.
24088
+ ...m.sources && m.sources.length > 0 ? { sources: m.sources } : {},
24089
+ ...m.refs && m.refs.length > 0 ? { refs: m.refs } : {}
24090
+ };
24091
+ }
24092
+ function pruneTimestampCache(timestampCache, liveIds) {
24093
+ if (timestampCache.size <= liveIds.size) return;
24094
+ for (const id of timestampCache.keys()) {
24095
+ if (!liveIds.has(id)) timestampCache.delete(id);
24096
+ }
24097
+ }
24098
+
23761
24099
  // src/components/chat/embeddable-chat.tsx
23762
24100
  import { Fragment as Fragment34, jsx as jsx97, jsxs as jsxs75 } from "react/jsx-runtime";
23763
24101
  var HISTORY_RAIL_WIDTH = 320;
@@ -23780,7 +24118,6 @@ var mentionTokenOf = (key, markerByType) => {
23780
24118
  const id = ci === -1 ? "" : key.slice(ci + 1);
23781
24119
  return `${markerByType.get(type) ?? type.toLowerCase()}:${id}`;
23782
24120
  };
23783
- var FALLBACK_TOP_RETRIEVED = 3;
23784
24121
  var RAIL_COLLAPSED_STORAGE_KEY = "mingo-chat-history-collapsed";
23785
24122
  var NO_CONTEXT_ITEMS = [];
23786
24123
  var RAIL_ANIM_MS = 320;
@@ -23844,13 +24181,13 @@ function dispatchSlashCommandAction(actionId, cmdId, ref) {
23844
24181
  input.setValue(`/${cmdId} `);
23845
24182
  return;
23846
24183
  case "find": {
23847
- const text = `/${cmdId} ""`;
23848
- input.setValueAndCursor(text, text.length - 1);
24184
+ const text2 = `/${cmdId} ""`;
24185
+ input.setValueAndCursor(text2, text2.length - 1);
23849
24186
  return;
23850
24187
  }
23851
24188
  case "display": {
23852
- const text = `/${cmdId} display ""`;
23853
- input.setValueAndCursor(text, text.length - 1);
24189
+ const text2 = `/${cmdId} display ""`;
24190
+ input.setValueAndCursor(text2, text2.length - 1);
23854
24191
  return;
23855
24192
  }
23856
24193
  }
@@ -24408,56 +24745,17 @@ function EmbeddableChatInner({
24408
24745
  const guideUserName = activeMode === "guide" ? [identityUser?.firstName, identityUser?.lastName].filter(Boolean).join(" ").trim() || identityUser?.name?.trim() || void 0 : void 0;
24409
24746
  const guideUserAvatar = activeMode === "guide" ? identityUser?.avatarUrl?.trim() || void 0 : void 0;
24410
24747
  const messages = useMemo30(() => {
24411
- const cache = timestampCache;
24412
- const seenIds = /* @__PURE__ */ new Set();
24413
- const mapped = rawMessages.map((m) => {
24414
- seenIds.add(m.id);
24415
- let timestamp;
24416
- if (m.timestamp != null) {
24417
- timestamp = new Date(m.timestamp);
24418
- } else {
24419
- const cached = cache.get(m.id);
24420
- timestamp = cached ?? /* @__PURE__ */ new Date();
24421
- if (!cached) cache.set(m.id, timestamp);
24422
- }
24423
- return {
24424
- id: m.id,
24425
- role: m.role,
24426
- // Host-supplied per-message name/avatar win (e.g. the signed-in user's
24427
- // full name + photo on a `user` bubble); fall back to the role default
24428
- // when the host doesn't provide them.
24429
- name: m.name ?? (m.role === "assistant" ? "Mingo" : guideUserName ?? "You"),
24430
- avatar: m.avatar ?? (m.role === "user" ? guideUserAvatar ?? null : null),
24431
- // Forward the host's authorType so user bubbles get the same accent
24432
- // name color as the standalone /mingo page (user → 'admin').
24433
- ...m.authorType ? { authorType: m.authorType } : {},
24434
- content: m.segments && m.segments.length > 0 ? m.segments : m.content,
24435
- timestamp,
24436
- assistantType: m.role === "assistant" ? "mingo" : void 0,
24437
- // `hidden` is load-bearing, NOT cosmetic: it carries synthetic rows
24438
- // (e.g. an auto-continuation directive) that the LLM must see but the
24439
- // reader must not. Dropping it here made the raw directive text render
24440
- // as an ordinary bubble. This field-by-field rebuild has to forward it
24441
- // explicitly — see `Message.hidden` and `chat-message-list`'s skip.
24442
- ...m.hidden ? { hidden: true } : {},
24443
- ...m.scrollAnchor ? { scrollAnchor: m.scrollAnchor } : {},
24444
- // Forward attached context items so the user bubble renders its chips.
24445
- ...m.contextItems && m.contextItems.length > 0 ? { contextItems: m.contextItems } : {}
24446
- };
24447
- });
24448
- if (cache.size > seenIds.size) {
24449
- for (const id of cache.keys()) {
24450
- if (!seenIds.has(id)) cache.delete(id);
24451
- }
24452
- }
24748
+ const options = { userName: guideUserName, userAvatar: guideUserAvatar, timestampCache };
24749
+ const mapped = rawMessages.map((m) => mapHostMessage(m, options));
24750
+ pruneTimestampCache(timestampCache, new Set(rawMessages.map((m) => m.id)));
24453
24751
  return mapped;
24454
24752
  }, [rawMessages, guideUserName, guideUserAvatar, timestampCache]);
24455
24753
  const handleSend = useCallback27(
24456
- (text) => {
24457
- let augmentedText = text;
24754
+ (text2) => {
24755
+ let augmentedText = text2;
24458
24756
  if (readyAttachments.length > 0) {
24459
24757
  const markdown = readyAttachments.map((att) => formatChatAttachmentMarkdownForBubble(att, viewUrlPrefix)).join("");
24460
- augmentedText = `${text}${markdown}`;
24758
+ augmentedText = `${text2}${markdown}`;
24461
24759
  }
24462
24760
  void sendMessage(augmentedText, {
24463
24761
  ...readyAttachments.length > 0 ? { attachments: readyAttachments } : {},
@@ -24593,21 +24891,26 @@ function EmbeddableChatInner({
24593
24891
  });
24594
24892
  return out;
24595
24893
  }, [commandsById, enabledSet]);
24596
- const lastAssistantMsg = [...rawMessages].reverse().find((m) => m.role === "assistant");
24597
- const lastSources = useMemo30(() => {
24598
- if (chatLoading) return void 0;
24599
- const sources = lastAssistantMsg?.sources;
24600
- if (!sources || sources.length === 0) return void 0;
24601
- const content = lastAssistantMsg?.content || "";
24602
- const citationOrder = [...content.matchAll(/\[(\d+)\]/g)].map((m) => parseInt(m[1], 10));
24603
- const seenOrder = /* @__PURE__ */ new Map();
24604
- citationOrder.forEach((idx) => {
24605
- if (!seenOrder.has(idx)) seenOrder.set(idx, seenOrder.size);
24606
- });
24607
- const cited = sources.filter((s) => seenOrder.has(s.index)).sort((a, b) => (seenOrder.get(a.index) ?? 0) - (seenOrder.get(b.index) ?? 0));
24608
- const uncited = sources.filter((s) => !seenOrder.has(s.index));
24609
- return { cited, uncited };
24610
- }, [lastAssistantMsg, chatLoading]);
24894
+ const renderMessageSources = useCallback27(
24895
+ (message, index) => {
24896
+ if (message.role !== "assistant") return null;
24897
+ if (chatLoading && index === messages.length - 1) return null;
24898
+ const { cited, uncited } = splitCitedSources(message.sources, flattenAssistantContent(message.content));
24899
+ if (cited.length === 0 && uncited.length === 0) return null;
24900
+ return /* @__PURE__ */ jsx97("div", { className: "pb-2", children: /* @__PURE__ */ jsx97(
24901
+ SourceChips,
24902
+ {
24903
+ cited,
24904
+ uncited,
24905
+ baseRoute: resolvedBaseRoute,
24906
+ chipBasePlatform,
24907
+ onClose: handleNavigationClose,
24908
+ onDiscuss: discussRef
24909
+ }
24910
+ ) });
24911
+ },
24912
+ [chatLoading, messages.length, resolvedBaseRoute, chipBasePlatform, handleNavigationClose, discussRef]
24913
+ );
24611
24914
  const [portalHost, setPortalHost] = useState48(null);
24612
24915
  const [panelBoundary, setPanelBoundary] = useState48(null);
24613
24916
  const [panelWidth, setPanelWidth] = useState48(0);
@@ -24923,56 +25226,44 @@ function EmbeddableChatInner({
24923
25226
  "div",
24924
25227
  {
24925
25228
  className: "flex min-h-0 flex-1 flex-col duration-200 animate-in fade-in-0",
24926
- children: hasConversation ? /* @__PURE__ */ jsxs75("div", { className: "flex min-h-0 flex-1 flex-col", children: [
24927
- messagesInitialLoading ? (
24928
- // Match the real list's `fullWidth` layout so swapping
24929
- // skeleton → bubbles doesn't shift the column. The panel
24930
- // wrapper above already pads (`p-[var(--spacing-system-m)]`),
24931
- // so the skeleton sits flush (no inner px/pb).
24932
- //
24933
- // In `previewMode` the chat lives in a fixed-height host box
24934
- // (e.g. the Mingo hero demo). The default bottom-anchored
24935
- // skeleton overflows a short panel and grows its OWN
24936
- // scrollbar — ugly. `fill` top-anchors + clips overflow so
24937
- // it reads as "the whole panel is loading" and never scrolls.
24938
- /* @__PURE__ */ jsx97(ChatMessageListSkeleton, { fullWidth: true, fill: previewMode, className: "flex-1" })
24939
- ) : /* @__PURE__ */ jsx97(
24940
- ChatMessageList,
24941
- {
24942
- messages,
24943
- isTyping: chatLoading,
24944
- pendingApprovals,
24945
- autoScroll: !previewMode,
24946
- pinBottom: previewMode,
24947
- overscrollContain: !previewMode,
24948
- assistantType: "mingo",
24949
- assistantIcon: mingoAssistantIcon,
24950
- renderEntityCard,
24951
- resolveContextIcon,
24952
- renderContextItem,
24953
- renderMention,
24954
- onAskSelect: chatLoading || previewMode ? void 0 : handleAskSelect,
24955
- NavLinkAnchor: NavLinkAnchorViaRuntime,
24956
- className: previewMode ? "pointer-events-auto flex-1" : "flex-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
24957
- contentClassName: "max-w-none pb-0",
24958
- fullWidth: true,
24959
- hasNextPage: hasMoreMessages,
24960
- isFetchingNextPage: isMessagesLoading,
24961
- onLoadMore: loadMoreMessages
24962
- }
24963
- ),
24964
- lastSources && (lastSources.cited.length > 0 || lastSources.uncited.length > 0) && !chatLoading && /* @__PURE__ */ jsx97("div", { className: "flex-shrink-0 pb-2", children: /* @__PURE__ */ jsx97(
24965
- SourceChips,
24966
- {
24967
- cited: lastSources.cited,
24968
- uncited: lastSources.uncited,
24969
- baseRoute: resolvedBaseRoute,
24970
- chipBasePlatform,
24971
- onClose: handleNavigationClose,
24972
- onDiscuss: discussRef
24973
- }
24974
- ) })
24975
- ] }) : activeMode === "mingo" ? (
25229
+ children: hasConversation ? /* @__PURE__ */ jsx97("div", { className: "flex min-h-0 flex-1 flex-col", children: messagesInitialLoading ? (
25230
+ // Match the real list's `fullWidth` layout so swapping
25231
+ // skeleton → bubbles doesn't shift the column. The panel
25232
+ // wrapper above already pads (`p-[var(--spacing-system-m)]`),
25233
+ // so the skeleton sits flush (no inner px/pb).
25234
+ //
25235
+ // In `previewMode` the chat lives in a fixed-height host box
25236
+ // (e.g. the Mingo hero demo). The default bottom-anchored
25237
+ // skeleton overflows a short panel and grows its OWN
25238
+ // scrollbar — ugly. `fill` top-anchors + clips overflow so
25239
+ // it reads as "the whole panel is loading" and never scrolls.
25240
+ /* @__PURE__ */ jsx97(ChatMessageListSkeleton, { fullWidth: true, fill: previewMode, className: "flex-1" })
25241
+ ) : /* @__PURE__ */ jsx97(
25242
+ ChatMessageList,
25243
+ {
25244
+ messages,
25245
+ isTyping: chatLoading,
25246
+ pendingApprovals,
25247
+ autoScroll: !previewMode,
25248
+ pinBottom: previewMode,
25249
+ overscrollContain: !previewMode,
25250
+ assistantType: "mingo",
25251
+ assistantIcon: mingoAssistantIcon,
25252
+ renderEntityCard,
25253
+ resolveContextIcon,
25254
+ renderContextItem,
25255
+ renderMention,
25256
+ renderAfterMessage: renderMessageSources,
25257
+ onAskSelect: chatLoading || previewMode ? void 0 : handleAskSelect,
25258
+ NavLinkAnchor: NavLinkAnchorViaRuntime,
25259
+ className: previewMode ? "pointer-events-auto flex-1" : "flex-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
25260
+ contentClassName: "max-w-none pb-0",
25261
+ fullWidth: true,
25262
+ hasNextPage: hasMoreMessages,
25263
+ isFetchingNextPage: isMessagesLoading,
25264
+ onLoadMore: loadMoreMessages
25265
+ }
25266
+ ) }) : activeMode === "mingo" ? (
24976
25267
  /* Figma node 7532:222444 — default (Mingo-mode) empty state:
24977
25268
  centred greeting + capability grid + Guide-chat promo +
24978
25269
  quick-action chips. Guide mode keeps the slash-command
@@ -25541,4 +25832,4 @@ export {
25541
25832
  buildStreamFrames,
25542
25833
  EmbeddableChat
25543
25834
  };
25544
- //# sourceMappingURL=chunk-BSMPCPOZ.js.map
25835
+ //# sourceMappingURL=chunk-F2C2U7CP.js.map