@flamingo-stack/openframe-frontend-core 0.0.598 → 0.0.599-2039.5716.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/dist/chat-protocol/index.cjs +8 -1
  2. package/dist/chat-protocol/index.cjs.map +1 -1
  3. package/dist/chat-protocol/index.d.ts +1 -0
  4. package/dist/chat-protocol/index.d.ts.map +1 -1
  5. package/dist/chat-protocol/index.js +7 -2
  6. package/dist/chat-protocol/index.js.map +1 -1
  7. package/dist/chat-protocol/nats-decoder.d.ts.map +1 -1
  8. package/dist/chat-protocol/wire-narrow.d.ts +17 -0
  9. package/dist/chat-protocol/wire-narrow.d.ts.map +1 -0
  10. package/dist/{chunk-VLJTJAHJ.cjs → chunk-2B4HSYAX.cjs} +25 -25
  11. package/dist/{chunk-VLJTJAHJ.cjs.map → chunk-2B4HSYAX.cjs.map} +1 -1
  12. package/dist/{chunk-UE7OFLLS.cjs → chunk-2GCBN73M.cjs} +14 -14
  13. package/dist/{chunk-UE7OFLLS.cjs.map → chunk-2GCBN73M.cjs.map} +1 -1
  14. package/dist/{chunk-STYNZ4QM.cjs → chunk-3IXDZI3R.cjs} +3 -3
  15. package/dist/{chunk-STYNZ4QM.cjs.map → chunk-3IXDZI3R.cjs.map} +1 -1
  16. package/dist/{chunk-DAPOBLAK.cjs → chunk-3RWSKUIN.cjs} +39 -39
  17. package/dist/{chunk-DAPOBLAK.cjs.map → chunk-3RWSKUIN.cjs.map} +1 -1
  18. package/dist/{chunk-VNSRNVPD.js → chunk-4HJYXP5O.js} +722 -406
  19. package/dist/chunk-4HJYXP5O.js.map +1 -0
  20. package/dist/{chunk-HWAYIK4U.cjs → chunk-4MOY5TQR.cjs} +22 -22
  21. package/dist/{chunk-HWAYIK4U.cjs.map → chunk-4MOY5TQR.cjs.map} +1 -1
  22. package/dist/{chunk-VIRTMRS4.js → chunk-4PBUEYAE.js} +7 -7
  23. package/dist/{chunk-TZPVRWPU.js → chunk-4TG5BWPE.js} +5 -5
  24. package/dist/{chunk-PTK3CINU.js → chunk-6JF65LRQ.js} +5 -5
  25. package/dist/{chunk-YWBAIFI2.cjs → chunk-6XISE63Q.cjs} +105 -105
  26. package/dist/{chunk-YWBAIFI2.cjs.map → chunk-6XISE63Q.cjs.map} +1 -1
  27. package/dist/{chunk-QD64Q4I2.cjs → chunk-A4HMGZ4L.cjs} +9 -9
  28. package/dist/{chunk-QD64Q4I2.cjs.map → chunk-A4HMGZ4L.cjs.map} +1 -1
  29. package/dist/{chunk-BK6CCQG6.js → chunk-AUCJ6I3R.js} +12 -12
  30. package/dist/{chunk-3WSS7C2V.cjs → chunk-BBBZ5QUB.cjs} +15 -15
  31. package/dist/{chunk-3WSS7C2V.cjs.map → chunk-BBBZ5QUB.cjs.map} +1 -1
  32. package/dist/{chunk-EVMHJB6X.js → chunk-BLUL2TE3.js} +4 -4
  33. package/dist/{chunk-GGQZBSFN.js → chunk-BVQEU5JB.js} +2 -2
  34. package/dist/{chunk-V2QK5W3O.cjs → chunk-BW644MGF.cjs} +3 -3
  35. package/dist/{chunk-V2QK5W3O.cjs.map → chunk-BW644MGF.cjs.map} +1 -1
  36. package/dist/{chunk-H64ZHSYR.cjs → chunk-CCWI3622.cjs} +4 -4
  37. package/dist/{chunk-H64ZHSYR.cjs.map → chunk-CCWI3622.cjs.map} +1 -1
  38. package/dist/{chunk-DI3SVVY5.cjs → chunk-COERKO4N.cjs} +85 -85
  39. package/dist/{chunk-DI3SVVY5.cjs.map → chunk-COERKO4N.cjs.map} +1 -1
  40. package/dist/{chunk-SE3PVN64.js → chunk-DZ44C6KB.js} +2 -2
  41. package/dist/{chunk-2SYX2Z7R.cjs → chunk-E27TMQRE.cjs} +34 -34
  42. package/dist/{chunk-2SYX2Z7R.cjs.map → chunk-E27TMQRE.cjs.map} +1 -1
  43. package/dist/{chunk-YH6IQTPI.cjs → chunk-EHAYNUOL.cjs} +3 -3
  44. package/dist/{chunk-YH6IQTPI.cjs.map → chunk-EHAYNUOL.cjs.map} +1 -1
  45. package/dist/{chunk-WZJOILPU.js → chunk-F2KBCLUG.js} +2 -2
  46. package/dist/{chunk-MYBXCWEI.js → chunk-FKBM6U43.js} +2 -2
  47. package/dist/{chunk-75YW6ET4.js → chunk-FNK4RZ25.js} +4 -4
  48. package/dist/{chunk-UG7JNQZY.cjs → chunk-GB5FPCUN.cjs} +37 -37
  49. package/dist/{chunk-UG7JNQZY.cjs.map → chunk-GB5FPCUN.cjs.map} +1 -1
  50. package/dist/{chunk-P24VPJTT.cjs → chunk-HJUXXWTM.cjs} +15 -15
  51. package/dist/{chunk-P24VPJTT.cjs.map → chunk-HJUXXWTM.cjs.map} +1 -1
  52. package/dist/{chunk-WPN545FW.js → chunk-ILJTXIEI.js} +12 -12
  53. package/dist/{chunk-YBPFIXV4.cjs → chunk-ITZDJYWI.cjs} +796 -480
  54. package/dist/chunk-ITZDJYWI.cjs.map +1 -0
  55. package/dist/{chunk-LRQCKSZC.js → chunk-IW746HJ7.js} +2 -2
  56. package/dist/{chunk-PX4IPM7Q.js → chunk-J62LLUDC.js} +3 -3
  57. package/dist/{chunk-M4YQUHOR.cjs → chunk-JJUV7Z4L.cjs} +15 -15
  58. package/dist/{chunk-M4YQUHOR.cjs.map → chunk-JJUV7Z4L.cjs.map} +1 -1
  59. package/dist/{chunk-GHYFVT52.js → chunk-JZF6EUMO.js} +5 -5
  60. package/dist/{chunk-JVZVVZOZ.cjs → chunk-KYGTR6EG.cjs} +9 -9
  61. package/dist/{chunk-JVZVVZOZ.cjs.map → chunk-KYGTR6EG.cjs.map} +1 -1
  62. package/dist/{chunk-QIKBISZM.cjs → chunk-L66UPFCQ.cjs} +242 -242
  63. package/dist/{chunk-QIKBISZM.cjs.map → chunk-L66UPFCQ.cjs.map} +1 -1
  64. package/dist/{chunk-NIAMPMKV.js → chunk-LJ4UG2SW.js} +4 -4
  65. package/dist/{chunk-WDWCQD75.js → chunk-MWQSHXYK.js} +9 -9
  66. package/dist/{chunk-BPVHDDNY.cjs → chunk-NLFST5II.cjs} +8 -8
  67. package/dist/{chunk-BPVHDDNY.cjs.map → chunk-NLFST5II.cjs.map} +1 -1
  68. package/dist/{chunk-SAEJGTCI.cjs → chunk-QPAPUIF3.cjs} +35 -35
  69. package/dist/{chunk-SAEJGTCI.cjs.map → chunk-QPAPUIF3.cjs.map} +1 -1
  70. package/dist/{chunk-HLPAVYK7.js → chunk-RSTEDWAT.js} +4 -4
  71. package/dist/{chunk-UAAXUFK6.js → chunk-RU3IKVY2.js} +3 -3
  72. package/dist/{chunk-EZM5DNII.js → chunk-S6WBBSII.js} +3 -3
  73. package/dist/{chunk-2JNCZDJR.js → chunk-TSCIVH7T.js} +2 -2
  74. package/dist/{chunk-RDTOMWDN.cjs → chunk-UPKZU6QU.cjs} +1 -1
  75. package/dist/chunk-UPKZU6QU.cjs.map +1 -0
  76. package/dist/{chunk-WCBRZCU4.cjs → chunk-UQEOAPAI.cjs} +9 -9
  77. package/dist/{chunk-WCBRZCU4.cjs.map → chunk-UQEOAPAI.cjs.map} +1 -1
  78. package/dist/{chunk-O4VZOA2Q.cjs → chunk-UXOOVP77.cjs} +3 -3
  79. package/dist/{chunk-O4VZOA2Q.cjs.map → chunk-UXOOVP77.cjs.map} +1 -1
  80. package/dist/{chunk-R4UV366K.js → chunk-UYLZAW6Y.js} +6 -6
  81. package/dist/{chunk-BZEWPW5A.cjs → chunk-VIBREYUK.cjs} +3 -3
  82. package/dist/{chunk-BZEWPW5A.cjs.map → chunk-VIBREYUK.cjs.map} +1 -1
  83. package/dist/{chunk-KHOZ52NR.js → chunk-XSMBLU44.js} +6 -6
  84. package/dist/{chunk-RYXIRVDC.js → chunk-YB6FI2G3.js} +1 -1
  85. package/dist/chunk-YB6FI2G3.js.map +1 -0
  86. package/dist/{chunk-XNPAVMPB.js → chunk-YG7DCXRD.js} +5 -5
  87. package/dist/components/case-studies/index.cjs +14 -14
  88. package/dist/components/case-studies/index.js +8 -8
  89. package/dist/components/chat/embeddable-chat.d.ts +10 -19
  90. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  91. package/dist/components/chat/hooks/index.d.ts +1 -0
  92. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  93. package/dist/components/chat/hooks/use-chat-history-hydration.d.ts +13 -3
  94. package/dist/components/chat/hooks/use-chat-history-hydration.d.ts.map +1 -1
  95. package/dist/components/chat/hooks/use-managed-dialog-list.d.ts +53 -0
  96. package/dist/components/chat/hooks/use-managed-dialog-list.d.ts.map +1 -0
  97. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +2 -16
  98. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  99. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  100. package/dist/components/chat/hooks/use-unified-chat.d.ts.map +1 -1
  101. package/dist/components/chat/index.cjs +9 -5
  102. package/dist/components/chat/index.cjs.map +1 -1
  103. package/dist/components/chat/index.js +8 -4
  104. package/dist/components/chat/types/unified-chat-state.types.d.ts +72 -6
  105. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  106. package/dist/components/chat/utils/chat-conversations-api.d.ts +29 -0
  107. package/dist/components/chat/utils/chat-conversations-api.d.ts.map +1 -0
  108. package/dist/components/chat/utils/index.d.ts +1 -0
  109. package/dist/components/chat/utils/index.d.ts.map +1 -1
  110. package/dist/components/contact/index.cjs +9 -9
  111. package/dist/components/contact/index.js +8 -8
  112. package/dist/components/docs/index.cjs +12 -12
  113. package/dist/components/docs/index.js +11 -11
  114. package/dist/components/embeds/index.cjs +9 -9
  115. package/dist/components/embeds/index.js +8 -8
  116. package/dist/components/faq/index.cjs +10 -10
  117. package/dist/components/faq/index.js +9 -9
  118. package/dist/components/features/index.cjs +8 -8
  119. package/dist/components/features/index.js +7 -7
  120. package/dist/components/help-center-pages/index.cjs +31 -31
  121. package/dist/components/help-center-pages/index.js +22 -22
  122. package/dist/components/index.cjs +70 -66
  123. package/dist/components/index.cjs.map +1 -1
  124. package/dist/components/index.js +26 -22
  125. package/dist/components/index.js.map +1 -1
  126. package/dist/components/meeting-scheduler/index.cjs +49 -49
  127. package/dist/components/meeting-scheduler/index.js +9 -9
  128. package/dist/components/navigation/index.cjs +11 -11
  129. package/dist/components/navigation/index.js +10 -10
  130. package/dist/components/onboarding-guides/index.cjs +12 -12
  131. package/dist/components/onboarding-guides/index.js +11 -11
  132. package/dist/components/related-content/index.cjs +7 -7
  133. package/dist/components/related-content/index.js +6 -6
  134. package/dist/components/tickets/index.cjs +13 -13
  135. package/dist/components/tickets/index.js +12 -12
  136. package/dist/components/ui/index.cjs +12 -8
  137. package/dist/components/ui/index.cjs.map +1 -1
  138. package/dist/components/ui/index.js +11 -7
  139. package/dist/contexts/chat-runtime-context.d.ts +12 -0
  140. package/dist/contexts/chat-runtime-context.d.ts.map +1 -1
  141. package/dist/contexts/index.cjs +2 -2
  142. package/dist/contexts/index.js +1 -1
  143. package/dist/hooks/index.cjs +5 -5
  144. package/dist/hooks/index.js +4 -4
  145. package/dist/index.cjs +16 -12
  146. package/dist/index.cjs.map +1 -1
  147. package/dist/index.js +15 -11
  148. package/dist/index.js.map +1 -1
  149. package/package.json +1 -1
  150. package/src/chat-protocol/index.ts +1 -0
  151. package/src/chat-protocol/nats-decoder.ts +1 -5
  152. package/src/chat-protocol/wire-narrow.ts +22 -0
  153. package/src/components/chat/.embeddable-chat.md +4 -2
  154. package/src/components/chat/embeddable-chat.tsx +136 -84
  155. package/src/components/chat/hooks/.index.md +1 -1
  156. package/src/components/chat/hooks/.use-managed-dialog-list.md +31 -0
  157. package/src/components/chat/hooks/.use-nats-chat-adapter.md +3 -1
  158. package/src/components/chat/hooks/.use-sse-chat-adapter.md +8 -1
  159. package/src/components/chat/hooks/.use-unified-chat.md +2 -2
  160. package/src/components/chat/hooks/__tests__/managed-dialog-list.test.ts +280 -0
  161. package/src/components/chat/hooks/__tests__/nats-adapter-managed-dialogs.test.ts +173 -0
  162. package/src/components/chat/hooks/__tests__/sse-managed-dialogs.test.ts +310 -0
  163. package/src/components/chat/hooks/index.ts +2 -0
  164. package/src/components/chat/hooks/use-chat-history-hydration.ts +67 -24
  165. package/src/components/chat/hooks/use-managed-dialog-list.ts +339 -0
  166. package/src/components/chat/hooks/use-nats-chat-adapter.ts +65 -150
  167. package/src/components/chat/hooks/use-sse-chat-adapter.ts +233 -59
  168. package/src/components/chat/hooks/use-unified-chat.ts +5 -0
  169. package/src/components/chat/types/.unified-chat-state.types.md +13 -1
  170. package/src/components/chat/types/unified-chat-state.types.ts +79 -6
  171. package/src/components/chat/utils/.chat-conversations-api.md +16 -0
  172. package/src/components/chat/utils/.index.md +1 -1
  173. package/src/components/chat/utils/__tests__/chat-conversations-api-golden.test.ts +105 -0
  174. package/src/components/chat/utils/chat-conversations-api.ts +83 -0
  175. package/src/components/chat/utils/index.ts +7 -0
  176. package/src/contexts/.chat-runtime-context.md +3 -1
  177. package/src/contexts/chat-runtime-context.tsx +12 -0
  178. package/dist/chunk-RDTOMWDN.cjs.map +0 -1
  179. package/dist/chunk-RYXIRVDC.js.map +0 -1
  180. package/dist/chunk-VNSRNVPD.js.map +0 -1
  181. package/dist/chunk-YBPFIXV4.cjs.map +0 -1
  182. /package/dist/{chunk-VIRTMRS4.js.map → chunk-4PBUEYAE.js.map} +0 -0
  183. /package/dist/{chunk-TZPVRWPU.js.map → chunk-4TG5BWPE.js.map} +0 -0
  184. /package/dist/{chunk-PTK3CINU.js.map → chunk-6JF65LRQ.js.map} +0 -0
  185. /package/dist/{chunk-BK6CCQG6.js.map → chunk-AUCJ6I3R.js.map} +0 -0
  186. /package/dist/{chunk-EVMHJB6X.js.map → chunk-BLUL2TE3.js.map} +0 -0
  187. /package/dist/{chunk-GGQZBSFN.js.map → chunk-BVQEU5JB.js.map} +0 -0
  188. /package/dist/{chunk-SE3PVN64.js.map → chunk-DZ44C6KB.js.map} +0 -0
  189. /package/dist/{chunk-WZJOILPU.js.map → chunk-F2KBCLUG.js.map} +0 -0
  190. /package/dist/{chunk-MYBXCWEI.js.map → chunk-FKBM6U43.js.map} +0 -0
  191. /package/dist/{chunk-75YW6ET4.js.map → chunk-FNK4RZ25.js.map} +0 -0
  192. /package/dist/{chunk-WPN545FW.js.map → chunk-ILJTXIEI.js.map} +0 -0
  193. /package/dist/{chunk-LRQCKSZC.js.map → chunk-IW746HJ7.js.map} +0 -0
  194. /package/dist/{chunk-PX4IPM7Q.js.map → chunk-J62LLUDC.js.map} +0 -0
  195. /package/dist/{chunk-GHYFVT52.js.map → chunk-JZF6EUMO.js.map} +0 -0
  196. /package/dist/{chunk-NIAMPMKV.js.map → chunk-LJ4UG2SW.js.map} +0 -0
  197. /package/dist/{chunk-WDWCQD75.js.map → chunk-MWQSHXYK.js.map} +0 -0
  198. /package/dist/{chunk-HLPAVYK7.js.map → chunk-RSTEDWAT.js.map} +0 -0
  199. /package/dist/{chunk-UAAXUFK6.js.map → chunk-RU3IKVY2.js.map} +0 -0
  200. /package/dist/{chunk-EZM5DNII.js.map → chunk-S6WBBSII.js.map} +0 -0
  201. /package/dist/{chunk-2JNCZDJR.js.map → chunk-TSCIVH7T.js.map} +0 -0
  202. /package/dist/{chunk-R4UV366K.js.map → chunk-UYLZAW6Y.js.map} +0 -0
  203. /package/dist/{chunk-KHOZ52NR.js.map → chunk-XSMBLU44.js.map} +0 -0
  204. /package/dist/{chunk-XNPAVMPB.js.map → chunk-YG7DCXRD.js.map} +0 -0
