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

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 (281) hide show
  1. package/dist/{chunk-BLZZXZNM.cjs → chunk-5USSSRAL.cjs} +26 -26
  2. package/dist/{chunk-BLZZXZNM.cjs.map → chunk-5USSSRAL.cjs.map} +1 -1
  3. package/dist/{chunk-CGNDAJ7V.js → chunk-6B27O3ZB.js} +4 -4
  4. package/dist/{chunk-P5JQDFRM.cjs → chunk-7IRPMNRL.cjs} +60 -60
  5. package/dist/chunk-7IRPMNRL.cjs.map +1 -0
  6. package/dist/{chunk-4XDWNAZW.cjs → chunk-DQ3EHM6G.cjs} +9 -9
  7. package/dist/{chunk-4XDWNAZW.cjs.map → chunk-DQ3EHM6G.cjs.map} +1 -1
  8. package/dist/{chunk-7KSEINAE.cjs → chunk-FTXDIDNX.cjs} +15 -15
  9. package/dist/{chunk-7KSEINAE.cjs.map → chunk-FTXDIDNX.cjs.map} +1 -1
  10. package/dist/{chunk-4R6H2U77.js → chunk-H7ETLG65.js} +4 -4
  11. package/dist/{chunk-LAOO7XHO.js → chunk-HWTUVLYB.js} +2 -2
  12. package/dist/{chunk-F2NMWV44.js → chunk-IDKDOQZL.js} +2 -2
  13. package/dist/{chunk-BQ7PMWLM.cjs → chunk-KIIOBK7G.cjs} +27 -28
  14. package/dist/chunk-KIIOBK7G.cjs.map +1 -0
  15. package/dist/{chunk-QO2XD3FR.js → chunk-KQGFKG6Y.js} +2 -2
  16. package/dist/{chunk-3N3TMZ62.cjs → chunk-L676XVP4.cjs} +7 -7
  17. package/dist/{chunk-3N3TMZ62.cjs.map → chunk-L676XVP4.cjs.map} +1 -1
  18. package/dist/{chunk-F7F43U7Q.cjs → chunk-LDAOPWXZ.cjs} +11 -11
  19. package/dist/{chunk-F7F43U7Q.cjs.map → chunk-LDAOPWXZ.cjs.map} +1 -1
  20. package/dist/{chunk-ADD3FPDG.cjs → chunk-MKLP2SOZ.cjs} +4886 -7004
  21. package/dist/chunk-MKLP2SOZ.cjs.map +1 -0
  22. package/dist/{chunk-VXJH5TDN.js → chunk-QL7ODLJA.js} +10 -10
  23. package/dist/chunk-QL7ODLJA.js.map +1 -0
  24. package/dist/{chunk-OR5AMXYN.js → chunk-R5QYMUKN.js} +2 -2
  25. package/dist/{chunk-REWRUV3K.js → chunk-TNLFAJPA.js} +9673 -11791
  26. package/dist/chunk-TNLFAJPA.js.map +1 -0
  27. package/dist/{chunk-XF5ROTMQ.js → chunk-U2YDR5DT.js} +2 -2
  28. package/dist/{chunk-PXZ7YQ5V.cjs → chunk-VTQSB6QB.cjs} +5 -5
  29. package/dist/{chunk-PXZ7YQ5V.cjs.map → chunk-VTQSB6QB.cjs.map} +1 -1
  30. package/dist/{chunk-UI7CIUAR.js → chunk-WGJPTFRH.js} +2 -2
  31. package/dist/{chunk-WCE66C2Z.cjs → chunk-XUNJILJT.cjs} +62 -62
  32. package/dist/{chunk-WCE66C2Z.cjs.map → chunk-XUNJILJT.cjs.map} +1 -1
  33. package/dist/{chunk-APF5QBAU.js → chunk-YQBPIUZU.js} +2 -2
  34. package/dist/{chunk-TA7MFVUS.cjs → chunk-YV2YA3QH.cjs} +31 -31
  35. package/dist/{chunk-TA7MFVUS.cjs.map → chunk-YV2YA3QH.cjs.map} +1 -1
  36. package/dist/{chunk-QSGZE6AZ.cjs → chunk-ZDJ4ZUQ4.cjs} +37 -37
  37. package/dist/{chunk-QSGZE6AZ.cjs.map → chunk-ZDJ4ZUQ4.cjs.map} +1 -1
  38. package/dist/{chunk-LJKZIIK4.js → chunk-ZHQQRYMB.js} +5 -6
  39. package/dist/chunk-ZHQQRYMB.js.map +1 -0
  40. package/dist/components/case-studies/index.cjs +8 -8
  41. package/dist/components/case-studies/index.js +2 -2
  42. package/dist/components/chart.d.ts +1 -1
  43. package/dist/components/chat/chat-message-enhanced.d.ts.map +1 -1
  44. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  45. package/dist/components/chat/hooks/index.d.ts +1 -0
  46. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  47. package/dist/components/chat/hooks/use-chat.d.ts.map +1 -1
  48. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +48 -15
  49. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  50. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts +6 -0
  51. package/dist/components/chat/hooks/use-realtime-chunk-processor.d.ts.map +1 -0
  52. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts +47 -3
  53. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  54. package/dist/components/chat/index.cjs +2 -10
  55. package/dist/components/chat/index.cjs.map +1 -1
  56. package/dist/components/chat/index.d.ts +0 -1
  57. package/dist/components/chat/index.d.ts.map +1 -1
  58. package/dist/components/chat/index.js +13 -21
  59. package/dist/components/chat/types/api.types.d.ts +81 -1
  60. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  61. package/dist/components/chat/types/processing.types.d.ts +90 -2
  62. package/dist/components/chat/types/processing.types.d.ts.map +1 -1
  63. package/dist/components/chat/utils/chunk-parser.d.ts +25 -0
  64. package/dist/components/chat/utils/chunk-parser.d.ts.map +1 -0
  65. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts +6 -34
  66. package/dist/components/chat/utils/extract-incomplete-message-state.d.ts.map +1 -1
  67. package/dist/components/chat/utils/index.d.ts +3 -2
  68. package/dist/components/chat/utils/index.d.ts.map +1 -1
  69. package/dist/components/chat/utils/process-historical-messages.d.ts +11 -59
  70. package/dist/components/chat/utils/process-historical-messages.d.ts.map +1 -1
  71. package/dist/components/contact/index.cjs +3 -3
  72. package/dist/components/contact/index.js +2 -2
  73. package/dist/components/docs/index.cjs +5 -5
  74. package/dist/components/docs/index.js +4 -4
  75. package/dist/components/embeds/index.cjs +3 -3
  76. package/dist/components/embeds/index.js +2 -2
  77. package/dist/components/faq/index.cjs +3 -3
  78. package/dist/components/faq/index.js +2 -2
  79. package/dist/components/features/index.cjs +2 -2
  80. package/dist/components/features/index.js +1 -1
  81. package/dist/components/help-center-pages/index.cjs +20 -20
  82. package/dist/components/help-center-pages/index.js +11 -11
  83. package/dist/components/index.cjs +129 -171
  84. package/dist/components/index.cjs.map +1 -1
  85. package/dist/components/index.js +21 -63
  86. package/dist/components/index.js.map +1 -1
  87. package/dist/components/navigation/index.cjs +2 -2
  88. package/dist/components/navigation/index.js +1 -1
  89. package/dist/components/onboarding-guides/index.cjs +5 -5
  90. package/dist/components/onboarding-guides/index.js +4 -4
  91. package/dist/components/onboarding-guides/onboarding-guide-detail-view.d.ts.map +1 -1
  92. package/dist/components/related-content/index.cjs +3 -3
  93. package/dist/components/related-content/index.js +2 -2
  94. package/dist/components/shared/product-release/release-detail-page.d.ts.map +1 -1
  95. package/dist/components/tickets/index.cjs +5 -5
  96. package/dist/components/tickets/index.js +4 -4
  97. package/dist/components/ui/index.cjs +2 -44
  98. package/dist/components/ui/index.cjs.map +1 -1
  99. package/dist/components/ui/index.d.ts +2 -1
  100. package/dist/components/ui/index.d.ts.map +1 -1
  101. package/dist/components/ui/index.js +13 -55
  102. package/dist/components/ui/rich-markdown-renderer.d.ts +34 -0
  103. package/dist/components/ui/rich-markdown-renderer.d.ts.map +1 -0
  104. package/dist/components/ui/simple-markdown-renderer.d.ts +73 -0
  105. package/dist/components/ui/simple-markdown-renderer.d.ts.map +1 -0
  106. package/dist/index.cjs +2 -60
  107. package/dist/index.cjs.map +1 -1
  108. package/dist/index.js +13 -71
  109. package/dist/utils/index.cjs +40 -169
  110. package/dist/utils/index.cjs.map +1 -1
  111. package/dist/utils/index.d.ts +0 -1
  112. package/dist/utils/index.d.ts.map +1 -1
  113. package/dist/utils/index.js +41 -162
  114. package/dist/utils/index.js.map +1 -1
  115. package/dist/utils/markdown-section-extractor.d.ts.map +1 -1
  116. package/package.json +1 -7
  117. package/src/components/chat/__tests__/chat-message-list.test.tsx +5 -293
  118. package/src/components/chat/chat-message-enhanced.tsx +17 -111
  119. package/src/components/chat/chat-message-list.tsx +113 -367
  120. package/src/components/chat/embeddable-chat.tsx +0 -6
  121. package/src/components/chat/hooks/.index.md +1 -1
  122. package/src/components/chat/hooks/.use-nats-chat-adapter.md +1 -1
  123. package/src/components/chat/hooks/.use-realtime-chunk-processor.md +50 -0
  124. package/src/components/chat/hooks/index.ts +1 -0
  125. package/src/components/chat/hooks/use-chat.ts +0 -8
  126. package/src/components/chat/hooks/use-nats-chat-adapter.ts +822 -243
  127. package/src/components/chat/hooks/use-realtime-chunk-processor.ts +479 -0
  128. package/src/components/chat/hooks/use-sse-chat-adapter.ts +666 -318
  129. package/src/components/chat/index.ts +0 -5
  130. package/src/components/chat/thinking-display.tsx +1 -1
  131. package/src/components/chat/types/.api.types.md +3 -1
  132. package/src/components/chat/types/.processing.types.md +23 -6
  133. package/src/components/chat/types/api.types.ts +73 -6
  134. package/src/components/chat/types/processing.types.ts +52 -11
  135. package/src/components/chat/utils/.chunk-parser.md +51 -0
  136. package/src/components/chat/utils/.index.md +5 -0
  137. package/src/components/chat/utils/chunk-parser.ts +255 -0
  138. package/src/components/chat/utils/extract-incomplete-message-state.ts +5 -63
  139. package/src/components/chat/utils/index.ts +8 -5
  140. package/src/components/chat/utils/process-historical-messages.ts +383 -352
  141. package/src/components/onboarding-guides/onboarding-guide-detail-view.tsx +4 -22
  142. package/src/components/shared/legal-document/legal-document-page.tsx +1 -1
  143. package/src/components/shared/product-release/release-detail-page.tsx +4 -19
  144. package/src/components/ui/.simple-markdown-renderer.md +40 -0
  145. package/src/components/ui/index.ts +2 -1
  146. package/src/components/ui/release-changelog-section.tsx +1 -1
  147. package/src/components/ui/rich-markdown-renderer.tsx +1223 -0
  148. package/src/components/ui/simple-markdown-renderer.tsx +965 -0
  149. package/src/components/ui/ticket-info-section.tsx +1 -1
  150. package/src/utils/index.ts +0 -1
  151. package/src/utils/markdown-section-extractor.ts +56 -41
  152. package/dist/chat-protocol/decode.d.ts +0 -58
  153. package/dist/chat-protocol/decode.d.ts.map +0 -1
  154. package/dist/chat-protocol/encode.d.ts +0 -44
  155. package/dist/chat-protocol/encode.d.ts.map +0 -1
  156. package/dist/chat-protocol/env-flag.d.ts +0 -35
  157. package/dist/chat-protocol/env-flag.d.ts.map +0 -1
  158. package/dist/chat-protocol/events.d.ts +0 -192
  159. package/dist/chat-protocol/events.d.ts.map +0 -1
  160. package/dist/chat-protocol/frames.d.ts +0 -206
  161. package/dist/chat-protocol/frames.d.ts.map +0 -1
  162. package/dist/chat-protocol/index.cjs +0 -493
  163. package/dist/chat-protocol/index.cjs.map +0 -1
  164. package/dist/chat-protocol/index.d.ts +0 -18
  165. package/dist/chat-protocol/index.d.ts.map +0 -1
  166. package/dist/chat-protocol/index.js +0 -477
  167. package/dist/chat-protocol/index.js.map +0 -1
  168. package/dist/chat-protocol/ip-normalize.d.ts +0 -44
  169. package/dist/chat-protocol/ip-normalize.d.ts.map +0 -1
  170. package/dist/chat-protocol/nats-decoder.d.ts +0 -26
  171. package/dist/chat-protocol/nats-decoder.d.ts.map +0 -1
  172. package/dist/chunk-ADD3FPDG.cjs.map +0 -1
  173. package/dist/chunk-BQ7PMWLM.cjs.map +0 -1
  174. package/dist/chunk-LJKZIIK4.js.map +0 -1
  175. package/dist/chunk-P5JQDFRM.cjs.map +0 -1
  176. package/dist/chunk-REWRUV3K.js.map +0 -1
  177. package/dist/chunk-VXJH5TDN.js.map +0 -1
  178. package/dist/components/chat/stream/chat-dialog-store.d.ts +0 -184
  179. package/dist/components/chat/stream/chat-dialog-store.d.ts.map +0 -1
  180. package/dist/components/chat/stream/chat-stream-reducer.d.ts +0 -367
  181. package/dist/components/chat/stream/chat-stream-reducer.d.ts.map +0 -1
  182. package/dist/components/chat/stream/delta-batcher.d.ts +0 -51
  183. package/dist/components/chat/stream/delta-batcher.d.ts.map +0 -1
  184. package/dist/components/chat/stream/index.d.ts +0 -17
  185. package/dist/components/chat/stream/index.d.ts.map +0 -1
  186. package/dist/components/chat/stream/message-mutations.d.ts +0 -77
  187. package/dist/components/chat/stream/message-mutations.d.ts.map +0 -1
  188. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts +0 -22
  189. package/dist/components/chat/stream/use-chat-stream-reducer.d.ts.map +0 -1
  190. package/dist/components/ui/markdown/base-components.d.ts +0 -56
  191. package/dist/components/ui/markdown/base-components.d.ts.map +0 -1
  192. package/dist/components/ui/markdown/engine.d.ts +0 -99
  193. package/dist/components/ui/markdown/engine.d.ts.map +0 -1
  194. package/dist/components/ui/markdown/heading-ids.d.ts +0 -65
  195. package/dist/components/ui/markdown/heading-ids.d.ts.map +0 -1
  196. package/dist/components/ui/markdown/index.d.ts +0 -18
  197. package/dist/components/ui/markdown/index.d.ts.map +0 -1
  198. package/dist/components/ui/markdown/mermaid-diagram.d.ts +0 -79
  199. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +0 -1
  200. package/dist/components/ui/markdown/rich/embed-overrides.d.ts +0 -14
  201. package/dist/components/ui/markdown/rich/embed-overrides.d.ts.map +0 -1
  202. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts +0 -40
  203. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts.map +0 -1
  204. package/dist/components/ui/markdown/rich/shortcodes.d.ts +0 -8
  205. package/dist/components/ui/markdown/rich/shortcodes.d.ts.map +0 -1
  206. package/dist/components/ui/markdown/sanitize.d.ts +0 -153
  207. package/dist/components/ui/markdown/sanitize.d.ts.map +0 -1
  208. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts +0 -23
  209. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts.map +0 -1
  210. package/dist/components/ui/markdown/streaming.d.ts +0 -78
  211. package/dist/components/ui/markdown/streaming.d.ts.map +0 -1
  212. package/dist/components/ui/markdown/text-size.d.ts +0 -34
  213. package/dist/components/ui/markdown/text-size.d.ts.map +0 -1
  214. package/dist/utils/markdown-fences.d.ts +0 -42
  215. package/dist/utils/markdown-fences.d.ts.map +0 -1
  216. package/dist/utils/markdown-heading-id.d.ts +0 -85
  217. package/dist/utils/markdown-heading-id.d.ts.map +0 -1
  218. package/src/chat-protocol/__tests__/__snapshots__/nats-decoder-golden.test.ts.snap +0 -307
  219. package/src/chat-protocol/__tests__/chat-protocol.test.ts +0 -515
  220. package/src/chat-protocol/__tests__/env-flag.test.ts +0 -52
  221. package/src/chat-protocol/__tests__/ip-normalize.test.ts +0 -136
  222. package/src/chat-protocol/__tests__/nats-decoder-golden.test.ts +0 -228
  223. package/src/chat-protocol/decode.ts +0 -277
  224. package/src/chat-protocol/encode.ts +0 -71
  225. package/src/chat-protocol/env-flag.ts +0 -39
  226. package/src/chat-protocol/events.ts +0 -228
  227. package/src/chat-protocol/frames.ts +0 -238
  228. package/src/chat-protocol/index.ts +0 -21
  229. package/src/chat-protocol/ip-normalize.ts +0 -146
  230. package/src/chat-protocol/nats-decoder.ts +0 -252
  231. package/src/components/chat/__tests__/chat-message-streaming-memo.test.tsx +0 -207
  232. package/src/components/chat/__tests__/chat-pending-turn.test.tsx +0 -209
  233. package/src/components/chat/hooks/__tests__/__snapshots__/persisted-state-v1-golden.test.ts.snap +0 -297
  234. package/src/components/chat/hooks/__tests__/__snapshots__/sse-stream-golden.test.ts.snap +0 -0
  235. package/src/components/chat/hooks/__tests__/persisted-state-v1-golden.test.ts +0 -272
  236. package/src/components/chat/hooks/__tests__/sse-stream-golden.test.ts +0 -318
  237. package/src/components/chat/stream/__tests__/__snapshots__/chat-stream-reducer-golden.test.ts.snap +0 -937
  238. package/src/components/chat/stream/__tests__/chat-dialog-store.test.ts +0 -756
  239. package/src/components/chat/stream/__tests__/chat-stream-reducer-golden.test.ts +0 -460
  240. package/src/components/chat/stream/__tests__/chat-stream-reducer.test.ts +0 -894
  241. package/src/components/chat/stream/__tests__/delta-batcher.test.ts +0 -255
  242. package/src/components/chat/stream/__tests__/use-chat-stream-reducer.test.ts +0 -98
  243. package/src/components/chat/stream/chat-dialog-store.ts +0 -536
  244. package/src/components/chat/stream/chat-stream-reducer.ts +0 -1796
  245. package/src/components/chat/stream/delta-batcher.ts +0 -159
  246. package/src/components/chat/stream/index.ts +0 -55
  247. package/src/components/chat/stream/message-mutations.ts +0 -338
  248. package/src/components/chat/stream/use-chat-stream-reducer.ts +0 -126
  249. package/src/components/chat/utils/__tests__/__snapshots__/process-historical-messages-golden.test.ts.snap +0 -418
  250. package/src/components/chat/utils/__tests__/__snapshots__/segment-accumulator-golden.test.ts.snap +0 -599
  251. package/src/components/chat/utils/__tests__/process-historical-messages-golden.test.ts +0 -317
  252. package/src/components/chat/utils/__tests__/segment-accumulator-golden.test.ts +0 -270
  253. package/src/components/ui/__tests__/__snapshots__/markdown-parity.test.tsx.snap +0 -2420
  254. package/src/components/ui/__tests__/markdown-parity.test.tsx +0 -2528
  255. package/src/components/ui/markdown/__tests__/mermaid-security.test.ts +0 -115
  256. package/src/components/ui/markdown/__tests__/mermaid-stale-render.test.tsx +0 -95
  257. package/src/components/ui/markdown/__tests__/sanitize-invariant.test.ts +0 -309
  258. package/src/components/ui/markdown/__tests__/streaming.test.tsx +0 -388
  259. package/src/components/ui/markdown/base-components.tsx +0 -341
  260. package/src/components/ui/markdown/engine.tsx +0 -315
  261. package/src/components/ui/markdown/heading-ids.ts +0 -239
  262. package/src/components/ui/markdown/index.ts +0 -49
  263. package/src/components/ui/markdown/mermaid-diagram.tsx +0 -291
  264. package/src/components/ui/markdown/rich/embed-overrides.tsx +0 -199
  265. package/src/components/ui/markdown/rich/rich-markdown-renderer.tsx +0 -184
  266. package/src/components/ui/markdown/rich/shortcodes.ts +0 -170
  267. package/src/components/ui/markdown/sanitize.ts +0 -3499
  268. package/src/components/ui/markdown/simple-markdown-renderer.tsx +0 -28
  269. package/src/components/ui/markdown/streaming.ts +0 -362
  270. package/src/components/ui/markdown/text-size.ts +0 -106
  271. package/src/utils/markdown-fences.ts +0 -127
  272. package/src/utils/markdown-heading-id.ts +0 -348
  273. /package/dist/{chunk-CGNDAJ7V.js.map → chunk-6B27O3ZB.js.map} +0 -0
  274. /package/dist/{chunk-4R6H2U77.js.map → chunk-H7ETLG65.js.map} +0 -0
  275. /package/dist/{chunk-LAOO7XHO.js.map → chunk-HWTUVLYB.js.map} +0 -0
  276. /package/dist/{chunk-F2NMWV44.js.map → chunk-IDKDOQZL.js.map} +0 -0
  277. /package/dist/{chunk-QO2XD3FR.js.map → chunk-KQGFKG6Y.js.map} +0 -0
  278. /package/dist/{chunk-OR5AMXYN.js.map → chunk-R5QYMUKN.js.map} +0 -0
  279. /package/dist/{chunk-XF5ROTMQ.js.map → chunk-U2YDR5DT.js.map} +0 -0
  280. /package/dist/{chunk-UI7CIUAR.js.map → chunk-WGJPTFRH.js.map} +0 -0
  281. /package/dist/{chunk-APF5QBAU.js.map → chunk-YQBPIUZU.js.map} +0 -0
