@flamingo-stack/openframe-frontend-core 0.0.490-1506.3944.1 → 0.0.490

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 (293) hide show
  1. package/dist/{chunk-5CJR2GZ4.cjs → chunk-2MKUHJ3O.cjs} +31 -31
  2. package/dist/{chunk-5CJR2GZ4.cjs.map → chunk-2MKUHJ3O.cjs.map} +1 -1
  3. package/dist/{chunk-S2NHJDKQ.cjs → chunk-3IEVA5AO.cjs} +62 -62
  4. package/dist/{chunk-S2NHJDKQ.cjs.map → chunk-3IEVA5AO.cjs.map} +1 -1
  5. package/dist/{chunk-GTWO5NAY.js → chunk-6CFFISUC.js} +2 -2
  6. package/dist/{chunk-VHG6AX5V.js → chunk-6CJ2K7BD.js} +2 -2
  7. package/dist/{chunk-4NWARV5I.js → chunk-6QK3ONDD.js} +2 -2
  8. package/dist/{chunk-YHOIAA2E.cjs → chunk-7I42V2OD.cjs} +60 -60
  9. package/dist/chunk-7I42V2OD.cjs.map +1 -0
  10. package/dist/{chunk-T2EGSZFN.js → chunk-AIRNG27G.js} +5 -6
  11. package/dist/chunk-AIRNG27G.js.map +1 -0
  12. package/dist/{chunk-NWX7MMF5.cjs → chunk-AW63ET2A.cjs} +15 -15
  13. package/dist/{chunk-NWX7MMF5.cjs.map → chunk-AW63ET2A.cjs.map} +1 -1
  14. package/dist/{chunk-TKN5667N.js → chunk-BZMOEWWS.js} +10 -10
  15. package/dist/chunk-BZMOEWWS.js.map +1 -0
  16. package/dist/{chunk-DSDZ5T4P.cjs → chunk-D5LQMRPU.cjs} +5 -5
  17. package/dist/{chunk-DSDZ5T4P.cjs.map → chunk-D5LQMRPU.cjs.map} +1 -1
  18. package/dist/{chunk-CORIBKHG.js → chunk-EGXCWZYP.js} +2 -2
  19. package/dist/{chunk-5EYRXSY5.cjs → chunk-EJQUYZXF.cjs} +9 -9
  20. package/dist/{chunk-5EYRXSY5.cjs.map → chunk-EJQUYZXF.cjs.map} +1 -1
  21. package/dist/{chunk-P4WTZU6L.cjs → chunk-FY5XAW3H.cjs} +11 -11
  22. package/dist/{chunk-P4WTZU6L.cjs.map → chunk-FY5XAW3H.cjs.map} +1 -1
  23. package/dist/{chunk-VQ523ORK.cjs → chunk-GMPYR3MX.cjs} +26 -26
  24. package/dist/{chunk-VQ523ORK.cjs.map → chunk-GMPYR3MX.cjs.map} +1 -1
  25. package/dist/{chunk-QSCHCZL3.cjs → chunk-GUTYUMGV.cjs} +7 -7
  26. package/dist/{chunk-QSCHCZL3.cjs.map → chunk-GUTYUMGV.cjs.map} +1 -1
  27. package/dist/{chunk-Q6E7VJ4W.cjs → chunk-IEZ3YBAP.cjs} +27 -28
  28. package/dist/chunk-IEZ3YBAP.cjs.map +1 -0
  29. package/dist/{chunk-HSACATCD.js → chunk-MPYDX5WX.js} +2 -2
  30. package/dist/{chunk-RQLBHKXN.js → chunk-NGEFYPY7.js} +2 -2
  31. package/dist/{chunk-BE6DK7QY.js → chunk-OQIMH2WQ.js} +8985 -11081
  32. package/dist/chunk-OQIMH2WQ.js.map +1 -0
  33. package/dist/{chunk-CSYSYJCF.cjs → chunk-UZZT65PQ.cjs} +37 -37
  34. package/dist/{chunk-CSYSYJCF.cjs.map → chunk-UZZT65PQ.cjs.map} +1 -1
  35. package/dist/{chunk-YZ2OIYQ3.js → chunk-VDZO6IDR.js} +4 -4
  36. package/dist/{chunk-UUYRJPGJ.js → chunk-VL2YMDPH.js} +4 -4
  37. package/dist/{chunk-5LMGFI4J.cjs → chunk-VUXNXWOQ.cjs} +4946 -7042
  38. package/dist/chunk-VUXNXWOQ.cjs.map +1 -0
  39. package/dist/{chunk-XQ2B74SI.js → chunk-WLM3F3WU.js} +2 -2
  40. package/dist/components/case-studies/index.cjs +8 -8
  41. package/dist/components/case-studies/index.js +2 -2
  42. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  43. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  44. package/dist/components/chat/guide-display.d.ts +14 -0
  45. package/dist/components/chat/guide-display.d.ts.map +1 -0
  46. package/dist/components/chat/hooks/index.d.ts +1 -0
  47. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  48. package/dist/components/chat/hooks/use-chat.d.ts.map +1 -1
  49. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +48 -15
  50. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  51. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts +6 -0
  52. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts.map +1 -0
  53. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +57 -10
  54. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  55. package/dist/components/chat/index.cjs +2 -8
  56. package/dist/components/chat/index.cjs.map +1 -1
  57. package/dist/components/chat/index.d.ts +1 -1
  58. package/dist/components/chat/index.d.ts.map +1 -1
  59. package/dist/components/chat/index.js +15 -21
  60. package/dist/components/chat/types/api.types.d.ts +81 -1
  61. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  62. package/dist/components/chat/types/component.types.d.ts +6 -0
  63. package/dist/components/chat/types/component.types.d.ts.map +1 -1
  64. package/dist/components/chat/types/message.types.d.ts +15 -2
  65. package/dist/components/chat/types/message.types.d.ts.map +1 -1
  66. package/dist/components/chat/types/processing.types.d.ts +93 -2
  67. package/dist/components/chat/types/processing.types.d.ts.map +1 -1
  68. package/dist/components/chat/utils/chunk-parser.d.ts +25 -0
  69. package/dist/components/chat/utils/chunk-parser.d.ts.map +1 -0
  70. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts +6 -34
  71. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts.map +1 -1
  72. package/dist/components/chat/utils/index.d.ts +3 -2
  73. package/dist/components/chat/utils/index.d.ts.map +1 -1
  74. package/dist/components/chat/utils/message-segment-accumulator.d.ts +5 -0
  75. package/dist/components/chat/utils/message-segment-accumulator.d.ts.map +1 -1
  76. package/dist/components/chat/utils/process-historical-messages.d.ts +11 -59
  77. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  78. package/dist/components/contact/index.cjs +3 -3
  79. package/dist/components/contact/index.js +2 -2
  80. package/dist/components/docs/index.cjs +5 -5
  81. package/dist/components/docs/index.js +4 -4
  82. package/dist/components/embeds/index.cjs +3 -3
  83. package/dist/components/embeds/index.js +2 -2
  84. package/dist/components/faq/index.cjs +3 -3
  85. package/dist/components/faq/index.js +2 -2
  86. package/dist/components/features/index.cjs +2 -2
  87. package/dist/components/features/index.js +1 -1
  88. package/dist/components/help-center-pages/index.cjs +20 -20
  89. package/dist/components/help-center-pages/index.js +11 -11
  90. package/dist/components/index.cjs +130 -170
  91. package/dist/components/index.cjs.map +1 -1
  92. package/dist/components/index.js +23 -63
  93. package/dist/components/index.js.map +1 -1
  94. package/dist/components/navigation/index.cjs +2 -2
  95. package/dist/components/navigation/index.js +1 -1
  96. package/dist/components/onboarding-guides/index.cjs +5 -5
  97. package/dist/components/onboarding-guides/index.js +4 -4
  98. package/dist/components/onboarding-guides/onboarding-guide-detail-view.d.ts.map +1 -1
  99. package/dist/components/related-content/index.cjs +3 -3
  100. package/dist/components/related-content/index.js +2 -2
  101. package/dist/components/shared/product-release/release-detail-page.d.ts.map +1 -1
  102. package/dist/components/tickets/index.cjs +5 -5
  103. package/dist/components/tickets/index.js +4 -4
  104. package/dist/components/ui/index.cjs +2 -42
  105. package/dist/components/ui/index.cjs.map +1 -1
  106. package/dist/components/ui/index.d.ts +2 -1
  107. package/dist/components/ui/index.d.ts.map +1 -1
  108. package/dist/components/ui/index.js +15 -55
  109. package/dist/components/ui/rich-markdown-renderer.d.ts +34 -0
  110. package/dist/components/ui/rich-markdown-renderer.d.ts.map +1 -0
  111. package/dist/components/ui/simple-markdown-renderer.d.ts +73 -0
  112. package/dist/components/ui/simple-markdown-renderer.d.ts.map +1 -0
  113. package/dist/index.cjs +2 -58
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.js +15 -71
  116. package/dist/utils/index.cjs +40 -169
  117. package/dist/utils/index.cjs.map +1 -1
  118. package/dist/utils/index.d.ts +0 -1
  119. package/dist/utils/index.d.ts.map +1 -1
  120. package/dist/utils/index.js +41 -162
  121. package/dist/utils/index.js.map +1 -1
  122. package/dist/utils/markdown-section-extractor.d.ts.map +1 -1
  123. package/package.json +1 -7
  124. package/src/components/chat/__tests__/chat-message-list.test.tsx +5 -293
  125. package/src/components/chat/chat-message-enhanced.tsx +80 -163
  126. package/src/components/chat/chat-message-list.tsx +109 -358
  127. package/src/components/chat/embeddable-chat.tsx +0 -6
  128. package/src/components/chat/guide-display.tsx +44 -0
  129. package/src/components/chat/hooks/.index.md +33 -30
  130. package/src/components/chat/hooks/.use-nats-chat-adapter.md +55 -36
  131. package/src/components/chat/hooks/.use-realtime-chunk-processor.md +77 -0
  132. package/src/components/chat/hooks/index.ts +1 -0
  133. package/src/components/chat/hooks/use-chat.ts +0 -8
  134. package/src/components/chat/hooks/use-nats-chat-adapter.ts +825 -243
  135. package/src/components/chat/hooks/use-realtime-chunk-processor.ts +489 -0
  136. package/src/components/chat/hooks/use-sse-chat-adapter.ts +684 -380
  137. package/src/components/chat/index.ts +1 -5
  138. package/src/components/chat/thinking-display.tsx +1 -1
  139. package/src/components/chat/types/.api.types.md +49 -39
  140. package/src/components/chat/types/.processing.types.md +58 -29
  141. package/src/components/chat/types/api.types.ts +73 -6
  142. package/src/components/chat/types/component.types.ts +9 -0
  143. package/src/components/chat/types/message.types.ts +17 -1
  144. package/src/components/chat/types/processing.types.ts +53 -11
  145. package/src/components/chat/utils/.chunk-parser.md +62 -0
  146. package/src/components/chat/utils/.index.md +40 -31
  147. package/src/components/chat/utils/chunk-parser.ts +262 -0
  148. package/src/components/chat/utils/extract-incomplete-message-state.ts +5 -63
  149. package/src/components/chat/utils/index.ts +8 -5
  150. package/src/components/chat/utils/message-segment-accumulator.ts +19 -0
  151. package/src/components/chat/utils/process-historical-messages.ts +390 -352
  152. package/src/components/onboarding-guides/onboarding-guide-detail-view.tsx +4 -22
  153. package/src/components/shared/legal-document/legal-document-page.tsx +1 -1
  154. package/src/components/shared/product-release/release-detail-page.tsx +4 -19
  155. package/src/components/ui/.simple-markdown-renderer.md +52 -0
  156. package/src/components/ui/index.ts +2 -1
  157. package/src/components/ui/release-changelog-section.tsx +1 -1
  158. package/src/components/ui/rich-markdown-renderer.tsx +1223 -0
  159. package/src/components/ui/simple-markdown-renderer.tsx +964 -0
  160. package/src/components/ui/ticket-info-section.tsx +1 -1
  161. package/src/stories/ChatMessageEnhanced.stories.tsx +48 -1
  162. package/src/utils/index.ts +0 -1
  163. package/src/utils/markdown-section-extractor.ts +56 -41
  164. package/dist/chat-protocol/decode.d.ts +0 -58
  165. package/dist/chat-protocol/decode.d.ts.map +0 -1
  166. package/dist/chat-protocol/encode.d.ts +0 -44
  167. package/dist/chat-protocol/encode.d.ts.map +0 -1
  168. package/dist/chat-protocol/env-flag.d.ts +0 -35
  169. package/dist/chat-protocol/env-flag.d.ts.map +0 -1
  170. package/dist/chat-protocol/events.d.ts +0 -196
  171. package/dist/chat-protocol/events.d.ts.map +0 -1
  172. package/dist/chat-protocol/frames.d.ts +0 -213
  173. package/dist/chat-protocol/frames.d.ts.map +0 -1
  174. package/dist/chat-protocol/index.cjs +0 -494
  175. package/dist/chat-protocol/index.cjs.map +0 -1
  176. package/dist/chat-protocol/index.d.ts +0 -18
  177. package/dist/chat-protocol/index.d.ts.map +0 -1
  178. package/dist/chat-protocol/index.js +0 -478
  179. package/dist/chat-protocol/index.js.map +0 -1
  180. package/dist/chat-protocol/ip-normalize.d.ts +0 -44
  181. package/dist/chat-protocol/ip-normalize.d.ts.map +0 -1
  182. package/dist/chat-protocol/nats-decoder.d.ts +0 -26
  183. package/dist/chat-protocol/nats-decoder.d.ts.map +0 -1
  184. package/dist/chunk-5LMGFI4J.cjs.map +0 -1
  185. package/dist/chunk-BE6DK7QY.js.map +0 -1
  186. package/dist/chunk-Q6E7VJ4W.cjs.map +0 -1
  187. package/dist/chunk-T2EGSZFN.js.map +0 -1
  188. package/dist/chunk-TKN5667N.js.map +0 -1
  189. package/dist/chunk-YHOIAA2E.cjs.map +0 -1
  190. package/dist/components/chat/stream/chat-dialog-store.d.ts +0 -184
  191. package/dist/components/chat/stream/chat-dialog-store.d.ts.map +0 -1
  192. package/dist/components/chat/stream/chat-stream-reducer.d.ts +0 -367
  193. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +0 -1
  194. package/dist/components/chat/stream/delta-batcher.d.ts +0 -51
  195. package/dist/components/chat/stream/delta-batcher.d.ts.map +0 -1
  196. package/dist/components/chat/stream/index.d.ts +0 -17
  197. package/dist/components/chat/stream/index.d.ts.map +0 -1
  198. package/dist/components/chat/stream/message-mutations.d.ts +0 -77
  199. package/dist/components/chat/stream/message-mutations.d.ts.map +0 -1
  200. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts +0 -22
  201. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts.map +0 -1
  202. package/dist/components/ui/markdown/base-components.d.ts +0 -51
  203. package/dist/components/ui/markdown/base-components.d.ts.map +0 -1
  204. package/dist/components/ui/markdown/engine.d.ts +0 -99
  205. package/dist/components/ui/markdown/engine.d.ts.map +0 -1
  206. package/dist/components/ui/markdown/heading-ids.d.ts +0 -65
  207. package/dist/components/ui/markdown/heading-ids.d.ts.map +0 -1
  208. package/dist/components/ui/markdown/index.d.ts +0 -18
  209. package/dist/components/ui/markdown/index.d.ts.map +0 -1
  210. package/dist/components/ui/markdown/mermaid-diagram.d.ts +0 -79
  211. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +0 -1
  212. package/dist/components/ui/markdown/rich/embed-overrides.d.ts +0 -14
  213. package/dist/components/ui/markdown/rich/embed-overrides.d.ts.map +0 -1
  214. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts +0 -40
  215. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts.map +0 -1
  216. package/dist/components/ui/markdown/rich/shortcodes.d.ts +0 -8
  217. package/dist/components/ui/markdown/rich/shortcodes.d.ts.map +0 -1
  218. package/dist/components/ui/markdown/sanitize.d.ts +0 -153
  219. package/dist/components/ui/markdown/sanitize.d.ts.map +0 -1
  220. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts +0 -23
  221. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts.map +0 -1
  222. package/dist/components/ui/markdown/streaming.d.ts +0 -78
  223. package/dist/components/ui/markdown/streaming.d.ts.map +0 -1
  224. package/dist/components/ui/markdown/text-size.d.ts +0 -34
  225. package/dist/components/ui/markdown/text-size.d.ts.map +0 -1
  226. package/dist/utils/markdown-fences.d.ts +0 -42
  227. package/dist/utils/markdown-fences.d.ts.map +0 -1
  228. package/dist/utils/markdown-heading-id.d.ts +0 -85
  229. package/dist/utils/markdown-heading-id.d.ts.map +0 -1
  230. package/src/chat-protocol/__tests__/__snapshots__/nats-decoder-golden.test.ts.snap +0 -307
  231. package/src/chat-protocol/__tests__/chat-protocol.test.ts +0 -516
  232. package/src/chat-protocol/__tests__/env-flag.test.ts +0 -52
  233. package/src/chat-protocol/__tests__/ip-normalize.test.ts +0 -136
  234. package/src/chat-protocol/__tests__/nats-decoder-golden.test.ts +0 -228
  235. package/src/chat-protocol/decode.ts +0 -278
  236. package/src/chat-protocol/encode.ts +0 -71
  237. package/src/chat-protocol/env-flag.ts +0 -39
  238. package/src/chat-protocol/events.ts +0 -232
  239. package/src/chat-protocol/frames.ts +0 -245
  240. package/src/chat-protocol/index.ts +0 -21
  241. package/src/chat-protocol/ip-normalize.ts +0 -146
  242. package/src/chat-protocol/nats-decoder.ts +0 -252
  243. package/src/components/chat/__tests__/chat-message-streaming-memo.test.tsx +0 -207
  244. package/src/components/chat/__tests__/chat-pending-turn.test.tsx +0 -209
  245. package/src/components/chat/hooks/__tests__/__snapshots__/conversation-id-persistence-golden.test.ts.snap +0 -37
  246. package/src/components/chat/hooks/__tests__/__snapshots__/sse-stream-golden.test.ts.snap +0 -0
  247. package/src/components/chat/hooks/__tests__/conversation-id-persistence-golden.test.ts +0 -438
  248. package/src/components/chat/hooks/__tests__/sse-stream-golden.test.ts +0 -318
  249. package/src/components/chat/stream/__tests__/__snapshots__/chat-stream-reducer-golden.test.ts.snap +0 -940
  250. package/src/components/chat/stream/__tests__/chat-dialog-store.test.ts +0 -756
  251. package/src/components/chat/stream/__tests__/chat-stream-reducer-golden.test.ts +0 -460
  252. package/src/components/chat/stream/__tests__/chat-stream-reducer.test.ts +0 -894
  253. package/src/components/chat/stream/__tests__/delta-batcher.test.ts +0 -255
  254. package/src/components/chat/stream/__tests__/use-chat-stream-reducer.test.ts +0 -98
  255. package/src/components/chat/stream/chat-dialog-store.ts +0 -536
  256. package/src/components/chat/stream/chat-stream-reducer.ts +0 -1796
  257. package/src/components/chat/stream/delta-batcher.ts +0 -159
  258. package/src/components/chat/stream/index.ts +0 -55
  259. package/src/components/chat/stream/message-mutations.ts +0 -338
  260. package/src/components/chat/stream/use-chat-stream-reducer.ts +0 -126
  261. package/src/components/chat/utils/__tests__/__snapshots__/process-historical-messages-golden.test.ts.snap +0 -420
  262. package/src/components/chat/utils/__tests__/__snapshots__/segment-accumulator-golden.test.ts.snap +0 -605
  263. package/src/components/chat/utils/__tests__/process-historical-messages-golden.test.ts +0 -317
  264. package/src/components/chat/utils/__tests__/segment-accumulator-golden.test.ts +0 -270
  265. package/src/components/ui/__tests__/__snapshots__/markdown-parity.test.tsx.snap +0 -2420
  266. package/src/components/ui/__tests__/markdown-parity.test.tsx +0 -2528
  267. package/src/components/ui/markdown/__tests__/mermaid-security.test.ts +0 -115
  268. package/src/components/ui/markdown/__tests__/mermaid-stale-render.test.tsx +0 -95
  269. package/src/components/ui/markdown/__tests__/sanitize-invariant.test.ts +0 -309
  270. package/src/components/ui/markdown/__tests__/streaming.test.tsx +0 -388
  271. package/src/components/ui/markdown/base-components.tsx +0 -360
  272. package/src/components/ui/markdown/engine.tsx +0 -315
  273. package/src/components/ui/markdown/heading-ids.ts +0 -239
  274. package/src/components/ui/markdown/index.ts +0 -49
  275. package/src/components/ui/markdown/mermaid-diagram.tsx +0 -291
  276. package/src/components/ui/markdown/rich/embed-overrides.tsx +0 -199
  277. package/src/components/ui/markdown/rich/rich-markdown-renderer.tsx +0 -184
  278. package/src/components/ui/markdown/rich/shortcodes.ts +0 -170
  279. package/src/components/ui/markdown/sanitize.ts +0 -3499
  280. package/src/components/ui/markdown/simple-markdown-renderer.tsx +0 -28
  281. package/src/components/ui/markdown/streaming.ts +0 -362
  282. package/src/components/ui/markdown/text-size.ts +0 -106
  283. package/src/utils/markdown-fences.ts +0 -127
  284. package/src/utils/markdown-heading-id.ts +0 -348
  285. /package/dist/{chunk-GTWO5NAY.js.map → chunk-6CFFISUC.js.map} +0 -0
  286. /package/dist/{chunk-VHG6AX5V.js.map → chunk-6CJ2K7BD.js.map} +0 -0
  287. /package/dist/{chunk-4NWARV5I.js.map → chunk-6QK3ONDD.js.map} +0 -0
  288. /package/dist/{chunk-CORIBKHG.js.map → chunk-EGXCWZYP.js.map} +0 -0
  289. /package/dist/{chunk-HSACATCD.js.map → chunk-MPYDX5WX.js.map} +0 -0
  290. /package/dist/{chunk-RQLBHKXN.js.map → chunk-NGEFYPY7.js.map} +0 -0
  291. /package/dist/{chunk-YZ2OIYQ3.js.map → chunk-VDZO6IDR.js.map} +0 -0
  292. /package/dist/{chunk-UUYRJPGJ.js.map → chunk-VL2YMDPH.js.map} +0 -0
  293. /package/dist/{chunk-XQ2B74SI.js.map → chunk-WLM3F3WU.js.map} +0 -0
