@flamingo-stack/openframe-frontend-core 0.0.457 → 0.0.458-snapshot.20260720215024

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 (290) 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-SQ3CP2IV.cjs → chunk-3N3TMZ62.cjs} +7 -7
  22. package/dist/{chunk-SQ3CP2IV.cjs.map → chunk-3N3TMZ62.cjs.map} +1 -1
  23. package/dist/{chunk-I7M6KCCS.js → chunk-4R6H2U77.js} +4 -4
  24. package/dist/{chunk-CCT5VCRP.cjs → chunk-4XDWNAZW.cjs} +9 -9
  25. package/dist/{chunk-CCT5VCRP.cjs.map → chunk-4XDWNAZW.cjs.map} +1 -1
  26. package/dist/{chunk-KQ36EHE4.cjs → chunk-7KSEINAE.cjs} +15 -15
  27. package/dist/{chunk-KQ36EHE4.cjs.map → chunk-7KSEINAE.cjs.map} +1 -1
  28. package/dist/{chunk-FM5DTJPA.cjs → chunk-ADD3FPDG.cjs} +6851 -4713
  29. package/dist/chunk-ADD3FPDG.cjs.map +1 -0
  30. package/dist/{chunk-RSW42GTZ.js → chunk-APF5QBAU.js} +2 -2
  31. package/dist/{chunk-YCIVMKRS.cjs → chunk-BLZZXZNM.cjs} +26 -26
  32. package/dist/{chunk-YCIVMKRS.cjs.map → chunk-BLZZXZNM.cjs.map} +1 -1
  33. package/dist/{chunk-YHB4MNUX.cjs → chunk-BQ7PMWLM.cjs} +28 -27
  34. package/dist/chunk-BQ7PMWLM.cjs.map +1 -0
  35. package/dist/{chunk-GJ7BN4MI.js → chunk-CGNDAJ7V.js} +4 -4
  36. package/dist/{chunk-R5IQJXA3.js → chunk-F2NMWV44.js} +2 -2
  37. package/dist/{chunk-EOVQVVDJ.cjs → chunk-F7F43U7Q.cjs} +11 -11
  38. package/dist/{chunk-EOVQVVDJ.cjs.map → chunk-F7F43U7Q.cjs.map} +1 -1
  39. package/dist/{chunk-2ZW2ZPDW.js → chunk-LAOO7XHO.js} +2 -2
  40. package/dist/{chunk-O7F7RZFN.js → chunk-LJKZIIK4.js} +6 -5
  41. package/dist/chunk-LJKZIIK4.js.map +1 -0
  42. package/dist/{chunk-AJGZ3YSR.js → chunk-OR5AMXYN.js} +2 -2
  43. package/dist/{chunk-5XFJG3TC.cjs → chunk-P5JQDFRM.cjs} +60 -60
  44. package/dist/chunk-P5JQDFRM.cjs.map +1 -0
  45. package/dist/{chunk-U4APSAAR.cjs → chunk-PXZ7YQ5V.cjs} +5 -5
  46. package/dist/{chunk-U4APSAAR.cjs.map → chunk-PXZ7YQ5V.cjs.map} +1 -1
  47. package/dist/{chunk-WXDEMTLD.js → chunk-QO2XD3FR.js} +2 -2
  48. package/dist/{chunk-C2TDHJBO.cjs → chunk-QSGZE6AZ.cjs} +37 -37
  49. package/dist/{chunk-C2TDHJBO.cjs.map → chunk-QSGZE6AZ.cjs.map} +1 -1
  50. package/dist/{chunk-NSL5MNS4.js → chunk-REWRUV3K.js} +11644 -9506
  51. package/dist/chunk-REWRUV3K.js.map +1 -0
  52. package/dist/{chunk-BDTQIIJR.cjs → chunk-TA7MFVUS.cjs} +31 -31
  53. package/dist/{chunk-BDTQIIJR.cjs.map → chunk-TA7MFVUS.cjs.map} +1 -1
  54. package/dist/{chunk-4423DHRX.js → chunk-UI7CIUAR.js} +2 -2
  55. package/dist/{chunk-5BKBG653.js → chunk-VXJH5TDN.js} +10 -10
  56. package/dist/chunk-VXJH5TDN.js.map +1 -0
  57. package/dist/{chunk-AB65PWU2.cjs → chunk-WCE66C2Z.cjs} +62 -62
  58. package/dist/{chunk-AB65PWU2.cjs.map → chunk-WCE66C2Z.cjs.map} +1 -1
  59. package/dist/{chunk-KXIIUE75.js → chunk-XF5ROTMQ.js} +2 -2
  60. package/dist/components/case-studies/index.cjs +8 -8
  61. package/dist/components/case-studies/index.js +2 -2
  62. package/dist/components/chart.d.ts +1 -1
  63. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  64. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  65. package/dist/components/chat/hooks/index.d.ts +0 -1
  66. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  67. package/dist/components/chat/hooks/use-chat.d.ts.map +1 -1
  68. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +15 -48
  69. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  70. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +3 -47
  71. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  72. package/dist/components/chat/index.cjs +10 -2
  73. package/dist/components/chat/index.cjs.map +1 -1
  74. package/dist/components/chat/index.d.ts +1 -0
  75. package/dist/components/chat/index.d.ts.map +1 -1
  76. package/dist/components/chat/index.js +21 -13
  77. package/dist/components/chat/stream/chat-dialog-store.d.ts +184 -0
  78. package/dist/components/chat/stream/chat-dialog-store.d.ts.map +1 -0
  79. package/dist/components/chat/stream/chat-stream-reducer.d.ts +367 -0
  80. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +1 -0
  81. package/dist/components/chat/stream/delta-batcher.d.ts +51 -0
  82. package/dist/components/chat/stream/delta-batcher.d.ts.map +1 -0
  83. package/dist/components/chat/stream/index.d.ts +17 -0
  84. package/dist/components/chat/stream/index.d.ts.map +1 -0
  85. package/dist/components/chat/stream/message-mutations.d.ts +77 -0
  86. package/dist/components/chat/stream/message-mutations.d.ts.map +1 -0
  87. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts +22 -0
  88. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts.map +1 -0
  89. package/dist/components/chat/types/api.types.d.ts +1 -81
  90. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  91. package/dist/components/chat/types/processing.types.d.ts +2 -90
  92. package/dist/components/chat/types/processing.types.d.ts.map +1 -1
  93. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts +34 -6
  94. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts.map +1 -1
  95. package/dist/components/chat/utils/index.d.ts +2 -3
  96. package/dist/components/chat/utils/index.d.ts.map +1 -1
  97. package/dist/components/chat/utils/process-historical-messages.d.ts +59 -11
  98. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  99. package/dist/components/contact/index.cjs +3 -3
  100. package/dist/components/contact/index.js +2 -2
  101. package/dist/components/docs/index.cjs +5 -5
  102. package/dist/components/docs/index.js +4 -4
  103. package/dist/components/embeds/index.cjs +3 -3
  104. package/dist/components/embeds/index.js +2 -2
  105. package/dist/components/faq/index.cjs +3 -3
  106. package/dist/components/faq/index.js +2 -2
  107. package/dist/components/features/index.cjs +2 -2
  108. package/dist/components/features/index.js +1 -1
  109. package/dist/components/features/time-tracker/time-tracker-panel.d.ts.map +1 -1
  110. package/dist/components/help-center-pages/index.cjs +20 -20
  111. package/dist/components/help-center-pages/index.js +11 -11
  112. package/dist/components/index.cjs +171 -129
  113. package/dist/components/index.cjs.map +1 -1
  114. package/dist/components/index.js +63 -21
  115. package/dist/components/index.js.map +1 -1
  116. package/dist/components/layout/page-container.d.ts.map +1 -1
  117. package/dist/components/navigation/index.cjs +2 -2
  118. package/dist/components/navigation/index.js +1 -1
  119. package/dist/components/onboarding-guides/index.cjs +5 -5
  120. package/dist/components/onboarding-guides/index.js +4 -4
  121. package/dist/components/onboarding-guides/onboarding-guide-detail-view.d.ts.map +1 -1
  122. package/dist/components/related-content/index.cjs +3 -3
  123. package/dist/components/related-content/index.js +2 -2
  124. package/dist/components/shared/product-release/release-detail-page.d.ts.map +1 -1
  125. package/dist/components/tickets/index.cjs +5 -5
  126. package/dist/components/tickets/index.js +4 -4
  127. package/dist/components/ui/index.cjs +44 -2
  128. package/dist/components/ui/index.cjs.map +1 -1
  129. package/dist/components/ui/index.d.ts +1 -2
  130. package/dist/components/ui/index.d.ts.map +1 -1
  131. package/dist/components/ui/index.js +55 -13
  132. package/dist/components/ui/markdown/base-components.d.ts +56 -0
  133. package/dist/components/ui/markdown/base-components.d.ts.map +1 -0
  134. package/dist/components/ui/markdown/engine.d.ts +99 -0
  135. package/dist/components/ui/markdown/engine.d.ts.map +1 -0
  136. package/dist/components/ui/markdown/heading-ids.d.ts +65 -0
  137. package/dist/components/ui/markdown/heading-ids.d.ts.map +1 -0
  138. package/dist/components/ui/markdown/index.d.ts +18 -0
  139. package/dist/components/ui/markdown/index.d.ts.map +1 -0
  140. package/dist/components/ui/markdown/mermaid-diagram.d.ts +79 -0
  141. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +1 -0
  142. package/dist/components/ui/markdown/rich/embed-overrides.d.ts +14 -0
  143. package/dist/components/ui/markdown/rich/embed-overrides.d.ts.map +1 -0
  144. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts +40 -0
  145. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts.map +1 -0
  146. package/dist/components/ui/markdown/rich/shortcodes.d.ts +8 -0
  147. package/dist/components/ui/markdown/rich/shortcodes.d.ts.map +1 -0
  148. package/dist/components/ui/markdown/sanitize.d.ts +153 -0
  149. package/dist/components/ui/markdown/sanitize.d.ts.map +1 -0
  150. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts +23 -0
  151. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts.map +1 -0
  152. package/dist/components/ui/markdown/streaming.d.ts +78 -0
  153. package/dist/components/ui/markdown/streaming.d.ts.map +1 -0
  154. package/dist/components/ui/markdown/text-size.d.ts +34 -0
  155. package/dist/components/ui/markdown/text-size.d.ts.map +1 -0
  156. package/dist/components/ui/modal-v2.d.ts.map +1 -1
  157. package/dist/components/ui/modal.d.ts.map +1 -1
  158. package/dist/index.cjs +60 -2
  159. package/dist/index.cjs.map +1 -1
  160. package/dist/index.js +71 -13
  161. package/dist/utils/index.cjs +169 -40
  162. package/dist/utils/index.cjs.map +1 -1
  163. package/dist/utils/index.d.ts +1 -0
  164. package/dist/utils/index.d.ts.map +1 -1
  165. package/dist/utils/index.js +162 -41
  166. package/dist/utils/index.js.map +1 -1
  167. package/dist/utils/markdown-fences.d.ts +42 -0
  168. package/dist/utils/markdown-fences.d.ts.map +1 -0
  169. package/dist/utils/markdown-heading-id.d.ts +85 -0
  170. package/dist/utils/markdown-heading-id.d.ts.map +1 -0
  171. package/dist/utils/markdown-section-extractor.d.ts.map +1 -1
  172. package/package.json +7 -1
  173. package/src/chat-protocol/__tests__/__snapshots__/nats-decoder-golden.test.ts.snap +307 -0
  174. package/src/chat-protocol/__tests__/chat-protocol.test.ts +515 -0
  175. package/src/chat-protocol/__tests__/env-flag.test.ts +52 -0
  176. package/src/chat-protocol/__tests__/ip-normalize.test.ts +136 -0
  177. package/src/chat-protocol/__tests__/nats-decoder-golden.test.ts +228 -0
  178. package/src/chat-protocol/decode.ts +277 -0
  179. package/src/chat-protocol/encode.ts +71 -0
  180. package/src/chat-protocol/env-flag.ts +39 -0
  181. package/src/chat-protocol/events.ts +228 -0
  182. package/src/chat-protocol/frames.ts +238 -0
  183. package/src/chat-protocol/index.ts +21 -0
  184. package/src/chat-protocol/ip-normalize.ts +146 -0
  185. package/src/chat-protocol/nats-decoder.ts +252 -0
  186. package/src/components/chat/__tests__/chat-message-list.test.tsx +293 -5
  187. package/src/components/chat/__tests__/chat-message-streaming-memo.test.tsx +207 -0
  188. package/src/components/chat/__tests__/chat-pending-turn.test.tsx +209 -0
  189. package/src/components/chat/chat-message-enhanced.tsx +111 -17
  190. package/src/components/chat/chat-message-list.tsx +367 -113
  191. package/src/components/chat/embeddable-chat.tsx +6 -0
  192. package/src/components/chat/hooks/.index.md +1 -1
  193. package/src/components/chat/hooks/.use-nats-chat-adapter.md +1 -1
  194. package/src/components/chat/hooks/__tests__/__snapshots__/persisted-state-v1-golden.test.ts.snap +297 -0
  195. package/src/components/chat/hooks/__tests__/__snapshots__/sse-stream-golden.test.ts.snap +0 -0
  196. package/src/components/chat/hooks/__tests__/persisted-state-v1-golden.test.ts +272 -0
  197. package/src/components/chat/hooks/__tests__/sse-stream-golden.test.ts +318 -0
  198. package/src/components/chat/hooks/index.ts +0 -1
  199. package/src/components/chat/hooks/use-chat.ts +8 -0
  200. package/src/components/chat/hooks/use-nats-chat-adapter.ts +243 -822
  201. package/src/components/chat/hooks/use-sse-chat-adapter.ts +318 -666
  202. package/src/components/chat/index.ts +5 -0
  203. package/src/components/chat/stream/__tests__/__snapshots__/chat-stream-reducer-golden.test.ts.snap +937 -0
  204. package/src/components/chat/stream/__tests__/chat-dialog-store.test.ts +756 -0
  205. package/src/components/chat/stream/__tests__/chat-stream-reducer-golden.test.ts +460 -0
  206. package/src/components/chat/stream/__tests__/chat-stream-reducer.test.ts +894 -0
  207. package/src/components/chat/stream/__tests__/delta-batcher.test.ts +255 -0
  208. package/src/components/chat/stream/__tests__/use-chat-stream-reducer.test.ts +98 -0
  209. package/src/components/chat/stream/chat-dialog-store.ts +536 -0
  210. package/src/components/chat/stream/chat-stream-reducer.ts +1796 -0
  211. package/src/components/chat/stream/delta-batcher.ts +159 -0
  212. package/src/components/chat/stream/index.ts +55 -0
  213. package/src/components/chat/stream/message-mutations.ts +338 -0
  214. package/src/components/chat/stream/use-chat-stream-reducer.ts +126 -0
  215. package/src/components/chat/thinking-display.tsx +1 -1
  216. package/src/components/chat/types/.api.types.md +1 -3
  217. package/src/components/chat/types/.processing.types.md +6 -23
  218. package/src/components/chat/types/api.types.ts +6 -73
  219. package/src/components/chat/types/processing.types.ts +11 -52
  220. package/src/components/chat/utils/.index.md +0 -5
  221. package/src/components/chat/utils/__tests__/__snapshots__/process-historical-messages-golden.test.ts.snap +418 -0
  222. package/src/components/chat/utils/__tests__/__snapshots__/segment-accumulator-golden.test.ts.snap +599 -0
  223. package/src/components/chat/utils/__tests__/process-historical-messages-golden.test.ts +317 -0
  224. package/src/components/chat/utils/__tests__/segment-accumulator-golden.test.ts +270 -0
  225. package/src/components/chat/utils/extract-incomplete-message-state.ts +63 -5
  226. package/src/components/chat/utils/index.ts +5 -8
  227. package/src/components/chat/utils/process-historical-messages.ts +352 -383
  228. package/src/components/features/notifications/notification-drawer.tsx +4 -2
  229. package/src/components/features/time-tracker/time-tracker-panel.tsx +8 -2
  230. package/src/components/layout/page-container.tsx +5 -1
  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/modal-v2.tsx +6 -0
  254. package/src/components/ui/modal.tsx +3 -0
  255. package/src/components/ui/release-changelog-section.tsx +1 -1
  256. package/src/components/ui/ticket-info-section.tsx +1 -1
  257. package/src/utils/index.ts +1 -0
  258. package/src/utils/markdown-fences.ts +127 -0
  259. package/src/utils/markdown-heading-id.ts +348 -0
  260. package/src/utils/markdown-section-extractor.ts +41 -56
  261. package/dist/chunk-5BKBG653.js.map +0 -1
  262. package/dist/chunk-5XFJG3TC.cjs.map +0 -1
  263. package/dist/chunk-FM5DTJPA.cjs.map +0 -1
  264. package/dist/chunk-NSL5MNS4.js.map +0 -1
  265. package/dist/chunk-O7F7RZFN.js.map +0 -1
  266. package/dist/chunk-YHB4MNUX.cjs.map +0 -1
  267. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts +0 -6
  268. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts.map +0 -1
  269. package/dist/components/chat/utils/chunk-parser.d.ts +0 -25
  270. package/dist/components/chat/utils/chunk-parser.d.ts.map +0 -1
  271. package/dist/components/ui/rich-markdown-renderer.d.ts +0 -34
  272. package/dist/components/ui/rich-markdown-renderer.d.ts.map +0 -1
  273. package/dist/components/ui/simple-markdown-renderer.d.ts +0 -73
  274. package/dist/components/ui/simple-markdown-renderer.d.ts.map +0 -1
  275. package/src/components/chat/hooks/.use-realtime-chunk-processor.md +0 -50
  276. package/src/components/chat/hooks/use-realtime-chunk-processor.ts +0 -479
  277. package/src/components/chat/utils/.chunk-parser.md +0 -51
  278. package/src/components/chat/utils/chunk-parser.ts +0 -255
  279. package/src/components/ui/.simple-markdown-renderer.md +0 -40
  280. package/src/components/ui/rich-markdown-renderer.tsx +0 -1223
  281. package/src/components/ui/simple-markdown-renderer.tsx +0 -965
  282. /package/dist/{chunk-I7M6KCCS.js.map → chunk-4R6H2U77.js.map} +0 -0
  283. /package/dist/{chunk-RSW42GTZ.js.map → chunk-APF5QBAU.js.map} +0 -0
  284. /package/dist/{chunk-GJ7BN4MI.js.map → chunk-CGNDAJ7V.js.map} +0 -0
  285. /package/dist/{chunk-R5IQJXA3.js.map → chunk-F2NMWV44.js.map} +0 -0
  286. /package/dist/{chunk-2ZW2ZPDW.js.map → chunk-LAOO7XHO.js.map} +0 -0
  287. /package/dist/{chunk-AJGZ3YSR.js.map → chunk-OR5AMXYN.js.map} +0 -0
  288. /package/dist/{chunk-WXDEMTLD.js.map → chunk-QO2XD3FR.js.map} +0 -0
  289. /package/dist/{chunk-4423DHRX.js.map → chunk-UI7CIUAR.js.map} +0 -0
  290. /package/dist/{chunk-KXIIUE75.js.map → chunk-XF5ROTMQ.js.map} +0 -0