@@ -0,0 +1,339 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * useManagedDialogList — the ONE cursor-paged dialog-list state machine. Two
5
+ * consumers: the NATS/Mingo adapter's managed-dialog mode and the SSE/Guide
6
+ * adapter (when `ChatRuntime.endpoints.chatConversationsUrl` is set).
7
+ *
8
+ * Owns: the loaded page of `DialogItem`s, the server cursor, first-page
9
+ * loading/error state (with the retry re-arm), cursor pagination, an
10
+ * optional server-side search term (a change re-runs page 1), and the
11
+ * optimistic rename / archive / delete mutations with rollback.
12
+ *
13
+ * Does NOT own: which dialog is active, message history for a dialog, or
14
+ * the transport (`fetchDialogMessages`, subscriptions, catch-up). Those stay
15
+ * in the adapters — they are transport-specific. The adapters react to a
16
+ * row leaving the list through `onDialogRemoved` (drop the active id, evict
17
+ * the reducer store …) so ordering stays: host callback → local removal →
18
+ * adapter side effect, exactly as the NATS adapter did before extraction.
19
+ *
20
+ * Host callbacks are all optional: without `fetchDialogs` the hook is inert
21
+ * (empty list, no network) and a mutation without its callback is a no-op —
22
+ * the presence of a callback IS the capability, mirroring the NATS config.
23
+ */
24
+
25
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
26
+ import type { DialogItem } from '../types/component.types';
27
+ import type { FetchDialogsParams, FetchDialogsResult } from '../types/unified-chat-state.types';
28
+
29
+ export interface UseManagedDialogListArgs {
30
+ /** Gates the AUTOMATIC first-page load only (every other operation is
31
+ * caller-driven). The adapters pass their own `active` gate so an idle
32
+ * transport does no network. */
33
+ autoLoad: boolean;
34
+ /** Pages the active dialog list. Absent = the hook is inert. */
35
+ fetchDialogs?: (params: FetchDialogsParams) => Promise<FetchDialogsResult>;
36
+ /** Backend rename — absent = `renameDialog` is a no-op. */
37
+ renameDialog?: (id: string, title: string) => Promise<void>;
38
+ /** Backend archive — absent = `archiveDialog` is a no-op. */
39
+ archiveDialog?: (id: string) => Promise<void>;
40
+ /** Backend delete — absent = `deleteDialog` is a no-op. */
41
+ deleteDialog?: (id: string) => Promise<void>;
42
+ /** Page size sent as `limit`. */
43
+ pageSize: number;
44
+ /** Server-side search term. `undefined` = no search support (the NATS
45
+ * adapter never sets it, so its wire params stay `{cursor, limit}`); any
46
+ * string change — including back to `''` — reloads page 1 with `search`. */
47
+ search?: string;
48
+ /** Fires AFTER a row was removed locally by a successful archive/delete.
49
+ * Read through a latest-ref so its identity never enters the mutation
50
+ * callbacks' deps. */
51
+ onDialogRemoved?: (id: string, reason: 'archived' | 'deleted') => void;
52
+ /** Console prefix for failure logs (`[useNatsChatAdapter]`, `[useSseChatAdapter]`). */
53
+ logTag: string;
54
+ }
55
+
56
+ export interface UseManagedDialogListResult {
57
+ dialogs: DialogItem[];
58
+ dialogsNextCursor: string | null;
59
+ /** Skeleton flag — true while a page request is in flight. */
60
+ isDialogsLoading: boolean;
61
+ /** True when the FIRST page failed — a pagination failure keeps the loaded rows. */
62
+ dialogsError: boolean;
63
+ hasMoreDialogs: boolean;
64
+ /** Load a page: `undefined` cursor = (re)load the first page. */
65
+ loadDialogsPage: (cursor?: string) => Promise<void>;
66
+ /** Retry / refresh the first page. */
67
+ reloadDialogs: () => void;
68
+ loadMoreDialogs: () => Promise<void>;
69
+ renameDialog: (id: string, title: string) => Promise<void>;
70
+ archiveDialog: (id: string) => Promise<void>;
71
+ deleteDialog: (id: string) => Promise<void>;
72
+ /** Prepend a row (dedupes by id) — a freshly created conversation. */
73
+ upsertDialogTop: (item: DialogItem) => void;
74
+ /** Move an existing row to the head of the list with a fresh `timestamp` —
75
+ * what a new turn does server-side (`last_message_at desc`). No-op for an
76
+ * id the list doesn't hold. */
77
+ bumpDialogToTop: (id: string) => void;
78
+ }
79
+
80
+ export function useManagedDialogList({
81
+ autoLoad,
82
+ fetchDialogs,
83
+ renameDialog: renameDialogCallback,
84
+ archiveDialog: archiveDialogCallback,
85
+ deleteDialog: deleteDialogCallback,
86
+ pageSize,
87
+ search,
88
+ onDialogRemoved,
89
+ logTag,
90
+ }: UseManagedDialogListArgs): UseManagedDialogListResult {
91
+ const [dialogs, setDialogs] = useState<DialogItem[]>([]);
92
+ const [dialogsNextCursor, setDialogsNextCursor] = useState<string | null>(null);
93
+ const [isDialogsLoading, setIsDialogsLoading] = useState<boolean>(false);
94
+ // Which `search` value's FIRST PAGE has settled (`null` = the no-search
95
+ // case). `undefined` = nothing has settled yet. Seeded unsettled exactly when
96
+ // a load is coming, so `isDialogsLoading` reads true from the FIRST render
97
+ // rather than only once the effect fires — a consumer that branches on "the
98
+ // list is empty" would otherwise see a one-frame empty list on mount, and
99
+ // again on every search change, before the request starts.
100
+ const [settledSearch, setSettledSearch] = useState<string | null | undefined>(
101
+ autoLoad && fetchDialogs ? undefined : null,
102
+ );
103
+ // The seed above is a FIRST-RENDER value, so it misses a consumer that mounts
104
+ // with `autoLoad: false` and turns it on later (a panel opened in the other
105
+ // transport's mode, then switched into this one). Re-arm on that transition
106
+ // — adjusting state during render, the documented React pattern, guarded so
107
+ // the extra pass takes the early exit.
108
+ const [autoLoadWas, setAutoLoadWas] = useState(autoLoad);
109
+ if (autoLoad !== autoLoadWas) {
110
+ setAutoLoadWas(autoLoad);
111
+ if (autoLoad && fetchDialogs) setSettledSearch(undefined);
112
+ }
113
+ // A page request is in flight. A REF, not state: its only reader is
114
+ // `loadMoreDialogs`, which must see a page-1 load dispatched in the SAME
115
+ // tick — something a render-closure state value would miss.
116
+ const pendingRef = useRef(false);
117
+ const [dialogsError, setDialogsError] = useState<boolean>(false);
118
+
119
+ // Latest-list mirror for the optimistic mutations: the rollback title must
120
+ // be read SYNCHRONOUSLY at call time. Capturing it inside a `setDialogs`
121
+ // updater is not reliable — React may run the updater only at render time,
122
+ // after an immediately-rejecting callback has already reached the catch.
123
+ const dialogsRef = useRef<DialogItem[]>(dialogs);
124
+ useEffect(() => {
125
+ dialogsRef.current = dialogs;
126
+ });
127
+
128
+ const onDialogRemovedRef = useRef(onDialogRemoved);
129
+ useEffect(() => {
130
+ onDialogRemovedRef.current = onDialogRemoved;
131
+ });
132
+
133
+ // Released on a first-page failure so a retry / re-activation re-runs the
134
+ // initial load.
135
+ const initialDialogsLoadedRef = useRef(false);
136
+
137
+ // Monotonic request id. Page-1 loads overlap in normal use — a search-term
138
+ // change, the end-of-turn refresh and an unarchive all trigger one — so
139
+ // without this the LAST-RESOLVING response wins: the list can show results
140
+ // for an earlier search term under a newer query, paginate with the wrong
141
+ // cursor, or have its loading flag cleared while another fetch is still in
142
+ // flight. Only the latest request may touch the list/cursor/flags. (Same
143
+ // guard `useChatDialogManager.loadArchivedPage` has always carried.)
144
+ const requestIdRef = useRef(0);
145
+
146
+ const loadDialogsPage = useCallback(
147
+ async (cursor?: string): Promise<void> => {
148
+ if (!fetchDialogs) return;
149
+ const requestId = ++requestIdRef.current;
150
+ const isCurrent = () => requestIdRef.current === requestId;
151
+ pendingRef.current = true;
152
+ setIsDialogsLoading(true);
153
+ // Clear a prior first-page error when (re)loading the first page.
154
+ if (cursor === undefined) setDialogsError(false);
155
+ try {
156
+ const result = await fetchDialogs({
157
+ cursor,
158
+ limit: pageSize,
159
+ // Only hosts that run a search ever see the key.
160
+ ...(search !== undefined ? { search } : {}),
161
+ });
162
+ // Superseded by a newer load — drop the response entirely.
163
+ if (!isCurrent()) return;
164
+ setDialogsNextCursor(result.nextCursor);
165
+ if (cursor === undefined) {
166
+ setDialogs(result.dialogs);
167
+ } else {
168
+ // Dedupe on append: a row whose `last_message_at` moved between page
169
+ // fetches can come back on a later page, and duplicate ids mean
170
+ // duplicate React keys.
171
+ setDialogs(prev => {
172
+ const seen = new Set(prev.map(d => d.id));
173
+ return [...prev, ...result.dialogs.filter(d => !seen.has(d.id))];
174
+ });
175
+ }
176
+ } catch (err) {
177
+ if (!isCurrent()) return;
178
+ console.error(`${logTag} fetchDialogs failed:`, err);
179
+ // Only the FIRST page failing is a "can't show the list" error — a
180
+ // pagination failure keeps the already-loaded list intact. Flag it and
181
+ // release the initial-load guard so a retry (or re-activation) re-runs.
182
+ if (cursor === undefined) {
183
+ setDialogsError(true);
184
+ initialDialogsLoadedRef.current = false;
185
+ }
186
+ } finally {
187
+ // Only the latest request owns the shared flags.
188
+ if (isCurrent()) {
189
+ pendingRef.current = false;
190
+ if (cursor === undefined) setSettledSearch(search ?? null);
191
+ setIsDialogsLoading(false);
192
+ }
193
+ }
194
+ },
195
+ [fetchDialogs, pageSize, search, logTag],
196
+ );
197
+
198
+ const reloadDialogs = useCallback(() => {
199
+ void loadDialogsPage();
200
+ }, [loadDialogsPage]);
201
+
202
+ // Initial dialog list load — and, for hosts that run a search, the page-1
203
+ // reload on every term change (the term the loaded page was fetched for is
204
+ // remembered so the same term never double-loads). Inert for hosts that
205
+ // never set `search` (NATS): `loadedSearchRef` stays `undefined` there and
206
+ // the once-guard alone decides.
207
+ const loadedSearchRef = useRef<string | undefined>(undefined);
208
+ useEffect(() => {
209
+ if (!fetchDialogs) return;
210
+ if (!autoLoad) return;
211
+ if (initialDialogsLoadedRef.current && loadedSearchRef.current === search) return;
212
+ initialDialogsLoadedRef.current = true;
213
+ loadedSearchRef.current = search;
214
+ void loadDialogsPage();
215
+ }, [autoLoad, fetchDialogs, search, loadDialogsPage]);
216
+
217
+ const removeLocal = useCallback((id: string) => {
218
+ setDialogs(prev => prev.filter(d => d.id !== id));
219
+ }, []);
220
+
221
+ const deleteDialog = useCallback(
222
+ async (id: string): Promise<void> => {
223
+ if (!deleteDialogCallback) return;
224
+ try {
225
+ await deleteDialogCallback(id);
226
+ removeLocal(id);
227
+ onDialogRemovedRef.current?.(id, 'deleted');
228
+ } catch (err) {
229
+ console.error(`${logTag} deleteDialog failed:`, err);
230
+ // Re-thrown: a caller that opened a confirmation modal must be able to
231
+ // keep it open and NOT tear down the open thread for a write that
232
+ // never landed (`useChatDialogManager.handleConfirmArchive`).
233
+ throw err;
234
+ }
235
+ },
236
+ [deleteDialogCallback, removeLocal, logTag],
237
+ );
238
+
239
+ const renameDialog = useCallback(
240
+ async (id: string, title: string): Promise<void> => {
241
+ if (!renameDialogCallback) return;
242
+ // Optimistic — update the local title immediately, roll back on error.
243
+ const previous = dialogsRef.current.find(d => d.id === id)?.title;
244
+ setDialogs(prev => prev.map(d => (d.id === id ? { ...d, title } : d)));
245
+ try {
246
+ await renameDialogCallback(id, title);
247
+ } catch (err) {
248
+ // SWALLOWED, unlike archive/delete. `useChatDialogManager` fires rename
249
+ // as `void renameDialog(...)` and closes its modal immediately, so a
250
+ // rejection here would surface only as an unhandled rejection. The
251
+ // optimistic rollback below is the user-visible signal, exactly as the
252
+ // pre-extraction NATS adapter behaved.
253
+ console.error(`${logTag} renameDialog failed:`, err);
254
+ if (previous !== undefined) {
255
+ setDialogs(prev => prev.map(d => (d.id === id ? { ...d, title: previous } : d)));
256
+ }
257
+ }
258
+ },
259
+ [renameDialogCallback, logTag],
260
+ );
261
+
262
+ const archiveDialog = useCallback(
263
+ async (id: string): Promise<void> => {
264
+ if (!archiveDialogCallback) return;
265
+ try {
266
+ await archiveDialogCallback(id);
267
+ removeLocal(id);
268
+ onDialogRemovedRef.current?.(id, 'archived');
269
+ } catch (err) {
270
+ console.error(`${logTag} archiveDialog failed:`, err);
271
+ // Re-thrown so `useChatDialogManager.handleConfirmArchive` can keep the
272
+ // confirmation modal open for a retry instead of closing it and wiping
273
+ // the open conversation over a write the server rejected.
274
+ throw err;
275
+ }
276
+ },
277
+ [archiveDialogCallback, removeLocal, logTag],
278
+ );
279
+
280
+ const loadMoreDialogs = useCallback(async (): Promise<void> => {
281
+ if (!dialogsNextCursor) return;
282
+ // A page-1 reload in flight will REPLACE the list and the cursor, so an
283
+ // append started now would land on a list that no longer exists, using a
284
+ // stale cursor. Skip it; the reload's own result is the fresh page 1.
285
+ if (pendingRef.current) return;
286
+ await loadDialogsPage(dialogsNextCursor);
287
+ }, [dialogsNextCursor, loadDialogsPage]);
288
+
289
+ const upsertDialogTop = useCallback((item: DialogItem) => {
290
+ setDialogs(prev => [item, ...prev.filter(d => d.id !== item.id)]);
291
+ }, []);
292
+
293
+ const bumpDialogToTop = useCallback((id: string) => {
294
+ setDialogs(prev => {
295
+ const row = prev.find(d => d.id === id);
296
+ if (!row) return prev;
297
+ return [{ ...row, timestamp: new Date() }, ...prev.filter(d => d.id !== id)];
298
+ });
299
+ }, []);
300
+
301
+ const hasMoreDialogs = dialogsNextCursor != null;
302
+ // Reported as loading until the first page for the CURRENT search settles —
303
+ // see `settledSearch`.
304
+ const awaitingFirstPage = !!fetchDialogs && settledSearch !== (search ?? null);
305
+ const dialogsLoading = isDialogsLoading || awaitingFirstPage;
306
+
307
+ return useMemo<UseManagedDialogListResult>(
308
+ () => ({
309
+ dialogs,
310
+ dialogsNextCursor,
311
+ isDialogsLoading: dialogsLoading,
312
+ dialogsError,
313
+ hasMoreDialogs,
314
+ loadDialogsPage,
315
+ reloadDialogs,
316
+ loadMoreDialogs,
317
+ renameDialog,
318
+ archiveDialog,
319
+ deleteDialog,
320
+ upsertDialogTop,
321
+ bumpDialogToTop,
322
+ }),
323
+ [
324
+ dialogs,
325
+ dialogsNextCursor,
326
+ dialogsLoading,
327
+ dialogsError,
328
+ hasMoreDialogs,
329
+ loadDialogsPage,
330
+ reloadDialogs,
331
+ loadMoreDialogs,
332
+ renameDialog,
333
+ archiveDialog,
334
+ deleteDialog,
335
+ upsertDialogTop,
336
+ bumpDialogToTop,
337
+ ],
338
+ );
339
+ }
@@ -62,10 +62,12 @@ import type {
62
62
  NatsMessageType,
63
63
  ChatApprovalStatus,
64
64
  } from '../types';