@@ -12,11 +12,11 @@
12
12
  * ┌──────────────────────────────────────────────────────────────┐
13
13
  * │ useNatsDialogSubscription live tail of agent events │
14
14
  * │ ↓ │
15
- * │ onEvent → decodeNatsChunk → ChatStreamEvent │
15
+ * │ onEvent → processChunk │
16
16
  * │ ↓ │
17
- * │ createChatStreamReducer THE master accumulation path │
18
- * │ (via ChatDialogStore + useChatStreamReducer wrapper — │
19
- * │ messages, phase, token usage, approvals all live there) │
17
+ * │ useRealtimeChunkProcessor chunk → MessageSegment[] │
18
+ * │ ↓ │
19
+ * │ onSegmentsUpdate → updates assistant message in state │
20
20
  * │ │
21
21
  * │ useChunkCatchup back-fill missed chunks after │
22
22
  * │ activation / reconnect │
@@ -24,38 +24,53 @@
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
- *
36
27
  * Two operating modes, distinguished by the presence of `fetchDialogs`:
37
28
  *
38
29
  * 1. **Bare-transport mode** (current Tauri Fae Chat usage):
39
30
  * consumer supplies `config.dialogId` explicitly and owns dialog
40
- * management above the adapter.
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.
41
35
  *