@@ -12,11 +12,11 @@
12
12
  * ┌──────────────────────────────────────────────────────────────┐
13
13
  * │ useNatsDialogSubscription live tail of agent events │
14
14
  * │ ↓ │
15
- * │ onEvent → processChunk │
15
+ * │ onEvent → decodeNatsChunk → ChatStreamEvent │
16
16
  * │ ↓ │
17
- * │ useRealtimeChunkProcessor chunk → MessageSegment[] │
18
- * │ ↓ │
19
- * │ onSegmentsUpdate → updates assistant message in state │
17
+ * │ createChatStreamReducer THE master accumulation path │
18
+ * │ (via ChatDialogStore + useChatStreamReducer wrapper — │
19
+ * │ messages, phase, token usage, approvals all live there) │
20
20
  * │ │
21
21
  * │ useChunkCatchup back-fill missed chunks after │
22
22
  * │ activation / reconnect │
@@ -24,53 +24,38 @@
24
24
  * │ config.publishUserMessage consumer-owned send (HTTP/NATS) │
25
25
  * └──────────────────────────────────────────────────────────────┘
26
26
  *
27
+ * Phase 3 of the chat unification: the adapter's local message-mutation
28
+ * layer (`updateTrailingAssistant` / `appendToTrailingAssistant` /
29
+ * `upsertTrailingCompaction` / `applyToolExecutionToMessages` and the
30
+ * chunk-callback body that drove them) is DELETED — those semantics live in
31
+ * `../stream/chat-stream-reducer` + `../stream/message-mutations` now. The
32
+ * adapter owns only what is genuinely transport/host wiring: dialog-list
33
+ * management, history fetch, catchup orchestration, the NATS subscription,
34
+ * and the publish path.
35
+ *
27
36
  * Two operating modes, distinguished by the presence of `fetchDialogs`:
28
37
  *
29
38
  * 1. **Bare-transport mode** (current Tauri Fae Chat usage):
30
39
  * consumer supplies `config.dialogId` explicitly and owns dialog
31
- * management above the adapter. The adapter does no list/select
32
- * bookkeeping — every dialog field on the return value falls back
33
- * to an empty default. This is the original v0 API; preserved
34
- * byte-compatible so existing pinned consumers keep working.
40
+ * management above the adapter.
35
41
  *
36
42
  * 2. **Managed-dialog mode** (openframe-frontend, EmbeddableChat
37
- * sidebar): consumer supplies `fetchDialogs`,
38
- * `fetchDialogMessages`, `createDialog`, etc. and the adapter
39
- * owns the dialog state machine. The active dialog id, the list,
40
- * pagination cursors, token usage hydration, and history merge
41
- * all live inside this hook. The host renders the sidebar via
42
- * `EmbeddableChat`'s built-in `<ChatSidebar>` slot and calls
43
- * `selectDialog` / `startNewDialog` from there.
44
- *
45
- * The two modes are NOT mutually exclusive — passing `config.dialogId`
46
- * alongside `fetchDialogs` forces the adapter into controlled mode (the
47
- * external id wins) while still using the host's list fetchers for the
48
- * sidebar.
49
- *
50
- * Why publish is consumer-owned: the NATS module exposes a low-level
51
- * `publishBytes/String/Json` but the actual user-message endpoint varies
52
- * by deployment (REST POST in some, NATS subject in others). The adapter
53
- * stays agnostic — caller wires up "user typed something, do X" via
54
- * the `publishUserMessage` callback.
43
+ * sidebar): consumer supplies `fetchDialogs`, `fetchDialogMessages`,
44
+ * `createDialog`, etc. and the adapter owns the dialog state machine.
55
45
  *
56
46
  * The `active` option gates the live subscription so the unified chat
57
47
  * shell can keep both adapters mounted while only paying network cost
58
48
  * for the currently-displayed mode.
59
49
  */
60
50
 
61
- import {
62
- useCallback,
63
- useEffect,
64
- useMemo,
65
- useRef,
66
- useState,
67
- type MutableRefObject,
68
- } from 'react'
51
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
69
52
  import { useNatsDialogSubscription } from './use-nats-dialog-subscription'
70
- import { useRealtimeChunkProcessor } from './use-realtime-chunk-processor'
71
53
  import { useChunkCatchup } from './use-chunk-catchup'
54
+ import { decodeNatsChunk } from '../../../chat-protocol/nats-decoder'
55
+ import { createChatDialogStore, DEFAULT_DIALOG_SIDE } from '../stream/chat-dialog-store'
56
+ import { useChatStreamReducer } from '../stream/use-chat-stream-reducer'
72
57
  import { processHistoricalMessagesWithErrors } from '../utils/process-historical-messages'
