@flamingo-stack/openframe-frontend-core 0.0.467 → 0.0.468-snapshot.20260723140929

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 (289) hide show
  1. package/dist/chat-protocol/decode.d.ts +58 -0
  2. package/dist/chat-protocol/decode.d.ts.map +1 -0
  3. package/dist/chat-protocol/encode.d.ts +44 -0
  4. package/dist/chat-protocol/encode.d.ts.map +1 -0
  5. package/dist/chat-protocol/env-flag.d.ts +35 -0
  6. package/dist/chat-protocol/env-flag.d.ts.map +1 -0
  7. package/dist/chat-protocol/events.d.ts +192 -0
  8. package/dist/chat-protocol/events.d.ts.map +1 -0
  9. package/dist/chat-protocol/frames.d.ts +206 -0
  10. package/dist/chat-protocol/frames.d.ts.map +1 -0
  11. package/dist/chat-protocol/index.cjs +493 -0
  12. package/dist/chat-protocol/index.cjs.map +1 -0
  13. package/dist/chat-protocol/index.d.ts +18 -0
  14. package/dist/chat-protocol/index.d.ts.map +1 -0
  15. package/dist/chat-protocol/index.js +477 -0
  16. package/dist/chat-protocol/index.js.map +1 -0
  17. package/dist/chat-protocol/ip-normalize.d.ts +44 -0
  18. package/dist/chat-protocol/ip-normalize.d.ts.map +1 -0
  19. package/dist/chat-protocol/nats-decoder.d.ts +26 -0
  20. package/dist/chat-protocol/nats-decoder.d.ts.map +1 -0
  21. package/dist/{chunk-BIDOIPIT.js → chunk-2BJSRTKU.js} +2 -2
  22. package/dist/{chunk-4DFPQKKJ.js → chunk-33FDAZDB.js} +2 -2
  23. package/dist/{chunk-LOWJWKM5.js → chunk-4QDFNDVW.js} +4 -4
  24. package/dist/{chunk-72NEN4G4.cjs → chunk-4UFRQT7Z.cjs} +15 -15
  25. package/dist/{chunk-72NEN4G4.cjs.map → chunk-4UFRQT7Z.cjs.map} +1 -1
  26. package/dist/{chunk-WWC75D3J.cjs → chunk-4W54HUP7.cjs} +6853 -4609
  27. package/dist/chunk-4W54HUP7.cjs.map +1 -0
  28. package/dist/{chunk-6DZ5QOUM.cjs → chunk-5HUTT3FD.cjs} +11 -11
  29. package/dist/{chunk-6DZ5QOUM.cjs.map → chunk-5HUTT3FD.cjs.map} +1 -1
  30. package/dist/{chunk-GXXLJHQX.js → chunk-7I2QMUEZ.js} +2 -2
  31. package/dist/{chunk-QJ7NIL6A.js → chunk-AJSNF5YF.js} +6 -5
  32. package/dist/chunk-AJSNF5YF.js.map +1 -0
  33. package/dist/{chunk-NYOQNYSI.js → chunk-AW3LVWVV.js} +2 -2
  34. package/dist/{chunk-25YYEVSE.js → chunk-DG7TX763.js} +2 -2
  35. package/dist/{chunk-CZFPPNYV.js → chunk-E6O6XATC.js} +11899 -9655
  36. package/dist/chunk-E6O6XATC.js.map +1 -0
  37. package/dist/{chunk-ZYPHZ3R3.cjs → chunk-GLKULDQN.cjs} +9 -9
  38. package/dist/{chunk-ZYPHZ3R3.cjs.map → chunk-GLKULDQN.cjs.map} +1 -1
  39. package/dist/{chunk-TZSPLSDU.js → chunk-GYEZV4GK.js} +2 -2
  40. package/dist/{chunk-G5D7NRH5.cjs → chunk-LRESZO4L.cjs} +26 -26
  41. package/dist/{chunk-G5D7NRH5.cjs.map → chunk-LRESZO4L.cjs.map} +1 -1
  42. package/dist/{chunk-ABU37QSG.js → chunk-MMF6HJB7.js} +4 -4
  43. package/dist/{chunk-O7LQYYUA.cjs → chunk-MTLBBSLP.cjs} +5 -5
  44. package/dist/{chunk-O7LQYYUA.cjs.map → chunk-MTLBBSLP.cjs.map} +1 -1
  45. package/dist/{chunk-UWW4PQQS.cjs → chunk-OVIUQJ2H.cjs} +28 -27
  46. package/dist/chunk-OVIUQJ2H.cjs.map +1 -0
  47. package/dist/{chunk-3L44PPMF.js → chunk-RPAOSHBN.js} +2 -2
  48. package/dist/{chunk-VERK32MO.cjs → chunk-TOFOK7G5.cjs} +37 -37
  49. package/dist/{chunk-VERK32MO.cjs.map → chunk-TOFOK7G5.cjs.map} +1 -1
  50. package/dist/{chunk-QITN43HN.cjs → chunk-U2KPMWO6.cjs} +7 -7
  51. package/dist/{chunk-QITN43HN.cjs.map → chunk-U2KPMWO6.cjs.map} +1 -1
  52. package/dist/{chunk-YGW7T57C.cjs → chunk-V5YWOQBP.cjs} +31 -31
  53. package/dist/{chunk-YGW7T57C.cjs.map → chunk-V5YWOQBP.cjs.map} +1 -1
  54. package/dist/{chunk-ILZ66CS6.js → chunk-VUCYS36H.js} +10 -10
  55. package/dist/chunk-VUCYS36H.js.map +1 -0
  56. package/dist/{chunk-SGDXS7VT.cjs → chunk-WHWDGCQV.cjs} +60 -60
  57. package/dist/chunk-WHWDGCQV.cjs.map +1 -0
  58. package/dist/{chunk-G2H4AKL3.cjs → chunk-YXNWEVER.cjs} +62 -62
  59. package/dist/{chunk-G2H4AKL3.cjs.map → chunk-YXNWEVER.cjs.map} +1 -1
  60. package/dist/components/case-studies/index.cjs +8 -8
  61. package/dist/components/case-studies/index.js +2 -2
  62. package/dist/components/chat/chat-composer.d.ts +8 -1
  63. package/dist/components/chat/chat-composer.d.ts.map +1 -1
  64. package/dist/components/chat/chat-context-memory-bar.d.ts +37 -0
  65. package/dist/components/chat/chat-context-memory-bar.d.ts.map +1 -0
  66. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  67. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  68. package/dist/components/chat/embeddable-chat.d.ts +14 -6
  69. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  70. package/dist/components/chat/hooks/index.d.ts +0 -1
  71. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  72. package/dist/components/chat/hooks/use-chat.d.ts.map +1 -1
  73. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +15 -48
  74. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  75. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +3 -47
  76. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  77. package/dist/components/chat/index.cjs +12 -2
  78. package/dist/components/chat/index.cjs.map +1 -1
  79. package/dist/components/chat/index.d.ts +2 -0
  80. package/dist/components/chat/index.d.ts.map +1 -1
  81. package/dist/components/chat/index.js +23 -13
  82. package/dist/components/chat/stream/chat-dialog-store.d.ts +184 -0
  83. package/dist/components/chat/stream/chat-dialog-store.d.ts.map +1 -0
  84. package/dist/components/chat/stream/chat-stream-reducer.d.ts +367 -0
  85. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +1 -0
  86. package/dist/components/chat/stream/delta-batcher.d.ts +51 -0
  87. package/dist/components/chat/stream/delta-batcher.d.ts.map +1 -0
  88. package/dist/components/chat/stream/index.d.ts +17 -0
  89. package/dist/components/chat/stream/index.d.ts.map +1 -0
  90. package/dist/components/chat/stream/message-mutations.d.ts +77 -0
  91. package/dist/components/chat/stream/message-mutations.d.ts.map +1 -0
  92. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts +22 -0
  93. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts.map +1 -0
  94. package/dist/components/chat/types/api.types.d.ts +1 -81
  95. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  96. package/dist/components/chat/types/processing.types.d.ts +2 -90
  97. package/dist/components/chat/types/processing.types.d.ts.map +1 -1
  98. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts +34 -6
  99. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts.map +1 -1
  100. package/dist/components/chat/utils/index.d.ts +2 -3
  101. package/dist/components/chat/utils/index.d.ts.map +1 -1
  102. package/dist/components/chat/utils/process-historical-messages.d.ts +59 -11
  103. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  104. package/dist/components/contact/index.cjs +3 -3
  105. package/dist/components/contact/index.js +2 -2
  106. package/dist/components/docs/index.cjs +5 -5
  107. package/dist/components/docs/index.js +4 -4
  108. package/dist/components/embeds/index.cjs +3 -3
  109. package/dist/components/embeds/index.js +2 -2
  110. package/dist/components/faq/index.cjs +3 -3
  111. package/dist/components/faq/index.js +2 -2
  112. package/dist/components/features/index.cjs +2 -2
  113. package/dist/components/features/index.js +1 -1
  114. package/dist/components/help-center-pages/index.cjs +20 -20
  115. package/dist/components/help-center-pages/index.js +11 -11
  116. package/dist/components/index.cjs +174 -130
  117. package/dist/components/index.cjs.map +1 -1
  118. package/dist/components/index.js +65 -21
  119. package/dist/components/index.js.map +1 -1
  120. package/dist/components/navigation/index.cjs +2 -2
  121. package/dist/components/navigation/index.js +1 -1
  122. package/dist/components/onboarding-guides/index.cjs +5 -5
  123. package/dist/components/onboarding-guides/index.js +4 -4
  124. package/dist/components/onboarding-guides/onboarding-guide-detail-view.d.ts.map +1 -1
  125. package/dist/components/related-content/index.cjs +3 -3
  126. package/dist/components/related-content/index.js +2 -2
  127. package/dist/components/shared/product-release/release-detail-page.d.ts.map +1 -1
  128. package/dist/components/tickets/index.cjs +5 -5
  129. package/dist/components/tickets/index.js +4 -4
  130. package/dist/components/ui/index.cjs +46 -2
  131. package/dist/components/ui/index.cjs.map +1 -1
  132. package/dist/components/ui/index.d.ts +1 -2
  133. package/dist/components/ui/index.d.ts.map +1 -1
  134. package/dist/components/ui/index.js +57 -13
  135. package/dist/components/ui/markdown/base-components.d.ts +56 -0
  136. package/dist/components/ui/markdown/base-components.d.ts.map +1 -0
  137. package/dist/components/ui/markdown/engine.d.ts +99 -0
  138. package/dist/components/ui/markdown/engine.d.ts.map +1 -0
  139. package/dist/components/ui/markdown/heading-ids.d.ts +65 -0
  140. package/dist/components/ui/markdown/heading-ids.d.ts.map +1 -0
  141. package/dist/components/ui/markdown/index.d.ts +18 -0
  142. package/dist/components/ui/markdown/index.d.ts.map +1 -0
  143. package/dist/components/ui/markdown/mermaid-diagram.d.ts +79 -0
  144. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +1 -0
  145. package/dist/components/ui/markdown/rich/embed-overrides.d.ts +14 -0
  146. package/dist/components/ui/markdown/rich/embed-overrides.d.ts.map +1 -0
  147. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts +40 -0
  148. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts.map +1 -0
  149. package/dist/components/ui/markdown/rich/shortcodes.d.ts +8 -0
  150. package/dist/components/ui/markdown/rich/shortcodes.d.ts.map +1 -0
  151. package/dist/components/ui/markdown/sanitize.d.ts +153 -0
  152. package/dist/components/ui/markdown/sanitize.d.ts.map +1 -0
  153. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts +23 -0
  154. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts.map +1 -0
  155. package/dist/components/ui/markdown/streaming.d.ts +78 -0
  156. package/dist/components/ui/markdown/streaming.d.ts.map +1 -0
  157. package/dist/components/ui/markdown/text-size.d.ts +34 -0
  158. package/dist/components/ui/markdown/text-size.d.ts.map +1 -0
  159. package/dist/index.cjs +62 -2
  160. package/dist/index.cjs.map +1 -1
  161. package/dist/index.js +73 -13
  162. package/dist/utils/index.cjs +169 -40
  163. package/dist/utils/index.cjs.map +1 -1
  164. package/dist/utils/index.d.ts +1 -0
  165. package/dist/utils/index.d.ts.map +1 -1
  166. package/dist/utils/index.js +162 -41
  167. package/dist/utils/index.js.map +1 -1
  168. package/dist/utils/markdown-fences.d.ts +42 -0
  169. package/dist/utils/markdown-fences.d.ts.map +1 -0
  170. package/dist/utils/markdown-heading-id.d.ts +85 -0
  171. package/dist/utils/markdown-heading-id.d.ts.map +1 -0
  172. package/dist/utils/markdown-section-extractor.d.ts.map +1 -1
  173. package/package.json +7 -1
  174. package/src/chat-protocol/__tests__/__snapshots__/nats-decoder-golden.test.ts.snap +307 -0
  175. package/src/chat-protocol/__tests__/chat-protocol.test.ts +515 -0
  176. package/src/chat-protocol/__tests__/env-flag.test.ts +52 -0
  177. package/src/chat-protocol/__tests__/ip-normalize.test.ts +136 -0
  178. package/src/chat-protocol/__tests__/nats-decoder-golden.test.ts +228 -0
  179. package/src/chat-protocol/decode.ts +277 -0
  180. package/src/chat-protocol/encode.ts +71 -0
  181. package/src/chat-protocol/env-flag.ts +39 -0
  182. package/src/chat-protocol/events.ts +228 -0
  183. package/src/chat-protocol/frames.ts +238 -0
  184. package/src/chat-protocol/index.ts +21 -0
  185. package/src/chat-protocol/ip-normalize.ts +146 -0
  186. package/src/chat-protocol/nats-decoder.ts +252 -0
  187. package/src/components/chat/__tests__/chat-message-list.test.tsx +293 -5
  188. package/src/components/chat/__tests__/chat-message-streaming-memo.test.tsx +207 -0
  189. package/src/components/chat/__tests__/chat-pending-turn.test.tsx +209 -0
  190. package/src/components/chat/chat-composer.tsx +32 -5
  191. package/src/components/chat/chat-context-memory-bar.tsx +159 -0
  192. package/src/components/chat/chat-message-enhanced.tsx +111 -17
  193. package/src/components/chat/chat-message-list.tsx +358 -109
  194. package/src/components/chat/embeddable-chat.tsx +23 -15
  195. package/src/components/chat/hooks/.index.md +1 -1
  196. package/src/components/chat/hooks/.use-nats-chat-adapter.md +1 -1
  197. package/src/components/chat/hooks/__tests__/__snapshots__/persisted-state-v1-golden.test.ts.snap +297 -0
  198. package/src/components/chat/hooks/__tests__/__snapshots__/sse-stream-golden.test.ts.snap +0 -0
  199. package/src/components/chat/hooks/__tests__/persisted-state-v1-golden.test.ts +272 -0
  200. package/src/components/chat/hooks/__tests__/sse-stream-golden.test.ts +318 -0
  201. package/src/components/chat/hooks/index.ts +0 -1
  202. package/src/components/chat/hooks/use-chat.ts +8 -0
  203. package/src/components/chat/hooks/use-nats-chat-adapter.ts +243 -822
  204. package/src/components/chat/hooks/use-sse-chat-adapter.ts +318 -666
  205. package/src/components/chat/index.ts +6 -0
  206. package/src/components/chat/stream/__tests__/__snapshots__/chat-stream-reducer-golden.test.ts.snap +937 -0
  207. package/src/components/chat/stream/__tests__/chat-dialog-store.test.ts +756 -0
  208. package/src/components/chat/stream/__tests__/chat-stream-reducer-golden.test.ts +460 -0
  209. package/src/components/chat/stream/__tests__/chat-stream-reducer.test.ts +894 -0
  210. package/src/components/chat/stream/__tests__/delta-batcher.test.ts +255 -0
  211. package/src/components/chat/stream/__tests__/use-chat-stream-reducer.test.ts +98 -0
  212. package/src/components/chat/stream/chat-dialog-store.ts +536 -0
  213. package/src/components/chat/stream/chat-stream-reducer.ts +1796 -0
  214. package/src/components/chat/stream/delta-batcher.ts +159 -0
  215. package/src/components/chat/stream/index.ts +55 -0
  216. package/src/components/chat/stream/message-mutations.ts +338 -0
  217. package/src/components/chat/stream/use-chat-stream-reducer.ts +126 -0
  218. package/src/components/chat/thinking-display.tsx +1 -1
  219. package/src/components/chat/types/.api.types.md +1 -3
  220. package/src/components/chat/types/.processing.types.md +6 -23
  221. package/src/components/chat/types/api.types.ts +6 -73
  222. package/src/components/chat/types/processing.types.ts +11 -52
  223. package/src/components/chat/utils/.index.md +0 -5
  224. package/src/components/chat/utils/__tests__/__snapshots__/process-historical-messages-golden.test.ts.snap +418 -0
  225. package/src/components/chat/utils/__tests__/__snapshots__/segment-accumulator-golden.test.ts.snap +599 -0
  226. package/src/components/chat/utils/__tests__/process-historical-messages-golden.test.ts +317 -0
  227. package/src/components/chat/utils/__tests__/segment-accumulator-golden.test.ts +270 -0
  228. package/src/components/chat/utils/extract-incomplete-message-state.ts +63 -5
  229. package/src/components/chat/utils/index.ts +5 -8
  230. package/src/components/chat/utils/process-historical-messages.ts +352 -383
  231. package/src/components/onboarding-guides/onboarding-guide-detail-view.tsx +22 -4
  232. package/src/components/shared/legal-document/legal-document-page.tsx +1 -1
  233. package/src/components/shared/product-release/release-detail-page.tsx +19 -4
  234. package/src/components/ui/__tests__/__snapshots__/markdown-parity.test.tsx.snap +2420 -0
  235. package/src/components/ui/__tests__/markdown-parity.test.tsx +2528 -0
  236. package/src/components/ui/index.ts +1 -2
  237. package/src/components/ui/markdown/__tests__/mermaid-security.test.ts +115 -0
  238. package/src/components/ui/markdown/__tests__/mermaid-stale-render.test.tsx +95 -0
  239. package/src/components/ui/markdown/__tests__/sanitize-invariant.test.ts +309 -0
  240. package/src/components/ui/markdown/__tests__/streaming.test.tsx +388 -0
  241. package/src/components/ui/markdown/base-components.tsx +341 -0
  242. package/src/components/ui/markdown/engine.tsx +315 -0
  243. package/src/components/ui/markdown/heading-ids.ts +239 -0
  244. package/src/components/ui/markdown/index.ts +49 -0
  245. package/src/components/ui/markdown/mermaid-diagram.tsx +291 -0
  246. package/src/components/ui/markdown/rich/embed-overrides.tsx +199 -0
  247. package/src/components/ui/markdown/rich/rich-markdown-renderer.tsx +184 -0
  248. package/src/components/ui/markdown/rich/shortcodes.ts +170 -0
  249. package/src/components/ui/markdown/sanitize.ts +3499 -0
  250. package/src/components/ui/markdown/simple-markdown-renderer.tsx +28 -0
  251. package/src/components/ui/markdown/streaming.ts +362 -0
  252. package/src/components/ui/markdown/text-size.ts +106 -0
  253. package/src/components/ui/release-changelog-section.tsx +1 -1
  254. package/src/components/ui/tab-selector.tsx +8 -8
  255. package/src/components/ui/ticket-info-section.tsx +1 -1
  256. package/src/utils/index.ts +1 -0
  257. package/src/utils/markdown-fences.ts +127 -0
  258. package/src/utils/markdown-heading-id.ts +348 -0
  259. package/src/utils/markdown-section-extractor.ts +41 -56
  260. package/dist/chunk-CZFPPNYV.js.map +0 -1
  261. package/dist/chunk-ILZ66CS6.js.map +0 -1
  262. package/dist/chunk-QJ7NIL6A.js.map +0 -1
  263. package/dist/chunk-SGDXS7VT.cjs.map +0 -1
  264. package/dist/chunk-UWW4PQQS.cjs.map +0 -1
  265. package/dist/chunk-WWC75D3J.cjs.map +0 -1
  266. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts +0 -6
  267. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts.map +0 -1
  268. package/dist/components/chat/utils/chunk-parser.d.ts +0 -25
  269. package/dist/components/chat/utils/chunk-parser.d.ts.map +0 -1
  270. package/dist/components/ui/rich-markdown-renderer.d.ts +0 -34
  271. package/dist/components/ui/rich-markdown-renderer.d.ts.map +0 -1
  272. package/dist/components/ui/simple-markdown-renderer.d.ts +0 -73
  273. package/dist/components/ui/simple-markdown-renderer.d.ts.map +0 -1
  274. package/src/components/chat/hooks/.use-realtime-chunk-processor.md +0 -50
  275. package/src/components/chat/hooks/use-realtime-chunk-processor.ts +0 -479
  276. package/src/components/chat/utils/.chunk-parser.md +0 -51
  277. package/src/components/chat/utils/chunk-parser.ts +0 -255
  278. package/src/components/ui/.simple-markdown-renderer.md +0 -40
  279. package/src/components/ui/rich-markdown-renderer.tsx +0 -1223
  280. package/src/components/ui/simple-markdown-renderer.tsx +0 -965
  281. /package/dist/{chunk-BIDOIPIT.js.map → chunk-2BJSRTKU.js.map} +0 -0
  282. /package/dist/{chunk-4DFPQKKJ.js.map → chunk-33FDAZDB.js.map} +0 -0
  283. /package/dist/{chunk-LOWJWKM5.js.map → chunk-4QDFNDVW.js.map} +0 -0
  284. /package/dist/{chunk-GXXLJHQX.js.map → chunk-7I2QMUEZ.js.map} +0 -0
  285. /package/dist/{chunk-NYOQNYSI.js.map → chunk-AW3LVWVV.js.map} +0 -0
  286. /package/dist/{chunk-25YYEVSE.js.map → chunk-DG7TX763.js.map} +0 -0
  287. /package/dist/{chunk-TZSPLSDU.js.map → chunk-GYEZV4GK.js.map} +0 -0
  288. /package/dist/{chunk-ABU37QSG.js.map → chunk-MMF6HJB7.js.map} +0 -0
  289. /package/dist/{chunk-3L44PPMF.js.map → chunk-RPAOSHBN.js.map} +0 -0