42
36
  * 2. **Managed-dialog mode** (openframe-frontend, EmbeddableChat
43
- * sidebar): consumer supplies `fetchDialogs`, `fetchDialogMessages`,
44
- * `createDialog`, etc. and the adapter owns the dialog state machine.
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.
45
55
  *
46
56
  * The `active` option gates the live subscription so the unified chat
47
57
  * shell can keep both adapters mounted while only paying network cost
48
58
  * for the currently-displayed mode.
49
59
  */
50
60
 
51
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
61
+ import {
62
+ useCallback,
63
+ useEffect,
64
+ useMemo,
65
+ useRef,
66
+ useState,
67
+ type MutableRefObject,
68
+ } from 'react'
52
69
  import { useNatsDialogSubscription } from './use-nats-dialog-subscription'
70
+ import { useRealtimeChunkProcessor } from './use-realtime-chunk-processor'
53
71
  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'
57
72
  import { processHistoricalMessagesWithErrors } from '../utils/process-historical-messages'
58
- import { extractIncompleteTailState } from '../utils/extract-incomplete-message-state'
73
+ import { extractIncompleteMessageState } from '../utils/extract-incomplete-message-state'
59
74
  import type {
60
75
  ChunkData,
61
76
  FetchChunksFunction,
@@ -63,7 +78,11 @@ import type {
63
78
  MessageProcessingOptions,
64
79
  MessageSegment,
65
80
  NatsMessageType,
81
+ StreamingPhase,
66
82
  ChatApprovalStatus,
83
+ SegmentsUpdateMetadata,
84
+ ToolExecutionSegment,
85
+ ApprovalBatchExecutionState,
67
86
  } from '../types'
68
87
  import type {
69
88
  ChatConnectionState,
@@ -75,16 +94,6 @@ import type {
75
94
  import type { DialogItem } from '../types/component.types'
76
95
  import type { ChatRef } from '../chat-ref.types'
77
96
 
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
-
88
97
  // =============================================================================
89
98
  // Config + options
90
99
  // =============================================================================
@@ -201,19 +210,19 @@ export interface UseNatsChatAdapterConfig {
201
210
  topics?: NatsMessageType[]
202
211
 
203
212
  /**
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.
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.
207
216
  */
208
217
  batchApprovalsEnabled?: boolean
209
218
 
210
219
  /**
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.
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.
217
226
  */
218
227
  displayApprovalTypes?: string[]
219
228
 
@@ -236,7 +245,7 @@ export interface UseNatsChatAdapterConfig {
236
245
  * Messages must arrive in the same wire shape the openframe backend
237
246
  * emits (HistoricalMessage with messageData[]); the adapter feeds
238
247
  * them through `processHistoricalMessagesWithErrors` to produce
239
- * reducer-compatible messages.
248
+ * accumulator-compatible segments.
240
249
  */
241
250
  fetchDialogMessages?: (
242
251
  params: FetchDialogMessagesParams,
@@ -274,9 +283,9 @@ export interface UseNatsChatAdapterConfig {
274
283
  unarchiveDialog?: (dialogId: string) => Promise<void>
275
284
 
276
285
  /**
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.
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.
280
289
  */
281
290
  approveRequest?: (requestId: string) => Promise<void>
282
291
 
@@ -335,9 +344,261 @@ export interface UseNatsChatAdapterOptions {
335
344
  }
336
345
 
337
346
  // =============================================================================
338
- // Historical-message mapping helpers (host-facing)
347
+ // Internal helpers
339
348
  // =============================================================================
340
349
 
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
+
341
602
  /**
342
603
  * Map `ProcessedMessage` (lib's historical-message format) into
343
604
  * `UnifiedChatMessage` (the unified-chat-state contract). Only `user`
@@ -407,9 +668,6 @@ export function historicalToUnified(
407
668
  // Hook
408
669
  // =============================================================================
409
670
 
410
- /** Store key for the draft ("no dialog selected") state. */
411
- const DRAFT_DIALOG_KEY = '__draft__'
412
-
413
671
  export function useNatsChatAdapter(
414
672
  config: UseNatsChatAdapterConfig,
415
673
  options: UseNatsChatAdapterOptions = {},
@@ -465,109 +723,56 @@ export function useNatsChatAdapter(
465
723
  const currentDialogIdRef = useRef<string | null>(dialogId)
466
724
  currentDialogIdRef.current = dialogId
467
725
 
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.
472
-
473
- const handleApproveRef = useRef<(requestId: string) => Promise<void>>(async () => {})
474
- const handleRejectRef = useRef<(requestId: string, reason?: string) => Promise<void>>(
475
- async () => {},
476
- )
477
-
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
- }, [])
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)
488
755
 
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
- }
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)
561
760
 
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
- )
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
+ >({})
571
776
 
572
777
  // ─── Dialog list state (managed-dialog mode only) ─────────────────────────
573
778
 
@@ -582,15 +787,383 @@ export function useNatsChatAdapter(
582
787
  const [messagesNextCursor, setMessagesNextCursor] = useState<string | null>(null)
583
788
  const [isMessagesLoading, setIsMessagesLoading] = useState<boolean>(false)
584
789
 
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
+
585
805
  // ─── Connection state ─────────────────────────────────────────────────────
586
806
 
587
807
  const [connectionState, setConnectionState] =
588
808
  useState<ChatConnectionState>('connecting')
589
809
 
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)
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
+ })
594
1167
 
595
1168
  // History catchup — back-fills chunks emitted while the adapter was
596
1169
  // inactive or before the WS came online.
@@ -610,8 +1183,8 @@ export function useNatsChatAdapter(
610
1183
  // ─── Historical message hydration ─────────────────────────────────────────
611
1184
  // When the active dialog changes AND a `fetchDialogMessages` callback
612
1185
  // is wired, load the first page of history, process it through the
613
- // history decoder + envelope, and seed the reducer. Streaming chunks for
614
- // the same dialog then append on top.
1186
+ // accumulator, and seed `messages`. Streaming chunks for the same
1187
+ // dialog then append on top.
615
1188
 
616
1189
  // Monotonic guard: each history load captures a sequence number; when a
617
1190
  // response resolves, it only applies if it's still the latest request. This
@@ -624,7 +1197,6 @@ export function useNatsChatAdapter(
624
1197
  if (!fetchDialogMessages) return
625
1198
  historyLoadSeqRef.current += 1
626
1199
  const seq = historyLoadSeqRef.current
627
- const store = storeRef.current
628
1200
  setIsMessagesLoading(true)
629
1201
  try {
630
1202
  const result = await fetchDialogMessages({
@@ -642,39 +1214,34 @@ export function useNatsChatAdapter(
642
1214
  chatTypeFilter,
643
1215
  onApprove: accumApprove,
644
1216
  onReject: accumReject,
645
- approvalStatuses: store.getSnapshot(id).approvalStatuses,
1217
+ approvalStatuses,
646
1218
  batchApprovalsEnabled,
647
1219
  ...(displayApprovalTypes ? { displayApprovalTypes } : {}),
648
1220
  },
649
1221
  )
650
1222
  const unified = mapProcessedToUnified(rawProcessed)
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
- })
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
+ }
677
1241
  setMessagesNextCursor(result.nextCursor)
1242
+ if (result.tokenUsage !== undefined) {
1243
+ setDialogTokenUsage(result.tokenUsage)
1244
+ }
678
1245
  } catch (err) {
679
1246
  console.error('[useNatsChatAdapter] fetchDialogMessages failed:', err)
680
1247
  } finally {
@@ -690,6 +1257,7 @@ export function useNatsChatAdapter(
690
1257
  messagesPageSize,
691
1258
  assistantName,
692
1259
  chatTypeFilter,
1260
+ approvalStatuses,
693
1261
  batchApprovalsEnabled,
694
1262
  displayApprovalTypes,
695
1263
  accumApprove,
@@ -710,19 +1278,20 @@ export function useNatsChatAdapter(
710
1278
  // this an in-flight response could repopulate the just-cleared state.
711
1279
  historyLoadSeqRef.current += 1
712
1280
 
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
- })
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')
723
1293
  // No load runs when there's no active dialog, so clear the flag here;
724
1294
  // otherwise the superseded load's guarded `finally` leaves it stuck on.
725
- setMessagesNextCursor(null)
726
1295
  setIsMessagesLoading(false)
727
1296
 
728
1297
  if (!active || !dialogId) return
@@ -730,7 +1299,7 @@ export function useNatsChatAdapter(
730
1299
  // Hydrate history first; then catchup will fold in any chunks that
731
1300
  // landed between the history snapshot and the live tail.
732
1301
  void loadDialogHistory(dialogId)
733
- }, [active, dialogId, dialogKey, loadDialogHistory])
1302
+ }, [active, dialogId, loadDialogHistory, resetAccumulator])
734
1303
 