65
- import type { DialogItem } from '../types/component.types';
66
65
  import type {
67
66
  ChatConnectionState,
67
+ ChatDialogCapabilities,
68
68
  DialogTokenUsage,
69
+ FetchDialogsParams,
70
+ FetchDialogsResult,
69
71
  UnifiedChatState,
70
72
  UnifiedChatMessage,
71
73
  UnifiedSendMessageOptions,
@@ -74,6 +76,7 @@ import { buildDiscussPrompt } from '../utils/discuss-ref-prompt';
74
76
  import { extractIncompleteTailState } from '../utils/extract-incomplete-message-state';
75
77
  import { processHistoricalMessagesWithErrors } from '../utils/process-historical-messages';
76
78
  import { useChunkCatchup } from './use-chunk-catchup';
79
+ import { useManagedDialogList } from './use-managed-dialog-list';
77
80
  import { useNatsDialogSubscription } from './use-nats-dialog-subscription';
78
81
 
79
82
  // Legacy public home of the pure message-mutation helpers ("exported for
@@ -90,21 +93,11 @@ export {
90
93
  // Config + options
91
94
  // =============================================================================
92
95
 
93
- /** Page-fetch parameters passed to `fetchDialogs`. The adapter owns the
94
- * cursor — the host only resolves it against the backend. */
95
- export interface FetchDialogsParams {
96
- cursor?: string;
97
- limit?: number;
98
- search?: string;
99
- }
100
-
101
- /** Successful `fetchDialogs` response. `nextCursor: null` means "no more
102
- * pages" — used to terminate the infinite-scroll observer in the
103
- * sidebar. */
104
- export interface FetchDialogsResult {
105
- dialogs: DialogItem[];
106
- nextCursor: string | null;
107
- }
96
+ // `FetchDialogsParams` / `FetchDialogsResult` moved to the unified types
97
+ // module (they are the host contract of the SHARED `useManagedDialogList`
98
+ // hook, consumed by both adapters); re-exported here so the public import
99
+ // path stays stable.
100
+ export type { FetchDialogsParams, FetchDialogsResult } from '../types/unified-chat-state.types';
108
101
 
109
102
  /** Page-fetch parameters passed to `fetchDialogMessages`. */
110
103
  export interface FetchDialogMessagesParams {
@@ -422,6 +415,8 @@ export function useNatsChatAdapter(
422
415
  deleteDialog: deleteDialogCallback,
423
416
  renameDialog: renameDialogCallback,
424
417
  archiveDialog: archiveDialogCallback,
418
+ fetchArchivedDialogs,
419
+ unarchiveDialog,
425
420
  approveRequest: approveRequestCallback,
426
421
  rejectRequest: rejectRequestCallback,
427
422
  stopGeneration: stopGenerationCallback,
@@ -570,12 +565,37 @@ export function useNatsChatAdapter(
570
565
  );
571
566
 
572
567
  // ─── Dialog list state (managed-dialog mode only) ─────────────────────────
568
+ // The list state machine itself is the SHARED `useManagedDialogList`
569
+ // (also behind the SSE/Guide adapter); this adapter only layers the
570
+ // active-id + reducer-store side effects on top via `onDialogRemoved`.
573
571
 
574
- const [dialogs, setDialogs] = useState<DialogItem[]>([]);
575
- const [dialogsNextCursor, setDialogsNextCursor] = useState<string | null>(null);
576
- const [isDialogsLoading, setIsDialogsLoading] = useState<boolean>(false);
577
- const [dialogsError, setDialogsError] = useState<boolean>(false);
578
572
  const [isCreatingDialog, setIsCreatingDialog] = useState<boolean>(false);
573
+ const {
574
+ dialogs,
575
+ isDialogsLoading,
576
+ dialogsError,
577
+ hasMoreDialogs,
578
+ reloadDialogs,
579
+ loadMoreDialogs,
580
+ renameDialog,
581
+ archiveDialog,
582
+ deleteDialog,
583
+ upsertDialogTop,
584
+ } = useManagedDialogList({
585
+ autoLoad: active,
586
+ fetchDialogs,
587
+ renameDialog: renameDialogCallback,
588
+ archiveDialog: archiveDialogCallback,
589
+ deleteDialog: deleteDialogCallback,
590
+ pageSize: dialogsPageSize,
591
+ logTag: '[useNatsChatAdapter]',
592
+ onDialogRemoved: (id, reason) => {
593
+ if (reason === 'deleted') dialogStore.remove(id);
594
+ if (isManagedMode && internalDialogId === id) {
595
+ setInternalDialogId(null);
596
+ }
597
+ },
598
+ });
579
599
 
580
600
  // ─── Message-history pagination ───────────────────────────────────────────
581
601
 
@@ -861,59 +881,6 @@ export function useNatsChatAdapter(
861
881
  const connectionState: ChatConnectionState =
862
882
  !active || !dialogId ? 'connected' : connectedForDialog === dialogId ? 'connected' : 'connecting';
863
883
 
864
- // ─── Dialog list management (managed-dialog mode) ─────────────────────────
865
-
866
- // Forward-declared so `loadDialogsPage` can reset the initial-load guard on
867
- // a first-page failure (enabling retry / auto-retry on re-activation).
868
- const initialDialogsLoadedRef = useRef(false);
869
-
870
- const loadDialogsPage = useCallback(
871
- async (cursor?: string): Promise<void> => {
872
- if (!fetchDialogs) return;
873
- setIsDialogsLoading(true);
874
- // Clear a prior first-page error when (re)loading the first page.
875
- if (cursor === undefined) setDialogsError(false);
876
- try {
877
- const result = await fetchDialogs({
878
- cursor,
879
- limit: dialogsPageSize,
880
- });
881
- setDialogsNextCursor(result.nextCursor);
882
- if (cursor === undefined) {
883
- setDialogs(result.dialogs);
884
- } else {
885
- setDialogs(prev => [...prev, ...result.dialogs]);
886
- }
887
- } catch (err) {
888
- console.error('[useNatsChatAdapter] fetchDialogs failed:', err);
889
- // Only the FIRST page failing is a "can't show the list" error — a
890
- // pagination failure keeps the already-loaded list intact. Flag it and
891
- // release the initial-load guard so a retry (or re-activation) re-runs.
892
- if (cursor === undefined) {
893
- setDialogsError(true);
894
- initialDialogsLoadedRef.current = false;
895
- }
896
- } finally {
897
- setIsDialogsLoading(false);
898
- }
899
- },
900
- [fetchDialogs, dialogsPageSize],
901
- );
902
-
903
- // Retry the initial dialog-list load after a failure.
904
- const reloadDialogs = useCallback(() => {
905
- void loadDialogsPage();
906
- }, [loadDialogsPage]);
907
-
908
- // Initial dialog list load.
909
- useEffect(() => {
910
- if (!fetchDialogs) return;
911
- if (!active) return;
912
- if (initialDialogsLoadedRef.current) return;
913
- initialDialogsLoadedRef.current = true;
914
- void loadDialogsPage();
915
- }, [active, fetchDialogs, loadDialogsPage]);
916
-
917
884
  // ─── Public action handlers ───────────────────────────────────────────────
918
885
 
919
886
  const sendMessage = useCallback(
@@ -968,14 +935,11 @@ export function useNatsChatAdapter(
968
935
  // Optimistically prepend a placeholder dialog so the sidebar shows
969
936
  // the new conversation immediately. The next list refresh will
970
937
  // replace it with the canonical entry.
971
- setDialogs(prev => [
972
- {
973
- id: result.dialogId,
974
- title: 'New Chat',
975
- timestamp: new Date(),
976
- },
977
- ...prev.filter(d => d.id !== result.dialogId),
978
- ]);
938
+ upsertDialogTop({
939
+ id: result.dialogId,
940
+ title: 'New Chat',
941
+ timestamp: new Date(),
942
+ });
979
943
  if (isManagedMode) {
980
944
  setInternalDialogId(result.dialogId);
981
945
  }
@@ -986,74 +950,7 @@ export function useNatsChatAdapter(
986
950
  } finally {
987
951
  setIsCreatingDialog(false);
988
952
  }
989
- }, [createDialogCallback, isCreatingDialog, isManagedMode]);
990
-
991
- const deleteDialog = useCallback(
992
- async (id: string): Promise<void> => {
993
- if (!deleteDialogCallback) return;
994
- try {
995
- await deleteDialogCallback(id);
996
- setDialogs(prev => prev.filter(d => d.id !== id));
997
- dialogStore.remove(id);
998
- if (isManagedMode && internalDialogId === id) {
999
- setInternalDialogId(null);
1000
- }
1001
- } catch (err) {
1002
- console.error('[useNatsChatAdapter] deleteDialog failed:', err);
1003
- }
1004
- },
1005
- [deleteDialogCallback, dialogStore, internalDialogId, isManagedMode],
1006
- );
1007
-
1008
- const renameDialog = useCallback(
1009
- async (id: string, title: string): Promise<void> => {
1010
- if (!renameDialogCallback) return;
1011
- // Optimistic — update the local title immediately, roll back on error.
1012
- let previous: string | undefined;
1013
- setDialogs(prev =>
1014
- prev.map(d => {
1015
- if (d.id !== id) return d;
1016
- previous = d.title;
1017
- return { ...d, title };
1018
- }),
1019
- );
1020
- try {
1021
- await renameDialogCallback(id, title);
1022
- } catch (err) {
1023
- console.error('[useNatsChatAdapter] renameDialog failed:', err);
1024
- // `previous` is a `let` written from inside the optimistic updater, so
1025
- // its narrowing does not reach the rollback closure. Freeze it into a
1026
- // const first — that is also what pins the rollback to the title we
1027
- // actually replaced.
1028
- const rollbackTitle = previous;
1029
- if (rollbackTitle !== undefined) {
1030
- setDialogs(prev => prev.map(d => (d.id === id ? { ...d, title: rollbackTitle } : d)));
1031
- }
1032
- }
1033
- },
1034
- [renameDialogCallback],
1035
- );
1036
-
1037
- const archiveDialog = useCallback(
1038
- async (id: string): Promise<void> => {
1039
- if (!archiveDialogCallback) return;
1040
- try {
1041
- await archiveDialogCallback(id);
1042
- setDialogs(prev => prev.filter(d => d.id !== id));
1043
- if (isManagedMode && internalDialogId === id) {
1044
- setInternalDialogId(null);
1045
- }
1046
- } catch (err) {
1047
- console.error('[useNatsChatAdapter] archiveDialog failed:', err);
1048
- }
1049
- },
1050
- [archiveDialogCallback, internalDialogId, isManagedMode],
1051
- );
1052
-
1053
- const loadMoreDialogs = useCallback(async (): Promise<void> => {
1054
- if (!dialogsNextCursor) return;
1055
- await loadDialogsPage(dialogsNextCursor);
1056
- }, [dialogsNextCursor, loadDialogsPage]);
953
+ }, [createDialogCallback, isCreatingDialog, isManagedMode, upsertDialogTop]);
1057
954
 
1058
955
  const loadMoreMessages = useCallback(async (): Promise<void> => {
1059
956
  if (!dialogId || !messagesNextCursor) return;
@@ -1102,9 +999,23 @@ export function useNatsChatAdapter(
1102
999
 
1103
1000
  const { messages, streamingPhase, dialogTokenUsage = null, liveModel = null } = state;
1104
1001
  const isLoading = streamingPhase !== 'idle';
1105
- const hasMoreDialogs = dialogsNextCursor != null;
1106
1002
  const hasMoreMessages = messagesNextCursor != null;
1107
1003
 
1004
+ // Capabilities for `EmbeddableChat` — the presence of a host callback IS the
1005
+ // capability (same rule the legacy per-mode derivation applied).
1006
+ const dialogCapabilities = useMemo<ChatDialogCapabilities | undefined>(
1007
+ () =>
1008
+ isManagedMode
1009
+ ? {
1010
+ canRename: !!renameDialogCallback,
1011
+ canArchive: !!archiveDialogCallback,
1012
+ fetchArchivedDialogs,
1013
+ unarchiveDialog,
1014
+ }
1015
+ : undefined,
1016
+ [isManagedMode, renameDialogCallback, archiveDialogCallback, fetchArchivedDialogs, unarchiveDialog],
1017
+ );
1018
+
1108
1019
  return useMemo<UnifiedChatState>(
1109
1020
  () => ({
1110
1021
  messages,
@@ -1142,6 +1053,8 @@ export function useNatsChatAdapter(
1142
1053
  loadMoreDialogs,
1143
1054
  hasMoreMessages,
1144
1055
  loadMoreMessages,
1056
+ dialogsManaged: isManagedMode,
1057
+ dialogCapabilities,
1145
1058
  // Approval mutations
1146
1059
  approveRequest,
1147
1060
  rejectRequest,
@@ -1174,6 +1087,8 @@ export function useNatsChatAdapter(
1174
1087
  loadMoreDialogs,
1175
1088
  hasMoreMessages,
1176
1089
  loadMoreMessages,
1090
+ isManagedMode,
1091
+ dialogCapabilities,
1177
1092
  approveRequest,
1178
1093
  rejectRequest,
1179
1094
  dialogTokenUsage,