@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,92 @@
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
+ });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Source metadata through the HISTORY path.
3
+ *
4
+ * The backend persists an answer's metadata as its OWN row, written when the
5
+ * remote tool returns — so it arrives as a separate history message, BEFORE the
6
+ * answer text, and has to end up on the answer anyway. These pin that regrouping,
7
+ * because the failure it prevents is invisible in the live thread and only shows
8
+ * up on reload: the chips are simply gone.
9
+ */
10
+
11
+ import { describe, expect, it } from 'vitest';
12
+
13
+ import type { HistoricalMessage } from '../../types';
14
+ import { processHistoricalMessages } from '../process-historical-messages';
15
+
16
+ const SOURCE = {
17
+ index: 1,
18
+ name: 'Install the OpenFrame Agent on Windows',
19
+ path: 'onboarding-guides/install-the-openframe-agent-on-windows',
20
+ documentType: 'onboarding_guide',
21
+ id: '88dd40cc',
22
+ sourceRepo: 'onboarding-guides',
23
+ };
24
+
25
+ /** The metadata row, as the backend persists it. */
26
+ const metadataRow = (id: string, createdAt: string): HistoricalMessage => ({
27
+ id,
28
+ chatType: 'ADMIN_AI_CHAT',
29
+ createdAt,
30
+ owner: { type: 'ASSISTANT' },
31
+ messageData: [
32
+ {
33
+ type: 'GUIDE',
34
+ payload: {
35
+ sources: [SOURCE],
36
+ cards: [{ ref: '[card://onboarding_guide:88dd40cc]', entityType: 'onboarding_guide', entityId: '88dd40cc' }],
37
+ },
38
+ },
39
+ ],
40
+ });
41
+
42
+ const answerRow = (id: string, createdAt: string, text: string): HistoricalMessage => ({
43
+ id,
44
+ chatType: 'ADMIN_AI_CHAT',
45
+ createdAt,
46
+ owner: { type: 'ASSISTANT' },
47
+ messageData: [{ type: 'TEXT', text }],
48
+ });
49
+
50
+ const userRow = (id: string, createdAt: string): HistoricalMessage => ({
51
+ id,
52
+ chatType: 'ADMIN_AI_CHAT',
53
+ createdAt,
54
+ owner: { type: 'ADMIN' },
55
+ messageData: [{ type: 'TEXT', text: 'How do I install the agent?' }],
56
+ });
57
+
58
+ describe('processHistoricalMessages — source metadata', () => {
59
+ it('attaches a metadata row to the answer it precedes', () => {
60
+ const { messages } = processHistoricalMessages([
61
+ userRow('u1', '2026-08-26T09:00:00Z'),
62
+ metadataRow('m1', '2026-08-26T09:00:01Z'),
63
+ answerRow('a1', '2026-08-26T09:00:02Z', 'Use this guide [1].'),
64
+ ]);
65
+
66
+ const answer = messages[messages.length - 1];
67
+ expect(answer.role).toBe('assistant');
68
+ expect(answer.sources).toEqual([SOURCE]);
69
+ expect(answer.refs).toEqual([
70
+ {
71
+ type: 'onboarding_guide',
72
+ id: '88dd40cc',
73
+ // Enriched off the matching source — the card row carries no title.
74
+ title: SOURCE.name,
75
+ url: null,
76
+ sourceRepo: 'onboarding-guides',
77
+ metadata: { path: SOURCE.path },
78
+ },
79
+ ]);
80
+ });
81
+
82
+ it('does not render a metadata-only row as its own empty bubble', () => {
83
+ const { messages } = processHistoricalMessages([
84
+ userRow('u1', '2026-08-26T09:00:00Z'),
85
+ metadataRow('m1', '2026-08-26T09:00:01Z'),
86
+ answerRow('a1', '2026-08-26T09:00:02Z', 'Answer.'),
87
+ ]);
88
+
89
+ expect(messages.filter(m => m.role === 'assistant')).toHaveLength(1);
90
+ });
91
+
92
+ it('keeps each answer’s metadata on its own answer', () => {
93
+ // The reason this is per-message at all: two turns, two different sets.
94
+ const secondSource = { ...SOURCE, index: 1, name: 'Configure Your Tenant Settings', id: 'other' };
95
+ const { messages } = processHistoricalMessages([
96
+ userRow('u1', '2026-08-26T09:00:00Z'),
97
+ metadataRow('m1', '2026-08-26T09:00:01Z'),
98
+ answerRow('a1', '2026-08-26T09:00:02Z', 'First answer [1].'),
99
+ userRow('u2', '2026-08-26T09:01:00Z'),
100
+ {
101
+ ...metadataRow('m2', '2026-08-26T09:01:01Z'),
102
+ messageData: [{ type: 'GUIDE', payload: { sources: [secondSource] } }],
103
+ },
104
+ answerRow('a2', '2026-08-26T09:01:02Z', 'Second answer [1].'),
105
+ ]);
106
+
107
+ const answers = messages.filter(m => m.role === 'assistant');
108
+ expect(answers).toHaveLength(2);
109
+ expect(answers[0].sources?.[0].name).toBe(SOURCE.name);
110
+ expect(answers[1].sources?.[0].name).toBe(secondSource.name);
111
+ });
112
+
113
+ it('leaves an answer with no metadata untouched', () => {
114
+ const { messages } = processHistoricalMessages([
115
+ userRow('u1', '2026-08-26T09:00:00Z'),
116
+ answerRow('a1', '2026-08-26T09:00:02Z', 'Plain answer.'),
117
+ ]);
118
+
119
+ const answer = messages[messages.length - 1];
120
+ expect(answer).not.toHaveProperty('sources');
121
+ expect(answer).not.toHaveProperty('refs');
122
+ });
123
+
124
+ it('unions metadata from several tool calls in one turn', () => {
125
+ const { messages } = processHistoricalMessages([
126
+ userRow('u1', '2026-08-26T09:00:00Z'),
127
+ metadataRow('m1', '2026-08-26T09:00:01Z'),
128
+ {
129
+ ...metadataRow('m2', '2026-08-26T09:00:02Z'),
130
+ messageData: [{ type: 'GUIDE', payload: { sources: [{ index: 2, name: 'Second tool result' }] } }],
131
+ },
132
+ answerRow('a1', '2026-08-26T09:00:03Z', 'Both [1] and [2].'),
133
+ ]);
134
+
135
+ const answer = messages[messages.length - 1];
136
+ expect(answer.sources?.map(source => source.index)).toEqual([1, 2]);
137
+ });
138
+ });
@@ -0,0 +1,43 @@
1
+ import type { ChatSource } from '../types/message.types';
2
+
3
+ /** How many retrieved sources to show when the answer cited none of them. */
4
+ export const FALLBACK_TOP_RETRIEVED = 3;
5
+
6
+ export interface CitedSources {
7
+ /** Sources the answer referenced, in the order the answer first referenced
8
+ * them — NOT in `index` order. */
9
+ cited: ChatSource[];
10
+ /** Everything retrieved but not referenced, in the order supplied. */
11
+ uncited: ChatSource[];
12
+ }
13
+
14
+ /** `[1]`, `[12]` — a citation marker in the answer body. */
15
+ const CITATION = /\[(\d+)\]/g;
16
+
17
+ /**
18
+ * Split an answer's sources into the ones it cited and the ones it did not.
19
+ *
20
+ * Reading order, not numeric order: the strip is a legend for the sentences
21
+ * above it, so the chip for the citation the reader meets first comes first,
22
+ * even when the model numbered it `[3]`. A number cited twice is placed once,
23
+ * at its first mention.
24
+ *
25
+ * `content` is the flat answer text. A segmented message has to be flattened by
26
+ * the caller — citation markers live in text segments, and this function
27
+ * deliberately does not know what a segment is.
28
+ */
29
+ export function splitCitedSources(sources: ChatSource[] | undefined, content: string): CitedSources {
30
+ if (!sources || sources.length === 0) return { cited: [], uncited: [] };
31
+
32
+ const firstMentionAt = new Map<number, number>();
33
+ for (const match of content.matchAll(CITATION)) {
34
+ const index = Number.parseInt(match[1], 10);
35
+ if (!firstMentionAt.has(index)) firstMentionAt.set(index, firstMentionAt.size);
36
+ }
37
+
38
+ const cited = sources
39
+ .filter(source => firstMentionAt.has(source.index))
40
+ .sort((a, b) => (firstMentionAt.get(a.index) ?? 0) - (firstMentionAt.get(b.index) ?? 0));
41
+ const uncited = sources.filter(source => !firstMentionAt.has(source.index));
42
+ return { cited, uncited };
43
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `UnifiedChatMessage` (what the chat state produces, and what a host like
3
+ * Mingo hands in) → `Message` (what the thread renders).
4
+ *
5
+ * The two types overlap but are not the same: this step resolves the role's
6
+ * default name and avatar, folds `segments` back into `content`, and stamps a
7
+ * timestamp for rows that arrived without one. So it is a REBUILD, and a
8
+ * rebuild names every field it keeps — which makes "a new field was added
9
+ * upstream" a silent data loss by default, not a compile error.
10
+ *
11
+ * It has cost us that twice already. `hidden` was dropped here, and a synthetic
12
+ * directive the reader was never meant to see rendered as an ordinary bubble.
13
+ * Then Guide Mode's `sources` / `refs` were dropped here, and every answer lost
14
+ * its citation strip while its cards fell back to being titled by their own id
15
+ * — with the decoder, the reducer and the renderer all working correctly, which
16
+ * is exactly why it took a screenshot diff to find.
17
+ *
18
+ * Hence this module: pure, cheap to render-free test, and the one place the
19
+ * pass-through list is pinned.
20
+ */
21
+
22
+ import type { Message } from '../types/message.types';
23
+ import type { UnifiedChatMessage } from '../types/unified-chat-state.types';
24
+
25
+ export interface HostMessageMapOptions {
26
+ /** Display name for `user` rows when the host supplies none. */
27
+ userName?: string;
28
+ /** Avatar for `user` rows when the host supplies none. */
29
+ userAvatar?: string;
30
+ /**
31
+ * Fallback timestamps for rows that carry none, keyed by message id. Mutated:
32
+ * a row must keep the SAME fallback across renders, or its bubble re-stamps
33
+ * itself on every keystroke elsewhere in the thread.
34
+ */
35
+ timestampCache: Map<string, Date>;
36
+ }
37
+
38
+ export function mapHostMessage(m: UnifiedChatMessage, options: HostMessageMapOptions): Message {
39
+ const { userName, userAvatar, timestampCache } = options;
40
+
41
+ let timestamp: Date;
42
+ if (m.timestamp != null) {
43
+ timestamp = new Date(m.timestamp);
44
+ } else {
45
+ const cached = timestampCache.get(m.id);
46
+ timestamp = cached ?? new Date();
47
+ if (!cached) timestampCache.set(m.id, timestamp);
48
+ }
49
+
50
+ return {
51
+ id: m.id,
52
+ role: m.role,
53
+ // Host-supplied per-message name/avatar win (e.g. the signed-in user's
54
+ // full name + photo on a `user` bubble); fall back to the role default
55
+ // when the host doesn't provide them.
56
+ name: m.name ?? (m.role === 'assistant' ? 'Mingo' : (userName ?? 'You')),
57
+ avatar: m.avatar ?? (m.role === 'user' ? (userAvatar ?? null) : null),
58
+ // Forward the host's authorType so user bubbles get the same accent
59
+ // name color as the standalone /mingo page (user → 'admin').
60
+ ...(m.authorType ? { authorType: m.authorType } : {}),
61
+ content: m.segments && m.segments.length > 0 ? m.segments : m.content,
62
+ timestamp,
63
+ assistantType: m.role === 'assistant' ? ('mingo' as const) : undefined,
64
+ // `hidden` is load-bearing, NOT cosmetic: it carries synthetic rows
65
+ // (e.g. an auto-continuation directive) that the LLM must see but the
66
+ // reader must not. See the module note above.
67
+ ...(m.hidden ? { hidden: true } : {}),
68
+ ...(m.scrollAnchor ? { scrollAnchor: m.scrollAnchor } : {}),
69
+ // Forward attached context items so the user bubble renders its chips.
70
+ ...(m.contextItems && m.contextItems.length > 0 ? { contextItems: m.contextItems } : {}),
71
+ // Per-answer source metadata: the citation strip under the answer, and the
72
+ // descriptions the `[card://…]` markers in its body expand into.
73
+ ...(m.sources && m.sources.length > 0 ? { sources: m.sources } : {}),
74
+ ...(m.refs && m.refs.length > 0 ? { refs: m.refs } : {}),
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Drop cached fallback timestamps for messages no longer in the thread, so the
80
+ * map cannot grow unbounded across a long-lived session.
81
+ */
82
+ export function pruneTimestampCache(timestampCache: Map<string, Date>, liveIds: Set<string>): void {
83
+ if (timestampCache.size <= liveIds.size) return;
84
+ for (const id of timestampCache.keys()) {
85
+ if (!liveIds.has(id)) timestampCache.delete(id);
86
+ }
87
+ }
@@ -34,6 +34,7 @@ import {
34
34
  // One normalizer for ask rows, shared with the live decoder — history and the
35
35
  // stream must agree on which options are usable.
36
36
  import { normalizeAskOptions } from '../../../chat-protocol/nats-decoder';
37
+ import { mergeSourceMetadata, sourceMetadataEvent, type SourceMetadata } from '../../../chat-protocol/source-metadata';
37
38
  import { applyApprovalStatusToSegment } from '../stream/message-mutations';
38
39
  import {
39
40
  MESSAGE_TYPE,
@@ -121,6 +122,13 @@ export function decodeHistoricalMessageData(data: MessageData): ChatStreamEvent
121
122
  }
122
123
  return null;
123
124
 
125
+ // Persisted source metadata, through the SAME decoder the live chunk uses
126
+ // (`sourceMetadataEvent`). That shared parse is the whole reason a reloaded
127
+ // answer renders identically to the one the reader watched arrive.
128
+ case MESSAGE_TYPE.GUIDE:
129
+ case MESSAGE_TYPE.SOURCES:
130
+ return 'payload' in data ? sourceMetadataEvent(data.payload) : null;
131
+
124
132
  // Same completeness gate as the live decoder (`decodeNatsChunk`): a
125
133
  // persisted row without a question or without options is not a card the
126
134
  // user can answer, so it replays as nothing rather than as empty chrome.
@@ -596,6 +604,12 @@ export function processHistoricalMessages(
596
604
  // MAX persisted seq across the rows grouped into the current assistant turn
597
605
  // — carried onto the flushed message's streamSeq for per-role merge coverage.
598
606
  let currentAssistantStreamSeq: number | undefined;
607
+ // Source metadata for the current assistant turn. It is persisted as its OWN
608
+ // row (the backend saves it when the remote tool returns, before the answer
609
+ // text exists), so it arrives as a separate history message that groups into
610
+ // the same turn — and has to be carried across the group rather than applied
611
+ // where it was read.
612
+ let currentAssistantSourceMetadata: SourceMetadata | null = null;
599
613
 
600
614
  /**
601
615
  * Flush the current assistant message to processedMessages.
@@ -614,6 +628,7 @@ export function processHistoricalMessages(
614
628
  timestamp: currentAssistantTimestamp || new Date(),
615
629
  avatar: assistantAvatar,
616
630
  ...(currentAssistantStreamSeq !== undefined ? { streamSeq: currentAssistantStreamSeq } : {}),
631
+ ...(currentAssistantSourceMetadata ?? {}),
617
632
  });
618
633
  accumulator.resetSegments();
619
634
  }
@@ -628,6 +643,10 @@ export function processHistoricalMessages(
628
643
  currentAssistantTimestamp = null;
629
644
  lastAssistantId = null;
630
645
  currentAssistantStreamSeq = undefined;
646
+ // Reset UNCONDITIONALLY, for the same reason the seq above is: a turn whose
647
+ // only row was metadata renders nothing, and leaving it set would stamp the
648
+ // NEXT answer with citations that belong to this one.
649
+ currentAssistantSourceMetadata = null;
631
650
  };
632
651
 
633
652
  messages.forEach((msg, index) => {
@@ -694,6 +713,12 @@ export function processHistoricalMessages(
694
713
  messageDataArray.forEach(data => {
695
714
  const event = decodeHistoricalMessageData(data);
696
715
  if (!event) return;
716
+ // Metadata is a property OF the turn, not a segment in it — it never
717
+ // reaches the accumulator, which would have nothing to do with it.
718
+ if (event.type === 'sources') {
719
+ currentAssistantSourceMetadata = mergeSourceMetadata(currentAssistantSourceMetadata, event);
720
+ return;
721
+ }
697
722
  applyHistoryEvent(
698
723
  event,
699
724
  accumulator,