735
1304
  // Trigger initial chunk backfill whenever a fresh dialog activates.
736
1305
  // Runs alongside history hydration — history seeds processed messages,
@@ -738,14 +1307,8 @@ export function useNatsChatAdapter(
738
1307
  // was already snapshotted.
739
1308
  useEffect(() => {
740
1309
  if (!active || !dialogId) return
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))
1310
+ // Gate onAgentBusy for the replay window (see suppressAgentBusyRef).
1311
+ suppressAgentBusyRef.current += 1
749
1312
  resetChunkTracking()
750
1313
  startInitialBuffering()
751
1314
  catchUpChunks()
@@ -753,15 +1316,16 @@ export function useNatsChatAdapter(
753
1316
  console.error('[useNatsChatAdapter] initial catchup failed:', err)
754
1317
  })
755
1318
  .finally(() => {
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
- })
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
+ }
765
1329
  })
766
1330
  }, [active, dialogId, resetChunkTracking, startInitialBuffering, catchUpChunks])
767
1331
 
@@ -794,13 +1358,7 @@ export function useNatsChatAdapter(
794
1358
  hasConnectedOnceRef.current = true
795
1359
  return
796
1360
  }
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
- }
1361
+ suppressAgentBusyRef.current += 1
804
1362
  // Buffer live deliveries for the WHOLE back-fill, including the history