@@ -1,28 +1,6 @@
1
1
  /**
2
- * Utility for processing historical messages from GraphQL/API into
3
- * display-ready format.
4
- *
5
- * Phase 3 of the chat unification reduced this file to DECODE + ENVELOPE:
6
- *
7
- * - `decodeHistoricalMessageData` maps one persisted `MessageData` item
8
- * into the shared `ChatStreamEvent` vocabulary (historical items share
9
- * the MESSAGE_TYPE vocabulary with NATS chunks but are NOT full chunk
10
- * envelopes — e.g. compaction summaries ride in `summary`, not `text`,
11
- * and APPROVAL_RESULT rows carry `resolvedByName` directly);
12
- * - `applyHistoryEvent` replays each decoded event into the shared
13
- * per-turn kernel (`MessageSegmentAccumulator` — the same kernel the
14
- * master `createChatStreamReducer` instantiates) with the
15
- * history-specific approval semantics (display-all default, pending
16
- * tracking + `flushPendingApprovals`, `approvalStatuses` overrides);
17
- * - the ENVELOPE (user/assistant flush-grouping, OWNER_TYPE author /
18
- * display-name / avatar resolution, standalone SYSTEM handling,
19
- * per-message contextItems mapping, per-turn streamSeq MAX) lives ONCE
20
- * in `processHistory` — the previous near-duplicate second copy was
21
- * deleted (`processHistoricalMessagesWithErrors` is an alias; the two
22
- * snapshots were byte-identical).
23
- *
24
- * Adapters then feed the processed rows into the reducer via
25
- * `initializeWithState` (see `useNatsChatAdapter.loadDialogHistory`).
2
+ * Utility for processing historical messages from GraphQL/API
3
+ * into display-ready format
26
4
  */