73
- import { extractIncompleteMessageState } from '../utils/extract-incomplete-message-state'
58
+ import { extractIncompleteTailState } from '../utils/extract-incomplete-message-state'
74
59
  import type {
75
60
  ChunkData,
76
61
  FetchChunksFunction,
@@ -78,11 +63,7 @@ import type {
78
63
  MessageProcessingOptions,
79
64
  MessageSegment,
80
65
  NatsMessageType,
81
- StreamingPhase,
82
66
  ChatApprovalStatus,
83
- SegmentsUpdateMetadata,
84
- ToolExecutionSegment,
85
- ApprovalBatchExecutionState,
86
67
  } from '../types'
87
68
  import type {
88
69
  ChatConnectionState,
@@ -94,6 +75,16 @@ import type {
94
75
  import type { DialogItem } from '../types/component.types'
95
76
  import type { ChatRef } from '../chat-ref.types'
96
77
 
78
+ // Legacy public home of the pure message-mutation helpers ("exported for
79
+ // host reuse"). Canonical implementation moved to the stream module in
80
+ // Phase 3 — these re-exports keep the import path stable until Phase 4
81
+ // migrates consumers.
82
+ export {
83
+ appendToTrailingAssistant,
84
+ applyToolExecutionToMessages,
85
+ upsertTrailingCompaction,
86
+ } from '../stream/message-mutations'
87
+
97
88
  // =============================================================================
98
89
  // Config + options
99
90
  // =============================================================================
@@ -210,19 +201,19 @@ export interface UseNatsChatAdapterConfig {
210
201
  topics?: NatsMessageType[]
211
202
 
212
203
  /**
213
- * Mirrors `UseRealtimeChunkProcessorOptions.batchApprovalsEnabled`.
214
- * Default `true` — single batch card per APPROVAL_REQUEST with
215
- * `toolCalls[]`. Set `false` to fall back to legacy per-tool cards.
204
+ * Mirrors the reducer's `batchApprovalsEnabled`. Default `true` —
205
+ * single batch card per APPROVAL_REQUEST with `toolCalls[]`. Set
206
+ * `false` to fall back to legacy per-tool cards.
216
207
  */
217
208
  batchApprovalsEnabled?: boolean
218
209
 
219
210
  /**
220
- * Approval types rendered as actionable cards inline. Mirrors
221
- * `UseRealtimeChunkProcessorOptions.displayApprovalTypes` (default
222
- * `['CLIENT']`) and is forwarded to the history processor so both paths
223
- * agree. Hosts whose backend emits other types (e.g. `USER`) MUST set this
224
- * — otherwise those approvals are escalated to a callback this adapter
225
- * doesn't surface and the card never renders.
211
+ * Approval types rendered as actionable cards inline. Mirrors the
212
+ * reducer's `displayApprovalTypes` (default `['CLIENT']`) and is
213
+ * forwarded to the history processor so both paths agree. Hosts whose
214
+ * backend emits other types (e.g. `USER`) MUST set this — otherwise
215
+ * those approvals are escalated to a callback this adapter doesn't
216
+ * surface and the card never renders.
226
217
  */
227
218
  displayApprovalTypes?: string[]
228
219
 
@@ -245,7 +236,7 @@ export interface UseNatsChatAdapterConfig {
245
236
  * Messages must arrive in the same wire shape the openframe backend
246
237
  * emits (HistoricalMessage with messageData[]); the adapter feeds
247
238
  * them through `processHistoricalMessagesWithErrors` to produce
248
- * accumulator-compatible segments.
239
+ * reducer-compatible messages.
249
240
  */
250
241
  fetchDialogMessages?: (
251
242
  params: FetchDialogMessagesParams,
@@ -283,9 +274,9 @@ export interface UseNatsChatAdapterConfig {
283
274
  unarchiveDialog?: (dialogId: string) => Promise<void>
284
275
 
285
276
  /**
286
- * Approve a pending tool-call request. Wired into the segment
287
- * accumulator's `onApprove` so approval-card buttons fire this
288
- * directly. When omitted, approval cards render disabled buttons.
277
+ * Approve a pending tool-call request. Wired into the reducer's
278
+ * approval-card callbacks so card buttons fire this directly. When
279
+ * omitted, approval cards render disabled buttons.
289
280
  */
290
281
  approveRequest?: (requestId: string) => Promise<void>
291
282
 
@@ -344,261 +335,9 @@ export interface UseNatsChatAdapterOptions {
344
335
  }
345
336
 
346
337
  // =============================================================================
347
- // Internal helpers
338
+ // Historical-message mapping helpers (host-facing)
348
339
  // =============================================================================
349
340
 
350
- function nextId(role: 'user' | 'assistant'): string {
351
- // Date.now() + counter sliver keeps ids monotonic even when two
352
- // messages are produced inside the same ms tick (user + assistant
353
- // placeholder fire back-to-back from a single sendMessage call).
354
- return `${role}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`
355
- }
356
-
357
- /**
358
- * Replace (or append) the trailing assistant message with the latest
359
- * accumulated segments. Mirrors the use-chat.ts pattern so render
360
- * behaviour matches the SSE adapter exactly.
361
- */
362
- function updateTrailingAssistant(
363
- prev: UnifiedChatMessage[],
364
- segments: MessageSegment[],
365
- ): UnifiedChatMessage[] {
366
- const last = prev[prev.length - 1]
367
- if (!last || last.role !== 'assistant') {
368
- // No placeholder exists — append a fresh assistant message.
369
- return [
370
- ...prev,
371
- {
372
- id: nextId('assistant'),
373
- role: 'assistant',
374
- content: '',
375
- segments,
376
- },
377
- ]
378
- }
379
- return [
380
- ...prev.slice(0, -1),
381
- { ...last, segments },
382
- ]
383
- }
384
-
385
- /**
386
- * Realtime user/direct/system chunks can be replays of rows already on
387
- * screen (our own optimistic send echoed back, catchup replaying the tail
388
- * over just-loaded history, reconnect back-fill).
389
- *
390
- * Dedup layers, in priority order:
391
- * 1. `streamSeq` identity (JetStream) — exact, never confuses a genuinely
392
- * repeated text with a replay; tracked in a per-dialog seen-set.
393
- * 2. One-shot optimistic-echo consumption — `sendMessage` records the text
394
- * it optimistically rendered; the backend's MESSAGE_REQUEST echo removes
395
- * exactly one entry.
396
- * 3. Content match over a SHORT same-author tail window — only for
397
- * seq-less transports (plain NATS replay over just-loaded history, where
398
- * the persisted twin sits at most a couple of rows up). Same-author so
399
- * an admin message can never suppress a user's identical text.
400
- */
401
- const CONTENT_DEDUP_WINDOW = 4
402
- const SYSTEM_DEDUP_WINDOW = 10
403
-
404
- function hasRecentMessage(
405
- prev: UnifiedChatMessage[],
406
- predicate: (message: UnifiedChatMessage) => boolean,
407
- window: number,
408
- ): boolean {
409
- const start = Math.max(0, prev.length - window)
410
- for (let i = prev.length - 1; i >= start; i--) {
411
- if (predicate(prev[i])) return true
412
- }
413
- return false
414
- }
415
-
416
- /**
417
- * Append-mode counterpart of `updateTrailingAssistant` for post-MESSAGE_END
418
- * continuation chunks (`SegmentsUpdateMetadata.append`). The processor emits
419
- * single text/thinking fragments there — replacing the bubble with them (the
420
- * old behaviour, which dropped the metadata) wiped everything the bubble
421
- * already showed. Coalesces trailing fragments of the same type, mirroring
422
- * the accumulator.
423
- *
424
- * Exported for host reuse (custom stores wiring the same processor) + tests.
425
- */
426
- export function appendToTrailingAssistant(
427
- prev: UnifiedChatMessage[],
428
- segments: MessageSegment[],
429
- ): UnifiedChatMessage[] {
430
- if (segments.length === 0) return prev
431
- const last = prev[prev.length - 1]
432
- if (!last || last.role !== 'assistant') {
433
- return [
434
- ...prev,
435
- { id: nextId('assistant'), role: 'assistant', content: '', segments },
436
- ]
437
- }
438
- const merged = [...(last.segments ?? [])]
439
- for (const seg of segments) {
440
- const tail = merged[merged.length - 1]
441
- if (seg.type === 'text' && tail?.type === 'text') {
442
- merged[merged.length - 1] = { type: 'text', text: tail.text + seg.text }
443
- } else if (seg.type === 'thinking' && tail?.type === 'thinking') {
444
- merged[merged.length - 1] = { type: 'thinking', text: tail.text + seg.text }
445
- } else if (seg.type === 'approval_batch') {
446
- // Approval deltas must be IDEMPOTENT: the escalated-result emit can be
447
- // seen twice (live + catch-up replay over hydrated history), so upsert
448
- // by request id instead of raw-appending a duplicate card.
449
- const idx = merged.findIndex(
450
- (m) => m.type === 'approval_batch' && m.data.approvalRequestId === seg.data.approvalRequestId,
451
- )
452
- if (idx !== -1) merged[idx] = seg
453
- else merged.push(seg)
454
- } else if (seg.type === 'approval_request') {
455
- // Legacy cards share one requestId across an unfolded batch — key on
456
- // (requestId, command) so each tool's card upserts its own twin.
457
- const idx = merged.findIndex(
458
- (m) =>
459
- m.type === 'approval_request' &&
460
- m.data.requestId === seg.data.requestId &&
461
- m.data.command === seg.data.command,
462
- )
463
- if (idx !== -1) merged[idx] = seg
464
- else merged.push(seg)
465
- } else {
466
- // Other non-text segments are pushed RAW on purpose: EXECUTING↔EXECUTED
467
- // pairing and batch merging are `applyToolExecutionToMessages`'s job
468
- // (post-END tool chunks never reach this helper — the processor routes
469
- // them to onToolExecuted). Running the accumulator here would
470
- // double-apply those rules.
471
- merged.push(seg)
472
- }
473
- }
474
- return [...prev.slice(0, -1), { ...last, segments: merged }]
475
- }
476
-
477
- /**
478
- * Upsert a standalone context-compaction segment into the trailing assistant
479
- * bubble. Compaction emissions arrive as the accumulator's CUMULATIVE array —
480
- * only the compaction segment itself may be applied, or interleaved
481
- * continuation text would duplicate. A `completed` segment replaces the last
482
- * `started` one in place.
483
- *
484
- * Exported for host reuse + tests.
485
- */
486
- export function upsertTrailingCompaction(
487
- prev: UnifiedChatMessage[],
488
- segments: MessageSegment[],
489
- ): UnifiedChatMessage[] {
490
- const compaction = [...segments].reverse().find((s) => s.type === 'context_compaction')
491
- if (!compaction) return prev
492
- const last = prev[prev.length - 1]
493
- if (!last || last.role !== 'assistant') {
494
- return [
495
- ...prev,
496
- { id: nextId('assistant'), role: 'assistant', content: '', segments: [compaction] },
497
- ]
498
- }
499
- const existing = last.segments ?? []
500
- // LAST 'started' segment (not first): with repeated compactions in one
501
- // bubble the earlier ones are already completed-in-place, so the newest
502
- // 'started' is the only one this completion can belong to.
503
- const startedIdx = existing.map((s) => s.type === 'context_compaction' && s.status === 'started').lastIndexOf(true)
504
- const merged =
505
- startedIdx !== -1
506
- ? existing.map((s, i) => (i === startedIdx ? compaction : s))
507
- : [...existing, compaction]
508
- return [...prev.slice(0, -1), { ...last, segments: merged }]
509
- }
510
-
511
- /**
512
- * Cross-message tool-execution updater for post-MESSAGE_END tool chunks
513
- * (approved commands executing after the approval bubble, async batch
514
- * results). Scans messages from the end:
515
- * 1) an `approval_batch` whose `toolCalls` contains the execution id →
516
- * merge into its `executions` map;
517
- * 2) a matching `tool_execution` segment (same id, or EXECUTING with the
518
- * same tool for legacy id-less backends) → update in place;
519
- * 3) no match → append the segment to the trailing assistant bubble.
520
- *
521
- * Exported for host reuse + tests.
522
- */
523
- export function applyToolExecutionToMessages(
524
- prev: UnifiedChatMessage[],
525
- segment: ToolExecutionSegment,
526
- ): UnifiedChatMessage[] {
527
- const toolData = segment.data
528
- const execId = toolData.toolExecutionRequestId
529
-
530
- for (let i = prev.length - 1; i >= 0; i--) {
531
- const message = prev[i]
532
- if (message.role !== 'assistant' || !message.segments) continue
533
-
534
- for (let j = message.segments.length - 1; j >= 0; j--) {
535
- const seg = message.segments[j]
536
-
537
- if (
538
- execId &&
539
- seg.type === 'approval_batch' &&
540
- seg.data.toolCalls.some((c) => c.toolExecutionRequestId === execId)
541
- ) {
542
- const prevExec: ApprovalBatchExecutionState | undefined = seg.data.executions?.[execId]
543
- // Never downgrade a done batch slot back to executing (JetStream
544
- // redelivery of the EXECUTING chunk after EXECUTED landed). Returning
545
- // prev = matched-with-no-change, so the caller doesn't append either.
546
- if (toolData.type === 'EXECUTING_TOOL' && prevExec?.status === 'done') {
547
- return prev
548
- }
549
- const nextExec: ApprovalBatchExecutionState =
550
- toolData.type === 'EXECUTED_TOOL'
551
- ? { status: 'done', result: toolData.result, success: toolData.success }
552
- : { status: 'executing', result: prevExec?.result, success: prevExec?.success }
553
- const nextSegments = [...message.segments]
554
- nextSegments[j] = {
555
- ...seg,
556
- data: { ...seg.data, executions: { ...(seg.data.executions ?? {}), [execId]: nextExec } },
557
- }
558
- const next = [...prev]
559
- next[i] = { ...message, segments: nextSegments }
560
- return next
561
- }
562
-
563
- if (seg.type === 'tool_execution') {
564
- // KNOWN LIMIT (id-less chunks only — current backends always send
565
- // toolExecutionRequestId): the fuzzy fallback pairs only with a
566
- // segment still EXECUTING, so a replayed id-less EXECUTING/EXECUTED
567
- // arriving after the pair completed matches nothing and falls to the
568
- // append below (duplicate card). Widening the predicate to EXECUTED
569
- // twins would instead swallow a LEGITIMATE second run of the same
570
- // tool — without ids the two are indistinguishable, and losing a
571
- // real run is worse than a duplicate card on a legacy transport.
572
- const matches = execId
573
- ? seg.data.toolExecutionRequestId === execId
574
- : seg.data.type === 'EXECUTING_TOOL' &&
575
- seg.data.integratedToolType === toolData.integratedToolType &&
576
- seg.data.toolFunction === toolData.toolFunction
577
- if (!matches) continue
578
- // Never downgrade a completed segment back to EXECUTING (replayed
579
- // EXECUTING chunk after its EXECUTED already landed).
580
- if (toolData.type === 'EXECUTING_TOOL' && seg.data.type === 'EXECUTED_TOOL') {
581
- return prev
582
- }
583
- const nextSegments = [...message.segments]
584
- nextSegments[j] = {
585
- type: 'tool_execution',
586
- data: {
587
- ...toolData,
588
- toolTitle: toolData.toolTitle ?? seg.data.toolTitle,
589
- parameters: toolData.parameters || seg.data.parameters,
590
- },
591
- }
592
- const next = [...prev]
593
- next[i] = { ...message, segments: nextSegments }
594
- return next
595
- }
596
- }
597
- }
598
-
599
- return appendToTrailingAssistant(prev, [segment])
600
- }
601
-
602
341
  /**
603
342
  * Map `ProcessedMessage` (lib's historical-message format) into
604
343
  * `UnifiedChatMessage` (the unified-chat-state contract). Only `user`
@@ -668,6 +407,9 @@ export function historicalToUnified(
668
407
  // Hook
669
408
  // =============================================================================
670
409
 
410
+ /** Store key for the draft ("no dialog selected") state. */
411
+ const DRAFT_DIALOG_KEY = '__draft__'
412
+
671
413
  export function useNatsChatAdapter(
672
414
  config: UseNatsChatAdapterConfig,
673
415
  options: UseNatsChatAdapterOptions = {},
@@ -723,56 +465,109 @@ export function useNatsChatAdapter(
723
465
  const currentDialogIdRef = useRef<string | null>(dialogId)
724
466
  currentDialogIdRef.current = dialogId
725
467
 
726
- // ─── Message thread + streaming phase ─────────────────────────────────────
727
-
728
- const [messages, setMessages] = useState<UnifiedChatMessage[]>([])
729
- const [streamingPhase, setStreamingPhase] = useState<StreamingPhase>('idle')
730
- // Live mirror for click handlers that must read the CURRENT phase without
731
- // re-creating on every phase change (handleApprove's scoped revert).
732
- const streamingPhaseRef = useRef(streamingPhase)
733
- streamingPhaseRef.current = streamingPhase
734
- // Gate: suppress onAgentBusy while the initial catchup replays historical
735
- // chunks. A dead tail (approval approved / tool started, then Stop or a
736
- // crash — no continuation ever persisted) replays its APPROVAL_RESULT /
737
- // EXECUTING_TOOL chunks on every dialog (re)open, and the releasing
738
- // MESSAGE_END never replays — locking the composer forever. Live chunks
739
- // after catchup lock normally; a reopened mid-execution dialog re-locks on
740
- // the next live chunk instead.
741
- // A COUNTER, not a boolean: the initial-catchup window and a reconnect
742
- // back-fill window can overlap (reconnect during the initial fetch), and
743
- // with a boolean whichever finished FIRST dropped the other's suppression
744
- // mid-replay. Each window increments on entry / decrements in its finally.
745
- const suppressAgentBusyRef = useRef(0)
746
-
747
- // True when the trailing assistant loaded from history is an INCOMPLETE
748
- // turn (mid-stream / mid-approval tail). The catchup replay re-streams that
749
- // turn from its MESSAGE_START, and the replayed stream must ADOPT (replace)
750
- // the partial history bubble. Any other MESSAGE_START over a non-empty
751
- // trailing assistant is a NEW turn (observer / second device / post-approval
752
- // continuation) and must open a fresh bubble instead of overwriting the
753
- // completed one. Consumed (reset) by the first MESSAGE_START.
754
- const adoptTrailingAssistantRef = useRef(false)
468
+ // ─── Approval handlers ────────────────────────────────────────────────────
469
+ // Defined before the reducer so the reducer's create-options can wire the
470
+ // approval-card buttons. Optimistically flip status before the network
471
+ // round-trip so the card reflects the user's choice immediately.
755
472
 
756
- // Set after the first successful NATS connect. Later 'connected' events are
757
- // RECONNECTS: plain NATS replays nothing, so the adapter must back-fill the
758
- // disconnect gap via `resetAndCatchUp` or those chunks are lost forever.
759
- const hasConnectedOnceRef = useRef(false)
473
+ const handleApproveRef = useRef<(requestId: string) => Promise<void>>(async () => {})
474
+ const handleRejectRef = useRef<(requestId: string, reason?: string) => Promise<void>>(
475
+ async () => {},
476
+ )
760
477
 
761
- // Exact-identity dedup for participant chunks (user/direct/system): the
762
- // JetStream streamSeq of every rendered participant row. Cleared per
763
- // dialog. See the dedup-layers note above `hasRecentMessage`.
764
- const seenParticipantSeqsRef = useRef<Set<number>>(new Set())
765
- // Texts `sendMessage` rendered optimistically and whose MESSAGE_REQUEST
766
- // echo hasn't come back yet — the echo consumes exactly ONE entry, so a
767
- // genuinely repeated send ("yes", "yes") still renders twice.
768
- const pendingEchoTextsRef = useRef<string[]>([])
769
-
770
- // Approval status map. Used both to dedupe pending segments at render
771
- // time and to feed `processHistoricalMessagesWithErrors` so previously
772
- // resolved approvals don't re-render as actionable on dialog switch.
773
- const [approvalStatuses, setApprovalStatuses] = useState<
774
- Record<string, ChatApprovalStatus>
775
- >({})
478
+ // Reducer-card adapters. The card contract is `(requestId?) => void |
479
+ // Promise<void>` — single optional arg; narrow at the boundary.
480
+ const accumApprove = useCallback((requestId?: string): void | Promise<void> => {
481
+ if (!requestId) return
482
+ return handleApproveRef.current(requestId)
483
+ }, [])
484
+ const accumReject = useCallback((requestId?: string): void | Promise<void> => {
485
+ if (!requestId) return
486
+ return handleRejectRef.current(requestId)
487
+ }, [])
488
+
489
+ // ─── THE reducer (master stream reader) ───────────────────────────────────
490
+ // One `ChatDialogStore` per adapter instance; one reducer per dialog.
491
+ // Approval statuses are request-id-keyed and GLOBAL across dialogs (a
492
+ // resolved approval must not resurrect as actionable after a dialog
493
+ // switch), so the adapter accumulates them into a ref that seeds every
494
+ // newly-created per-dialog reducer.
495
+
496
+ const storeRef = useRef(createChatDialogStore())
497
+ const globalApprovalStatusesRef = useRef<Record<string, ChatApprovalStatus>>({})
498
+ const dialogKey = dialogId ?? DRAFT_DIALOG_KEY
499
+
500
+ const { state, applyEvent, mutate } = useChatStreamReducer({
501
+ store: storeRef.current,
502
+ dialogId: dialogKey,
503
+ createReducerOptions: () => ({
504
+ transport: 'nats',
505
+ batchApprovalsEnabled,
506
+ ...(displayApprovalTypes ? { displayApprovalTypes } : {}),
507
+ approvalStatuses: globalApprovalStatusesRef.current,
508
+ callbacks: { onApprove: accumApprove, onReject: accumReject },
509
+ }),
510
+ })
511
+
512
+ // Accumulate resolved statuses globally (render-time merge is cheap and
513
+ // keeps the ref current for the next dialog's reducer seed).
514
+ globalApprovalStatusesRef.current = {
515
+ ...globalApprovalStatusesRef.current,
516
+ ...state.approvalStatuses,
517
+ }
518
+
519
+ // Live handleApprove/handleReject bodies (need `mutate` + state access).
520
+ handleApproveRef.current = async (requestId: string) => {
521
+ if (!approveRequestCallback) return
522
+ // Approval hands the turn back to the agent — lock the composer now
523
+ // rather than waiting for the APPROVAL_RESULT/EXECUTING_TOOL chunks.
524
+ // Remember whether THIS click took the lock: if the phase was already
525
+ // busy (another approval's command executing), a failure of this
526
+ // request must not release a lock it doesn't own.
527
+ const store = storeRef.current
528
+ const key = dialogKey
529
+ const tookLock = store.mutate(key, DEFAULT_DIALOG_SIDE, (r) => {
530
+ const took = r.state.streamingPhase === 'idle'
531
+ r.setApprovalStatus(requestId, 'approved')
532
+ if (took) r.setPhase('thinking')
533
+ return took
534
+ })
535
+ try {
536
+ await approveRequestCallback(requestId)
537
+ } catch (err) {
538
+ // Revert the optimistic flip on failure so the user can retry.
539
+ store.mutate(key, DEFAULT_DIALOG_SIDE, (r) => {
540
+ r.setApprovalStatus(requestId, null)
541
+ if (tookLock && r.state.streamingPhase === 'thinking') r.setPhase('idle')
542
+ })
543
+ console.error('[useNatsChatAdapter] approveRequest failed:', err)
544
+ }
545
+ }
546
+ handleRejectRef.current = async (requestId: string, reason?: string) => {
547
+ if (!rejectRequestCallback) return
548
+ // Deliberately NO phase lock here (asymmetric with approve): rejection
549
+ // keeps the composer free so the user can type a correction right away —
550
+ // the reducer's `approved`-only agent-busy gate is the same asymmetry.
551
+ const store = storeRef.current
552
+ const key = dialogKey
553
+ store.mutate(key, DEFAULT_DIALOG_SIDE, (r) => r.setApprovalStatus(requestId, 'rejected'))
554
+ try {
555
+ await rejectRequestCallback(requestId, reason)
556
+ } catch (err) {
557
+ store.mutate(key, DEFAULT_DIALOG_SIDE, (r) => r.setApprovalStatus(requestId, null))
558
+ console.error('[useNatsChatAdapter] rejectRequest failed:', err)
559
+ }
560
+ }
561
+
562
+ // Decode + apply — the ONLY chunk entry point (catchup routes the live
563
+ // tail through here too, so buffering/dedupe stay consistent).
564
+ const processChunk = useCallback(
565
+ (chunk: unknown) => {
566
+ const event = decodeNatsChunk(chunk)
567
+ if (event) applyEvent(event)
568
+ },
569
+ [applyEvent],
570
+ )
776
571
 
777
572
  // ─── Dialog list state (managed-dialog mode only) ─────────────────────────
778
573
 
@@ -787,383 +582,15 @@ export function useNatsChatAdapter(
787
582
  const [messagesNextCursor, setMessagesNextCursor] = useState<string | null>(null)
788
583
  const [isMessagesLoading, setIsMessagesLoading] = useState<boolean>(false)
789
584
 
790
- // ─── Token usage (Mingo per-dialog cumulative) ────────────────────────────
791
-
792
- const [dialogTokenUsage, setDialogTokenUsage] = useState<DialogTokenUsage | null>(
793
- null,
794
- )
795
-
796
- // ─── Live model metadata (from streaming `metadata` frames) ───────────────
797
- // Refines the composer's model badge per-turn. Falls back to the config
798
- // baseline (`modelProvider`/`modelLabel`) until the first frame lands.
799
- const [liveModel, setLiveModel] = useState<{
800
- provider: string | null
801
- modelLabel: string | null
802
- contextWindowMaxTokens: number | null
803
- } | null>(null)
804
-
805
585
  // ─── Connection state ─────────────────────────────────────────────────────
806
586
 
807
587
  const [connectionState, setConnectionState] =
808
588
  useState<ChatConnectionState>('connecting')
809
589
 
810
- // ─── Approval handlers ────────────────────────────────────────────────────
811
- // Optimistically flip status before the network round-trip so the
812
- // accumulator's render reflects the user's choice immediately.
813
-
814
- const handleApprove = useCallback(
815
- async (requestId: string) => {
816
- if (!approveRequestCallback) return
817
- setApprovalStatuses((prev) => ({ ...prev, [requestId]: 'approved' }))
818
- // Approval hands the turn back to the agent — lock the composer now
819
- // rather than waiting for the APPROVAL_RESULT/EXECUTING_TOOL chunks.
820
- // Remember whether THIS click took the lock: if the phase was already
821
- // busy (another approval's command executing), a failure of this
822
- // request must not release a lock it doesn't own.
823
- const tookLock = streamingPhaseRef.current === 'idle'
824
- setStreamingPhase((p) => (p === 'idle' ? 'thinking' : p))
825
- try {
826
- await approveRequestCallback(requestId)
827
- } catch (err) {
828
- // Revert the optimistic flip on failure so the user can retry.
829
- setApprovalStatuses((prev) => {
830
- const next = { ...prev }
831
- delete next[requestId]
832
- return next
833
- })
834
- if (tookLock) {
835
- setStreamingPhase((p) => (p === 'thinking' ? 'idle' : p))
836
- }
837
- console.error('[useNatsChatAdapter] approveRequest failed:', err)
838
- }
839
- },
840
- [approveRequestCallback],
841
- )
842
-
843
- const handleReject = useCallback(
844
- async (requestId: string, reason?: string) => {
845
- if (!rejectRequestCallback) return
846
- // Deliberately NO phase lock here (asymmetric with handleApprove):
847
- // rejection keeps the composer free so the user can type a correction
848
- // right away — see the matching `approved`-only onAgentBusy guard in
849
- // use-realtime-chunk-processor's approval_result case. If the agent
850
- // does stream an acknowledgment, MESSAGE_START locks the composer then.
851
- setApprovalStatuses((prev) => ({ ...prev, [requestId]: 'rejected' }))
852
- try {
853
- await rejectRequestCallback(requestId, reason)
854
- } catch (err) {
855
- setApprovalStatuses((prev) => {
856
- const next = { ...prev }
857
- delete next[requestId]
858
- return next
859
- })
860
- console.error('[useNatsChatAdapter] rejectRequest failed:', err)
861
- }
862
- },
863
- [rejectRequestCallback],
864
- )
865
-
866
- // Stable refs so the accumulator's callbacks don't churn on re-render.
867
- const handleApproveRef = useRef(handleApprove)
868
- handleApproveRef.current = handleApprove
869
- const handleRejectRef = useRef(handleReject)
870
- handleRejectRef.current = handleReject
871
-
872
- // Accumulator-compatible adapters. The lib's accumulator contract is
873
- // `(requestId?: string) => void | Promise<void>` — single optional arg,
874
- // no rejection reason. Our public API surface widens that to require a
875
- // string + accept a reason, so we narrow here at the boundary. Reason
876
- // is unavailable from button-click callers (the accumulator doesn't
877
- // pass it) so we only forward the requestId; consumers that need
878
- // structured reject reasons can call `rejectRequest` directly.
879
- const accumApprove = useCallback((requestId?: string): void | Promise<void> => {
880
- if (!requestId) return
881
- return handleApproveRef.current(requestId)
882
- }, [])
883
- const accumReject = useCallback((requestId?: string): void | Promise<void> => {
884
- if (!requestId) return
885
- return handleRejectRef.current(requestId)
886
- }, [])
887
-
888
- // Stable callback ref so `useRealtimeChunkProcessor`'s options object
889
- // doesn't churn every render and tear down the accumulator state.
890
- const callbacksRef: MutableRefObject<{
891
- onSegmentsUpdate: (segments: MessageSegment[], meta?: SegmentsUpdateMetadata) => void
892
- onStreamStart: () => void
893
- onStreamEnd: () => void
894
- onAgentBusy: () => void
895
- onError: () => void
896
- onTokenUsage: (data: DialogTokenUsage) => void
897
- onMetadata: (meta: {
898
- modelDisplayName?: string
899
- modelName: string
900
- providerName: string
901
- contextWindow: number
902
- }) => void
903
- onToolExecuted: (segment: ToolExecutionSegment) => void
904
- onApprovalResolved: (
905
- requestId: string,
906
- status: ChatApprovalStatus,
907
- approvalType: string,
908
- resolvedByName?: string | null,
909
- ) => void
910
- onUserMessage: (
911
- text: string,
912
- meta?: { ownerType?: string; displayName?: string; userId?: string; streamSeq?: number; contextItems?: Array<{ type: string; id: string }> },
913
- ) => void
914
- onDirectMessage: (
915
- text: string,
916
- meta?: { ownerType?: string; displayName?: string; userId?: string; streamSeq?: number },
917
- ) => void
918
- onSystemMessage: (text: string, meta?: { streamSeq?: number }) => void
919
- }> = useRef({
920
- onSegmentsUpdate: (segments: MessageSegment[], meta?: SegmentsUpdateMetadata) => {
921
- // Standalone compaction updates carry the accumulator's cumulative
922
- // array — apply only the compaction segment (upsert) or interleaved
923
- // continuation text would duplicate.
924
- if (meta?.append && meta.isCompacting) {
925
- setMessages((prev) => upsertTrailingCompaction(prev, segments))
926
- return
927
- }
928
- // Post-MESSAGE_END continuation fragments append into the existing
929
- // bubble; replacing (the pre-fix behaviour, which dropped `meta`)
930
- // wiped the completed reply and left only the newest fragment.
931
- if (meta?.append) {
932
- setMessages((prev) => appendToTrailingAssistant(prev, segments))
933
- return
934
- }
935
- setMessages((prev) => updateTrailingAssistant(prev, segments))
936
- },
937
- onStreamStart: () => {
938
- setStreamingPhase('streaming')
939
- // A new stream must never overwrite a COMPLETED trailing assistant
940
- // bubble (observer tab / second device / post-approval continuation
941
- // turn). Open a fresh bubble unless the trailing assistant is empty
942
- // (our own optimistic placeholder) or is the incomplete history tail
943
- // the catchup replay is legitimately re-streaming (adopt-once flag).
944
- const adoptTail = adoptTrailingAssistantRef.current
945
- adoptTrailingAssistantRef.current = false
946
- setMessages((prev) => {
947
- const last = prev[prev.length - 1]
948
- if (!last || last.role !== 'assistant' || adoptTail) return prev
949
- const hasContent = (last.segments?.length ?? 0) > 0 || last.content !== ''
950
- if (!hasContent) return prev
951
- return [
952
- ...prev,
953
- { id: nextId('assistant'), role: 'assistant', content: '', segments: [] },
954
- ]
955
- })
956
- },
957
- onStreamEnd: () => setStreamingPhase('idle'),
958
- // Agent is executing (approved) commands outside an open stream — keep
959
- // the composer locked exactly like the in-stream phases. An open stream
960
- // keeps ownership: only 'idle' upgrades to 'thinking'. Suppressed during
961
- // initial catchup so a replayed dead tail can't lock a finished dialog.
962
- onAgentBusy: () => {
963
- if (suppressAgentBusyRef.current > 0) return
964
- setStreamingPhase((p) => (p === 'idle' ? 'thinking' : p))
965
- },
966
- // Terminal turn failures can arrive without a MESSAGE_END; unlock the
967
- // composer unless an open stream still owns the phase (in-stream errors
968
- // are followed by the stream's own MESSAGE_END).
969
- onError: () => setStreamingPhase((p) => (p === 'streaming' ? p : 'idle')),
970
- // Live cumulative token counter for the active dialog — drives the
971
- // composer's "X / Y tokens used" tail as the assistant streams.
972
- onTokenUsage: (data: DialogTokenUsage) => setDialogTokenUsage(data),
973
- // Per-turn model badge (provider/label/context window).
974
- onMetadata: (meta) =>
975
- setLiveModel({
976
- provider: meta.providerName || null,
977
- modelLabel: meta.modelDisplayName || meta.modelName || null,
978
- contextWindowMaxTokens: meta.contextWindow || null,
979
- }),
980
- // Post-MESSAGE_END tool chunks (approved commands executing after the
981
- // approval bubble, async batch results). Routed through the cross-message
982
- // updater — the accumulator was reset at MESSAGE_END, so the old
983
- // fallthrough replaced the whole trailing bubble with one tool segment.
984
- onToolExecuted: (segment: ToolExecutionSegment) => {
985
- setMessages((prev) => applyToolExecutionToMessages(prev, segment))
986
- },
987
- // Cross-message approval status flip. Wiring this also makes the
988
- // processor skip its cumulative re-emit for resolved approvals — which,
989
- // post-MESSAGE_END, was an empty array that blanked the trailing bubble.
990
- onApprovalResolved: (requestId, status, _approvalType, resolvedByName) => {
991
- setMessages((prev) => {
992
- let changed = false
993
- const next = prev.map((m) => {
994
- if (m.role !== 'assistant' || !m.segments) return m
995
- let msgChanged = false
996
- const segs = m.segments.map((s) => {
997
- if (s.type === 'approval_request' && s.data.requestId === requestId && s.status !== status) {
998
- msgChanged = true
999
- return { ...s, status }
1000
- }
1001
- if (s.type === 'approval_batch' && s.data.approvalRequestId === requestId) {
1002
- const nextResolvedBy = resolvedByName ?? s.resolvedByName
1003
- if (s.status === status && nextResolvedBy === s.resolvedByName) return s
1004
- msgChanged = true
1005
- return { ...s, status, resolvedByName: nextResolvedBy }
1006
- }
1007
- return s
1008
- })
1009
- if (!msgChanged) return m
1010
- changed = true
1011
- return { ...m, segments: segs }
1012
- })
1013
- return changed ? next : prev
1014
- })
1015
- // Mirror into the status map so history re-processing (dialog reopen,
1016
- // pagination) renders the card resolved instead of actionable.
1017
- setApprovalStatuses((prev) =>
1018
- prev[requestId] === status ? prev : { ...prev, [requestId]: status },
1019
- )
1020
- },
1021
- // MESSAGE_REQUEST echo — a user message from THIS or another session.
1022
- onUserMessage: (text, meta) => {
1023
- if (!text) return
1024
- // Layer 1 FIRST: exact event identity. A seq we've handled is a
1025
- // replay; a fresh seq is appended with NO content matching, so
1026
- // genuinely repeated texts from other participants always render.
1027
- // Must run (and RECORD) before the echo consume below — the echo
1028
- // branch early-returns, and skipping the record there let an
1029
- // at-least-once redelivery of the same event pass as fresh (and eat
1030
- // a second pending echo entry).
1031
- const seq = meta?.streamSeq
1032
- if (typeof seq === 'number') {
1033
- if (seenParticipantSeqsRef.current.has(seq)) return
1034
- seenParticipantSeqsRef.current.add(seq)
1035
- }
1036
- // Layer 2: our own optimistic echo — consume exactly one recorded send.
1037
- if (meta?.ownerType !== 'ADMIN') {
1038
- const echoIdx = pendingEchoTextsRef.current.indexOf(text)
1039
- if (echoIdx !== -1) {
1040
- pendingEchoTextsRef.current.splice(echoIdx, 1)
1041
- return
1042
- }
1043
- }
1044
- const authorType = meta?.ownerType === 'ADMIN' ? 'admin' : 'user'
1045
- setMessages((prev) => {
1046
- // Layer 3: seq-less transports only — same-author content twin in the
1047
- // immediate tail (replay over just-loaded history).
1048
- if (
1049
- typeof seq !== 'number' &&
1050
- hasRecentMessage(
1051
- prev,
1052
- (m) => m.role === 'user' && (m.authorType ?? 'user') === authorType && m.content === text,
1053
- CONTENT_DEDUP_WINDOW,
1054
- )
1055
- ) {
1056
- return prev
1057
- }
1058
- return [
1059
- ...prev,
1060
- {
1061
- id: nextId('user'),
1062
- role: 'user',
1063
- content: text,
1064
- ...(meta?.displayName ? { name: meta.displayName } : {}),
1065
- authorType,
1066
- ...(meta?.contextItems && meta.contextItems.length > 0
1067
- ? {
1068
- contextItems: meta.contextItems.map((ci) => ({
1069
- type: ci.type,
1070
- id: ci.id,
1071
- label: (ci as { label?: string }).label ?? ci.id,
1072
- })),
1073
- }
1074
- : {}),
1075
- },
1076
- ]
1077
- })
1078
- },
1079
- // Technician / admin direct message into the dialog.
1080
- onDirectMessage: (text, meta) => {
1081
- if (!text) return
1082
- const seq = meta?.streamSeq
1083
- if (typeof seq === 'number') {
1084
- if (seenParticipantSeqsRef.current.has(seq)) return
1085
- seenParticipantSeqsRef.current.add(seq)
1086
- }
1087
- setMessages((prev) => {
1088
- // Seq-less fallback matches only prior ADMIN-authored twins — a
1089
- // client's identical text must never suppress the technician's.
1090
- if (
1091
- typeof seq !== 'number' &&
1092
- hasRecentMessage(
1093
- prev,
1094
- (m) => m.role === 'user' && m.authorType === 'admin' && m.content === text,
1095
- CONTENT_DEDUP_WINDOW,
1096
- )
1097
- ) {
1098
- return prev
1099
- }
1100
- return [
1101
- ...prev,
1102
- {
1103
- id: `direct-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
1104
- role: 'user',
1105
- content: text,
1106
- name: meta?.displayName ?? 'Admin',
1107
- authorType: 'admin',
1108
- },
1109
- ]
1110
- })
1111
- },
1112
- // System notice — rendered as a name-only row (same shape the history
1113
- // processor produces via `pushStandaloneMessages`).
1114
- onSystemMessage: (text, meta) => {
1115
- if (!text) return
1116
- const seq = meta?.streamSeq
1117
- if (typeof seq === 'number') {
1118
- if (seenParticipantSeqsRef.current.has(seq)) return
1119
- seenParticipantSeqsRef.current.add(seq)
1120
- }
1121
- setMessages((prev) => {
1122
- if (
1123
- typeof seq !== 'number' &&
1124
- hasRecentMessage(prev, (m) => m.authorType === 'system' && m.name === text, SYSTEM_DEDUP_WINDOW)
1125
- ) {
1126
- return prev
1127
- }
1128
- return [
1129
- ...prev,
1130
- {
1131
- id: `system-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
1132
- role: 'user',
1133
- content: '',
1134
- name: text,
1135
- authorType: 'system',
1136
- },
1137
- ]
1138
- })
1139
- },
1140
- })
1141
-
1142
- // Real-time chunk → segment processor. Approval handlers route through
1143
- // the refs so a config change (e.g. callback identity churn from the
1144
- // host) doesn't tear down the accumulator.
1145
- const { processChunk, reset: resetAccumulator } = useRealtimeChunkProcessor({
1146
- callbacks: {
1147
- onSegmentsUpdate: (segments, meta) => callbacksRef.current.onSegmentsUpdate(segments, meta),
1148
- onStreamStart: () => callbacksRef.current.onStreamStart(),
1149
- onStreamEnd: () => callbacksRef.current.onStreamEnd(),
1150
- onAgentBusy: () => callbacksRef.current.onAgentBusy(),
1151
- onError: () => callbacksRef.current.onError(),
1152
- onTokenUsage: (data) => callbacksRef.current.onTokenUsage(data),
1153
- onMetadata: (meta) => callbacksRef.current.onMetadata(meta),
1154
- onToolExecuted: (segment) => callbacksRef.current.onToolExecuted(segment),
1155
- onApprovalResolved: (requestId, status, approvalType, resolvedByName) =>
1156
- callbacksRef.current.onApprovalResolved(requestId, status, approvalType, resolvedByName),
1157
- onUserMessage: (text, meta) => callbacksRef.current.onUserMessage(text, meta),
1158
- onDirectMessage: (text, meta) => callbacksRef.current.onDirectMessage(text, meta),
1159
- onSystemMessage: (text, meta) => callbacksRef.current.onSystemMessage(text, meta),
1160
- onApprove: accumApprove,
1161
- onReject: accumReject,
1162
- },
1163
- batchApprovalsEnabled,
1164
- approvalStatuses,
1165
- ...(displayApprovalTypes ? { displayApprovalTypes } : {}),
1166
- })
590
+ // Set after the first successful NATS connect. Later 'connected' events are
591
+ // RECONNECTS: plain NATS replays nothing, so the adapter must back-fill the
592
+ // disconnect gap via `resetAndCatchUp` or those chunks are lost forever.
593
+ const hasConnectedOnceRef = useRef(false)
1167
594
 
1168
595
  // History catchup — back-fills chunks emitted while the adapter was
1169
596
  // inactive or before the WS came online.
@@ -1183,8 +610,8 @@ export function useNatsChatAdapter(
1183
610
  // ─── Historical message hydration ─────────────────────────────────────────
1184
611
  // When the active dialog changes AND a `fetchDialogMessages` callback
1185
612
  // is wired, load the first page of history, process it through the
1186
- // accumulator, and seed `messages`. Streaming chunks for the same
1187
- // dialog then append on top.
613
+ // history decoder + envelope, and seed the reducer. Streaming chunks for
614
+ // the same dialog then append on top.
1188
615
 
1189
616
  // Monotonic guard: each history load captures a sequence number; when a
1190
617
  // response resolves, it only applies if it's still the latest request. This
@@ -1197,6 +624,7 @@ export function useNatsChatAdapter(
1197
624
  if (!fetchDialogMessages) return
1198
625
  historyLoadSeqRef.current += 1
1199
626
  const seq = historyLoadSeqRef.current
627
+ const store = storeRef.current
1200
628
  setIsMessagesLoading(true)
1201
629
  try {
1202
630
  const result = await fetchDialogMessages({
@@ -1214,34 +642,39 @@ export function useNatsChatAdapter(
1214
642
  chatTypeFilter,
1215
643
  onApprove: accumApprove,
1216
644
  onReject: accumReject,
1217
- approvalStatuses,
645
+ approvalStatuses: store.getSnapshot(id).approvalStatuses,
1218
646
  batchApprovalsEnabled,
1219
647
  ...(displayApprovalTypes ? { displayApprovalTypes } : {}),
1220
648
  },
1221
649
  )
1222
650
  const unified = mapProcessedToUnified(rawProcessed)
1223
- if (cursor === undefined) {
1224
- // First page — replace. When the trailing assistant is an
1225
- // INCOMPLETE turn, the catchup replay will re-stream it from its
1226
- // MESSAGE_START — let that stream adopt (replace) the partial
1227
- // bubble instead of opening a duplicate one.
1228
- // Gated on an ACTIVE catchup buffer: when the catchup already
1229
- // finalized before this history page resolved, no replay is coming
1230
- // to consume the flag — arming it anyway would hand the adoption
1231
- // to the NEXT genuine turn, which would overwrite the partial
1232
- // bubble instead of opening a fresh one.
1233
- adoptTrailingAssistantRef.current =
1234
- isBufferingActive() &&
1235
- extractIncompleteMessageState(rawProcessed[rawProcessed.length - 1]) !== undefined
1236
- setMessages(unified)
1237
- } else {
1238
- // Older page — prepend.
1239
- setMessages((prev) => [...unified, ...prev])
1240
- }
651
+ store.mutate(id, DEFAULT_DIALOG_SIDE, (r) => {
652
+ if (cursor === undefined) {
653
+ // First page — replace. When the trailing assistant is an
654
+ // INCOMPLETE turn, the catchup replay will re-stream it from its
655
+ // MESSAGE_START — let that stream adopt (replace) the partial
656
+ // bubble instead of opening a duplicate one.
657
+ // Gated on an ACTIVE catchup buffer: when the catchup already
658
+ // finalized before this history page resolved, no replay is
659
+ // coming to consume the flag — arming it anyway would hand the
660
+ // adoption to the NEXT genuine turn, which would overwrite the
661
+ // partial bubble instead of opening a fresh one.
662
+ // `extractIncompleteTailState` (not the single-row extractor):
663
+ // one logical turn can span several trailing assistant bubbles,
664
+ // so the unfinished artifact may sit above the last row.
665
+ r.armAdoptTrailingAssistant(
666
+ isBufferingActive() && extractIncompleteTailState(rawProcessed) !== undefined,
667
+ )
668
+ r.setMessages(unified)
669
+ } else {
670
+ // Older page — prepend.
671
+ r.prependMessages(unified)
672
+ }
673
+ if (result.tokenUsage !== undefined) {
674
+ r.setDialogTokenUsage(result.tokenUsage ?? null)
675
+ }
676
+ })
1241
677
  setMessagesNextCursor(result.nextCursor)
1242
- if (result.tokenUsage !== undefined) {
1243
- setDialogTokenUsage(result.tokenUsage)
1244
- }
1245
678
  } catch (err) {
1246
679
  console.error('[useNatsChatAdapter] fetchDialogMessages failed:', err)
1247
680
  } finally {
@@ -1257,7 +690,6 @@ export function useNatsChatAdapter(
1257
690
  messagesPageSize,
1258
691
  assistantName,
1259
692
  chatTypeFilter,
1260
- approvalStatuses,
1261
693
  batchApprovalsEnabled,
1262
694
  displayApprovalTypes,
1263
695
  accumApprove,
@@ -1278,20 +710,19 @@ export function useNatsChatAdapter(
1278
710
  // this an in-flight response could repopulate the just-cleared state.
1279
711
  historyLoadSeqRef.current += 1
1280
712
 
1281
- // Drop accumulator + message state for the previous dialog.
1282
- resetAccumulator()
1283
- adoptTrailingAssistantRef.current = false
1284
- seenParticipantSeqsRef.current.clear()
1285
- pendingEchoTextsRef.current = []
1286
- setMessages([])
1287
- setMessagesNextCursor(null)
1288
- setDialogTokenUsage(null)
1289
- // Clear per-dialog live model metadata too — otherwise the composer briefly
1290
- // shows the previous dialog's provider/model until the next chunk streams.
1291
- setLiveModel(null)
1292
- setStreamingPhase('idle')
713
+ // Clean slate for the (re)entered dialog: thread, per-turn kernel,
714
+ // participant dedup sets, seq gate, phase. Approval statuses survive
715
+ // per-reducer AND get topped up with the adapter's global map (request
716
+ // ids are dialog-independent).
717
+ storeRef.current.mutate(dialogKey, DEFAULT_DIALOG_SIDE, (r) => {
718
+ r.resetForDialogSwitch()
719
+ // Canonical precedence lives in the reducer: persisted (the adapter's
720
+ // global map) fills gaps, stream-learned statuses always win.
721
+ r.mergeApprovalStatuses(globalApprovalStatusesRef.current)
722
+ })
1293
723
  // No load runs when there's no active dialog, so clear the flag here;
1294
724
  // otherwise the superseded load's guarded `finally` leaves it stuck on.
725
+ setMessagesNextCursor(null)
1295
726
  setIsMessagesLoading(false)
1296
727
 
1297
728
  if (!active || !dialogId) return
@@ -1299,7 +730,7 @@ export function useNatsChatAdapter(
1299
730
  // Hydrate history first; then catchup will fold in any chunks that
1300
731
  // landed between the history snapshot and the live tail.
1301
732
  void loadDialogHistory(dialogId)
1302
- }, [active, dialogId, loadDialogHistory, resetAccumulator])
733
+ }, [active, dialogId, dialogKey, loadDialogHistory])
1303
734
 
1304
735
  // Trigger initial chunk backfill whenever a fresh dialog activates.
1305
736
  // Runs alongside history hydration — history seeds processed messages,
@@ -1307,8 +738,14 @@ export function useNatsChatAdapter(
1307
738
  // was already snapshotted.
1308
739
  useEffect(() => {
1309
740
  if (!active || !dialogId) return
1310
- // Gate onAgentBusy for the replay window (see suppressAgentBusyRef).
1311
- suppressAgentBusyRef.current += 1
741
+ const store = storeRef.current
742
+ // Gate agent-busy locks for the replay window: a dead tail (approval
743
+ // approved / tool started, then Stop or a crash) replays its
744
+ // APPROVAL_RESULT / EXECUTING_TOOL chunks on every dialog (re)open, and
745
+ // the releasing MESSAGE_END never replays — locking the composer
746
+ // forever. The suppression is a COUNTER inside the reducer: the
747
+ // initial-catchup window and a reconnect back-fill window can overlap.
748
+ store.mutate(dialogId, DEFAULT_DIALOG_SIDE, (r) => r.adjustAgentBusySuppression(1))
1312
749
  resetChunkTracking()
1313
750
  startInitialBuffering()
1314
751
  catchUpChunks()
@@ -1316,16 +753,15 @@ export function useNatsChatAdapter(
1316
753
  console.error('[useNatsChatAdapter] initial catchup failed:', err)
1317
754
  })
1318
755
  .finally(() => {
1319
- suppressAgentBusyRef.current = Math.max(0, suppressAgentBusyRef.current - 1)
1320
- // The adopt-once flag targets the replayed MESSAGE_START of the
1321
- // incomplete history tail. When the replay produced none (chunk
1322
- // store expired past its ~10-min retention / empty), the armed flag
1323
- // would survive and make the NEXT genuine turn (post-approval
1324
- // continuation, second device) adopt-and-overwrite the partial
1325
- // bubble. Scoped: only the still-active dialog clears its own flag.
1326
- if (dialogId === currentDialogIdRef.current) {
1327
- adoptTrailingAssistantRef.current = false
1328
- }
756
+ store.mutate(dialogId, DEFAULT_DIALOG_SIDE, (r) => {
757
+ r.adjustAgentBusySuppression(-1)
758
+ // The adopt-once flag targets the replayed MESSAGE_START of the
759
+ // incomplete history tail. When the replay produced none (chunk
760
+ // store expired past its ~10-min retention / empty), the armed
761
+ // flag would survive and make the NEXT genuine turn adopt-and-
762
+ // overwrite the partial bubble.
763
+ r.armAdoptTrailingAssistant(false)
764
+ })
1329
765
  })
1330
766
  }, [active, dialogId, resetChunkTracking, startInitialBuffering, catchUpChunks])
1331
767
 
@@ -1358,7 +794,13 @@ export function useNatsChatAdapter(
1358
794
  hasConnectedOnceRef.current = true
1359
795
  return
1360
796
  }
1361
- suppressAgentBusyRef.current += 1
797
+ const store = storeRef.current
798
+ const reconnectDialogId = dialogId
799
+ if (reconnectDialogId) {
800
+ store.mutate(reconnectDialogId, DEFAULT_DIALOG_SIDE, (r) =>
801
+ r.adjustAgentBusySuppression(1),
802
+ )
803
+ }
1362
804
  // Buffer live deliveries for the WHOLE back-fill, including the history
1363
805
  // await — otherwise chunks landing mid-fetch are processed unbuffered
1364
806
  // (advancing lastSequenceId + dedup keys) and the history replace then
@@ -1372,28 +814,27 @@ export function useNatsChatAdapter(
1372
814
  // so the chunk back-fill can't recover them — the persisted history
1373
815
  // page is the only source. Then replay the unsaved chunk tail on
1374
816
  // top of the fresh snapshot.
1375
- if (dialogId && fetchDialogMessages) {
1376
- await loadDialogHistory(dialogId)
817
+ if (reconnectDialogId && fetchDialogMessages) {
818
+ await loadDialogHistory(reconnectDialogId)
1377
819
  }
1378
820
  // The user may have switched dialogs during the await — the new
1379
821
  // dialog's own effects run their catchup cycle; re-running it here
1380
- // (via refs it would target the NEW dialog) would reset that cycle
1381
- // mid-flight.
1382
- if (dialogId !== currentDialogIdRef.current) return
822
+ // would reset that cycle mid-flight.
823
+ if (reconnectDialogId !== currentDialogIdRef.current) return
1383
824
  await resetAndCatchUp()
1384
825
  } catch (err) {
1385
826
  console.error('[useNatsChatAdapter] reconnect catchup failed:', err)
1386
827
  } finally {
1387
- suppressAgentBusyRef.current = Math.max(0, suppressAgentBusyRef.current - 1)
1388
- // The adopt-once flag targets the replayed MESSAGE_START of the
1389
- // incomplete tail — but on reconnect that START was already
1390
- // consumed live and is dedup-skipped by the replay, so it never
1391
- // fires onStreamStart. Clear the flag or the NEXT genuine turn
1392
- // adopts (and overwrites) the completed trailing bubble. Scoped:
1393
- // a stale back-fill must not clear the NEW dialog's freshly armed
1394
- // flag.
1395
- if (dialogId === currentDialogIdRef.current) {
1396
- adoptTrailingAssistantRef.current = false
828
+ if (reconnectDialogId) {
829
+ store.mutate(reconnectDialogId, DEFAULT_DIALOG_SIDE, (r) => {
830
+ r.adjustAgentBusySuppression(-1)
831
+ // The adopt-once flag targets the replayed MESSAGE_START of the
832
+ // incomplete tail — but on reconnect that START was already
833
+ // consumed live and is dedup-skipped by the replay, so it never
834
+ // fires. Clear the flag or the NEXT genuine turn adopts (and
835
+ // overwrites) the completed trailing bubble.
836
+ r.armAdoptTrailingAssistant(false)
837
+ })
1397
838
  }
1398
839
  }
1399
840
  })()
@@ -1473,52 +914,30 @@ export function useNatsChatAdapter(
1473
914
  ): Promise<void> => {
1474
915
  const hidden = sendOptions?.hidden ?? false
1475
916
 
1476
- // Record the text so the backend's MESSAGE_REQUEST echo consumes this
1477
- // send instead of rendering a duplicate row (cap keeps the list from
1478
- // growing if a backend never echoes).
1479
- pendingEchoTextsRef.current.push(text)
1480
- if (pendingEchoTextsRef.current.length > 5) pendingEchoTextsRef.current.shift()
1481
-
1482
917
  // Optimistically append the user bubble + an empty assistant
1483
- // placeholder. The assistant body fills in as NATS chunks land.
1484
- setMessages((prev) => [
1485
- ...prev,
1486
- {
1487
- id: nextId('user'),
1488
- role: 'user',
1489
- content: text,
1490
- ...(hidden ? { hidden: true } : {}),
1491
- },
1492
- {
1493
- id: nextId('assistant'),
1494
- role: 'assistant',
1495
- content: '',
1496
- segments: [],
1497
- },
1498
- ])
1499
- setStreamingPhase('thinking')
918
+ // placeholder, record the echo text, and flip the phase — all inside
919
+ // the reducer. The assistant body fills in as NATS chunks land.
920
+ mutate((r) => r.pushOptimisticSend(text, hidden))
1500
921
 
1501
922
  await publishUserMessage(text, { hidden, dialogId })
1502
923
  },
1503
- [publishUserMessage, dialogId],
924
+ [mutate, publishUserMessage, dialogId],
1504
925
  )
1505
926
 
1506
927
  const stopMessage = useCallback(() => {
1507
928
  // Best-effort UI flip. The actual backend cancellation is gated on
1508
929
  // the host-supplied callback.
1509
- setStreamingPhase('idle')
930
+ mutate((r) => r.setPhase('idle'))
1510
931
  if (stopGenerationCallback && dialogId) {
1511
932
  void stopGenerationCallback(dialogId).catch((err) => {
1512
933
  console.error('[useNatsChatAdapter] stopGeneration failed:', err)
1513
934
  })
1514
935
  }
1515
- }, [stopGenerationCallback, dialogId])
936
+ }, [mutate, stopGenerationCallback, dialogId])
1516
937
 
1517
938
  const clearMessages = useCallback(() => {
1518
- setMessages([])
1519
- resetAccumulator()
1520
- setStreamingPhase('idle')
1521
- }, [resetAccumulator])
939
+ mutate((r) => r.clearThread())
940
+ }, [mutate])
1522
941
 
1523
942
  const selectDialog = useCallback(
1524
943
  (id: string | null) => {
@@ -1569,6 +988,7 @@ export function useNatsChatAdapter(
1569
988
  try {
1570
989
  await deleteDialogCallback(id)
1571
990
  setDialogs((prev) => prev.filter((d) => d.id !== id))
991
+ storeRef.current.remove(id)
1572
992
  if (isManagedMode && internalDialogId === id) {
1573
993
  setInternalDialogId(null)
1574
994
  }
@@ -1655,6 +1075,7 @@ export function useNatsChatAdapter(
1655
1075
 
1656
1076
  // ─── Return shape ─────────────────────────────────────────────────────────
1657
1077
 
1078
+ const { messages, streamingPhase, dialogTokenUsage = null, liveModel = null } = state
1658
1079
  const isLoading = streamingPhase !== 'idle'
1659
1080
  const hasMoreDialogs = dialogsNextCursor != null
1660
1081
  const hasMoreMessages = messagesNextCursor != null