@@ -1,6 +1,28 @@
1
1
  /**
2
- * Utility for processing historical messages from GraphQL/API
3
- * into display-ready format
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`).
4
26
  */
5
27
 
6
28
  import {
@@ -15,6 +37,7 @@ import {
15
37
  type MessageData,
16
38
  type MessageOwner,
17
39
  } from '../types'
40
+ import type { ChatStreamEvent } from '../../../chat-protocol/events'
18
41
  import { MessageSegmentAccumulator, createMessageSegmentAccumulator } from './message-segment-accumulator'
19
42
  import { getCommandText } from './tool-call-helpers'
20
43
 
@@ -53,232 +76,45 @@ function pushStandaloneMessages(
53
76
  })
54
77
  }
55
78
 
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
- }
79
+ // =============================================================================
80
+ // Decode — persisted MessageData item → shared ChatStreamEvent vocabulary
81
+ // =============================================================================
66
82
 
67
83
  /**
68
- * Process an array of historical messages into display-ready format
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).
69
99
  */
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
100
+ export function decodeHistoricalMessageData(data: MessageData): ChatStreamEvent | null {
265
101
  switch (data.type) {
266
102
  case MESSAGE_TYPE.TEXT:
267
103
  if ('text' in data && data.text) {
268
- accumulator.appendText(data.text)
104
+ return { type: 'text-delta', text: data.text }
269
105
  }
270
- break
106
+ return null
271
107
 
272
108
  case MESSAGE_TYPE.THINKING:
273
109
  if ('text' in data && data.text) {
274
- accumulator.appendThinking(data.text)
110
+ return { type: 'thinking-delta', text: data.text }
275
111
  }
276
- break
112
+ return null
277
113
 
278
114
  case MESSAGE_TYPE.EXECUTING_TOOL:
279
115
  if ('integratedToolType' in data) {
280
- accumulator.addToolExecution({
281
- type: 'tool_execution',
116
+ return {
117
+ type: 'tool-execution',
282
118
  data: {
283
119
  type: 'EXECUTING_TOOL',
284
120
  integratedToolType: data.integratedToolType || '',
@@ -287,14 +123,14 @@ function processMessageData(
287
123
  parameters: data.parameters,
288
124
  toolExecutionRequestId: data.toolExecutionRequestId,
289
125
  },
290
- })
126
+ }
291
127
  }
292
- break
128
+ return null
293
129
 
294
130
  case MESSAGE_TYPE.EXECUTED_TOOL:
295
131
  if ('integratedToolType' in data) {
296
- accumulator.addToolExecution({
297
- type: 'tool_execution',
132
+ return {
133
+ type: 'tool-execution',
298
134
  data: {
299
135
  type: 'EXECUTED_TOOL',
300
136
  integratedToolType: data.integratedToolType || '',
@@ -305,218 +141,294 @@ function processMessageData(
305
141
  success: data.success,
306
142
  toolExecutionRequestId: data.toolExecutionRequestId,
307
143
  },
308
- })
144
+ }
309
145
  }
310
- break
146
+ return null
311
147
 
312
148
  case MESSAGE_TYPE.APPROVAL_REQUEST:
313
149
  if ('approvalRequestId' in data && data.approvalRequestId) {
314
- const approvalType = data.approvalType || 'CLIENT'
315
- const toolCalls: PendingToolCallData[] | undefined = Array.isArray(data.toolCalls)
316
- ? data.toolCalls
317
- : undefined
318
- const isBatch = !!toolCalls && toolCalls.length > 0
319
-
320
- if (!displayApprovalTypes || displayApprovalTypes.includes(approvalType)) {
321
- if (isBatch) {
322
- const status = (approvalStatuses[data.approvalRequestId] as ChatApprovalStatus) || 'pending'
323
- if (batchApprovalsEnabled) {
324
- accumulator.addApprovalBatch(data.approvalRequestId, approvalType, toolCalls!, status)
325
- } else {
326
- // Flag OFF — unfold batch into N legacy approval cards (same id).
327
- for (const call of toolCalls!) {
328
- if (!call.requiresApproval) continue
329
- accumulator.addApprovalRequest(
330
- data.approvalRequestId,
331
- getCommandText(call),
332
- call.toolExplanation,
333
- approvalType,
334
- status,
335
- )
336
- }
337
- }
338
- } else {
339
- // The resolution may already be known to the consumer (realtime
340
- // flipped it and fed it back via `approvalStatuses`) while the
341
- // matching APPROVAL_RESULT row is absent from the fetched history
342
- // pages. Without this, the single-approval path tracks it as
343
- // pending and `flushPendingApprovals()` resurrects it as a stale
344
- // sticky card on every history re-process. Mirror the batch path
345
- // and honor `approvalStatuses`.
346
- const resolvedStatus = approvalStatuses[data.approvalRequestId] as ChatApprovalStatus | undefined
347
- if (resolvedStatus === 'approved' || resolvedStatus === 'rejected') {
348
- accumulator.addApprovalRequest(
349
- data.approvalRequestId,
350
- data.command || '',
351
- data.explanation,
352
- approvalType,
353
- resolvedStatus,
354
- )
355
- } else {
356
- accumulator.trackApprovalRequest(data.approvalRequestId, {
357
- command: data.command || '',
358
- explanation: data.explanation,
359
- approvalType,
360
- })
361
- }
362
- }
363
- } else {
364
- escalatedApprovals?.set(data.approvalRequestId, {
365
- command: data.command || '',
366
- explanation: data.explanation,
367
- approvalType,
368
- ...(isBatch ? { toolCalls } : {}),
369
- })
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 } : {}),
370
157
  }
371
158
  }
372
- break
159
+ return null
373
160
 
374
161
  case MESSAGE_TYPE.APPROVAL_RESULT:
375
162
  if ('approvalRequestId' in data && data.approvalRequestId) {
376
- const existingStatus = approvalStatuses[data.approvalRequestId] as ChatApprovalStatus | undefined
377
- const status: ChatApprovalStatus = existingStatus || (data.approved ? 'approved' : 'rejected')
378
- const resolvedByName = 'resolvedByName' in data ? data.resolvedByName : undefined
379
- const escalatedData = escalatedApprovals?.get(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' }
185
+
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
380
240
 
381
- if (escalatedData?.toolCalls && escalatedData.toolCalls.length > 0) {
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'
382
253
  if (batchApprovalsEnabled) {
383
- accumulator.addApprovalBatch(
384
- data.approvalRequestId,
385
- escalatedData.approvalType,
386
- escalatedData.toolCalls,
387
- status,
388
- undefined,
389
- resolvedByName,
390
- )
254
+ accumulator.addApprovalBatch(event.requestId, approvalType, toolCalls!, status)
391
255
  } else {
392
- for (const call of escalatedData.toolCalls) {
256
+ // Flag OFF — unfold batch into N legacy approval cards (same id).
257
+ for (const call of toolCalls!) {
393
258
  if (!call.requiresApproval) continue
394
259
  accumulator.addApprovalRequest(
395
- data.approvalRequestId,
260
+ event.requestId,
396
261
  getCommandText(call),
397
262
  call.toolExplanation,
398
- escalatedData.approvalType,
263
+ approvalType,
399
264
  status,
400
265
  )
401
266
  }
402
267
  }
403
- escalatedApprovals?.delete(data.approvalRequestId)
404
- break
405
- }
406
-
407
- if (escalatedData) {
408
- accumulator.trackApprovalRequest(data.approvalRequestId, {
409
- command: escalatedData.command,
410
- explanation: escalatedData.explanation,
411
- approvalType: escalatedData.approvalType,
412
- })
413
- escalatedApprovals?.delete(data.approvalRequestId)
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
+ }
414
292
  }
415
-
416
- // If a segment with this id is already present (batch or legacy), just flip its status.
417
- // updateApprovalStatus matches both `approval_batch` and `approval_request` segments.
418
- const before = accumulator.getSegments()
419
- const after = accumulator.updateApprovalStatus(data.approvalRequestId, status, resolvedByName)
420
- const updatedExisting = before.some((s, i) => after[i] !== s)
421
- if (updatedExisting) break
422
-
423
- accumulator.processApprovalResult(
424
- data.approvalRequestId,
425
- status === 'approved',
426
- data.approvalType || 'USER'
427
- )
293
+ } else {
294
+ escalatedApprovals?.set(event.requestId, {
295
+ command: event.command || '',
296
+ explanation: event.explanation,
297
+ approvalType,
298
+ ...(isBatch ? { toolCalls } : {}),
299
+ })
428
300
  }
429
301
  break
302
+ }
430
303
 
431
- case MESSAGE_TYPE.ERROR:
432
- if ('error' in data) {
433
- let message: string | undefined
434
- if ('details' in data && data?.details) {
435
- try {
436
- message = JSON.parse(data.details)?.error?.message
437
- } catch {
438
- message = data.details
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
+ )
439
332
  }
440
333
  }
441
- accumulator.addError(
442
- data.error || 'An error occurred',
443
- message
444
- )
334
+ escalatedApprovals?.delete(requestId)
335
+ break
445
336
  }
446
- break
447
337
 
448
- case MESSAGE_TYPE.CONTEXT_COMPACTION_START:
449
- accumulator.addContextCompaction()
338
+ if (escalatedData) {
339
+ accumulator.trackApprovalRequest(requestId, {
340
+ command: escalatedData.command,
341
+ explanation: escalatedData.explanation,
342
+ approvalType: escalatedData.approvalType,
343
+ })
344
+ escalatedApprovals?.delete(requestId)
345
+ }
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
+ )
450
360
  break
