@flamingo-stack/openframe-frontend-core 0.0.609-snapshot.20260908170120 → 0.0.609

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/events.d.ts +2 -21
  2. package/dist/chat-protocol/events.d.ts.map +1 -1
  3. package/dist/chat-protocol/index.cjs +9 -211
  4. package/dist/chat-protocol/index.cjs.map +1 -1
  5. package/dist/chat-protocol/index.js +9 -211
  6. package/dist/chat-protocol/index.js.map +1 -1
  7. package/dist/chat-protocol/nats-decoder.d.ts.map +1 -1
  8. package/dist/{chunk-2YMDDD5V.cjs → chunk-3N4FXBVJ.cjs} +3 -3
  9. package/dist/{chunk-2YMDDD5V.cjs.map → chunk-3N4FXBVJ.cjs.map} +1 -1
  10. package/dist/{chunk-THCB7NHV.cjs → chunk-3XNMDLGB.cjs} +9 -9
  11. package/dist/{chunk-THCB7NHV.cjs.map → chunk-3XNMDLGB.cjs.map} +1 -1
  12. package/dist/{chunk-GFAHCXIL.cjs → chunk-45XXK2VU.cjs} +10 -10
  13. package/dist/{chunk-GFAHCXIL.cjs.map → chunk-45XXK2VU.cjs.map} +1 -1
  14. package/dist/{chunk-2QBXG74C.js → chunk-6MLRFM3T.js} +5 -5
  15. package/dist/{chunk-IBMHEOBV.js → chunk-B3UXNGVM.js} +3 -3
  16. package/dist/{chunk-O6PO5BHE.js → chunk-B7LYKBCD.js} +5 -5
  17. package/dist/{chunk-F2C2U7CP.js → chunk-BSMPCPOZ.js} +299 -590
  18. package/dist/chunk-BSMPCPOZ.js.map +1 -0
  19. package/dist/{chunk-MGXSJI23.js → chunk-BUXGWBTF.js} +2 -2
  20. package/dist/{chunk-OIKZDXNW.js → chunk-C7CTEUU7.js} +2 -2
  21. package/dist/{chunk-EANAFFAD.cjs → chunk-CZTOSG7Q.cjs} +22 -22
  22. package/dist/{chunk-EANAFFAD.cjs.map → chunk-CZTOSG7Q.cjs.map} +1 -1
  23. package/dist/{chunk-C4KQ2XPK.cjs → chunk-D3DTC7SZ.cjs} +15 -15
  24. package/dist/{chunk-C4KQ2XPK.cjs.map → chunk-D3DTC7SZ.cjs.map} +1 -1
  25. package/dist/{chunk-HKJ3WKGW.cjs → chunk-DKNXAJMP.cjs} +159 -159
  26. package/dist/{chunk-HKJ3WKGW.cjs.map → chunk-DKNXAJMP.cjs.map} +1 -1
  27. package/dist/{chunk-UFFVMZDL.cjs → chunk-FYG7QNAO.cjs} +5 -5
  28. package/dist/{chunk-UFFVMZDL.cjs.map → chunk-FYG7QNAO.cjs.map} +1 -1
  29. package/dist/{chunk-THCSSPXU.cjs → chunk-GMOBT5NP.cjs} +70 -70
  30. package/dist/{chunk-THCSSPXU.cjs.map → chunk-GMOBT5NP.cjs.map} +1 -1
  31. package/dist/{chunk-HQSCJYCF.js → chunk-HGVW7OHI.js} +2 -2
  32. package/dist/{chunk-FS3CTGIR.js → chunk-JKM5FH63.js} +3 -3
  33. package/dist/{chunk-37CAZTLP.js → chunk-JOCVQZGT.js} +5 -5
  34. package/dist/{chunk-ROOIHDLS.js → chunk-JR7I2AGL.js} +3 -3
  35. package/dist/{chunk-OVVKVIMH.cjs → chunk-L2JWC5VS.cjs} +43 -43
  36. package/dist/{chunk-OVVKVIMH.cjs.map → chunk-L2JWC5VS.cjs.map} +1 -1
  37. package/dist/{chunk-25YIHMZ6.js → chunk-LA2W5L6K.js} +2 -2
  38. package/dist/{chunk-V6TINNLD.js → chunk-MVBRMQGU.js} +2 -2
  39. package/dist/{chunk-Q3APHZK5.cjs → chunk-NJUSDREV.cjs} +22 -22
  40. package/dist/{chunk-Q3APHZK5.cjs.map → chunk-NJUSDREV.cjs.map} +1 -1
  41. package/dist/{chunk-FASOANK7.cjs → chunk-O2M4T34Q.cjs} +4 -4
  42. package/dist/{chunk-FASOANK7.cjs.map → chunk-O2M4T34Q.cjs.map} +1 -1
  43. package/dist/{chunk-R2UDEMKK.js → chunk-OTYV6SDN.js} +3 -3
  44. package/dist/{chunk-HZS4TV34.js → chunk-QX4ANESW.js} +6 -6
  45. package/dist/{chunk-ZDLCWNM6.cjs → chunk-RZM6FPOT.cjs} +25 -25
  46. package/dist/{chunk-ZDLCWNM6.cjs.map → chunk-RZM6FPOT.cjs.map} +1 -1
  47. package/dist/{chunk-GNLV326I.cjs → chunk-SEW25Y2W.cjs} +10 -10
  48. package/dist/{chunk-GNLV326I.cjs.map → chunk-SEW25Y2W.cjs.map} +1 -1
  49. package/dist/{chunk-QE2Z6WME.cjs → chunk-TCEALWE3.cjs} +33 -33
  50. package/dist/{chunk-QE2Z6WME.cjs.map → chunk-TCEALWE3.cjs.map} +1 -1
  51. package/dist/{chunk-OJZW3GE2.js → chunk-TJ3GFULR.js} +3 -3
  52. package/dist/{chunk-Q2CNCBMK.js → chunk-VCYRJY7J.js} +4 -4
  53. package/dist/{chunk-YXTAV2E3.cjs → chunk-XNDTYTVT.cjs} +683 -974
  54. package/dist/chunk-XNDTYTVT.cjs.map +1 -0
  55. package/dist/{chunk-WJQOYSR3.cjs → chunk-ZRLFBLME.cjs} +3 -3
  56. package/dist/{chunk-WJQOYSR3.cjs.map → chunk-ZRLFBLME.cjs.map} +1 -1
  57. package/dist/components/case-studies/index.cjs +9 -9
  58. package/dist/components/case-studies/index.js +3 -3
  59. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  60. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  61. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  62. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +28 -5
  63. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  64. package/dist/components/chat/index.cjs +2 -2
  65. package/dist/components/chat/index.js +1 -1
  66. package/dist/components/chat/remark-card-links.d.ts +4 -5
  67. package/dist/components/chat/remark-card-links.d.ts.map +1 -1
  68. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +1 -1
  69. package/dist/components/chat/tool-execution-display.d.ts.map +1 -1
  70. package/dist/components/chat/types/component.types.d.ts +0 -27
  71. package/dist/components/chat/types/component.types.d.ts.map +1 -1
  72. package/dist/components/chat/types/message.types.d.ts +1 -81
  73. package/dist/components/chat/types/message.types.d.ts.map +1 -1
  74. package/dist/components/chat/types/unified-chat-state.types.d.ts +3 -12
  75. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  76. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  77. package/dist/components/contact/index.cjs +4 -4
  78. package/dist/components/contact/index.js +3 -3
  79. package/dist/components/docs/index.cjs +7 -7
  80. package/dist/components/docs/index.js +6 -6
  81. package/dist/components/embeds/index.cjs +4 -4
  82. package/dist/components/embeds/index.js +3 -3
  83. package/dist/components/faq/index.cjs +4 -4
  84. package/dist/components/faq/index.js +3 -3
  85. package/dist/components/features/index.cjs +3 -3
  86. package/dist/components/features/index.js +2 -2
  87. package/dist/components/help-center-pages/index.cjs +23 -23
  88. package/dist/components/help-center-pages/index.js +14 -14
  89. package/dist/components/index.cjs +38 -38
  90. package/dist/components/index.js +13 -13
  91. package/dist/components/meeting-scheduler/index.cjs +24 -24
  92. package/dist/components/meeting-scheduler/index.js +2 -2
  93. package/dist/components/navigation/index.cjs +6 -6
  94. package/dist/components/navigation/index.js +5 -5
  95. package/dist/components/onboarding-guides/index.cjs +6 -6
  96. package/dist/components/onboarding-guides/index.js +5 -5
  97. package/dist/components/tickets/index.cjs +7 -7
  98. package/dist/components/tickets/index.js +6 -6
  99. package/dist/components/ui/index.cjs +3 -3
  100. package/dist/components/ui/index.js +2 -2
  101. package/dist/index.cjs +7 -7
  102. package/dist/index.js +6 -6
  103. package/dist/utils/index.cjs.map +1 -1
  104. package/dist/utils/index.js.map +1 -1
  105. package/package.json +1 -1
  106. package/src/chat-protocol/events.ts +1 -22
  107. package/src/chat-protocol/nats-decoder.ts +0 -12
  108. package/src/components/chat/chat-message-enhanced.tsx +12 -37
  109. package/src/components/chat/chat-message-list.tsx +1 -14
  110. package/src/components/chat/embeddable-chat.tsx +87 -47
  111. package/src/components/chat/hooks/use-sse-chat-adapter.ts +28 -5
  112. package/src/components/chat/remark-card-links.ts +12 -14
  113. package/src/components/chat/stream/chat-stream-reducer.ts +3 -48
  114. package/src/components/chat/tool-execution-display.tsx +4 -18
  115. package/src/components/chat/types/component.types.ts +0 -27
  116. package/src/components/chat/types/message.types.ts +0 -83
  117. package/src/components/chat/types/unified-chat-state.types.ts +3 -12
  118. package/src/components/chat/utils/process-historical-messages.ts +0 -25
  119. package/dist/chat-protocol/card-marker.d.ts +0 -31
  120. package/dist/chat-protocol/card-marker.d.ts.map +0 -1
  121. package/dist/chat-protocol/source-metadata.d.ts +0 -56
  122. package/dist/chat-protocol/source-metadata.d.ts.map +0 -1
  123. package/dist/chunk-F2C2U7CP.js.map +0 -1
  124. package/dist/chunk-YXTAV2E3.cjs.map +0 -1
  125. package/dist/components/chat/utils/cited-sources.d.ts +0 -24
  126. package/dist/components/chat/utils/cited-sources.d.ts.map +0 -1
  127. package/dist/components/chat/utils/host-message.d.ts +0 -41
  128. package/dist/components/chat/utils/host-message.d.ts.map +0 -1
  129. package/src/chat-protocol/__tests__/card-marker.test.ts +0 -63
  130. package/src/chat-protocol/__tests__/source-metadata.test.ts +0 -243
  131. package/src/chat-protocol/card-marker.ts +0 -40
  132. package/src/chat-protocol/source-metadata.ts +0 -336
  133. package/src/components/chat/__tests__/tool-execution-display.test.tsx +0 -70
  134. package/src/components/chat/utils/__tests__/cited-sources.test.ts +0 -80
  135. package/src/components/chat/utils/__tests__/host-message.test.ts +0 -92
  136. package/src/components/chat/utils/__tests__/process-historical-messages-sources.test.ts +0 -138
  137. package/src/components/chat/utils/cited-sources.ts +0 -61
  138. package/src/components/chat/utils/host-message.ts +0 -87
  139. /package/dist/{chunk-2QBXG74C.js.map → chunk-6MLRFM3T.js.map} +0 -0
  140. /package/dist/{chunk-IBMHEOBV.js.map → chunk-B3UXNGVM.js.map} +0 -0
  141. /package/dist/{chunk-O6PO5BHE.js.map → chunk-B7LYKBCD.js.map} +0 -0
  142. /package/dist/{chunk-MGXSJI23.js.map → chunk-BUXGWBTF.js.map} +0 -0
  143. /package/dist/{chunk-OIKZDXNW.js.map → chunk-C7CTEUU7.js.map} +0 -0
  144. /package/dist/{chunk-HQSCJYCF.js.map → chunk-HGVW7OHI.js.map} +0 -0
  145. /package/dist/{chunk-FS3CTGIR.js.map → chunk-JKM5FH63.js.map} +0 -0
  146. /package/dist/{chunk-37CAZTLP.js.map → chunk-JOCVQZGT.js.map} +0 -0
  147. /package/dist/{chunk-ROOIHDLS.js.map → chunk-JR7I2AGL.js.map} +0 -0
  148. /package/dist/{chunk-25YIHMZ6.js.map → chunk-LA2W5L6K.js.map} +0 -0
  149. /package/dist/{chunk-V6TINNLD.js.map → chunk-MVBRMQGU.js.map} +0 -0
  150. /package/dist/{chunk-R2UDEMKK.js.map → chunk-OTYV6SDN.js.map} +0 -0
  151. /package/dist/{chunk-HZS4TV34.js.map → chunk-QX4ANESW.js.map} +0 -0
  152. /package/dist/{chunk-OJZW3GE2.js.map → chunk-TJ3GFULR.js.map} +0 -0
  153. /package/dist/{chunk-Q2CNCBMK.js.map → chunk-VCYRJY7J.js.map} +0 -0