27
5
 
28
6
  import {
@@ -37,7 +15,6 @@ import {
37
15
  type MessageData,
38
16
  type MessageOwner,
39
17
  } from '../types'
40
- import type { ChatStreamEvent } from '../../../chat-protocol/events'
41
18
  import { MessageSegmentAccumulator, createMessageSegmentAccumulator } from './message-segment-accumulator'
42
19
  import { getCommandText } from './tool-call-helpers'
43
20
 
@@ -76,61 +53,255 @@ function pushStandaloneMessages(
76
53
  })
77
54
  }
78
55
 
79
- // =============================================================================
80
- // Decode persisted MessageData item shared ChatStreamEvent vocabulary
81
- // =============================================================================
56
+ /**
57
+ * Result type for historical message processing
58
+ */
59
+ export interface ProcessHistoricalMessagesResult {
60
+ messages: ProcessedMessage[]
61
+ escalatedApprovals: Map<
62
+ string,
63
+ { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
64
+ >
65
+ }
82
66
 
83
67
  /**
84
- * Map one persisted `MessageData` item to a normalized `ChatStreamEvent`.
85
- * Thin shim over the NATS chunk decoder's core mapping — the differences
86
- * are exactly the persisted-row divergences from the realtime envelope:
87
- *
88
- * - compaction summaries arrive in `summary` (realtime: `text`);
89
- * - APPROVAL_RESULT rows carry `resolvedByName` (realtime chunks carry
90
- * the resolver's name as `displayName`);
91
- * - `approvalType` defaults to 'CLIENT' (legacy history parity;
92
- * realtime defaults APPROVAL_REQUEST to 'USER');
93
- * - batch `toolCalls` pass through verbatim (already the persisted
94
- * `PendingToolCallData` shape — no normalization pass).
95
- *
96
- * Returns `null` for rows the assistant-turn path doesn't decode (SYSTEM
97
- * is handled by the envelope's standalone path; user TEXT rows are handled
98
- * by the envelope's user path).
68
+ * Process an array of historical messages into display-ready format
99
69
  */
100
- export function decodeHistoricalMessageData(data: MessageData): ChatStreamEvent | null {
70
+ export function processHistoricalMessages(
71
+ messages: HistoricalMessage[],
72
+ options: MessageProcessingOptions = {}
73
+ ): ProcessHistoricalMessagesResult {
74
+ const {
75
+ assistantName = 'Fae',
76
+ assistantType = 'fae',
77
+ assistantAvatar,
78
+ onApprove,
79
+ onReject,
80
+ chatTypeFilter,
81
+ approvalStatuses = {},
82
+ // An omitted option means "display every approval type" — the original
83
+ // history semantics. Deliberately NOT defaulted to the realtime
84
+ // processor's ['CLIENT']: consumers that pass a wider list to their
85
+ // realtime processor but omit it on the history path would silently lose
86
+ // pending non-CLIENT approval cards on every reload/reconnect refetch
87
+ // (they also ignore `escalatedApprovals`). Realtime/history parity is
88
+ // opt-in: pass the same explicit list to both.
89
+ displayApprovalTypes,
90
+ batchApprovalsEnabled,
91
+ } = options
92
+
93
+ const processedMessages: ProcessedMessage[] = []
94
+ const accumulator = createMessageSegmentAccumulator({ onApprove, onReject })
95
+ const escalatedApprovals = new Map<
96
+ string,
97
+ { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
98
+ >()
99
+
100
+ let currentAssistantId: string | null = null
101
+ let currentAssistantTimestamp: Date | null = null
102
+ let lastAssistantId: string | null = null
103
+ // MAX persisted seq across the rows grouped into the current assistant turn
104
+ // — carried onto the flushed message's streamSeq for per-role merge coverage.
105
+ let currentAssistantStreamSeq: number | undefined
106
+
107
+ /**
108
+ * Flush the current assistant message to processedMessages.
109
+ * Uses the LAST message ID in the group for stable React keys across page boundaries.
110
+ */
111
+ const flushAssistantMessage = () => {
112
+ const idToUse = lastAssistantId || currentAssistantId
113
+ if (idToUse && accumulator.hasContent()) {
114
+ processedMessages.push({
115
+ id: idToUse,
116
+ role: 'assistant',
117
+ content: accumulator.getSegments(),
118
+ name: assistantName,
119
+ assistantType,
120
+ authorType: assistantType as AuthorType,
121
+ timestamp: currentAssistantTimestamp || new Date(),
122
+ avatar: assistantAvatar,
123
+ ...(currentAssistantStreamSeq !== undefined ? { streamSeq: currentAssistantStreamSeq } : {}),
124
+ })
125
+ accumulator.resetSegments()
126
+ }
127
+ // Reset grouping identity + seq UNCONDITIONALLY — even on an EMPTY flush (an
128
+ // assistant turn whose only data was a filtered/escalated approval renders
129
+ // nothing, so `hasContent()` is false and nothing is pushed). Left inside
130
+ // the push-block, a stale id/timestamp and (worse) a stale
131
+ // `currentAssistantStreamSeq` bleed into the NEXT assistant turn: `!currentAssistantId`
132
+ // stays false so it keeps the old id/timestamp, and `Math.max` inflates its
133
+ // streamSeq — which then over-covers synthetics in the history merge.
134
+ currentAssistantId = null
135
+ currentAssistantTimestamp = null
136
+ lastAssistantId = null
137
+ currentAssistantStreamSeq = undefined
138
+ }
139
+
140
+ messages.forEach((msg, index) => {
141
+ // Filter by chat type if specified
142
+ if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
143
+
144
+ const messageDataArray = Array.isArray(msg.messageData)
145
+ ? msg.messageData
146
+ : msg.messageData
147
+ ? [msg.messageData]
148
+ : []
149
+
150
+ const hasStandaloneData = messageDataArray.some((data) =>
151
+ data.type === MESSAGE_TYPE.SYSTEM
152
+ )
153
+ if (hasStandaloneData) {
154
+ flushAssistantMessage()
155
+ pushStandaloneMessages(processedMessages, msg, messageDataArray)
156
+ return
157
+ }
158
+
159
+ const isUserMessage =
160
+ msg.owner?.type === OWNER_TYPE.CLIENT || msg.owner?.type === OWNER_TYPE.ADMIN
161
+
162
+ if (isUserMessage) {
163
+ flushAssistantMessage()
164
+
165
+ const userAuthorType: AuthorType = msg.owner?.type === OWNER_TYPE.ADMIN ? 'admin' : 'user'
166
+ messageDataArray.forEach((data) => {
167
+ if (data.type === MESSAGE_TYPE.TEXT && 'text' in data && data.text) {
168
+ // `TextData.contextItems` (server: `[{ type, id }]`) — the entity
169
+ // context the user attached to this message. Surface it so the bubble
170
+ // renders its chip strip from history (no label on the wire → fall
171
+ // back to the id, matching the realtime path).
172
+ const rawContext = (data as { contextItems?: Array<{ type?: unknown; id?: unknown }> }).contextItems
173
+ const contextItems = Array.isArray(rawContext)
174
+ ? rawContext
175
+ .filter((c) => typeof c?.type === 'string' && typeof c?.id === 'string')
176
+ .map((c) => ({ type: c.type as string, id: c.id as string, label: c.id as string }))
177
+ : undefined
178
+ processedMessages.push({
179
+ id: msg.id,
180
+ role: 'user',
181
+ content: data.text,
182
+ name: getOwnerDisplayName(msg.owner),
183
+ avatar: getOwnerAvatar(msg.owner),
184
+ authorType: userAuthorType,
185
+ timestamp: new Date(msg.createdAt),
186
+ ...(contextItems && contextItems.length > 0 ? { contextItems } : {}),
187
+ ...(typeof msg.lastChunkStreamSeq === 'number' ? { streamSeq: msg.lastChunkStreamSeq } : {}),
188
+ })
189
+ }
190
+ })
191
+ } else {
192
+ if (!currentAssistantId) {
193
+ currentAssistantId = msg.id
194
+ currentAssistantTimestamp = new Date(msg.createdAt)
195
+ }
196
+ lastAssistantId = msg.id
197
+ if (typeof msg.lastChunkStreamSeq === 'number') {
198
+ currentAssistantStreamSeq =
199
+ currentAssistantStreamSeq === undefined
200
+ ? msg.lastChunkStreamSeq
201
+ : Math.max(currentAssistantStreamSeq, msg.lastChunkStreamSeq)
202
+ }
203
+
204
+ messageDataArray.forEach((data) => {
205
+ processMessageData(
206
+ data,
207
+ accumulator,
208
+ approvalStatuses,
209
+ { displayApprovalTypes, batchApprovalsEnabled },
210
+ escalatedApprovals,
211
+ )
212
+ })
213
+
214
+ // Check if we should flush (next message is from user or last message)
215
+ const nextMsg = messages[index + 1]
216
+ const isLastMessage = index === messages.length - 1
217
+ const nextIsFromUser =
218
+ nextMsg &&
219
+ (nextMsg.owner?.type === OWNER_TYPE.CLIENT || nextMsg.owner?.type === OWNER_TYPE.ADMIN)
220
+
221
+ if (isLastMessage || nextIsFromUser) {
222
+ flushAssistantMessage()
223
+ }
224
+ }
225
+ })
226
+
227
+ flushAssistantMessage()
228
+
229
+ const pendingApprovalSegments = accumulator.flushPendingApprovals()
230
+ if (pendingApprovalSegments.length > 0) {
231
+ processedMessages.push({
232
+ id: `pending-approvals-${Date.now()}`,
233
+ role: 'assistant',
234
+ content: pendingApprovalSegments,
235
+ name: assistantName,
236
+ assistantType,
237
+ timestamp: new Date(),
238
+ avatar: assistantAvatar,
239
+ })
240
+ }
241
+
242
+ return {
243
+ messages: processedMessages,
244
+ escalatedApprovals: escalatedApprovals
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Process a single message data item into segments
250
+ */
251
+ function processMessageData(
252
+ data: MessageData,
253
+ accumulator: MessageSegmentAccumulator,
254
+ approvalStatuses: Record<string, string>,
255
+ options: MessageProcessingOptions = {},
256
+ escalatedApprovals?: Map<
257
+ string,
258
+ { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
259
+ >
260
+ ): void {
261
+ // batchApprovalsEnabled is owned by the consumer (oss-tenant chat client /
262
+ // openframe-frontend tickets). Defaults to ON so consumers that haven't
263
+ // wired the flag yet get the batch UI; pass `false` to force legacy.
264
+ const { displayApprovalTypes, batchApprovalsEnabled = true } = options
101
265
  switch (data.type) {
102
266
  case MESSAGE_TYPE.TEXT:
103
267
  if ('text' in data && data.text) {
104
- return { type: 'text-delta', text: data.text }
268
+ accumulator.appendText(data.text)
105
269
  }
106
- return null
270
+ break
107
271
 
108
272
  case MESSAGE_TYPE.THINKING:
109
273
  if ('text' in data && data.text) {
110
- return { type: 'thinking-delta', text: data.text }
274
+ accumulator.appendThinking(data.text)
111
275
  }
112
- return null
276
+ break
277
+
278
+ case MESSAGE_TYPE.GUIDE:
279
+ if ('text' in data && data.text) {
280
+ accumulator.appendGuide(data.text)
281
+ }
282
+ break
113
283
 
114
284
  case MESSAGE_TYPE.EXECUTING_TOOL:
115
285
  if ('integratedToolType' in data) {
116
- return {
117
- type: 'tool-execution',
286
+ accumulator.addToolExecution({
287
+ type: 'tool_execution',
118
288
  data: {
119
289
  type: 'EXECUTING_TOOL',
120
290
  integratedToolType: data.integratedToolType || '',
121
291
  toolFunction: data.toolFunction || '',
122
292
  toolTitle: typeof data.title === 'string' ? data.title : undefined,
293
+ toolExplanation: typeof data.toolExplanation === 'string' ? data.toolExplanation : undefined,
123
294
  parameters: data.parameters,
124
295
  toolExecutionRequestId: data.toolExecutionRequestId,
125
296
  },
126
- }
297
+ })
127
298
  }
128
- return null
299
+ break
129
300
 
130
301
  case MESSAGE_TYPE.EXECUTED_TOOL:
131
302
  if ('integratedToolType' in data) {
132
- return {
133
- type: 'tool-execution',
303
+ accumulator.addToolExecution({
304
+ type: 'tool_execution',
134
305
  data: {
135
306
  type: 'EXECUTED_TOOL',
136
307
  integratedToolType: data.integratedToolType || '',
@@ -141,294 +312,218 @@ export function decodeHistoricalMessageData(data: MessageData): ChatStreamEvent
141
312
  success: data.success,
142
313
  toolExecutionRequestId: data.toolExecutionRequestId,
143
314
  },
144
- }
315
+ })
145
316
  }
146
- return null
317
+ break
147
318
 
148
319
  case MESSAGE_TYPE.APPROVAL_REQUEST:
149
320
  if ('approvalRequestId' in data && data.approvalRequestId) {
150
- return {
151
- type: 'approval-request',
152
- requestId: data.approvalRequestId,
153
- approvalType: data.approvalType || 'CLIENT',
154
- command: data.command || '',
155
- explanation: data.explanation,
156
- ...(Array.isArray(data.toolCalls) ? { toolCalls: data.toolCalls } : {}),
321
+ const approvalType = data.approvalType || 'CLIENT'
322
+ const toolCalls: PendingToolCallData[] | undefined = Array.isArray(data.toolCalls)
323
+ ? data.toolCalls
324
+ : undefined
325
+ const isBatch = !!toolCalls && toolCalls.length > 0
326
+
327
+ if (!displayApprovalTypes || displayApprovalTypes.includes(approvalType)) {
328
+ if (isBatch) {
329
+ const status = (approvalStatuses[data.approvalRequestId] as ChatApprovalStatus) || 'pending'
330
+ if (batchApprovalsEnabled) {
331
+ accumulator.addApprovalBatch(data.approvalRequestId, approvalType, toolCalls!, status)
332
+ } else {
333
+ // Flag OFF — unfold batch into N legacy approval cards (same id).
334
+ for (const call of toolCalls!) {
335
+ if (!call.requiresApproval) continue
336
+ accumulator.addApprovalRequest(
337
+ data.approvalRequestId,
338
+ getCommandText(call),
339
+ call.toolExplanation,
340
+ approvalType,
341
+ status,
342
+ )
343
+ }
344
+ }
345
+ } else {
346
+ // The resolution may already be known to the consumer (realtime
347
+ // flipped it and fed it back via `approvalStatuses`) while the
348
+ // matching APPROVAL_RESULT row is absent from the fetched history
349
+ // pages. Without this, the single-approval path tracks it as
350
+ // pending and `flushPendingApprovals()` resurrects it as a stale
351
+ // sticky card on every history re-process. Mirror the batch path
352
+ // and honor `approvalStatuses`.
353
+ const resolvedStatus = approvalStatuses[data.approvalRequestId] as ChatApprovalStatus | undefined
354
+ if (resolvedStatus === 'approved' || resolvedStatus === 'rejected') {
355
+ accumulator.addApprovalRequest(
356
+ data.approvalRequestId,
357
+ data.command || '',
358
+ data.explanation,
359
+ approvalType,
360
+ resolvedStatus,
361
+ )
362
+ } else {
363
+ accumulator.trackApprovalRequest(data.approvalRequestId, {
364
+ command: data.command || '',
365
+ explanation: data.explanation,
366
+ approvalType,
367
+ })
368
+ }
369
+ }
370
+ } else {
371
+ escalatedApprovals?.set(data.approvalRequestId, {
372
+ command: data.command || '',
373
+ explanation: data.explanation,
374
+ approvalType,
375
+ ...(isBatch ? { toolCalls } : {}),
376
+ })
157
377
  }
158
378
  }
159
- return null
379
+ break
160
380
 
161
381
  case MESSAGE_TYPE.APPROVAL_RESULT:
162
382
  if ('approvalRequestId' in data && data.approvalRequestId) {
163
- return {
164
- type: 'approval-resolved',
165
- requestId: data.approvalRequestId,
166
- status: data.approved ? 'approved' : 'rejected',
167
- approvalType: data.approvalType,
168
- resolvedByName: 'resolvedByName' in data ? data.resolvedByName : undefined,
169
- }
170
- }
171
- return null
172
-
173
- case MESSAGE_TYPE.ERROR:
174
- if ('error' in data) {
175
- return {
176
- type: 'error',
177
- title: data.error || 'An error occurred',
178
- details: 'details' in data ? data.details : undefined,
179
- }
180
- }
181
- return null
182
-
183
- case MESSAGE_TYPE.CONTEXT_COMPACTION_START:
184
- return { type: 'compaction', phase: 'start' }
383
+ const existingStatus = approvalStatuses[data.approvalRequestId] as ChatApprovalStatus | undefined
384
+ const status: ChatApprovalStatus = existingStatus || (data.approved ? 'approved' : 'rejected')
385
+ const resolvedByName = 'resolvedByName' in data ? data.resolvedByName : undefined
386
+ const escalatedData = escalatedApprovals?.get(data.approvalRequestId)
185
387
 
186
- case MESSAGE_TYPE.CONTEXT_COMPACTION_END:
187
- return {
188
- type: 'compaction',
189
- phase: 'end',
190
- summary: 'summary' in data && typeof data.summary === 'string' ? data.summary : undefined,
191
- }
192
-
193
- case MESSAGE_TYPE.SYSTEM:
194
- if ('text' in data && data.text) {
195
- return { type: 'participant', kind: 'system', text: data.text }
196
- }
197
- return null
198
-
199
- default:
200
- // Unknown message type — ignore.
201
- return null
202
- }
203
- }
204
-
205
- // =============================================================================
206
- // Replay — decoded event → per-turn kernel (history approval semantics)
207
- // =============================================================================
208
-
209
- type EscalatedApprovals = Map<
210
- string,
211
- { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
212
- >
213
-
214
- /**
215
- * Replay one decoded event into the shared per-turn segment kernel with the
216
- * HISTORY approval semantics (an omitted `displayApprovalTypes` means
217
- * "display every approval type" — the original history behavior; the
218
- * realtime reducer defaults to `['CLIENT']`).
219
- */
220
- function applyHistoryEvent(
221
- event: ChatStreamEvent,
222
- accumulator: MessageSegmentAccumulator,
223
- approvalStatuses: Record<string, string>,
224
- options: MessageProcessingOptions,
225
- escalatedApprovals?: EscalatedApprovals,
226
- ): void {
227
- // batchApprovalsEnabled is owned by the consumer (oss-tenant chat client /
228
- // openframe-frontend tickets). Defaults to ON so consumers that haven't
229
- // wired the flag yet get the batch UI; pass `false` to force legacy.
230
- const { displayApprovalTypes, batchApprovalsEnabled = true } = options
231
-
232
- switch (event.type) {
233
- case 'text-delta':
234
- accumulator.appendText(event.text)
235
- break
236
-
237
- case 'thinking-delta':
238
- accumulator.appendThinking(event.text)
239
- break
240
-
241
- case 'tool-execution':
242
- accumulator.addToolExecution({ type: 'tool_execution', data: event.data })
243
- break
244
-
245
- case 'approval-request': {
246
- const approvalType = event.approvalType || 'CLIENT'
247
- const toolCalls = event.toolCalls as PendingToolCallData[] | undefined
248
- const isBatch = !!toolCalls && toolCalls.length > 0
249
-
250
- if (!displayApprovalTypes || displayApprovalTypes.includes(approvalType)) {
251
- if (isBatch) {
252
- const status = (approvalStatuses[event.requestId] as ChatApprovalStatus) || 'pending'
388
+ if (escalatedData?.toolCalls && escalatedData.toolCalls.length > 0) {
253
389
  if (batchApprovalsEnabled) {
254
- accumulator.addApprovalBatch(event.requestId, approvalType, toolCalls!, status)
390
+ accumulator.addApprovalBatch(
391
+ data.approvalRequestId,
392
+ escalatedData.approvalType,
393
+ escalatedData.toolCalls,
394
+ status,
395
+ undefined,
396
+ resolvedByName,
397
+ )
255
398
  } else {
256
- // Flag OFF unfold batch into N legacy approval cards (same id).
257
- for (const call of toolCalls!) {
399
+ for (const call of escalatedData.toolCalls) {
258
400
  if (!call.requiresApproval) continue
259
401
  accumulator.addApprovalRequest(
260
- event.requestId,
402
+ data.approvalRequestId,
261
403
  getCommandText(call),
262
404
  call.toolExplanation,
263
- approvalType,
405
+ escalatedData.approvalType,
264
406
  status,
265
407
  )
266
408
  }
267
409
  }
268
- } else {
269
- // The resolution may already be known to the consumer (realtime
270
- // flipped it and fed it back via `approvalStatuses`) while the
271
- // matching APPROVAL_RESULT row is absent from the fetched history
272
- // pages. Without this, the single-approval path tracks it as
273
- // pending and `flushPendingApprovals()` resurrects it as a stale
274
- // sticky card on every history re-process. Mirror the batch path
275
- // and honor `approvalStatuses`.
276
- const resolvedStatus = approvalStatuses[event.requestId] as ChatApprovalStatus | undefined
277
- if (resolvedStatus === 'approved' || resolvedStatus === 'rejected') {
278
- accumulator.addApprovalRequest(
279
- event.requestId,
280
- event.command || '',
281
- event.explanation,
282
- approvalType,
283
- resolvedStatus,
284
- )
285
- } else {
286
- accumulator.trackApprovalRequest(event.requestId, {
287
- command: event.command || '',
288
- explanation: event.explanation,
289
- approvalType,
290
- })
291
- }
410
+ escalatedApprovals?.delete(data.approvalRequestId)
411
+ break
292
412
  }
293
- } else {
294
- escalatedApprovals?.set(event.requestId, {
295
- command: event.command || '',
296
- explanation: event.explanation,
297
- approvalType,
298
- ...(isBatch ? { toolCalls } : {}),
299
- })
300
- }
301
- break
302
- }
303
413
 
304
- case 'approval-resolved': {
305
- const requestId = event.requestId
306
- if (!requestId) break
307
- const existingStatus = approvalStatuses[requestId] as ChatApprovalStatus | undefined
308
- const status: ChatApprovalStatus = existingStatus || event.status
309
- const resolvedByName = event.resolvedByName
310
- const escalatedData = escalatedApprovals?.get(requestId)
311
-
312
- if (escalatedData?.toolCalls && escalatedData.toolCalls.length > 0) {
313
- if (batchApprovalsEnabled) {
314
- accumulator.addApprovalBatch(
315
- requestId,
316
- escalatedData.approvalType,
317
- escalatedData.toolCalls,
318
- status,
319
- undefined,
320
- resolvedByName,
321
- )
322
- } else {
323
- for (const call of escalatedData.toolCalls) {
324
- if (!call.requiresApproval) continue
325
- accumulator.addApprovalRequest(
326
- requestId,
327
- getCommandText(call),
328
- call.toolExplanation,
329
- escalatedData.approvalType,
330
- status,
331
- )
332
- }
414
+ if (escalatedData) {
415
+ accumulator.trackApprovalRequest(data.approvalRequestId, {
416
+ command: escalatedData.command,
417
+ explanation: escalatedData.explanation,
418
+ approvalType: escalatedData.approvalType,
419
+ })
420
+ escalatedApprovals?.delete(data.approvalRequestId)
333
421
  }
334
- escalatedApprovals?.delete(requestId)
335
- break
336
- }
337
422
 
338
- if (escalatedData) {
339
- accumulator.trackApprovalRequest(requestId, {
340
- command: escalatedData.command,
341
- explanation: escalatedData.explanation,
342
- approvalType: escalatedData.approvalType,
343
- })
344
- escalatedApprovals?.delete(requestId)
423
+ // If a segment with this id is already present (batch or legacy), just flip its status.
424
+ // updateApprovalStatus matches both `approval_batch` and `approval_request` segments.
425
+ const before = accumulator.getSegments()
426
+ const after = accumulator.updateApprovalStatus(data.approvalRequestId, status, resolvedByName)
427
+ const updatedExisting = before.some((s, i) => after[i] !== s)
428
+ if (updatedExisting) break
429
+
430
+ accumulator.processApprovalResult(
431
+ data.approvalRequestId,
432
+ status === 'approved',
433
+ data.approvalType || 'USER'
434
+ )
345
435
  }
346
-
347
- // If a segment with this id is already present (batch or legacy), just
348
- // flip its status. updateApprovalStatus matches both `approval_batch`
349
- // and `approval_request` segments.
350
- const before = accumulator.getSegments()
351
- const after = accumulator.updateApprovalStatus(requestId, status, resolvedByName)
352
- const updatedExisting = before.some((s, i) => after[i] !== s)
353
- if (updatedExisting) break
354
-
355
- accumulator.processApprovalResult(
356
- requestId,
357
- status === 'approved',
358
- event.approvalType || 'USER',
359
- )
360
436
  break
361
- }
362
437
 
363
- case 'error': {
364
- let message: string | undefined
365
- if (event.details) {
366
- try {
367
- message = JSON.parse(event.details)?.error?.message
368
- } catch {
369
- message = event.details
438
+ case MESSAGE_TYPE.ERROR:
439
+ if ('error' in data) {
440
+ let message: string | undefined
441
+ if ('details' in data && data?.details) {
442
+ try {
443
+ message = JSON.parse(data.details)?.error?.message
444
+ } catch {
445
+ message = data.details
446
+ }
370
447
  }
448
+ accumulator.addError(
449
+ data.error || 'An error occurred',
450
+ message
451
+ )
371
452
  }
372
- accumulator.addError(event.title, message)
373
453
  break
374
- }
375
454
 
376
- case 'compaction':
377
- if (event.phase === 'start') {
378
- accumulator.addContextCompaction()
379
- } else {
380
- accumulator.completeContextCompaction(event.summary)
381
- }
455
+ case MESSAGE_TYPE.CONTEXT_COMPACTION_START:
456
+ accumulator.addContextCompaction()
457
+ break
458
+
459
+ case MESSAGE_TYPE.CONTEXT_COMPACTION_END: {
460
+ const summary = 'summary' in data && typeof data.summary === 'string' ? data.summary : undefined
461
+ accumulator.completeContextCompaction(summary)
382
462
  break
463
+ }
383
464
 
384
465
  default:
385
- // Participant/system rows are envelope concerns; everything else is
386
- // realtime-only vocabulary that never appears in persisted rows.
466
+ // Unknown message type - ignore
387
467
  break
388
468
  }
389
469
  }
390
470
 
391
- // =============================================================================
392
- // Envelope — ONE implementation (previous duplicate deleted)
393
- // =============================================================================
394
-
395
471
  /**
396
- * Result type for historical message processing
472
+ * Extract error messages from historical messages
473
+ * Returns a separate array of error messages that should be displayed
397
474
  */
398
- export interface ProcessHistoricalMessagesResult {
399
- messages: ProcessedMessage[]
400
- escalatedApprovals: EscalatedApprovals
475
+ export function extractErrorMessages(
476
+ messages: HistoricalMessage[],
477
+ options: MessageProcessingOptions = {}
478
+ ): ProcessedMessage[] {
479
+ const { assistantName = 'Fae', assistantType = 'fae', assistantAvatar, chatTypeFilter } = options
480
+
481
+ const errorMessages: ProcessedMessage[] = []
482
+
483
+ messages.forEach((msg) => {
484
+ if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
485
+
486
+ const messageDataArray = Array.isArray(msg.messageData)
487
+ ? msg.messageData
488
+ : msg.messageData
489
+ ? [msg.messageData]
490
+ : []
491
+
492
+ messageDataArray.forEach((data) => {
493
+ if (data.type === MESSAGE_TYPE.ERROR) {
494
+ errorMessages.push({
495
+ id: `${msg.id}-error`,
496
+ role: 'error',
497
+ content: 'error' in data && data.error ? data.error : 'An error occurred',
498
+ name: assistantName,
499
+ assistantType,
500
+ timestamp: new Date(msg.createdAt),
501
+ avatar: assistantAvatar,
502
+ })
503
+ }
504
+ })
505
+ })
506
+
507
+ return errorMessages
401
508
  }
402
509
 
403
510
  /**
404
- * Process an array of historical messages into display-ready format
511
+ * Process messages and include error messages in the correct order
405
512
  */
406
- export function processHistoricalMessages(
513
+ export function processHistoricalMessagesWithErrors(
407
514
  messages: HistoricalMessage[],
408
- options: MessageProcessingOptions = {},
515
+ options: MessageProcessingOptions = {}
409
516
  ): ProcessHistoricalMessagesResult {
410
- const {
411
- assistantName = 'Fae',
412
- assistantType = 'fae',
413
- assistantAvatar,
414
- onApprove,
415
- onReject,
416
- chatTypeFilter,
417
- approvalStatuses = {},
418
- // An omitted option means "display every approval type" — the original
419
- // history semantics. Deliberately NOT defaulted to the realtime
420
- // reducer's ['CLIENT']: consumers that pass a wider list to their
421
- // realtime path but omit it on the history path would silently lose
422
- // pending non-CLIENT approval cards on every reload/reconnect refetch
423
- // (they also ignore `escalatedApprovals`). Realtime/history parity is
424
- // opt-in: pass the same explicit list to both.
425
- displayApprovalTypes,
426
- batchApprovalsEnabled,
427
- } = options
517
+ // displayApprovalTypes omitted = display every approval type (original
518
+ // history semantics — see the matching note in processHistoricalMessages).
519
+ const { chatTypeFilter, assistantName = 'Fae', assistantType = 'fae', assistantAvatar, onApprove, onReject, approvalStatuses = {}, displayApprovalTypes, batchApprovalsEnabled } = options
428
520
 
429
521
  const processedMessages: ProcessedMessage[] = []
430
522
  const accumulator = createMessageSegmentAccumulator({ onApprove, onReject })
431
- const escalatedApprovals: EscalatedApprovals = new Map()
523
+ const escalatedApprovals = new Map<
524
+ string,
525
+ { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
526
+ >()
432
527
 
433
528
  let currentAssistantId: string | null = null
434
529
  let currentAssistantTimestamp: Date | null = null
@@ -437,10 +532,6 @@ export function processHistoricalMessages(
437
532
  // — carried onto the flushed message's streamSeq for per-role merge coverage.
438
533
  let currentAssistantStreamSeq: number | undefined
439
534
 
440
- /**
441
- * Flush the current assistant message to processedMessages.
442
- * Uses the LAST message ID in the group for stable React keys across page boundaries.
443
- */
444
535
  const flushAssistantMessage = () => {
445
536
  const idToUse = lastAssistantId || currentAssistantId
446
537
  if (idToUse && accumulator.hasContent()) {
@@ -471,7 +562,6 @@ export function processHistoricalMessages(
471
562
  }
472
563
 
473
564
  messages.forEach((msg, index) => {
474
- // Filter by chat type if specified
475
565
  if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
476
566
 
477
567
  const messageDataArray = Array.isArray(msg.messageData)
@@ -535,10 +625,8 @@ export function processHistoricalMessages(
535
625
  }
536
626
 
537
627
  messageDataArray.forEach((data) => {
538
- const event = decodeHistoricalMessageData(data)
539
- if (!event) return
540
- applyHistoryEvent(
541
- event,
628
+ processMessageData(
629
+ data,
542
630
  accumulator,
543
631
  approvalStatuses,
544
632
  { displayApprovalTypes, batchApprovalsEnabled },
@@ -546,7 +634,6 @@ export function processHistoricalMessages(
546
634
  )
547
635
  })
548
636
 
549
- // Check if we should flush (next message is from user or last message)
550
637
  const nextMsg = messages[index + 1]
551
638
  const isLastMessage = index === messages.length - 1
552
639
  const nextIsFromUser =
@@ -579,52 +666,3 @@ export function processHistoricalMessages(
579
666
  escalatedApprovals: escalatedApprovals
580
667
  }
581
668
  }
582
-
583
- /**
584
- * Extract error messages from historical messages
585
- * Returns a separate array of error messages that should be displayed
586
- */
587
- export function extractErrorMessages(
588
- messages: HistoricalMessage[],
589
- options: MessageProcessingOptions = {}
590
- ): ProcessedMessage[] {
591
- const { assistantName = 'Fae', assistantType = 'fae', assistantAvatar, chatTypeFilter } = options
592
-
593
- const errorMessages: ProcessedMessage[] = []
594
-
595
- messages.forEach((msg) => {
596
- if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
597
-
598
- const messageDataArray = Array.isArray(msg.messageData)
599
- ? msg.messageData
600
- : msg.messageData
601
- ? [msg.messageData]
602
- : []
603
-
604
- messageDataArray.forEach((data) => {
605
- if (data.type === MESSAGE_TYPE.ERROR) {
606
- errorMessages.push({
607
- id: `${msg.id}-error`,
608
- role: 'error',
609
- content: 'error' in data && data.error ? data.error : 'An error occurred',
610
- name: assistantName,
611
- assistantType,
612
- timestamp: new Date(msg.createdAt),
613
- avatar: assistantAvatar,
614
- })
615
- }
616
- })
617
- })
618
-
619
- return errorMessages
620
- }
621
-
622
- /**
623
- * Process messages and include error messages in the correct order.
624
- *
625
- * HISTORICAL ALIAS: this was a byte-identical second copy of
626
- * `processHistoricalMessages` (both goldens snapshot identical output on the
627
- * same corpus). The duplicate envelope was deleted in Phase 3 — kept as an
628
- * alias for the established import sites.
629
- */
630
- export const processHistoricalMessagesWithErrors = processHistoricalMessages