361
+ }
451
362
 
452
- case MESSAGE_TYPE.CONTEXT_COMPACTION_END: {
453
- const summary = 'summary' in data && typeof data.summary === 'string' ? data.summary : undefined
454
- accumulator.completeContextCompaction(summary)
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
370
+ }
371
+ }
372
+ accumulator.addError(event.title, message)
455
373
  break
456
374
  }
457
375
 
376
+ case 'compaction':
377
+ if (event.phase === 'start') {
378
+ accumulator.addContextCompaction()
379
+ } else {
380
+ accumulator.completeContextCompaction(event.summary)
381
+ }
382
+ break
383
+
458
384
  default:
459
- // Unknown message type - ignore
385
+ // Participant/system rows are envelope concerns; everything else is
386
+ // realtime-only vocabulary that never appears in persisted rows.
460
387
  break
461
388
  }
462
389
  }
463
390
 
391
+ // =============================================================================
392
+ // Envelope — ONE implementation (previous duplicate deleted)
393
+ // =============================================================================
394
+
464
395
  /**
465
- * Extract error messages from historical messages
466
- * Returns a separate array of error messages that should be displayed
396
+ * Result type for historical message processing
467
397
  */
468
- export function extractErrorMessages(
469
- messages: HistoricalMessage[],
470
- options: MessageProcessingOptions = {}
471
- ): ProcessedMessage[] {
472
- const { assistantName = 'Fae', assistantType = 'fae', assistantAvatar, chatTypeFilter } = options
473
-
474
- const errorMessages: ProcessedMessage[] = []
475
-
476
- messages.forEach((msg) => {
477
- if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
478
-
479
- const messageDataArray = Array.isArray(msg.messageData)
480
- ? msg.messageData
481
- : msg.messageData
482
- ? [msg.messageData]
483
- : []
484
-
485
- messageDataArray.forEach((data) => {
486
- if (data.type === MESSAGE_TYPE.ERROR) {
487
- errorMessages.push({
488
- id: `${msg.id}-error`,
489
- role: 'error',
490
- content: 'error' in data && data.error ? data.error : 'An error occurred',
491
- name: assistantName,
492
- assistantType,
493
- timestamp: new Date(msg.createdAt),
494
- avatar: assistantAvatar,
495
- })
496
- }
497
- })
498
- })
499
-
500
- return errorMessages
398
+ export interface ProcessHistoricalMessagesResult {
399
+ messages: ProcessedMessage[]
400
+ escalatedApprovals: EscalatedApprovals
501
401
  }
502
402
 
503
403
  /**
504
- * Process messages and include error messages in the correct order
404
+ * Process an array of historical messages into display-ready format
505
405
  */
506
- export function processHistoricalMessagesWithErrors(
406
+ export function processHistoricalMessages(
507
407
  messages: HistoricalMessage[],
508
- options: MessageProcessingOptions = {}
408
+ options: MessageProcessingOptions = {},
509
409
  ): ProcessHistoricalMessagesResult {
510
- // displayApprovalTypes omitted = display every approval type (original
511
- // history semantics — see the matching note in processHistoricalMessages).
512
- const { chatTypeFilter, assistantName = 'Fae', assistantType = 'fae', assistantAvatar, onApprove, onReject, approvalStatuses = {}, displayApprovalTypes, batchApprovalsEnabled } = options
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
513
428
 
514
429
  const processedMessages: ProcessedMessage[] = []
515
430
  const accumulator = createMessageSegmentAccumulator({ onApprove, onReject })
516
- const escalatedApprovals = new Map<
517
- string,
518
- { command: string; explanation?: string; approvalType: string; toolCalls?: PendingToolCallData[] }
519
- >()
431
+ const escalatedApprovals: EscalatedApprovals = new Map()
520
432
 
521
433
  let currentAssistantId: string | null = null
522
434
  let currentAssistantTimestamp: Date | null = null
@@ -525,6 +437,10 @@ export function processHistoricalMessagesWithErrors(
525
437
  // — carried onto the flushed message's streamSeq for per-role merge coverage.
526
438
  let currentAssistantStreamSeq: number | undefined
527
439
 
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
+ */
528
444
  const flushAssistantMessage = () => {
529
445
  const idToUse = lastAssistantId || currentAssistantId
530
446
  if (idToUse && accumulator.hasContent()) {
@@ -555,6 +471,7 @@ export function processHistoricalMessagesWithErrors(
555
471
  }
556
472
 
557
473
  messages.forEach((msg, index) => {
474
+ // Filter by chat type if specified
558
475
  if (chatTypeFilter && msg.chatType !== chatTypeFilter) return
559
476
 
560
477
  const messageDataArray = Array.isArray(msg.messageData)
@@ -618,8 +535,10 @@ export function processHistoricalMessagesWithErrors(
618
535
  }
619
536
 
620
537
  messageDataArray.forEach((data) => {
621
- processMessageData(
622
- data,
538
+ const event = decodeHistoricalMessageData(data)
539
+ if (!event) return
540
+ applyHistoryEvent(
541
+ event,
623
542
  accumulator,
624
543
  approvalStatuses,
625
544
  { displayApprovalTypes, batchApprovalsEnabled },
@@ -627,6 +546,7 @@ export function processHistoricalMessagesWithErrors(
627
546
  )
628
547
  })
629
548
 
549
+ // Check if we should flush (next message is from user or last message)
630
550
  const nextMsg = messages[index + 1]
631
551
  const isLastMessage = index === messages.length - 1
632
552
  const nextIsFromUser =
@@ -659,3 +579,52 @@ export function processHistoricalMessagesWithErrors(
659
579
  escalatedApprovals: escalatedApprovals
660
580
  }
661
581
  }
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