@@ -1,336 +0,0 @@
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
- }
@@ -1,70 +0,0 @@
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,80 +0,0 @@
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
- });
54
-
55
- describe('splitCitedSources — code is not prose', () => {
56
- const retrieved = [
57
- { index: 1, name: 'Install the agent', path: '', documentType: '' },
58
- { index: 2, name: 'Configure the tenant', path: '', documentType: '' },
59
- ];
60
-
61
- it('ignores array indexing inside a fenced block', () => {
62
- // This assistant answers with scripts, so `$hosts[1]` is common — and a
63
- // source marked cited by a snippet is a citation the prose never made.
64
- const answer = ['Run the script below.', '```powershell', '$hosts[1] | Restart-Service', '```'].join('\n');
65
- const { cited, uncited } = splitCitedSources(retrieved, answer);
66
-
67
- expect(cited).toEqual([]);
68
- expect(uncited).toHaveLength(2);
69
- });
70
-
71
- it('ignores an index inside an inline code span', () => {
72
- expect(splitCitedSources(retrieved, 'Read `argv[1]` first.').cited).toEqual([]);
73
- });
74
-
75
- it('still reads a citation that sits beside code', () => {
76
- const { cited } = splitCitedSources(retrieved, 'Per the guide [1], run `argv[2]`.');
77
-
78
- expect(cited.map(row => row.index)).toEqual([1]);
79
- });
80
- });
@@ -1,92 +0,0 @@
1
- /**
2
- * The host-rows → rendered-Message seam.
3
- *
4
- * It rebuilds field by field, so anything the upstream type gains and this step
5
- * is not updated for vanishes with no error anywhere: the thread still renders,
6
- * just missing whatever the new field carried. That has happened twice — see
7
- * the note on the module. These pin the fields whose loss is invisible.
8
- */
9
-
10
- import { describe, expect, it } from 'vitest';
11
-
12
- import type { UnifiedChatMessage } from '../../types/unified-chat-state.types';
13
- import { mapHostMessage, pruneTimestampCache } from '../host-message';
14
-
15
- const cache = () => new Map<string, Date>();
16
-
17
- function assistantRow(fields: Partial<UnifiedChatMessage> = {}): UnifiedChatMessage {
18
- return { id: 'a1', role: 'assistant', content: 'Use this guide [1].', ...fields };
19
- }
20
-
21
- describe('mapHostMessage', () => {
22
- it('carries an answer’s source metadata to the renderer', () => {
23
- // Without this the citation strip never renders and each `[card://…]` in
24
- // the body falls back to being titled by its own id.
25
- const sources = [{ index: 1, name: 'Install the agent', path: 'docs/agent.md', documentType: 'markdown' }];
26
- const refs = [{ type: 'video', id: 'MdFJNoJeqZQ', title: 'Install the agent', url: null }];
27
-
28
- const message = mapHostMessage(assistantRow({ sources, refs }), { timestampCache: cache() });
29
-
30
- // By reference: the message memo compares this way.
31
- expect(message.sources).toBe(sources);
32
- expect(message.refs).toBe(refs);
33
- });
34
-
35
- it('omits empty metadata rather than stamping empty arrays', () => {
36
- const message = mapHostMessage(assistantRow({ sources: [], refs: [] }), { timestampCache: cache() });
37
-
38
- expect(message).not.toHaveProperty('sources');
39
- expect(message).not.toHaveProperty('refs');
40
- });
41
-
42
- it('keeps a hidden row hidden', () => {
43
- // A synthetic directive the model must see and the reader must not.
44
- expect(mapHostMessage(assistantRow({ hidden: true }), { timestampCache: cache() }).hidden).toBe(true);
45
- });
46
-
47
- it('forwards the scroll anchor and a user row’s context chips', () => {
48
- const contextItems = [{ type: 'DEVICE', id: 'device-42', label: 'ELK-PROD-07' }];
49
- const message = mapHostMessage(
50
- { id: 'u1', role: 'user', content: 'Why is it offline?', scrollAnchor: 'top', contextItems },
51
- { timestampCache: cache() },
52
- );
53
-
54
- expect(message.scrollAnchor).toBe('top');
55
- expect(message.contextItems).toBe(contextItems);
56
- });
57
-
58
- it('renders segments as the bubble’s content', () => {
59
- const segments = [{ type: 'text' as const, text: '## Install' }];
60
- expect(mapHostMessage(assistantRow({ content: '', segments }), { timestampCache: cache() }).content).toBe(segments);
61
- });
62
-
63
- it('resolves role defaults only where the host supplied nothing', () => {
64
- const options = { userName: 'Ada Lovelace', userAvatar: 'https://cdn.test/ada.png', timestampCache: cache() };
65
-
66
- expect(mapHostMessage({ id: 'u1', role: 'user', content: 'Hi' }, options)).toMatchObject({
67
- name: 'Ada Lovelace',
68
- avatar: 'https://cdn.test/ada.png',
69
- });
70
- expect(mapHostMessage({ id: 'u2', role: 'user', content: 'Hi', name: 'Support' }, options).name).toBe('Support');
71
- expect(mapHostMessage(assistantRow(), options).name).toBe('Mingo');
72
- });
73
-
74
- it('keeps one row’s fallback timestamp stable across renders', () => {
75
- // Re-stamping it would move a bubble's time on every unrelated keystroke.
76
- const timestampCache = cache();
77
- const first = mapHostMessage(assistantRow(), { timestampCache }).timestamp;
78
- expect(mapHostMessage(assistantRow(), { timestampCache }).timestamp).toEqual(first);
79
- });
80
- });
81
-
82
- describe('pruneTimestampCache', () => {
83
- it('forgets rows that left the thread and keeps the ones still in it', () => {
84
- const timestampCache = new Map([
85
- ['a1', new Date()],
86
- ['gone', new Date()],
87
- ]);
88
- pruneTimestampCache(timestampCache, new Set(['a1']));
89
-
90
- expect([...timestampCache.keys()]).toEqual(['a1']);
91
- });
92
- });