805
1363
  // await — otherwise chunks landing mid-fetch are processed unbuffered
806
1364
  // (advancing lastSequenceId + dedup keys) and the history replace then
@@ -814,27 +1372,28 @@ export function useNatsChatAdapter(
814
1372
  // so the chunk back-fill can't recover them — the persisted history
815
1373
  // page is the only source. Then replay the unsaved chunk tail on
816
1374
  // top of the fresh snapshot.
817
- if (reconnectDialogId && fetchDialogMessages) {
818
- await loadDialogHistory(reconnectDialogId)
1375
+ if (dialogId && fetchDialogMessages) {
1376
+ await loadDialogHistory(dialogId)
819
1377
  }
820
1378
  // The user may have switched dialogs during the await — the new
821
1379
  // dialog's own effects run their catchup cycle; re-running it here
822
- // would reset that cycle mid-flight.
823
- if (reconnectDialogId !== currentDialogIdRef.current) return
1380
+ // (via refs it would target the NEW dialog) would reset that cycle
1381
+ // mid-flight.
1382
+ if (dialogId !== currentDialogIdRef.current) return
824
1383
  await resetAndCatchUp()
825
1384
  } catch (err) {
826
1385
  console.error('[useNatsChatAdapter] reconnect catchup failed:', err)
827
1386
  } finally {
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
- })
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
838
1397
  }
