@flamingo-stack/openframe-frontend-core 0.0.609 → 0.0.610-2115.5921.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 (149) 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-VCYRJY7J.js → chunk-2W6AQ6ST.js} +4 -4
  13. package/dist/{chunk-NJUSDREV.cjs → chunk-52GSR6PX.cjs} +22 -22
  14. package/dist/{chunk-NJUSDREV.cjs.map → chunk-52GSR6PX.cjs.map} +1 -1
  15. package/dist/{chunk-3XNMDLGB.cjs → chunk-5L76ULXI.cjs} +9 -9
  16. package/dist/{chunk-3XNMDLGB.cjs.map → chunk-5L76ULXI.cjs.map} +1 -1
  17. package/dist/{chunk-JKM5FH63.js → chunk-6BONRQGG.js} +3 -3
  18. package/dist/{chunk-RZM6FPOT.cjs → chunk-7VERMVYP.cjs} +25 -25
  19. package/dist/{chunk-RZM6FPOT.cjs.map → chunk-7VERMVYP.cjs.map} +1 -1
  20. package/dist/{chunk-XNDTYTVT.cjs → chunk-A7B4JGEH.cjs} +969 -682
  21. package/dist/chunk-A7B4JGEH.cjs.map +1 -0
  22. package/dist/{chunk-B7LYKBCD.js → chunk-AFUO6CNL.js} +5 -5
  23. package/dist/{chunk-D3DTC7SZ.cjs → chunk-BWCS5QNU.cjs} +15 -15
  24. package/dist/{chunk-D3DTC7SZ.cjs.map → chunk-BWCS5QNU.cjs.map} +1 -1
  25. package/dist/{chunk-BUXGWBTF.js → chunk-EMDT666K.js} +2 -2
  26. package/dist/{chunk-BSMPCPOZ.js → chunk-EQ3CWMCH.js} +585 -298
  27. package/dist/chunk-EQ3CWMCH.js.map +1 -0
  28. package/dist/{chunk-L2JWC5VS.cjs → chunk-EQPHDXIO.cjs} +43 -43
  29. package/dist/{chunk-L2JWC5VS.cjs.map → chunk-EQPHDXIO.cjs.map} +1 -1
  30. package/dist/{chunk-SEW25Y2W.cjs → chunk-GDQKVIKE.cjs} +10 -10
  31. package/dist/{chunk-SEW25Y2W.cjs.map → chunk-GDQKVIKE.cjs.map} +1 -1
  32. package/dist/{chunk-HGVW7OHI.js → chunk-GSTDCLFX.js} +2 -2
  33. package/dist/{chunk-O2M4T34Q.cjs → chunk-HAVUDRW5.cjs} +4 -4
  34. package/dist/{chunk-O2M4T34Q.cjs.map → chunk-HAVUDRW5.cjs.map} +1 -1
  35. package/dist/{chunk-ZRLFBLME.cjs → chunk-HDNKO4OV.cjs} +3 -3
  36. package/dist/{chunk-ZRLFBLME.cjs.map → chunk-HDNKO4OV.cjs.map} +1 -1
  37. package/dist/{chunk-TJ3GFULR.js → chunk-ISHPLUDJ.js} +3 -3
  38. package/dist/{chunk-JOCVQZGT.js → chunk-K5P4ESF6.js} +5 -5
  39. package/dist/{chunk-TCEALWE3.cjs → chunk-NEGKVF4S.cjs} +33 -33
  40. package/dist/{chunk-TCEALWE3.cjs.map → chunk-NEGKVF4S.cjs.map} +1 -1
  41. package/dist/{chunk-GMOBT5NP.cjs → chunk-NKVUCS66.cjs} +70 -70
  42. package/dist/{chunk-GMOBT5NP.cjs.map → chunk-NKVUCS66.cjs.map} +1 -1
  43. package/dist/{chunk-LA2W5L6K.js → chunk-OHL5N6G7.js} +2 -2
  44. package/dist/{chunk-FYG7QNAO.cjs → chunk-OPUHPZAM.cjs} +5 -5
  45. package/dist/{chunk-FYG7QNAO.cjs.map → chunk-OPUHPZAM.cjs.map} +1 -1
  46. package/dist/{chunk-QX4ANESW.js → chunk-P5CMQKRI.js} +6 -6
  47. package/dist/{chunk-6MLRFM3T.js → chunk-Q42T74A7.js} +5 -5
  48. package/dist/{chunk-3N4FXBVJ.cjs → chunk-SEOJAWTR.cjs} +3 -3
  49. package/dist/{chunk-3N4FXBVJ.cjs.map → chunk-SEOJAWTR.cjs.map} +1 -1
  50. package/dist/{chunk-OTYV6SDN.js → chunk-U3D3OT2O.js} +3 -3
  51. package/dist/{chunk-JR7I2AGL.js → chunk-U3JZ6GSD.js} +3 -3
  52. package/dist/{chunk-B3UXNGVM.js → chunk-VNQYE7PB.js} +3 -3
  53. package/dist/{chunk-DKNXAJMP.cjs → chunk-VPJSNVBS.cjs} +159 -159
  54. package/dist/{chunk-DKNXAJMP.cjs.map → chunk-VPJSNVBS.cjs.map} +1 -1
  55. package/dist/{chunk-MVBRMQGU.js → chunk-WTKKTHED.js} +2 -2
  56. package/dist/{chunk-C7CTEUU7.js → chunk-XPA4ANHJ.js} +2 -2
  57. package/dist/{chunk-CZTOSG7Q.cjs → chunk-XXF5KWMA.cjs} +22 -22
  58. package/dist/{chunk-CZTOSG7Q.cjs.map → chunk-XXF5KWMA.cjs.map} +1 -1
  59. package/dist/{chunk-45XXK2VU.cjs → chunk-YN3YBB5T.cjs} +10 -10
  60. package/dist/{chunk-45XXK2VU.cjs.map → chunk-YN3YBB5T.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/stream/chat-stream-reducer.d.ts.map +1 -1
  71. package/dist/components/chat/tool-execution-display.d.ts.map +1 -1
  72. package/dist/components/chat/types/component.types.d.ts +27 -0
  73. package/dist/components/chat/types/component.types.d.ts.map +1 -1
  74. package/dist/components/chat/types/message.types.d.ts +81 -1
  75. package/dist/components/chat/types/message.types.d.ts.map +1 -1
  76. package/dist/components/chat/types/unified-chat-state.types.d.ts +12 -3
  77. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  78. package/dist/components/chat/utils/cited-sources.d.ts +24 -0
  79. package/dist/components/chat/utils/cited-sources.d.ts.map +1 -0
  80. package/dist/components/chat/utils/host-message.d.ts +41 -0
  81. package/dist/components/chat/utils/host-message.d.ts.map +1 -0
  82. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  83. package/dist/components/contact/index.cjs +4 -4
  84. package/dist/components/contact/index.js +3 -3
  85. package/dist/components/docs/index.cjs +7 -7
  86. package/dist/components/docs/index.js +6 -6
  87. package/dist/components/embeds/index.cjs +4 -4
  88. package/dist/components/embeds/index.js +3 -3
  89. package/dist/components/faq/index.cjs +4 -4
  90. package/dist/components/faq/index.js +3 -3
  91. package/dist/components/features/index.cjs +3 -3
  92. package/dist/components/features/index.js +2 -2
  93. package/dist/components/help-center-pages/index.cjs +23 -23
  94. package/dist/components/help-center-pages/index.js +14 -14
  95. package/dist/components/index.cjs +38 -38
  96. package/dist/components/index.js +13 -13
  97. package/dist/components/meeting-scheduler/index.cjs +24 -24
  98. package/dist/components/meeting-scheduler/index.js +2 -2
  99. package/dist/components/navigation/index.cjs +6 -6
  100. package/dist/components/navigation/index.js +5 -5
  101. package/dist/components/onboarding-guides/index.cjs +6 -6
  102. package/dist/components/onboarding-guides/index.js +5 -5
  103. package/dist/components/tickets/index.cjs +7 -7
  104. package/dist/components/tickets/index.js +6 -6
  105. package/dist/components/ui/index.cjs +3 -3
  106. package/dist/components/ui/index.js +2 -2
  107. package/dist/index.cjs +7 -7
  108. package/dist/index.js +6 -6
  109. package/dist/utils/index.cjs.map +1 -1
  110. package/dist/utils/index.js.map +1 -1
  111. package/package.json +1 -1
  112. package/src/chat-protocol/__tests__/source-metadata.test.ts +243 -0
  113. package/src/chat-protocol/card-marker.ts +40 -0
  114. package/src/chat-protocol/events.ts +22 -1
  115. package/src/chat-protocol/nats-decoder.ts +12 -0
  116. package/src/chat-protocol/source-metadata.ts +336 -0
  117. package/src/components/chat/__tests__/tool-execution-display.test.tsx +70 -0
  118. package/src/components/chat/chat-message-enhanced.tsx +37 -6
  119. package/src/components/chat/chat-message-list.tsx +14 -1
  120. package/src/components/chat/embeddable-chat.tsx +42 -87
  121. package/src/components/chat/hooks/use-sse-chat-adapter.ts +5 -28
  122. package/src/components/chat/stream/chat-stream-reducer.ts +48 -3
  123. package/src/components/chat/tool-execution-display.tsx +18 -4
  124. package/src/components/chat/types/component.types.ts +27 -0
  125. package/src/components/chat/types/message.types.ts +83 -0
  126. package/src/components/chat/types/unified-chat-state.types.ts +12 -3
  127. package/src/components/chat/utils/__tests__/cited-sources.test.ts +53 -0
  128. package/src/components/chat/utils/__tests__/host-message.test.ts +92 -0
  129. package/src/components/chat/utils/__tests__/process-historical-messages-sources.test.ts +138 -0
  130. package/src/components/chat/utils/cited-sources.ts +43 -0
  131. package/src/components/chat/utils/host-message.ts +87 -0
  132. package/src/components/chat/utils/process-historical-messages.ts +25 -0
  133. package/dist/chunk-BSMPCPOZ.js.map +0 -1
  134. package/dist/chunk-XNDTYTVT.cjs.map +0 -1
  135. /package/dist/{chunk-VCYRJY7J.js.map → chunk-2W6AQ6ST.js.map} +0 -0
  136. /package/dist/{chunk-JKM5FH63.js.map → chunk-6BONRQGG.js.map} +0 -0
  137. /package/dist/{chunk-B7LYKBCD.js.map → chunk-AFUO6CNL.js.map} +0 -0
  138. /package/dist/{chunk-BUXGWBTF.js.map → chunk-EMDT666K.js.map} +0 -0
  139. /package/dist/{chunk-HGVW7OHI.js.map → chunk-GSTDCLFX.js.map} +0 -0
  140. /package/dist/{chunk-TJ3GFULR.js.map → chunk-ISHPLUDJ.js.map} +0 -0
  141. /package/dist/{chunk-JOCVQZGT.js.map → chunk-K5P4ESF6.js.map} +0 -0
  142. /package/dist/{chunk-LA2W5L6K.js.map → chunk-OHL5N6G7.js.map} +0 -0
  143. /package/dist/{chunk-QX4ANESW.js.map → chunk-P5CMQKRI.js.map} +0 -0
  144. /package/dist/{chunk-6MLRFM3T.js.map → chunk-Q42T74A7.js.map} +0 -0
  145. /package/dist/{chunk-OTYV6SDN.js.map → chunk-U3D3OT2O.js.map} +0 -0
  146. /package/dist/{chunk-JR7I2AGL.js.map → chunk-U3JZ6GSD.js.map} +0 -0
  147. /package/dist/{chunk-B3UXNGVM.js.map → chunk-VNQYE7PB.js.map} +0 -0
  148. /package/dist/{chunk-MVBRMQGU.js.map → chunk-WTKKTHED.js.map} +0 -0
  149. /package/dist/{chunk-C7CTEUU7.js.map → chunk-XPA4ANHJ.js.map} +0 -0
@@ -97,7 +97,10 @@ import type { ChatDialogCapabilities, UnifiedChatState } from './types/unified-c
97
97
  import { formatChatAttachmentMarkdownForBubble } from './utils/chat-attachment-markdown';
98
98
  import { resolveHrefForRuntime } from './utils/chat-nav-resolution';
99
99
  import { chatChipClass } from './utils/chip-styles';
100
+ import { FALLBACK_TOP_RETRIEVED, splitCitedSources } from './utils/cited-sources';
100
101
  import { executeNavigation } from './utils/execute-navigation';
102
+ import { flattenAssistantContent } from './utils/flatten-assistant-content';
103
+ import { mapHostMessage, pruneTimestampCache } from './utils/host-message';
101
104
  import { resolveIcon } from './utils/icon-library';
102
105
  import { computeIsNewTab, newTabAnchorAttrs } from './utils/nav-anchor-props';
103
106
  import { formatSingularLookupInvocation } from './utils/slash-dispatch-utils';
@@ -435,12 +438,6 @@ const mentionTokenOf = (key: string, markerByType: Map<string, string>): string
435
438
  return `${markerByType.get(type) ?? type.toLowerCase()}:${id}`;
436
439
  };
