@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
@@ -0,0 +1,336 @@
1
+ /**
2
+ * Source-metadata payload → `{ sources, refs }`.
3
+ *
4
+ * ONE decoder for two arrival paths: the live `GUIDE`/`SOURCES` NATS chunk and
5
+ * the persisted row of the same name in dialog history. That is the whole point
6
+ * of putting it here rather than in either consumer — a reloaded thread has to
7
+ * render identically to the live turn, and two parsers is exactly how that stops
8
+ * being true.
9
+ *
10
+ * Everything is validated, and anything that fails is DROPPED rather than
11
+ * repaired: this payload is assembled from a remote MCP server's tool output,
12
+ * so a malformed row means an upstream contract slip, and rendering a chip with
13
+ * a blank title or a link to a non-https URL is worse than rendering nothing.
14
+ *
15
+ * Server-safe: no React, no browser APIs beyond `URL`.
16
+ */
17
+
18
+ import type { ChatRef } from '../components/chat/chat-ref.types';
19
+ import type { ChatSource } from '../components/chat/types/message.types';
20
+ import { CARD_REFERENCE } from './card-marker';
21
+ import type { SourcesEvent } from './events';
22
+ import { isRecord } from './wire-narrow';
23
+
24
+ /** YouTube ids are exactly 11 chars of the URL-safe alphabet. */
25
+ const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;
26
+
27
+ /** Video URL fields carried through verbatim, once validated as https. */
28
+ const VIDEO_URL_KEYS = ['videoUrl', 'highlightVideoUrl', 'videoPoster', 'highlightVideoPoster'] as const;
29
+
30
+ function text(value: unknown): string | undefined {
31
+ if (typeof value !== 'string') return undefined;
32
+ const trimmed = value.trim();
33
+ return trimmed || undefined;
34
+ }
35
+
36
+ /**
37
+ * `null` survives, anything non-string becomes `undefined`.
38
+ *
39
+ * The distinction is load-bearing for `targetPlatform` and `path`, where the
40
+ * backend uses an explicit `null` to mean "this row has no destination" — which
41
+ * downstream navigation treats differently from "the field was not sent".
42
+ */
43
+ function nullableText(value: unknown): string | null | undefined {
44
+ return value === null ? null : text(value);
45
+ }
46
+
47
+ /** An https URL, or nothing. Plain http and non-URLs are dropped — these become
48
+ * hrefs and video sources in the panel. */
49
+ function httpsUrl(value: unknown): string | undefined {
50
+ const candidate = text(value);
51
+ if (!candidate) return undefined;
52
+ try {
53
+ return new URL(candidate).protocol === 'https:' ? candidate : undefined;
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * A YouTube video id, from either a bare id or any of the watch/short/embed URL
61
+ * shapes. Returns the ID, never a URL — the player takes an id.
62
+ */
63
+ export function youtubeVideoId(value: unknown): string | undefined {
64
+ const candidate = text(value);
65
+ if (!candidate) return undefined;
66
+ if (YOUTUBE_ID.test(candidate)) return candidate;
67
+
68
+ const url = httpsUrl(candidate);
69
+ if (!url) return undefined;
70
+ const parsed = new URL(url);
71
+ const hostname = parsed.hostname.toLowerCase();
72
+ const isYoutubeHost = hostname === 'youtu.be' || hostname === 'youtube.com' || hostname.endsWith('.youtube.com');
73
+ if (!isYoutubeHost) return undefined;
74
+
75
+ const fromPath =
76
+ hostname === 'youtu.be'
77
+ ? parsed.pathname.split('/').filter(Boolean)[0]
78
+ : /^\/(?:embed|v|shorts)\/([A-Za-z0-9_-]{11})(?:\/|$)/.exec(parsed.pathname)?.[1];
79
+ const id = fromPath ?? parsed.searchParams.get('v') ?? undefined;
80
+ return id && YOUTUBE_ID.test(id) ? id : undefined;
81
+ }
82
+
83
+ function sourceItems(value: unknown): NonNullable<ChatSource['items']> | undefined {
84
+ if (!Array.isArray(value)) return undefined;
85
+ const items = value.filter(isRecord).flatMap(item => {
86
+ const id = text(item.id);
87
+ const documentType = text(item.documentType);
88
+ const name = text(item.name);
89
+ // A grouped row without these three has nothing to render OR navigate with.
90
+ if (!id || !documentType || !name) return [];
91
+
92
+ const externalUrl = httpsUrl(item.externalUrl);
93
+ const targetPlatform = nullableText(item.targetPlatform);
94
+ const path = nullableText(item.path);
95
+ return [
96
+ {
97
+ id,
98
+ documentType,
99
+ name,
100
+ ...(externalUrl ? { externalUrl } : {}),
101
+ ...(targetPlatform !== undefined ? { targetPlatform } : {}),
102
+ ...(path !== undefined ? { path } : {}),
103
+ },
104
+ ];
105
+ });
106
+ return items.length > 0 ? items : undefined;
107
+ }
108
+
109
+ /**
110
+ * Cited documents, keyed by their citation number.
111
+ *
112
+ * `index` and `name` are required because they ARE the chip: the number the
113
+ * answer's `[1]` refers to, and the text on it. `path` is NOT required — it is
114
+ * one of several ways a chip resolves a destination (an `externalUrl` or a
115
+ * grouped item can carry it instead), and a source is still worth showing when
116
+ * it has none.
117
+ *
118
+ * A duplicate `index` keeps the first occurrence: two chips answering to the
119
+ * same `[1]` is not a state the strip can render meaningfully.
120
+ */
121
+ function sources(value: unknown): ChatSource[] {
122
+ if (!Array.isArray(value)) return [];
123
+ const claimed = new Set<number>();
124
+ const decoded: ChatSource[] = [];
125
+
126
+ for (const candidate of value) {
127
+ if (!isRecord(candidate)) continue;
128
+ const index = candidate.index;
129
+ const name = text(candidate.name);
130
+ const isUsableIndex = typeof index === 'number' && Number.isInteger(index) && index > 0 && !claimed.has(index);
131
+ if (!isUsableIndex || !name) continue;
132
+ claimed.add(index);
133
+
134
+ const path = text(candidate.path);
135
+ const documentType = text(candidate.documentType);
136
+ const externalUrl = httpsUrl(candidate.externalUrl);
137
+ const targetPlatform = nullableText(candidate.targetPlatform);
138
+ const id = text(candidate.id);
139
+ const sourceRepo = text(candidate.sourceRepo);
140
+ const label = text(candidate.label);
141
+ const items = sourceItems(candidate.items);
142
+
143
+ decoded.push({
144
+ index,
145
+ name,
146
+ // Both are typed non-optional on `ChatSource` and predate this decoder;
147
+ // '' is the established "no value" for them across the SSE path.
148
+ path: path ?? '',
149
+ documentType: documentType ?? '',
150
+ ...(externalUrl ? { externalUrl } : {}),
151
+ ...(targetPlatform !== undefined ? { targetPlatform } : {}),
152
+ ...(id ? { id } : {}),
153
+ ...(sourceRepo ? { sourceRepo } : {}),
154
+ ...(label ? { label } : {}),
155
+ ...(items ? { items } : {}),
156
+ });
157
+ }
158
+ return decoded;
159
+ }
160
+
161
+ /**
162
+ * Player metadata for a video ref, in the key vocabulary the card dispatcher
163
+ * already reads (`itemVideoMetadata` / `decodeVideoMarkerId` in
164
+ * `entity-cards/dispatch.tsx`).
165
+ *
166
+ * `youtubeUrl` holds a bare video ID, not a URL. The name is inaccurate and
167
+ * predates this decoder — but it is the established key on both the producing
168
+ * and the consuming side, and a more honest name here would simply be a field
169
+ * nothing reads. Renaming it is a separate change that has to move both ends at
170
+ * once.
171
+ *
172
+ * `videoUrl` and `youtubeUrl` stay mutually exclusive: they select different
173
+ * players (a `<video>`/HLS source vs an embed facade), so carrying both would
174
+ * make the renderer guess.
175
+ */
176
+ function videoMetadata(value: unknown, url: string | null): Record<string, string> {
177
+ const metadata: Record<string, string> = {};
178
+ if (isRecord(value)) {
179
+ for (const key of VIDEO_URL_KEYS) {
180
+ const validated = httpsUrl(value[key]);
181
+ if (validated) metadata[key] = validated;
182
+ }
183
+ const declaredId = youtubeVideoId(value.youtubeUrl);
184
+ if (declaredId) metadata.youtubeUrl = declaredId;
185
+ }
186
+
187
+ // The top-level `url` is the authority when present: it is what the backend
188
+ // resolved for THIS video, while `metadata` is passthrough from the row.
189
+ if (url) {
190
+ const idFromUrl = youtubeVideoId(url);
191
+ if (idFromUrl) {
192
+ metadata.youtubeUrl = idFromUrl;
193
+ delete metadata.videoUrl;
194
+ } else {
195
+ metadata.videoUrl = url;
196
+ delete metadata.youtubeUrl;
197
+ }
198
+ }
199
+ return metadata;
200
+ }
201
+
202
+ /** Video references. `ref` must parse AND be of type `video` — a mistyped row
203
+ * would otherwise render through the entity-card path with no player. */
204
+ function videos(value: unknown): ChatRef[] {
205
+ if (!Array.isArray(value)) return [];
206
+ return value.filter(isRecord).flatMap(video => {
207
+ const match = typeof video.ref === 'string' ? CARD_REFERENCE.exec(video.ref) : null;
208
+ if (!match || match[1] !== 'video') return [];
209
+
210
+ const id = match[2];
211
+ const url = httpsUrl(video.url) ?? null;
212
+ const sourceRepo = text(video.sourceRepo);
213
+ const metadata = videoMetadata(video.metadata, url);
214
+ return [
215
+ {
216
+ type: 'video',
217
+ id,
218
+ title: text(video.title) ?? id,
219
+ url,
220
+ ...(sourceRepo ? { sourceRepo } : {}),
221
+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
222
+ },
223
+ ];
224
+ });
225
+ }
226
+
227
+ /**
228
+ * Entity-card references, enriched from `sources` where the two describe the
229
+ * same row.
230
+ *
231
+ * A card carries only `type` + `id` on the wire; its human title and link live
232
+ * on the matching source. Without the match the card still renders — with its
233
+ * id as the title, which is ugly but honest, and better than dropping a card
234
+ * the answer text explicitly points at.
235
+ *
236
+ * `entityType`/`entityId` are cross-checked against the parsed `ref` because
237
+ * they are three statements of the same fact, and a disagreement means the row
238
+ * was assembled wrongly upstream.
239
+ */
240
+ function cards(value: unknown, decodedSources: ChatSource[]): ChatRef[] {
241
+ if (!Array.isArray(value)) return [];
242
+ return value.filter(isRecord).flatMap(card => {
243
+ const match = typeof card.ref === 'string' ? CARD_REFERENCE.exec(card.ref) : null;
244
+ // `video` is handled by `videos()`; a card claiming that type would render
245
+ // the wrong component.
246
+ if (!match || match[1] === 'video') return [];
247
+
248
+ const type = text(card.entityType);
249
+ const id = text(card.entityId);
250
+ if (!type || !id || type !== match[1] || id !== match[2]) return [];
251
+
252
+ const source = decodedSources.find(candidate => candidate.id === id && candidate.documentType === type);
253
+ return [
254
+ {
255
+ type,
256
+ id,
257
+ title: source?.name ?? id,
258
+ url: source?.externalUrl ?? null,
259
+ ...(source?.sourceRepo ? { sourceRepo: source.sourceRepo } : {}),
260
+ ...(source?.targetPlatform !== undefined ? { targetPlatform: source.targetPlatform } : {}),
261
+ ...(source?.path ? { metadata: { path: source.path } } : {}),
262
+ },
263
+ ];
264
+ });
265
+ }
266
+
267
+ /** Last `type:id` wins nothing — the FIRST occurrence is kept, so a payload that
268
+ * lists a card twice cannot flip which copy the body expands to. */
269
+ function deduplicateRefs(refs: ChatRef[]): ChatRef[] {
270
+ const byIdentity = new Map<string, ChatRef>();
271
+ for (const ref of refs) {
272
+ const identity = `${ref.type}:${ref.id}`;
273
+ if (!byIdentity.has(identity)) byIdentity.set(identity, ref);
274
+ }
275
+ return [...byIdentity.values()];
276
+ }
277
+
278
+ /**
279
+ * Decode one source-metadata payload into its event, or `null` when there is
280
+ * nothing usable in it.
281
+ *
282
+ * Returning `null` for an empty result matters: the reducer stamps this onto a
283
+ * message, and an event carrying two empty arrays would overwrite metadata that
284
+ * an earlier chunk of the same turn had already supplied.
285
+ */
286
+ export function sourceMetadataEvent(payload: unknown): SourcesEvent | null {
287
+ if (!isRecord(payload)) return null;
288
+
289
+ const decodedSources = sources(payload.sources);
290
+ const refs = deduplicateRefs([...videos(payload.videos), ...cards(payload.cards, decodedSources)]);
291
+ if (decodedSources.length === 0 && refs.length === 0) return null;
292
+
293
+ return {
294
+ type: 'sources',
295
+ ...(decodedSources.length > 0 ? { sources: decodedSources } : {}),
296
+ ...(refs.length > 0 ? { refs } : {}),
297
+ };
298
+ }
299
+
300
+ /** What one assistant answer carries: its citations and its expandable refs. */
301
+ export interface SourceMetadata {
302
+ sources?: ChatSource[];
303
+ refs?: ChatRef[];
304
+ }
305
+
306
+ /**
307
+ * Fold one decoded chunk into an answer's accumulated metadata.
308
+ *
309
+ * A single turn can call several remote tools, each returning its own metadata,
310
+ * so this merges rather than replaces — and it is shared by the live reducer and
311
+ * the history replay precisely because those two must agree on what a reloaded
312
+ * answer shows.
313
+ *
314
+ * First writer wins per identity (`index` for a source, `type:id` for a ref),
315
+ * the same rule the decoder applies within one payload.
316
+ *
317
+ * KNOWN LIMIT: citation numbers are assigned per tool result, so two tool calls
318
+ * in one turn can both claim `[1]`. The later source is dropped rather than
319
+ * renumbered — by then the numbers are already written into the answer text,
320
+ * and renumbering would point `[1]` at a document the sentence is not about.
321
+ */
322
+ export function mergeSourceMetadata(previous: SourceMetadata | null, event: SourcesEvent): SourceMetadata {
323
+ const byIndex = new Map<number, ChatSource>();
324
+ for (const source of [...(previous?.sources ?? []), ...(event.sources ?? [])]) {
325
+ if (!byIndex.has(source.index)) byIndex.set(source.index, source);
326
+ }
327
+ const byIdentity = new Map<string, ChatRef>();
328
+ for (const ref of [...(previous?.refs ?? []), ...(event.refs ?? [])]) {
329
+ const identity = `${ref.type}:${ref.id}`;
330
+ if (!byIdentity.has(identity)) byIdentity.set(identity, ref);
331
+ }
332
+ return {
333
+ ...(byIndex.size > 0 ? { sources: [...byIndex.values()] } : {}),
334
+ ...(byIdentity.size > 0 ? { refs: [...byIdentity.values()] } : {}),
335
+ };
336
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `ToolExecutionDisplay` — the running/ran-a-tool row.
3
+ *
4
+ * These pin WHO gets an expander. A remote (MCP) read-only tool publishes no
5
+ * parameters and no result on purpose, so a chevron on that row opens an empty
6
+ * box — the failure this file exists to prevent. Local tools, and anything that
7
+ * actually has detail, must keep theirs.
8
+ */
9
+
10
+ import { render, screen } from '@testing-library/react';
11
+ import { describe, expect, it } from 'vitest';
12
+
13
+ import { ToolExecutionDisplay } from '../tool-execution-display';
14
+ import type { ToolExecutionData } from '../types/message.types';
15
+
16
+ /**
17
+ * The `EXECUTING_TOOL` shape the backend sends for a remote read-only tool: a
18
+ * human title, and nothing else to show.
19
+ *
20
+ * `integratedToolType: ''` is what a remote tool looks like after decoding —
21
+ * the wire sends `null` and the decoder normalizes it (`strOr`). That empty
22
+ * value is the marker "not one of our integrations".
23
+ */
24
+ const remoteRead: ToolExecutionData = {
25
+ type: 'EXECUTING_TOOL',
26
+ integratedToolType: '',
27
+ toolFunction: 'search_docs',
28
+ toolTitle: 'Searching OpenFrame resources',
29
+ toolExecutionRequestId: 'execution-123',
30
+ };
31
+
32
+ /** The row is a `<button>` only when it can be expanded. */
33
+ const expander = () => screen.queryByRole('button');
34
+
35
+ describe('ToolExecutionDisplay', () => {
36
+ it('renders a remote read-only tool as a static row', () => {
37
+ render(<ToolExecutionDisplay message={remoteRead} assistantType="mingo" />);
38
+
39
+ expect(screen.getByText('Searching OpenFrame resources')).toBeTruthy();
40
+ expect(expander()).toBeNull();
41
+ });
42
+
43
+ it('keeps the expander when a remote tool does have a result', () => {
44
+ render(
45
+ <ToolExecutionDisplay
46
+ message={{ ...remoteRead, type: 'EXECUTED_TOOL', success: true, result: '{"tickets":[]}' }}
47
+ assistantType="mingo"
48
+ />,
49
+ );
50
+ expect(expander()).toBeTruthy();
51
+ });
52
+
53
+ it('keeps the expander when a remote tool does have arguments', () => {
54
+ render(<ToolExecutionDisplay message={{ ...remoteRead, parameters: { query: 'agent' } }} assistantType="mingo" />);
55
+ expect(expander()).toBeTruthy();
56
+ });
57
+
58
+ it('keeps the expander for a local tool, whose empty body still shows progress', () => {
59
+ // `integratedToolType` is what marks a tool as one of ours; those rows show
60
+ // a live "Result:" placeholder while executing, so the body is not empty.
61
+ render(<ToolExecutionDisplay message={{ ...remoteRead, integratedToolType: 'FLEET' }} assistantType="mingo" />);
62
+ expect(expander()).toBeTruthy();
63
+ });
64
+
65
+ it('keeps the old behaviour when the backend sent no title', () => {
66
+ // Collapsing to a static row here would render a blank line.
67
+ render(<ToolExecutionDisplay message={{ ...remoteRead, toolTitle: undefined }} assistantType="mingo" />);
68
+ expect(expander()).toBeTruthy();
69
+ });
70
+ });
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import React, { forwardRef, memo, useEffect, useMemo, useRef } from 'react';
4
+ import { createCardMarkerScanner } from '../../chat-protocol/card-marker';
4
5
  import { cn } from '../../utils/cn';
5
6
  import { isToday } from '../../utils/date-utils';
6
7
  import { formatDate, formatTime } from '../../utils/format-date';
@@ -42,7 +43,10 @@ const MENTION_MARKER_REGEX = /(^|[^\w@])@[a-zA-Z]+:([A-Za-z0-9_.+/=-]*[A-Za-z0-9
42
43
  * grammar widens (today: snake_case OR kebab-case; closer `]` OR `)`),
43
44
  * both files must update.
44
45
  */
45
- const CARD_MARKER_REGEX = /\[card:\/\/([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)[\])]/g;
46
+ /** Scanner for `[card://type:id]` in answer text. Built from the shared
47
+ * grammar so the body renderer and the metadata decoder cannot disagree on
48
+ * what a marker is — see `chat-protocol/card-marker.ts`. */
49
+ const CARD_MARKER_REGEX = createCardMarkerScanner();
46
50
 
47
51
  /** Timestamp label: today's messages show time only ("2:47 PM"),
48
52
  * older messages prepend a locale-formatted date ("05/05/2026 2:47 PM"
@@ -103,6 +107,7 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
103
107
  renderContextItem,
104
108
  renderMention,
105
109
  renderEntityCard,
110
+ refs,
106
111
  onAskSelect,
107
112
  NavLinkAnchor,
108
113
  ...props
@@ -180,9 +185,29 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
180
185
  // (and its open menu) survives across chunks. Invalidated per key when the
181
186
  // render fn identity changes.
182
187
  const renderedCardNodeCache = useRef(
183
- new Map<string, { render: ((ref: ChatRef) => React.ReactNode) | undefined; node: React.ReactNode }>(),
188
+ new Map<
189
+ string,
190
+ {
191
+ render: ((ref: ChatRef) => React.ReactNode) | undefined;
192
+ /** The descriptor the node was built from. Part of the cache identity
193
+ * because metadata can arrive AFTER the marker was first rendered —
194
+ * a card mounted from the bare `{type, id}` descriptor has to be
195
+ * rebuilt once its real title and URL land. */
196
+ ref: ChatRef | undefined;
197
+ node: React.ReactNode;
198
+ }
199
+ >(),
184
200
  );
185
201
 
202
+ /** The answer's own references, by `type:id`. What turns a bare marker into
203
+ * a card with a title and a link, without a per-entity lookup the host may
204
+ * not even have an API for. */
205
+ const refByKey = useMemo(() => {
206
+ const byKey = new Map<string, ChatRef>();
207
+ for (const described of refs ?? []) byKey.set(`${described.type}:${described.id}`, described);
208
+ return byKey;
209
+ }, [refs]);
210
+
186
211
  /**
187
212
  * Per-message rendering plan for `[card://type:id]` markers.
188
213
  *
@@ -241,8 +266,11 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
241
266
  // stops React from re-mounting the card (and closing its open
242
267
  // menu / re-fetching) on every stream chunk. Also dedups the same
243
268
  // key emitted twice within one message.
269
+ // The answer's metadata wins when it described this reference: it
270
+ // carries the title, URL and source the wire marker cannot.
271
+ const describedRef = refByKey.get(key);
244
272
  let entry = cache.get(key);
245
- if (!entry || entry.render !== render) {
273
+ if (!entry || entry.render !== render || entry.ref !== describedRef) {
246
274
  // The marker is the ONLY data on the wire: cards hydrate by id
247
275
  // from the host's per-object APIs, so a minimal {type, id}
248
276
  // descriptor is all the renderer needs to mount the loader.
@@ -257,13 +285,13 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
257
285
  // the id rather than `undefined`) and `url` to null (matches
258
286
  // the no-link semantics fetch-mode cards rely on — they
259
287
  // resolve their own URL after fetch).
260
- const refForRender: ChatRef = {
288
+ const refForRender: ChatRef = describedRef ?? {
261
289
  type: cardType,
262
290
  id: cardId,
263
291
  title: cardId,
264
292
  url: null,
265
293
  };
266
- entry = { render, node: render(refForRender) };
294
+ entry = { render, ref: describedRef, node: render(refForRender) };
267
295
  cache.set(key, entry);
268
296
  }
269
297
  const rendered = entry.node;
@@ -326,7 +354,7 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
326
354
  }
327
355
  });
328
356
  return { inlineByKey, partsBySegment, usedKeys };
329
- }, [hasMarkerSupport, renderEntityCard, segments]);
357
+ }, [hasMarkerSupport, renderEntityCard, refByKey, segments]);
330
358
 
331
359
  // Drop cached nodes for markers no longer present so the cache can't grow
332
360
  // unbounded as a long message's markers change. Deliberately an EFFECT,
@@ -716,6 +744,9 @@ const MemoizedChatMessageEnhanced = memo(ChatMessageEnhanced, (prevProps, nextPr
716
744
  // equality holds across streaming chunks.
717
745
  prevProps.renderMention === nextProps.renderMention &&
718
746
  prevProps.renderEntityCard === nextProps.renderEntityCard &&
747
+ // Reference equality: the reducer sets this once per answer and the host
748
+ // forwards the same array instance, so it holds across streaming chunks.
749
+ prevProps.refs === nextProps.refs &&
719
750
  // Same stability contract as the renderers above: hosts pass a `useCallback`
720
751
  // (EmbeddableChat passes its memoized `handleSend`), so this holds across
721
752
  // streaming chunks instead of re-rendering every ask card per chunk.
@@ -137,6 +137,7 @@ const ChatMessageList = forwardRef<HTMLDivElement, ChatMessageListProps>(
137
137
  resolveContextIcon,
138
138
  renderContextItem,
139
139
  renderMention,
140
+ renderAfterMessage,
140
141
  onAskSelect,
141
142
  NavLinkAnchor,
142
143
  ...props
@@ -985,7 +986,8 @@ const ChatMessageList = forwardRef<HTMLDivElement, ChatMessageListProps>(
985
986
  !hasNonEmptyContent(message.content) &&
986
987
  (!Array.isArray(message.content) || message.content.every(s => s.type === 'text'));
987
988
  if (isEmptyPendingTurn) return null;
988
- return (
989
+ const ownedContent = renderAfterMessage?.(message, index);
990
+ const row = (
989
991
  <ChatMessageEnhanced
990
992
  key={message.id}
991
993
  ref={getRegisterMessageEl(message.id)}
@@ -1005,10 +1007,21 @@ const ChatMessageList = forwardRef<HTMLDivElement, ChatMessageListProps>(
1005
1007
  renderContextItem={renderContextItem}
1006
1008
  renderMention={renderMention}
1007
1009
  renderEntityCard={renderEntityCard}
1010
+ refs={message.refs}
1008
1011
  onAskSelect={index > lastUserMessageIndex ? onAskSelect : undefined}
1009
1012
  NavLinkAnchor={NavLinkAnchor}
1010
1013
  />
1011
1014
  );
1015
+ // Only wrap when there IS owned content: the bare row keeps
1016
+ // its own key and its place as a direct flex child, so a
1017
+ // thread without any stays byte-identical to before.
1018
+ if (!ownedContent) return row;
1019
+ return (
1020
+ <div key={message.id} className="flex w-full min-w-0 flex-col">
1021
+ {row}
1022
+ {ownedContent}
1023
+ </div>
1024
+ );
1012
1025
  })}
1013
1026
  </div>
1014
1027
  </div>