839
1398
  }
840
1399
  })()
@@ -914,30 +1473,52 @@ export function useNatsChatAdapter(
914
1473
  ): Promise<void> => {
915
1474
  const hidden = sendOptions?.hidden ?? false
916
1475
 
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
+
917
1482
  // Optimistically append the user bubble + an empty assistant
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))
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')
921
1500
 
922
1501
  await publishUserMessage(text, { hidden, dialogId })
923
1502
  },
924
- [mutate, publishUserMessage, dialogId],
1503
+ [publishUserMessage, dialogId],
925
1504
  )
926
1505
 
927
1506
  const stopMessage = useCallback(() => {
928
1507
  // Best-effort UI flip. The actual backend cancellation is gated on
929
1508
  // the host-supplied callback.
930
- mutate((r) => r.setPhase('idle'))
1509
+ setStreamingPhase('idle')
931
1510
  if (stopGenerationCallback && dialogId) {
932
1511
  void stopGenerationCallback(dialogId).catch((err) => {
933
1512
  console.error('[useNatsChatAdapter] stopGeneration failed:', err)
934
1513
  })
935
1514
  }
936
- }, [mutate, stopGenerationCallback, dialogId])
1515
+ }, [stopGenerationCallback, dialogId])
937
1516
 
938
1517
  const clearMessages = useCallback(() => {
939
- mutate((r) => r.clearThread())
940
- }, [mutate])
1518
+ setMessages([])
1519
+ resetAccumulator()
1520
+ setStreamingPhase('idle')
1521
+ }, [resetAccumulator])
941
1522
 
942
1523
  const selectDialog = useCallback(
943
1524
  (id: string | null) => {
@@ -988,7 +1569,6 @@ export function useNatsChatAdapter(
988
1569
  try {
989
1570
  await deleteDialogCallback(id)
990
1571
  setDialogs((prev) => prev.filter((d) => d.id !== id))
991
- storeRef.current.remove(id)
992
1572
  if (isManagedMode && internalDialogId === id) {
993
1573
  setInternalDialogId(null)
994
1574
  }
@@ -1075,7 +1655,6 @@ export function useNatsChatAdapter(
1075
1655
 
1076
1656
  // ─── Return shape ─────────────────────────────────────────────────────────
1077
1657
 
1078
- const { messages, streamingPhase, dialogTokenUsage = null, liveModel = null } = state
1079
1658
  const isLoading = streamingPhase !== 'idle'
1080
1659
  const hasMoreDialogs = dialogsNextCursor != null
1081
1660
  const hasMoreMessages = messagesNextCursor != null