437
440
 
438
- /**
439
- * Fallback fan-out when the model didn't cite any source. Show the top-N
440
- * retrieved sources instead of zero chips. Mirrors Perplexity's behavior.
441
- */
442
- const FALLBACK_TOP_RETRIEVED = 3;
443
-
444
441
  /** Persists the user's rail collapse choice across drawer open/close + reloads. */
445
442
  const RAIL_COLLAPSED_STORAGE_KEY = 'mingo-chat-history-collapsed';
446
443
 
@@ -1539,56 +1536,12 @@ function EmbeddableChatInner({
1539
1536
  : undefined;
1540
1537
  const guideUserAvatar = activeMode === 'guide' ? identityUser?.avatarUrl?.trim() || undefined : undefined;
1541
1538
 
1542
- // Map docMessages → lib's Message type, forwarding scrollAnchor.
1539
+ // Map the host's rows → the lib's Message type. The mapping itself lives in
1540
+ // `mapHostMessage`, which is where its pass-through list is pinned by tests.
1543
1541
  const messages: Message[] = useMemo(() => {
1544
- const cache = timestampCache;
1545
- const seenIds = new Set<string>();
1546
-
1547
- const mapped = rawMessages.map(m => {
1548
- seenIds.add(m.id);
1549
- let timestamp: Date;
1550
- if (m.timestamp != null) {
1551
- timestamp = new Date(m.timestamp);
1552
- } else {
1553
- const cached = cache.get(m.id);
1554
- timestamp = cached ?? new Date();
1555
- if (!cached) cache.set(m.id, timestamp);
1556
- }
1557
-
1558
- return {
1559
- id: m.id,
1560
- role: m.role,
1561
- // Host-supplied per-message name/avatar win (e.g. the signed-in user's
1562
- // full name + photo on a `user` bubble); fall back to the role default
1563
- // when the host doesn't provide them.
1564
- name: m.name ?? (m.role === 'assistant' ? 'Mingo' : (guideUserName ?? 'You')),
1565
- avatar: m.avatar ?? (m.role === 'user' ? (guideUserAvatar ?? null) : null),
1566
- // Forward the host's authorType so user bubbles get the same accent
1567
- // name color as the standalone /mingo page (user → 'admin').
1568
- ...(m.authorType ? { authorType: m.authorType } : {}),
1569
- content: m.segments && m.segments.length > 0 ? m.segments : m.content,
1570
- timestamp,
1571
- assistantType: m.role === 'assistant' ? ('mingo' as const) : undefined,
1572
- // `hidden` is load-bearing, NOT cosmetic: it carries synthetic rows
1573
- // (e.g. an auto-continuation directive) that the LLM must see but the
1574
- // reader must not. Dropping it here made the raw directive text render
1575
- // as an ordinary bubble. This field-by-field rebuild has to forward it
1576
- // explicitly — see `Message.hidden` and `chat-message-list`'s skip.
1577
- ...(m.hidden ? { hidden: true } : {}),
1578
- ...(m.scrollAnchor ? { scrollAnchor: m.scrollAnchor } : {}),
1579
- // Forward attached context items so the user bubble renders its chips.
1580
- ...(m.contextItems && m.contextItems.length > 0 ? { contextItems: m.contextItems } : {}),
1581
- };
1582
- });
1583
-
1584
- // Drop cached fallbacks for messages no longer present so the map can't
1585
- // grow unbounded across a long-lived session.
1586
- if (cache.size > seenIds.size) {
1587
- for (const id of cache.keys()) {
1588
- if (!seenIds.has(id)) cache.delete(id);
1589
- }
1590
- }
1591
-
1542
+ const options = { userName: guideUserName, userAvatar: guideUserAvatar, timestampCache };
1543
+ const mapped = rawMessages.map(m => mapHostMessage(m, options));
1544
+ pruneTimestampCache(timestampCache, new Set(rawMessages.map(m => m.id)));
1592
1545
  return mapped;
1593
1546
  }, [rawMessages, guideUserName, guideUserAvatar, timestampCache]);
1594
1547
 
@@ -1836,24 +1789,39 @@ function EmbeddableChatInner({
1836
1789
  return out;
1837
1790
  }, [commandsById, enabledSet]);
1838
1791
 
1839
- // Find sources for the last assistant message; split into cited / uncited.
1840
- const lastAssistantMsg = [...rawMessages].reverse().find(m => m.role === 'assistant');
1841
- const lastSources = useMemo(() => {
1842
- if (chatLoading) return undefined;
1843
- const sources = lastAssistantMsg?.sources;
1844
- if (!sources || sources.length === 0) return undefined;
1845
- const content = lastAssistantMsg?.content || '';
1846
- const citationOrder = [...content.matchAll(/\[(\d+)\]/g)].map(m => parseInt(m[1], 10));
1847
- const seenOrder = new Map<number, number>();
1848
- citationOrder.forEach(idx => {
1849
- if (!seenOrder.has(idx)) seenOrder.set(idx, seenOrder.size);
1850
- });
1851
- const cited = sources
1852
- .filter(s => seenOrder.has(s.index))
1853
- .sort((a, b) => (seenOrder.get(a.index) ?? 0) - (seenOrder.get(b.index) ?? 0));
1854
- const uncited = sources.filter(s => !seenOrder.has(s.index));
1855
- return { cited, uncited };
1856
- }, [lastAssistantMsg, chatLoading]);
1792
+ /**
1793
+ * Source chips, under the answer that cited them.
1794
+ *
1795
+ * Per message, not once per thread. The strip names where THAT answer came
1796
+ * from, and a conversation holds several answers — pinning one strip to the
1797
+ * bottom of the thread attributes the newest answer's sources to whichever
1798
+ * answer the reader is looking at. Both transports produce them now, so this
1799
+ * is no longer a Guide-mode-only affordance either.
1800
+ */
1801
+ const renderMessageSources = useCallback(
1802
+ (message: Message) => {
1803
+ if (message.role !== 'assistant') return null;
1804
+ // Suppressed while the turn is still streaming: the citation markers the
1805
+ // order is derived from arrive WITH the text, so a strip rendered mid-turn
1806
+ // reshuffles under the reader as more sentences land.
1807
+ if (chatLoading) return null;
1808
+ const { cited, uncited } = splitCitedSources(message.sources, flattenAssistantContent(message.content));
1809
+ if (cited.length === 0 && uncited.length === 0) return null;
1810
+ return (
1811
+ <div className="pb-2">
1812
+ <SourceChips
1813
+ cited={cited}
1814
+ uncited={uncited}
1815
+ baseRoute={resolvedBaseRoute}
1816
+ chipBasePlatform={chipBasePlatform}
1817
+ onClose={handleNavigationClose}
1818
+ onDiscuss={discussRef}
1819
+ />
1820
+ </div>
1821
+ );
1822
+ },
1823
+ [chatLoading, resolvedBaseRoute, chipBasePlatform, handleNavigationClose, discussRef],
1824
+ );
1857
1825
 
1858
1826
  // Host node for in-panel Radix portals (see the body wrapper below).
1859
1827
  const [portalHost, setPortalHost] = useState<HTMLDivElement | null>(null);
@@ -2434,6 +2402,7 @@ function EmbeddableChatInner({
2434
2402
  resolveContextIcon={resolveContextIcon}
2435
2403
  renderContextItem={renderContextItem}
2436
2404
  renderMention={renderMention}
2405
+ renderAfterMessage={renderMessageSources}
2437
2406
  // Gated on `chatLoading` for the same reason the composer
2438
2407
  // is: no second send while a turn is in flight. Passive
2439
2408
  // demo hosts (previewMode) stay read-only.
@@ -2471,20 +2440,6 @@ function EmbeddableChatInner({
2471
2440
  onLoadMore={loadMoreMessages}
2472
2441
  />
2473
2442
  )}
2474
- {lastSources &&
2475
- (lastSources.cited.length > 0 || lastSources.uncited.length > 0) &&
2476
- !chatLoading && (
2477
- <div className="flex-shrink-0 pb-2">
2478
- <SourceChips
2479
- cited={lastSources.cited}
2480
- uncited={lastSources.uncited}
2481
- baseRoute={resolvedBaseRoute}
2482
- chipBasePlatform={chipBasePlatform}
2483
- onClose={handleNavigationClose}
2484
- onDiscuss={discussRef}
2485
- />
2486
- </div>
2487
- )}
2488
2443
  </div>
2489
2444
  ) : activeMode === 'mingo' ? (
2490
2445
  /* Figma node 7532:222444 — default (Mingo-mode) empty state:
@@ -62,7 +62,7 @@ import { createChatDialogStore } from '../stream/chat-dialog-store';
62
62
  import type { ChatDialogStore } from '../stream/chat-dialog-store';
63
63
  import type { ChatStreamReducerOptions } from '../stream/chat-stream-reducer';
64
64
  import { useChatStreamReducer } from '../stream/use-chat-stream-reducer';
65
- import type { Message, MessageSegment } from '../types/message.types';
65
+ import type { ChatSource, Message, MessageSegment } from '../types/message.types';
66
66
  import type {
67
67
  ChatDialogCapabilities,
68
68
  FetchDialogsParams,
@@ -121,33 +121,10 @@ const noopBumpMetaTick = (): void => {};
121
121
  * hub-side platform-utils, not in lib). */
122
122
  export type DocSource = string;
123
123
 
124
- export interface ChatSource {
125
- index: number;
126
- name: string;
127
- path: string;
128
- documentType: string;
129
- externalUrl?: string;
130
- /** Platform that owns the destination at `externalUrl`. */
131
- targetPlatform?: string | null;
132
- /** Primary-key value for single-row chips. */
133
- id?: string;
134
- /** Per-row items for grouped chips. */
135
- items?: Array<{
136
- id: string;
137
- documentType: string;
138
- name: string;
139
- externalUrl?: string;
140
- targetPlatform?: string | null;
141
- /** In-app doc-tree path for markdown / data-room-doc rows so the
142
- * grouped chip's anchor can trigger an in-page doc-tree swap via
143
- * `handleChatNavClick` (parity with single-row chips + cards). */
144
- path?: string | null;
145
- }>;
146
- /** RagTableConfig.id for this source. */
147
- sourceRepo?: string;
148
- /** Optional display label override returned by the chat API. */
149
- label?: string;
150
- }
124
+ /** Re-export: `ChatSource` moved to `message.types` when the NATS transport
125
+ * started producing it too. Kept so existing `use-sse-chat-adapter` imports
126
+ * keep resolving. */
127
+ export type { ChatSource };
151
128
 
152
129
  export interface DocChatMessage {
153
130
  id: string;
@@ -60,6 +60,7 @@ import {
60
60
  type ParticipantEvent,
61
61
  type UsageEvent,
62
62
  } from '../../../chat-protocol/events';
63
+ import { mergeSourceMetadata, type SourceMetadata } from '../../../chat-protocol/source-metadata';
63
64
  import type {
64
65
  ApprovalBatchSegment,
65
66
  ApprovalRequestSegment,
@@ -755,22 +756,56 @@ export function createChatStreamReducer(options: ChatStreamReducerOptions = {}):
755
756
  return [...next.slice(0, -1), { ...last, streamSeq: seq }];
756
757
  }
757
758
 
759
+ /**
760
+ * Source metadata accumulated for the CURRENT turn.
761
+ *
762
+ * The chunk is published when a remote tool returns, so it lands inside the
763
+ * turn but usually BEFORE the answer text the reader will see it under —
764
+ * sometimes before the assistant bubble exists at all. Holding it here and
765
+ * stamping it on every trailing-assistant write is what makes the arrival
766
+ * order stop mattering.
767
+ *
768
+ * Reset at `turn-start`, so metadata can never leak onto the next answer.
769
+ * Losing a chunk that somehow arrived outside a turn is the better failure of
770
+ * the two: a stale citation strip under an unrelated answer is a wrong
771
+ * statement about where that answer came from.
772
+ */
773
+ let turnSourceMetadata: SourceMetadata | null = null;
774
+
775
+ /** Stamp the turn's metadata onto the trailing assistant bubble. A no-op
776
+ * when there is none yet — the next write through here picks it up. */
777
+ function stampTrailingAssistantSourceMetadata(next: UnifiedChatMessage[]): UnifiedChatMessage[] {
778
+ const metadata = turnSourceMetadata;
779
+ if (!metadata) return next;
780
+ const last = next[next.length - 1];
781
+ if (!last || last.role !== 'assistant') return next;
782
+ if (last.sources === metadata.sources && last.refs === metadata.refs) return next;
783
+ return [...next.slice(0, -1), { ...last, ...metadata }];
784
+ }
785
+
786
+ /** The two stamps every trailing-assistant write needs, in one place — a
787
+ * write that skips either loses the seq the merge decides with, or the
788
+ * citations the answer was built from. */
789
+ function commitTrailingAssistant(next: UnifiedChatMessage[], seq: number | undefined): UnifiedChatMessage[] {
790
+ return stampTrailingAssistantSourceMetadata(stampTrailingAssistantSeq(next, seq));
791
+ }
792
+
758
793
  function applySegmentsToState(segments: MessageSegment[], meta?: SegmentsUpdateMetadata): void {
759
794
  const seq = meta?.streamSeq;
760
795
  // Standalone compaction updates carry the accumulator's cumulative
761
796
  // array — apply only the compaction segment (upsert) or interleaved
762
797
  // continuation text would duplicate.
763
798
  if (meta?.append && meta.isCompacting) {
764
- setMessagesInternal(stampTrailingAssistantSeq(upsertTrailingCompaction(messages, segments), seq));
799
+ setMessagesInternal(commitTrailingAssistant(upsertTrailingCompaction(messages, segments), seq));
765
800
  return;
766
801
  }
767
802
  // Post-MESSAGE_END continuation fragments append into the existing
768
803
  // bubble; replacing would wipe the completed reply.
769
804
  if (meta?.append) {
770
- setMessagesInternal(stampTrailingAssistantSeq(appendToTrailingAssistant(messages, segments), seq));
805
+ setMessagesInternal(commitTrailingAssistant(appendToTrailingAssistant(messages, segments), seq));
771
806
  return;
772
807
  }
773
- setMessagesInternal(stampTrailingAssistantSeq(updateTrailingAssistant(messages, segments), seq));
808
+ setMessagesInternal(commitTrailingAssistant(updateTrailingAssistant(messages, segments), seq));
774
809
  }
775
810
 
776
811
  function applyStreamStartToState(): void {
@@ -969,6 +1004,7 @@ export function createChatStreamReducer(options: ChatStreamReducerOptions = {}):
969
1004
  isInStream = true;
970
1005
  hasEverStreamed = true;
971
1006
  turnStartedAt = Date.now();
1007
+ turnSourceMetadata = null;
972
1008
  emit('onStreamStart');
973
1009
  applyStreamStartToState();
974
1010
  accumulator.resetSegments();
@@ -984,6 +1020,15 @@ export function createChatStreamReducer(options: ChatStreamReducerOptions = {}):
984
1020
  break;
985
1021
  }
986
1022
 
1023
+ // Per-answer source metadata. Applied to the trailing assistant bubble
1024
+ // immediately when there is one, and held for the next write when the
1025
+ // chunk beat the answer text to the reducer.
1026
+ case 'sources': {
1027
+ turnSourceMetadata = mergeSourceMetadata(turnSourceMetadata, event);
1028
+ setMessagesInternal(stampTrailingAssistantSourceMetadata(messages));
1029
+ break;
1030
+ }
1031
+
987
1032
  case 'metadata': {
988
1033
  // Legacy `parseChunkToAction` action shape, reconstructed for the
989
1034
  // callback contract.
@@ -53,6 +53,19 @@ const ToolExecutionDisplay = forwardRef<HTMLDivElement, ToolExecutionDisplayProp
53
53
  }, [message.parameters, variant]);
54
54
 
55
55
  const hasResult = isExecuted && typeof message.result === 'string' && message.result.length > 0;
56
+
57
+ // A remote (MCP) read-only tool deliberately publishes NO parameters and NO
58
+ // result — the backend hides both, and sends a human title instead. There is
59
+ // therefore nothing behind the chevron, and offering one is a promise the
60
+ // row cannot keep: the reader expands it and gets an empty box. Render the
61
+ // title as a status line instead, the same static shape the client view uses.
62
+ //
63
+ // Keyed on the absent `integratedToolType`, which is what marks a tool as
64
+ // remote rather than one of ours — and guarded on there being a title to
65
+ // show, so a title-less row keeps the old behaviour rather than collapsing
66
+ // to a blank line.
67
+ const isConciseRemoteRead = !message.integratedToolType && !!previewText && argEntries.length === 0 && !hasResult;
68
+ const isStaticRow = isClientView || isConciseRemoteRead;
56
69
  const hasBody = argEntries.length > 0 || hasResult || isExecuting;
57
70
 
58
71
  const renderStatusIcon = () => {
@@ -82,7 +95,7 @@ const ToolExecutionDisplay = forwardRef<HTMLDivElement, ToolExecutionDisplayProp
82
95
  {previewText}
83
96
  </div>
84
97
  <div className="flex h-5 w-5 shrink-0 items-center justify-center">{renderStatusIcon()}</div>
85
- {!isClientView && (
98
+ {!isStaticRow && (
86
99
  <div className="flex h-5 w-5 shrink-0 items-center justify-center">
87
100
  <ExpandChevron expanded={expanded} />
88
101
  </div>
@@ -101,9 +114,10 @@ const ToolExecutionDisplay = forwardRef<HTMLDivElement, ToolExecutionDisplayProp
101
114
  )}
102
115
  {...props}
103
116
  >
104
- {isClientView ? (
105
- // Client (Fae end-user): static, non-expandable row — no chevron, no
106
- // body. Just the explanation + status; command/args/result are hidden.
117
+ {isStaticRow ? (
118
+ // Static, non-expandable row — no chevron, no body. Two cases reach
119
+ // here: the Fae end-user view (command/args/result are admin-only
120
+ // detail) and a remote read-only tool (there IS no detail).
107
121
  <div className="flex w-full items-start gap-[var(--spacing-system-xs)] p-[var(--spacing-system-s)] text-left">
108
122
  {headerContent}
109
123
  </div>
@@ -195,6 +195,20 @@ export interface ChatMessageEnhancedProps extends Omit<HTMLAttributes<HTMLDivEle
195
195
  * back to plain text title-only.
196
196
  */
197
197
  renderEntityCard?: (reference: ChatRef) => ReactNode;
198
+ /**
199
+ * References this answer's metadata described, used to expand the
200
+ * `[card://type:id]` markers in its body.
201
+ *
202
+ * A marker on the wire carries only a type and an id, so without these a card
203
+ * has to be hydrated by id through a per-entity API — which the host may not
204
+ * have for entities that live on another platform. Supplying the reference
205
+ * here is what lets such a card render with a real title and link instead of
206
+ * falling back to its raw id.
207
+ *
208
+ * Presence is NOT a render list: only markers actually written into the body
209
+ * render, and the metadata routinely describes more than the model cited.
210
+ */
211
+ refs?: ChatRef[];
198
212
  /**
199
213
  * Host-provided anchor component for markdown links. When supplied, the
200
214
  * `<a>` override in the markdown renderer delegates to this component
@@ -296,6 +310,19 @@ export interface ChatMessageListProps extends HTMLAttributes<HTMLDivElement> {
296
310
  /** Host-provided renderer for inline entity cards. Forwarded verbatim
297
311
  * to every message's ChatMessageEnhanced. v6.1 §B.2.7. */
298
312
  renderEntityCard?: (reference: ChatRef) => ReactNode;
313
+ /**
314
+ * Content owned by ONE message, rendered directly beneath it.
315
+ *
316
+ * For anything whose subject is that specific answer rather than the thread —
317
+ * the source chips a Guide answer cites, today. Rendering such content once at
318
+ * the bottom of the thread instead is a quiet lie in a multi-answer
319
+ * conversation: it attributes the newest answer's sources to whichever answer
320
+ * the reader is actually looking at.
321
+ *
322
+ * Return `null` for messages that own nothing. Hidden and pending-placeholder
323
+ * messages never reach it — they do not render at all.
324
+ */
325
+ renderAfterMessage?: (message: Message, index: number) => ReactNode;
299
326
  /** Host-provided anchor for markdown links. Forwarded verbatim to every
300
327
  * message's ChatMessageEnhanced. Owns the unified click rule
301
328
  * (same-origin soft nav, cross-origin new tab). */
@@ -3,6 +3,7 @@
3
3
  * Contains all message structures, segments, and content types
4
4
  */
5
5
 
6
+ import type { ChatRef } from '../chat-ref.types';
6
7
  import type { AssistantType, AuthorType, ChatApprovalStatus, MessageOwner } from './chat.types';
7
8
 
8
9
  // ========== Message Type Definitions ==========
@@ -11,6 +12,15 @@ export const MESSAGE_TYPE = {
11
12
  TEXT: 'TEXT',
12
13
  THINKING: 'THINKING',
13
14
  ASK: 'ASK',
15
+ /** Per-answer source metadata (documents, videos, entity cards).
16
+ *
17
+ * TWO names for ONE payload, on purpose. `SOURCES` is the contract the
18
+ * backend is moving to; `GUIDE` is the envelope it ships in today, reused
19
+ * from Guide Mode v2 so a released frontend keeps working during the v2→v3
20
+ * rollout. Both decode through the same path, so dropping `GUIDE` later is a
21
+ * deletion here and nothing else. */
22
+ GUIDE: 'GUIDE',
23
+ SOURCES: 'SOURCES',
14
24
  EXECUTING_TOOL: 'EXECUTING_TOOL',
15
25
  EXECUTED_TOOL: 'EXECUTED_TOOL',
16
26
  APPROVAL_REQUEST: 'APPROVAL_REQUEST',
@@ -391,6 +401,55 @@ export interface ThinkingMessageData extends MessageDataBase {
391
401
  text?: string;
392
402
  }
393
403
 
404
+ /**
405
+ * A document cited by an assistant answer, rendered as a chip under it.
406
+ *
407
+ * Lives here, beside `Message`, because BOTH transports produce it now: the SSE
408
+ * adapter reads it off the per-turn metadata frame, and the NATS path decodes it
409
+ * out of a `GUIDE`/`SOURCES` chunk. It used to be declared inside
410
+ * `use-sse-chat-adapter`, which made "a Guide answer's citations" structurally a
411
+ * property of one transport — `use-sse-chat-adapter` still re-exports the name
412
+ * so existing imports keep working.
413
+ */
414
+ export interface ChatSource {
415
+ /** 1-based citation number. `[1]` in the answer text refers to this. */
416
+ index: number;
417
+ name: string;
418
+ path: string;
419
+ documentType: string;
420
+ externalUrl?: string;
421
+ /** Platform that owns the destination at `externalUrl`. */
422
+ targetPlatform?: string | null;
423
+ /** Primary-key value for single-row chips. */
424
+ id?: string;
425
+ /** Per-row items for grouped chips. */
426
+ items?: Array<{
427
+ id: string;
428
+ documentType: string;
429
+ name: string;
430
+ externalUrl?: string;
431
+ targetPlatform?: string | null;
432
+ /** In-app doc-tree path for markdown / data-room-doc rows so the
433
+ * grouped chip's anchor can trigger an in-page doc-tree swap via
434
+ * `handleChatNavClick` (parity with single-row chips + cards). */
435
+ path?: string | null;
436
+ }>;
437
+ /** RagTableConfig.id for this source. */
438
+ sourceRepo?: string;
439
+ /** Optional display label override returned by the chat API. */
440
+ label?: string;
441
+ }
442
+
443
+ /** Persisted source-metadata row. `payload` is the SAME object the live chunk
444
+ * carries, so history and realtime share one decoder (`sourceMetadataEvent`)
445
+ * and cannot drift apart. Left as an open record here rather than typed
446
+ * structurally: it is unvalidated wire data, and the decoder is what turns it
447
+ * into `ChatSource[]` / `ChatRef[]`. */
448
+ export interface SourceMetadataMessageData extends MessageDataBase {
449
+ type: 'GUIDE' | 'SOURCES';
450
+ payload?: unknown;
451
+ }
452
+
394
453
  /** Persisted `ASK` row (GraphQL `AskData`). `text` is the intro sentence, which
395
454
  * history replays as a text segment ahead of the card — same split the live
396
455
  * `ASK` chunk carries. */
@@ -533,6 +592,7 @@ export type MessageData =
533
592
  | TextMessageData
534
593
  | ThinkingMessageData
535
594
  | AskMessageData
595
+ | SourceMetadataMessageData
536
596
  | ExecutingToolMessageData
537
597
  | ExecutedToolMessageData
538
598
  | ApprovalRequestMessageData
@@ -582,6 +642,12 @@ export interface ProcessedMessage {
582
642
  * `streamSeq` so the history/realtime merge can do per-role seq coverage.
583
643
  * Absent when the source row(s) carried no seq. */
584
644
  streamSeq?: number;
645
+ /** Documents this answer cited — see `Message.sources`, the same field.
646
+ * Replayed from the turn's persisted `GUIDE`/`SOURCES` row, so a reloaded
647
+ * answer carries the citations the live one did. */
648
+ sources?: ChatSource[];
649
+ /** Entity references this answer's metadata described — see `Message.refs`. */
650
+ refs?: ChatRef[];
585
651
  }
586
652
 
587
653
  // ========== Base Message Interface ==========
@@ -633,4 +699,21 @@ export interface Message {
633
699
  * bubble like "(continue per protocol)" between the approval card
634
700
  * and the AI's follow-up. */
635
701
  hidden?: boolean;
702
+ /**
703
+ * Documents this answer cited, rendered as chips beneath it.
704
+ *
705
+ * Per MESSAGE, not per conversation: an answer's citations belong to the
706
+ * answer, and a thread can hold several answers that each cited something
707
+ * different. Ordering is a rendering concern — see `splitCitedSources`.
708
+ */
709
+ sources?: ChatSource[];
710
+ /**
711
+ * Entity references this answer's metadata described — videos and cards.
712
+ *
713
+ * Presence here does NOT mean "render it": only the `[card://type:id]`
714
+ * markers actually written into the answer text are rendered, and these
715
+ * supply the data those markers expand with. The metadata frame routinely
716
+ * describes more than the model chose to cite.
717
+ */
718
+ refs?: ChatRef[];
636
719
  }
@@ -17,12 +17,11 @@
17
17
  */
18
18
 
19
19
  import type { ChatRef } from '../chat-ref.types';
20
- import type { ChatSource } from '../hooks/use-sse-chat-adapter';
21
20
  import type { ChatAttachment } from '../utils/chat-attachment-markdown';
22
21
  import type { AuthorType } from './chat.types';
23
22
  import type { DialogItem } from './component.types';
24
23
  import type { ChatContextItem } from './context-item.types';
25
- import type { MessageSegment, ScrollAnchor } from './message.types';
24
+ import type { ChatSource, MessageSegment, ScrollAnchor } from './message.types';
26
25
 
27
26
  // ─── Dialog-list host contract (shared by the NATS + SSE adapters) ───────────
28
27
 
@@ -230,8 +229,18 @@ export interface UnifiedChatMessage {
230
229
  */
231
230
  timestamp?: Date | string | number;
232
231
 
233
- /** Guide/SSE-only: document citations. Undefined in Mingo mode. */
232
+ /**
233
+ * Documents this answer cited, rendered as chips beneath it. Produced by
234
+ * BOTH transports now — SSE reads them off the per-turn metadata frame, NATS
235
+ * decodes them out of a `GUIDE`/`SOURCES` chunk.
236
+ */
234
237
  sources?: ChatSource[];
238
+ /**
239
+ * Entity references this answer's metadata described — videos and cards.
240
+ * Data for the `[card://type:id]` markers in the body, not a render list:
241
+ * only markers actually present in the text are rendered.
242
+ */
243
+ refs?: ChatRef[];
235
244
 
236
245
  /**
237
246
  * Per-message viewport-positioning hint. Common to both modes; the
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The source strip is a legend for the sentences above it, so its order is
3
+ * READING order, not the numbering the model happened to assign. These pin that
4
+ * — and the fallback for an answer that cited nothing at all.
5
+ */
6
+
7
+ import { describe, expect, it } from 'vitest';
8
+
9
+ import type { ChatSource } from '../../types/message.types';
10
+ import { splitCitedSources } from '../cited-sources';
11
+
12
+ const source = (index: number): ChatSource => ({
13
+ index,
14
+ name: `Source ${index}`,
15
+ path: `docs/${index}`,
16
+ documentType: 'markdown',
17
+ });
18
+
19
+ const sources = [source(1), source(2), source(3)];
20
+
21
+ describe('splitCitedSources', () => {
22
+ it('orders cited sources by first mention, not by number', () => {
23
+ const { cited, uncited } = splitCitedSources(sources, 'See [3], then [1].');
24
+
25
+ expect(cited.map(s => s.index)).toEqual([3, 1]);
26
+ expect(uncited.map(s => s.index)).toEqual([2]);
27
+ });
28
+
29
+ it('places a repeated citation once, at its first mention', () => {
30
+ const { cited } = splitCitedSources(sources, '[2] … [1] … [2] again.');
31
+ expect(cited.map(s => s.index)).toEqual([2, 1]);
32
+ });
33
+
34
+ it('treats every source as uncited when the answer cited nothing', () => {
35
+ // The caller then shows the top few as "retrieved" rather than no strip.
36
+ const { cited, uncited } = splitCitedSources(sources, 'No citations in this answer.');
37
+
38
+ expect(cited).toEqual([]);
39
+ expect(uncited).toEqual(sources);
40
+ });
41
+
42
+ it('ignores a citation number no source claims', () => {
43
+ const { cited, uncited } = splitCitedSources([source(1)], 'See [7] and [1].');
44
+
45
+ expect(cited.map(s => s.index)).toEqual([1]);
46
+ expect(uncited).toEqual([]);
47
+ });
48
+
49
+ it('handles an answer with no sources', () => {
50
+ expect(splitCitedSources(undefined, '[1]')).toEqual({ cited: [], uncited: [] });
51
+ expect(splitCitedSources([], '[1]')).toEqual({ cited: [], uncited: [] });
52
+ });
53
+ });