@flamingo-stack/openframe-frontend-core 0.0.597 → 0.0.598-2039.5702.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 (186) hide show
  1. package/dist/{chunk-PT54TJWD.js → chunk-26MKONC3.js} +5 -5
  2. package/dist/{chunk-NK6COZ3P.cjs → chunk-2TWJF4AB.cjs} +22 -22
  3. package/dist/{chunk-NK6COZ3P.cjs.map → chunk-2TWJF4AB.cjs.map} +1 -1
  4. package/dist/{chunk-E74GL4E3.cjs → chunk-3GLZDKWZ.cjs} +8 -8
  5. package/dist/{chunk-E74GL4E3.cjs.map → chunk-3GLZDKWZ.cjs.map} +1 -1
  6. package/dist/{chunk-STYNZ4QM.cjs → chunk-3IXDZI3R.cjs} +3 -3
  7. package/dist/{chunk-STYNZ4QM.cjs.map → chunk-3IXDZI3R.cjs.map} +1 -1
  8. package/dist/{chunk-DNQP4VPB.js → chunk-3XHNV6W7.js} +12 -12
  9. package/dist/{chunk-TVK7PQON.js → chunk-442V6CPU.js} +6 -6
  10. package/dist/{chunk-BZ4UEHNJ.js → chunk-5IMAIYID.js} +9 -9
  11. package/dist/{chunk-VQ6INRQ4.cjs → chunk-5VQKQIOG.cjs} +105 -105
  12. package/dist/{chunk-VQ6INRQ4.cjs.map → chunk-5VQKQIOG.cjs.map} +1 -1
  13. package/dist/{chunk-6QZNDPMV.cjs → chunk-7WTEFZP7.cjs} +9 -9
  14. package/dist/{chunk-6QZNDPMV.cjs.map → chunk-7WTEFZP7.cjs.map} +1 -1
  15. package/dist/{chunk-B4BZRBKC.js → chunk-7YMVB7GE.js} +4 -4
  16. package/dist/{chunk-BOILDHSY.js → chunk-AC2TI6UT.js} +12 -12
  17. package/dist/{chunk-YBPFIXV4.cjs → chunk-B6ZJV7L4.cjs} +746 -448
  18. package/dist/{chunk-YBPFIXV4.cjs.map → chunk-B6ZJV7L4.cjs.map} +1 -1
  19. package/dist/{chunk-RYZKWZBG.cjs → chunk-B72CD6YE.cjs} +15 -15
  20. package/dist/{chunk-RYZKWZBG.cjs.map → chunk-B72CD6YE.cjs.map} +1 -1
  21. package/dist/{chunk-EVMHJB6X.js → chunk-BLUL2TE3.js} +4 -4
  22. package/dist/{chunk-GGQZBSFN.js → chunk-BVQEU5JB.js} +2 -2
  23. package/dist/{chunk-H64ZHSYR.cjs → chunk-CCWI3622.cjs} +4 -4
  24. package/dist/{chunk-H64ZHSYR.cjs.map → chunk-CCWI3622.cjs.map} +1 -1
  25. package/dist/{chunk-ELG2QNW5.js → chunk-D7X33EAT.js} +7 -7
  26. package/dist/{chunk-L3L2ATFK.cjs → chunk-E2K2LYSM.cjs} +85 -85
  27. package/dist/{chunk-L3L2ATFK.cjs.map → chunk-E2K2LYSM.cjs.map} +1 -1
  28. package/dist/{chunk-YH6IQTPI.cjs → chunk-EHAYNUOL.cjs} +3 -3
  29. package/dist/{chunk-YH6IQTPI.cjs.map → chunk-EHAYNUOL.cjs.map} +1 -1
  30. package/dist/{chunk-WZJOILPU.js → chunk-F2KBCLUG.js} +2 -2
  31. package/dist/{chunk-MYBXCWEI.js → chunk-FKBM6U43.js} +2 -2
  32. package/dist/{chunk-FKOYQPMK.js → chunk-GQLYYZF4.js} +5 -5
  33. package/dist/{chunk-LRQCKSZC.js → chunk-IW746HJ7.js} +2 -2
  34. package/dist/{chunk-GKZUTZT3.cjs → chunk-JI2R4UW5.cjs} +15 -15
  35. package/dist/{chunk-GKZUTZT3.cjs.map → chunk-JI2R4UW5.cjs.map} +1 -1
  36. package/dist/{chunk-M4YQUHOR.cjs → chunk-JJUV7Z4L.cjs} +15 -15
  37. package/dist/{chunk-M4YQUHOR.cjs.map → chunk-JJUV7Z4L.cjs.map} +1 -1
  38. package/dist/{chunk-2JOIC34G.cjs → chunk-KJMXCDYI.cjs} +37 -37
  39. package/dist/{chunk-2JOIC34G.cjs.map → chunk-KJMXCDYI.cjs.map} +1 -1
  40. package/dist/{chunk-IRXLB6GV.js → chunk-KV24I5MD.js} +5 -5
  41. package/dist/{chunk-Z4QFA4BF.cjs → chunk-M7U3MT2Q.cjs} +14 -14
  42. package/dist/{chunk-Z4QFA4BF.cjs.map → chunk-M7U3MT2Q.cjs.map} +1 -1
  43. package/dist/{chunk-R2YJKREE.js → chunk-NJCVIERS.js} +4 -4
  44. package/dist/{chunk-VXEHG53O.js → chunk-OIUXJUMH.js} +6 -6
  45. package/dist/{chunk-SAEJGTCI.cjs → chunk-QPAPUIF3.cjs} +35 -35
  46. package/dist/{chunk-SAEJGTCI.cjs.map → chunk-QPAPUIF3.cjs.map} +1 -1
  47. package/dist/{chunk-CPJP7GKL.cjs → chunk-R6LFBCGC.cjs} +3 -3
  48. package/dist/{chunk-CPJP7GKL.cjs.map → chunk-R6LFBCGC.cjs.map} +1 -1
  49. package/dist/{chunk-FHWL7QFL.js → chunk-RTCKC6RH.js} +5 -5
  50. package/dist/{chunk-UAAXUFK6.js → chunk-RU3IKVY2.js} +3 -3
  51. package/dist/{chunk-EZM5DNII.js → chunk-S6WBBSII.js} +3 -3
  52. package/dist/{chunk-WWGSYT7R.js → chunk-SYFSVIGH.js} +2 -2
  53. package/dist/{chunk-R2MOCGZ7.cjs → chunk-SZRP4264.cjs} +34 -34
  54. package/dist/{chunk-R2MOCGZ7.cjs.map → chunk-SZRP4264.cjs.map} +1 -1
  55. package/dist/{chunk-2JNCZDJR.js → chunk-TSCIVH7T.js} +2 -2
  56. package/dist/{chunk-JJFYMYBJ.cjs → chunk-TYENRLNN.cjs} +39 -39
  57. package/dist/{chunk-JJFYMYBJ.cjs.map → chunk-TYENRLNN.cjs.map} +1 -1
  58. package/dist/{chunk-EGQ345IA.js → chunk-UHWDSVZI.js} +4 -4
  59. package/dist/{chunk-RDTOMWDN.cjs → chunk-UPKZU6QU.cjs} +1 -1
  60. package/dist/chunk-UPKZU6QU.cjs.map +1 -0
  61. package/dist/{chunk-WCBRZCU4.cjs → chunk-UQEOAPAI.cjs} +9 -9
  62. package/dist/{chunk-WCBRZCU4.cjs.map → chunk-UQEOAPAI.cjs.map} +1 -1
  63. package/dist/{chunk-O4VZOA2Q.cjs → chunk-UXOOVP77.cjs} +3 -3
  64. package/dist/{chunk-O4VZOA2Q.cjs.map → chunk-UXOOVP77.cjs.map} +1 -1
  65. package/dist/{chunk-BZEWPW5A.cjs → chunk-VIBREYUK.cjs} +3 -3
  66. package/dist/{chunk-BZEWPW5A.cjs.map → chunk-VIBREYUK.cjs.map} +1 -1
  67. package/dist/{chunk-E27AKT4A.cjs → chunk-WRZV3HGH.cjs} +9 -9
  68. package/dist/{chunk-E27AKT4A.cjs.map → chunk-WRZV3HGH.cjs.map} +1 -1
  69. package/dist/{chunk-PIQRGLTF.cjs → chunk-WU53IOY6.cjs} +25 -25
  70. package/dist/{chunk-PIQRGLTF.cjs.map → chunk-WU53IOY6.cjs.map} +1 -1
  71. package/dist/{chunk-VNSRNVPD.js → chunk-XAJZIDFH.js} +673 -375
  72. package/dist/chunk-XAJZIDFH.js.map +1 -0
  73. package/dist/{chunk-UIVLSMEZ.cjs → chunk-XRVFQQ7W.cjs} +242 -242
  74. package/dist/{chunk-UIVLSMEZ.cjs.map → chunk-XRVFQQ7W.cjs.map} +1 -1
  75. package/dist/{chunk-RYXIRVDC.js → chunk-YB6FI2G3.js} +1 -1
  76. package/dist/chunk-YB6FI2G3.js.map +1 -0
  77. package/dist/{chunk-V6KX4KO3.js → chunk-YPJB4LJD.js} +3 -3
  78. package/dist/components/case-studies/index.cjs +14 -14
  79. package/dist/components/case-studies/index.js +8 -8
  80. package/dist/components/chat/hooks/index.d.ts +1 -0
  81. package/dist/components/chat/hooks/index.d.ts.map +1 -1
  82. package/dist/components/chat/hooks/use-chat-history-hydration.d.ts +5 -3
  83. package/dist/components/chat/hooks/use-chat-history-hydration.d.ts.map +1 -1
  84. package/dist/components/chat/hooks/use-managed-dialog-list.d.ts +49 -0
  85. package/dist/components/chat/hooks/use-managed-dialog-list.d.ts.map +1 -0
  86. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +2 -16
  87. package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
  88. package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
  89. package/dist/components/chat/hooks/use-unified-chat.d.ts.map +1 -1
  90. package/dist/components/chat/index.cjs +9 -5
  91. package/dist/components/chat/index.cjs.map +1 -1
  92. package/dist/components/chat/index.js +8 -4
  93. package/dist/components/chat/types/unified-chat-state.types.d.ts +55 -0
  94. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  95. package/dist/components/chat/utils/chat-conversations-api.d.ts +29 -0
  96. package/dist/components/chat/utils/chat-conversations-api.d.ts.map +1 -0
  97. package/dist/components/chat/utils/index.d.ts +1 -0
  98. package/dist/components/chat/utils/index.d.ts.map +1 -1
  99. package/dist/components/contact/index.cjs +9 -9
  100. package/dist/components/contact/index.js +8 -8
  101. package/dist/components/docs/index.cjs +12 -12
  102. package/dist/components/docs/index.js +11 -11
  103. package/dist/components/embeds/index.cjs +9 -9
  104. package/dist/components/embeds/index.js +8 -8
  105. package/dist/components/faq/index.cjs +10 -10
  106. package/dist/components/faq/index.js +9 -9
  107. package/dist/components/features/index.cjs +8 -8
  108. package/dist/components/features/index.js +7 -7
  109. package/dist/components/help-center-pages/index.cjs +31 -31
  110. package/dist/components/help-center-pages/index.js +22 -22
  111. package/dist/components/index.cjs +70 -66
  112. package/dist/components/index.cjs.map +1 -1
  113. package/dist/components/index.js +26 -22
  114. package/dist/components/index.js.map +1 -1
  115. package/dist/components/meeting-scheduler/index.cjs +49 -49
  116. package/dist/components/meeting-scheduler/index.js +9 -9
  117. package/dist/components/navigation/index.cjs +11 -11
  118. package/dist/components/navigation/index.js +10 -10
  119. package/dist/components/onboarding-guides/index.cjs +12 -12
  120. package/dist/components/onboarding-guides/index.js +11 -11
  121. package/dist/components/related-content/index.cjs +7 -7
  122. package/dist/components/related-content/index.js +6 -6
  123. package/dist/components/tickets/index.cjs +13 -13
  124. package/dist/components/tickets/index.js +12 -12
  125. package/dist/components/ui/index.cjs +12 -8
  126. package/dist/components/ui/index.cjs.map +1 -1
  127. package/dist/components/ui/index.js +11 -7
  128. package/dist/contexts/chat-runtime-context.d.ts +12 -0
  129. package/dist/contexts/chat-runtime-context.d.ts.map +1 -1
  130. package/dist/contexts/index.cjs +2 -2
  131. package/dist/contexts/index.js +1 -1
  132. package/dist/hooks/index.cjs +5 -5
  133. package/dist/hooks/index.js +4 -4
  134. package/dist/index.cjs +16 -12
  135. package/dist/index.cjs.map +1 -1
  136. package/dist/index.js +15 -11
  137. package/dist/index.js.map +1 -1
  138. package/package.json +1 -1
  139. package/src/components/chat/.embeddable-chat.md +2 -1
  140. package/src/components/chat/embeddable-chat.tsx +69 -37
  141. package/src/components/chat/hooks/.use-managed-dialog-list.md +28 -0
  142. package/src/components/chat/hooks/.use-nats-chat-adapter.md +2 -0
  143. package/src/components/chat/hooks/.use-sse-chat-adapter.md +7 -0
  144. package/src/components/chat/hooks/.use-unified-chat.md +1 -1
  145. package/src/components/chat/hooks/__tests__/managed-dialog-list.test.ts +92 -0
  146. package/src/components/chat/hooks/__tests__/nats-adapter-managed-dialogs.test.ts +167 -0
  147. package/src/components/chat/hooks/__tests__/sse-managed-dialogs.test.ts +256 -0
  148. package/src/components/chat/hooks/index.ts +2 -0
  149. package/src/components/chat/hooks/use-chat-history-hydration.ts +8 -7
  150. package/src/components/chat/hooks/use-managed-dialog-list.ts +263 -0
  151. package/src/components/chat/hooks/use-nats-chat-adapter.ts +65 -150
  152. package/src/components/chat/hooks/use-sse-chat-adapter.ts +213 -39
  153. package/src/components/chat/hooks/use-unified-chat.ts +5 -0
  154. package/src/components/chat/types/unified-chat-state.types.ts +62 -0
  155. package/src/components/chat/utils/.chat-conversations-api.md +16 -0
  156. package/src/components/chat/utils/__tests__/chat-conversations-api-golden.test.ts +90 -0
  157. package/src/components/chat/utils/chat-conversations-api.ts +92 -0
  158. package/src/components/chat/utils/index.ts +7 -0
  159. package/src/contexts/.chat-runtime-context.md +2 -0
  160. package/src/contexts/chat-runtime-context.tsx +12 -0
  161. package/dist/chunk-RDTOMWDN.cjs.map +0 -1
  162. package/dist/chunk-RYXIRVDC.js.map +0 -1
  163. package/dist/chunk-VNSRNVPD.js.map +0 -1
  164. /package/dist/{chunk-PT54TJWD.js.map → chunk-26MKONC3.js.map} +0 -0
  165. /package/dist/{chunk-DNQP4VPB.js.map → chunk-3XHNV6W7.js.map} +0 -0
  166. /package/dist/{chunk-TVK7PQON.js.map → chunk-442V6CPU.js.map} +0 -0
  167. /package/dist/{chunk-BZ4UEHNJ.js.map → chunk-5IMAIYID.js.map} +0 -0
  168. /package/dist/{chunk-B4BZRBKC.js.map → chunk-7YMVB7GE.js.map} +0 -0
  169. /package/dist/{chunk-BOILDHSY.js.map → chunk-AC2TI6UT.js.map} +0 -0
  170. /package/dist/{chunk-EVMHJB6X.js.map → chunk-BLUL2TE3.js.map} +0 -0
  171. /package/dist/{chunk-GGQZBSFN.js.map → chunk-BVQEU5JB.js.map} +0 -0
  172. /package/dist/{chunk-ELG2QNW5.js.map → chunk-D7X33EAT.js.map} +0 -0
  173. /package/dist/{chunk-WZJOILPU.js.map → chunk-F2KBCLUG.js.map} +0 -0
  174. /package/dist/{chunk-MYBXCWEI.js.map → chunk-FKBM6U43.js.map} +0 -0
  175. /package/dist/{chunk-FKOYQPMK.js.map → chunk-GQLYYZF4.js.map} +0 -0
  176. /package/dist/{chunk-LRQCKSZC.js.map → chunk-IW746HJ7.js.map} +0 -0
  177. /package/dist/{chunk-IRXLB6GV.js.map → chunk-KV24I5MD.js.map} +0 -0
  178. /package/dist/{chunk-R2YJKREE.js.map → chunk-NJCVIERS.js.map} +0 -0
  179. /package/dist/{chunk-VXEHG53O.js.map → chunk-OIUXJUMH.js.map} +0 -0
  180. /package/dist/{chunk-FHWL7QFL.js.map → chunk-RTCKC6RH.js.map} +0 -0
  181. /package/dist/{chunk-UAAXUFK6.js.map → chunk-RU3IKVY2.js.map} +0 -0
  182. /package/dist/{chunk-EZM5DNII.js.map → chunk-S6WBBSII.js.map} +0 -0
  183. /package/dist/{chunk-WWGSYT7R.js.map → chunk-SYFSVIGH.js.map} +0 -0
  184. /package/dist/{chunk-2JNCZDJR.js.map → chunk-TSCIVH7T.js.map} +0 -0
  185. /package/dist/{chunk-EGQ345IA.js.map → chunk-UHWDSVZI.js.map} +0 -0
  186. /package/dist/{chunk-V6KX4KO3.js.map → chunk-YPJB4LJD.js.map} +0 -0
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Unit tests for the shared `useManagedDialogList` hook — the parts the NATS
3
+ * characterization test cannot reach: `upsertDialogTop` dedupe, `patchDialog`,
4
+ * the `onDialogRemoved` reasons, and the inert no-`fetchDialogs` shape.
5
+ */
6
+
7
+ import { renderHook, act, waitFor } from '@testing-library/react';
8
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
9
+ import { useManagedDialogList } from '../use-managed-dialog-list';
10
+
11
+ const page = (ids: string[], nextCursor: string | null = null) => ({
12
+ dialogs: ids.map(id => ({ id, title: `Chat ${id}` })),
13
+ nextCursor,
14
+ });
15
+
16
+ describe('useManagedDialogList', () => {
17
+ beforeEach(() => {
18
+ vi.spyOn(console, 'error').mockImplementation(() => {});
19
+ });
20
+ afterEach(() => {
21
+ vi.restoreAllMocks();
22
+ });
23
+
24
+ it('is inert without fetchDialogs', () => {
25
+ const { result } = renderHook(() => useManagedDialogList({ active: true, pageSize: 20, logTag: '[t]' }));
26
+ expect(result.current.dialogs).toEqual([]);
27
+ expect(result.current.hasMoreDialogs).toBe(false);
28
+ expect(result.current.isDialogsLoading).toBe(false);
29
+ });
30
+
31
+ it('upsertDialogTop prepends + dedupes; patchDialog patches in place', async () => {
32
+ const fetchDialogs = vi.fn(() => Promise.resolve(page(['a', 'b'])));
33
+ const { result } = renderHook(() =>
34
+ useManagedDialogList({ active: true, pageSize: 20, logTag: '[t]', fetchDialogs }),
35
+ );
36
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
37
+ act(() => result.current.upsertDialogTop({ id: 'b', title: 'B again' }));
38
+ expect(result.current.dialogs.map(d => [d.id, d.title])).toEqual([
39
+ ['b', 'B again'],
40
+ ['a', 'Chat a'],
41
+ ]);
42
+ act(() => result.current.patchDialog('a', { title: 'A patched' }));
43
+ expect(result.current.dialogs.find(d => d.id === 'a')?.title).toBe('A patched');
44
+ });
45
+
46
+ it('reports removal reasons AFTER the local removal', async () => {
47
+ const seen: Array<[string, string, number]> = [];
48
+ let latest: string[] = [];
49
+ const { result } = renderHook(() =>
50
+ useManagedDialogList({
51
+ active: true,
52
+ pageSize: 20,
53
+ logTag: '[t]',
54
+ fetchDialogs: () => Promise.resolve(page(['a', 'b'])),
55
+ archiveDialog: () => Promise.resolve(),
56
+ deleteDialog: () => Promise.resolve(),
57
+ onDialogRemoved: (id, reason) => seen.push([id, reason, latest.length]),
58
+ }),
59
+ );
60
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
61
+ latest = result.current.dialogs.map(d => d.id);
62
+ await act(async () => {
63
+ await result.current.archiveDialog('a');
64
+ });
65
+ await act(async () => {
66
+ await result.current.deleteDialog('b');
67
+ });
68
+ expect(seen.map(([id, reason]) => [id, reason])).toEqual([
69
+ ['a', 'archived'],
70
+ ['b', 'deleted'],
71
+ ]);
72
+ expect(result.current.dialogs).toEqual([]);
73
+ });
74
+
75
+ it('mutations without their callback are no-ops', async () => {
76
+ const { result } = renderHook(() =>
77
+ useManagedDialogList({
78
+ active: true,
79
+ pageSize: 20,
80
+ logTag: '[t]',
81
+ fetchDialogs: () => Promise.resolve(page(['a'])),
82
+ }),
83
+ );
84
+ await waitFor(() => expect(result.current.dialogs.length).toBe(1));
85
+ await act(async () => {
86
+ await result.current.renameDialog('a', 'x');
87
+ await result.current.archiveDialog('a');
88
+ await result.current.deleteDialog('a');
89
+ });
90
+ expect(result.current.dialogs.map(d => [d.id, d.title])).toEqual([['a', 'Chat a']]);
91
+ });
92
+ });
@@ -0,0 +1,167 @@
1
+ /**
2
+ * CHARACTERIZATION TESTS — `useNatsChatAdapter` managed-dialog mode.
3
+ *
4
+ * Pins the dialog-list state machine (initial load, retry, pagination,
5
+ * optimistic rename/archive/delete) BEFORE that block moves into the shared
6
+ * `useManagedDialogList` hook consumed by both transport adapters. Every
7
+ * assertion here is observable host behaviour that must survive the
8
+ * extraction byte-for-byte: the wire params sent to `fetchDialogs`, the
9
+ * list contents after each mutation, and the active-id side effects.
10
+ */
11
+
12
+ import { renderHook, act, waitFor } from '@testing-library/react';
13
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
14
+ import type { DialogItem } from '../../types/component.types';
15
+ import { useNatsChatAdapter, type FetchDialogsParams, type UseNatsChatAdapterConfig } from '../use-nats-chat-adapter';
16
+
17
+ const page = (ids: string[], nextCursor: string | null = null) => ({
18
+ dialogs: ids.map<DialogItem>(id => ({ id, title: `Chat ${id}`, timestamp: new Date('2026-01-01T00:00:00Z') })),
19
+ nextCursor,
20
+ });
21
+
22
+ function makeConfig(overrides: Partial<UseNatsChatAdapterConfig> = {}): UseNatsChatAdapterConfig {
23
+ return {
24
+ getNatsWsUrl: () => null,
25
+ publishUserMessage: vi.fn(),
26
+ fetchChunks: vi.fn(() => Promise.resolve([])),
27
+ fetchDialogs: vi.fn((_p: FetchDialogsParams) => Promise.resolve(page(['a', 'b']))),
28
+ fetchDialogMessages: vi.fn(() => Promise.resolve({ messages: [], nextCursor: null })),
29
+ renameDialog: vi.fn(() => Promise.resolve()),
30
+ archiveDialog: vi.fn(() => Promise.resolve()),
31
+ deleteDialog: vi.fn(() => Promise.resolve()),
32
+ dialogsPageSize: 2,
33
+ ...overrides,
34
+ };
35
+ }
36
+
37
+ describe('useNatsChatAdapter — managed-dialog mode (characterization)', () => {
38
+ beforeEach(() => {
39
+ vi.spyOn(console, 'error').mockImplementation(() => {});
40
+ });
41
+ afterEach(() => {
42
+ vi.restoreAllMocks();
43
+ });
44
+
45
+ it('loads the first page only when active, with exactly {cursor, limit} (no search key)', async () => {
46
+ const config = makeConfig();
47
+ const { result, rerender } = renderHook(({ active }) => useNatsChatAdapter(config, { active }), {
48
+ initialProps: { active: false },
49
+ });
50
+ expect(config.fetchDialogs).not.toHaveBeenCalled();
51
+ expect(result.current.dialogs).toEqual([]);
52
+
53
+ rerender({ active: true });
54
+ await waitFor(() => expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b']));
55
+ expect(config.fetchDialogs).toHaveBeenCalledTimes(1);
56
+ const params = (config.fetchDialogs as ReturnType<typeof vi.fn>).mock.calls[0][0] as FetchDialogsParams;
57
+ expect(params).toEqual({ cursor: undefined, limit: 2 });
58
+ expect(Object.keys(params)).toEqual(['cursor', 'limit']);
59
+ expect(result.current.dialogsError).toBe(false);
60
+ expect(result.current.isDialogsLoading).toBe(false);
61
+ });
62
+
63
+ it('first-page failure flags dialogsError and reloadDialogs retries', async () => {
64
+ const fetchDialogs = vi
65
+ .fn<(p: FetchDialogsParams) => Promise<ReturnType<typeof page>>>()
66
+ .mockRejectedValueOnce(new Error('boom'))
67
+ .mockResolvedValue(page(['a']));
68
+ const config = makeConfig({ fetchDialogs });
69
+ const { result } = renderHook(() => useNatsChatAdapter(config));
70
+ await waitFor(() => expect(result.current.dialogsError).toBe(true));
71
+ expect(result.current.dialogs).toEqual([]);
72
+
73
+ act(() => result.current.reloadDialogs());
74
+ await waitFor(() => expect(result.current.dialogs.map(d => d.id)).toEqual(['a']));
75
+ expect(result.current.dialogsError).toBe(false);
76
+ expect(fetchDialogs).toHaveBeenCalledTimes(2);
77
+ });
78
+
79
+ it('paginates with the server cursor; a pagination failure keeps the loaded rows', async () => {
80
+ const fetchDialogs = vi
81
+ .fn<(p: FetchDialogsParams) => Promise<ReturnType<typeof page>>>()
82
+ .mockResolvedValueOnce(page(['a', 'b'], 'c2'))
83
+ .mockRejectedValueOnce(new Error('page 2 down'))
84
+ .mockResolvedValueOnce(page(['c'], null));
85
+ const config = makeConfig({ fetchDialogs });
86
+ const { result } = renderHook(() => useNatsChatAdapter(config));
87
+ await waitFor(() => expect(result.current.hasMoreDialogs).toBe(true));
88
+
89
+ await act(async () => {
90
+ await result.current.loadMoreDialogs();
91
+ });
92
+ expect(fetchDialogs.mock.calls[1][0]).toEqual({ cursor: 'c2', limit: 2 });
93
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b']);
94
+ expect(result.current.dialogsError).toBe(false);
95
+ expect(result.current.hasMoreDialogs).toBe(true);
96
+
97
+ await act(async () => {
98
+ await result.current.loadMoreDialogs();
99
+ });
100
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b', 'c']);
101
+ expect(result.current.hasMoreDialogs).toBe(false);
102
+ });
103
+
104
+ it('rename is optimistic and rolls back on failure', async () => {
105
+ const renameDialog = vi
106
+ .fn<(id: string, title: string) => Promise<void>>()
107
+ .mockResolvedValueOnce(undefined)
108
+ .mockRejectedValueOnce(new Error('nope'));
109
+ const config = makeConfig({ renameDialog });
110
+ const { result } = renderHook(() => useNatsChatAdapter(config));
111
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
112
+
113
+ await act(async () => {
114
+ await result.current.renameDialog('a', 'Renamed');
115
+ });
116
+ expect(result.current.dialogs.find(d => d.id === 'a')?.title).toBe('Renamed');
117
+
118
+ await act(async () => {
119
+ await result.current.renameDialog('a', 'Will fail');
120
+ });
121
+ expect(result.current.dialogs.find(d => d.id === 'a')?.title).toBe('Renamed');
122
+ expect(renameDialog).toHaveBeenCalledTimes(2);
123
+ });
124
+
125
+ it('archiving the ACTIVE dialog removes it and clears activeDialogId; delete removes too', async () => {
126
+ const config = makeConfig();
127
+ const { result } = renderHook(() => useNatsChatAdapter(config));
128
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
129
+
130
+ act(() => result.current.selectDialog('a'));
131
+ expect(result.current.activeDialogId).toBe('a');
132
+
133
+ await act(async () => {
134
+ await result.current.archiveDialog('a');
135
+ });
136
+ expect(config.archiveDialog).toHaveBeenCalledWith('a');
137
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['b']);
138
+ expect(result.current.activeDialogId).toBeNull();
139
+
140
+ await act(async () => {
141
+ await result.current.deleteDialog('b');
142
+ });
143
+ expect(config.deleteDialog).toHaveBeenCalledWith('b');
144
+ expect(result.current.dialogs).toEqual([]);
145
+ });
146
+
147
+ it('archive failure keeps the row and the active id', async () => {
148
+ const config = makeConfig({ archiveDialog: vi.fn(() => Promise.reject(new Error('down'))) });
149
+ const { result } = renderHook(() => useNatsChatAdapter(config));
150
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
151
+ act(() => result.current.selectDialog('a'));
152
+ await act(async () => {
153
+ await result.current.archiveDialog('a');
154
+ });
155
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b']);
156
+ expect(result.current.activeDialogId).toBe('a');
157
+ });
158
+
159
+ it('bare-transport mode (no fetchDialogs) never lists and ignores selectDialog', () => {
160
+ const config = makeConfig({ fetchDialogs: undefined, dialogId: 'host-owned' });
161
+ const { result } = renderHook(() => useNatsChatAdapter(config));
162
+ act(() => result.current.selectDialog('other'));
163
+ expect(result.current.activeDialogId).toBe('host-owned');
164
+ expect(result.current.dialogs).toEqual([]);
165
+ expect(result.current.hasMoreDialogs).toBe(false);
166
+ });
167
+ });
@@ -0,0 +1,256 @@
1
+ /**
2
+ * GOLDEN CONTRACT TESTS — Guide/SSE adapter with a managed conversation list
3
+ * (`ChatRuntime.endpoints.chatConversationsUrl`).
4
+ *
5
+ * Pins:
6
+ * - mount with a stored id → `activeDialogId` = stored, ONE list GET
7
+ * (`status=active&limit=20`), ONE history GET;
8
+ * - `selectDialog('b')` → thread reset, history GET for `b`, storage = `b`,
9
+ * `isMessagesLoading` true → false;
10
+ * - `clearMessages` → draft state (null id, storage cleared);
11
+ * - first send of a NEW conversation → id captured from the metadata frame,
12
+ * NO history GET for that id, list re-read at end of turn;
13
+ * - rename / archive / restore go to the PATCH wire; archiving the open
14
+ * conversation drops to draft;
15
+ * - ZERO-REGRESSION: without the endpoint `dialogs` is `[]`,
16
+ * `dialogsManaged` is false and no conversations request is issued.
17
+ */
18
+
19
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
20
+ import { renderHook, act, waitFor } from '@testing-library/react';
21
+ import { createElement, type ReactNode } from 'react';
22
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
23
+ import { ChatRuntimeContext, type ChatRuntime } from '../../../../contexts/chat-runtime-context';
24
+ import { useSseChatAdapter } from '../use-sse-chat-adapter';
25
+
26
+ const SOURCE = 'managedsrc';
27
+ const CONVERSATION_KEY = `mingo-chat-${SOURCE}.conversation`;
28
+ const CONVERSATIONS_URL = '/api/docs/chat/conversations';
29
+
30
+ const baseEndpoints: ChatRuntime['endpoints'] = {
31
+ chatStreamUrl: '/api/docs/chat',
32
+ approvalToolUrl: '/api/chat/agent/confirm-tool',
33
+ commandsUrl: '/api/docs/commands',
34
+ buildListUrl: () => null,
35
+ attachmentUploadUrl: '/api/storage/generate-upload-url',
36
+ attachmentViewUrlPrefix: '/api/storage/view/chat-attachments/',
37
+ identityUrl: '/api/chat/identity',
38
+ };
39
+
40
+ function makeWrapper(runtime: ChatRuntime) {
41
+ return function wrapper({ children }: { children: ReactNode }) {
42
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
43
+ return createElement(
44
+ QueryClientProvider,
45
+ { client: queryClient },
46
+ createElement(ChatRuntimeContext.Provider, { value: runtime }, children),
47
+ );
48
+ };
49
+ }
50
+
51
+ const managedRuntime: ChatRuntime = {
52
+ endpoints: { ...baseEndpoints, chatConversationsUrl: CONVERSATIONS_URL },
53
+ navigation: { mode: 'host' },
54
+ source: SOURCE,
55
+ };
56
+ const plainRuntime: ChatRuntime = { endpoints: baseEndpoints, navigation: { mode: 'host' }, source: SOURCE };
57
+
58
+ const enc = new TextEncoder();
59
+ function streamOf(chunks: string[]): ReadableStream<Uint8Array> {
60
+ return new ReadableStream<Uint8Array>({
61
+ start(controller) {
62
+ for (const c of chunks) controller.enqueue(enc.encode(c));
63
+ controller.close();
64
+ },
65
+ });
66
+ }
67
+ const USAGE_END_TRAILER = '{"kind":"usage","stage":"end","input_tokens":10,"output_tokens":5,"hit_rate_pct":50}';
68
+ function wireTurn(conversationId: string, answer: string): string[] {
69
+ return [
70
+ `{"modelLabel":"Claude Sonnet","provider":"anthropic","conversationId":"${conversationId}"}\0`,
71
+ '\x1E',
72
+ answer,
73
+ '\x1F' + USAGE_END_TRAILER,
74
+ ];
75
+ }
76
+
77
+ const historyFor = (id: string) => ({
78
+ data: {
79
+ messages: [
80
+ { seq: 0, role: 'user', content: `q for ${id}`, created_at: '2026-09-01T09:00:00.000Z' },
81
+ { seq: 1, role: 'assistant', content: `a for ${id}`, created_at: '2026-09-01T09:00:05.000Z' },
82
+ ],
83
+ },
84
+ });
85
+ const listPayload = (ids: string[]) => ({
86
+ data: {
87
+ dialogs: ids.map(id => ({ id, title: `Chat ${id}`, timestamp: '2026-09-01T09:00:00.000Z' })),
88
+ nextCursor: null,
89
+ },
90
+ });
91
+
92
+ type Call = { url: string; init: RequestInit };
93
+ function mockFetch(options: { list?: () => unknown; streams?: string[][] }) {
94
+ const calls: Call[] = [];
95
+ let streamCall = 0;
96
+ const fetchMock = vi.fn((url: string, init?: RequestInit) => {
97
+ const u = String(url);
98
+ calls.push({ url: u, init: init ?? {} });
99
+ const json = (body: unknown, status = 200) =>
100
+ Promise.resolve({ ok: status < 300, status, json: () => Promise.resolve(body) } as unknown as Response);
101
+ if (u.startsWith(CONVERSATIONS_URL + '/')) return json({ data: { id: 'x' } });
102
+ if (u.startsWith(CONVERSATIONS_URL)) return json(options.list ? options.list() : listPayload([]));
103
+ if (u.includes('/history')) {
104
+ const id = new URL(u, 'http://x').searchParams.get('conversationId') ?? '';
105
+ return json(historyFor(id));
106
+ }
107
+ if (u.includes('/commands')) return json({ commands: [] });
108
+ const streams = options.streams ?? [];
109
+ const chunks = streams[Math.min(streamCall, streams.length - 1)] ?? [];
110
+ streamCall += 1;
111
+ return Promise.resolve({ ok: true, status: 200, body: streamOf(chunks) } as unknown as Response);
112
+ });
113
+ vi.stubGlobal('fetch', fetchMock);
114
+ return { fetchMock, calls };
115
+ }
116
+ const urlsOf = (calls: Call[], prefix: string) => calls.filter(c => c.url.startsWith(prefix)).map(c => c.url);
117
+
118
+ describe('useSseChatAdapter — managed conversation list', () => {
119
+ beforeEach(() => {
120
+ window.localStorage.clear();
121
+ vi.spyOn(console, 'error').mockImplementation(() => {});
122
+ });
123
+ afterEach(() => {
124
+ vi.restoreAllMocks();
125
+ vi.unstubAllGlobals();
126
+ });
127
+
128
+ it('mount with a stored id: lists once, hydrates once, highlights the stored conversation', async () => {
129
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
130
+ const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
131
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
132
+
133
+ await waitFor(() => expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b']));
134
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
135
+ expect(result.current.dialogsManaged).toBe(true);
136
+ expect(result.current.activeDialogId).toBe('a');
137
+ expect(urlsOf(calls, CONVERSATIONS_URL)).toEqual([`${CONVERSATIONS_URL}?status=active&limit=20`]);
138
+ expect(urlsOf(calls, '/api/docs/chat/history')).toEqual(['/api/docs/chat/history?conversationId=a']);
139
+ expect(result.current.dialogCapabilities).toMatchObject({ canRename: true, canArchive: true, searchQuery: '' });
140
+ expect(result.current.dialogCapabilities?.fetchArchivedDialogs).toBeTypeOf('function');
141
+ expect(result.current.dialogCapabilities?.unarchiveDialog).toBeTypeOf('function');
142
+ });
143
+
144
+ it('selectDialog switches the thread: reset, hydrate the new id, persist it', async () => {
145
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
146
+ const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
147
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
148
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
149
+
150
+ act(() => result.current.selectDialog('b'));
151
+ expect(result.current.activeDialogId).toBe('b');
152
+ expect(JSON.parse(window.localStorage.getItem(CONVERSATION_KEY) ?? '{}')).toEqual({ conversationId: 'b' });
153
+ await waitFor(() => expect(result.current.messages.map(m => m.content)).toEqual(['q for b', 'a for b']));
154
+ expect(result.current.isMessagesLoading).toBe(false);
155
+ expect(urlsOf(calls, '/api/docs/chat/history')).toEqual([
156
+ '/api/docs/chat/history?conversationId=a',
157
+ '/api/docs/chat/history?conversationId=b',
158
+ ]);
159
+
160
+ // Idempotent on the active id — no extra fetch.
161
+ act(() => result.current.selectDialog('b'));
162
+ expect(urlsOf(calls, '/api/docs/chat/history').length).toBe(2);
163
+ });
164
+
165
+ it('clearMessages drops to draft state (null id, storage cleared)', async () => {
166
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
167
+ mockFetch({ list: () => listPayload(['a']) });
168
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
169
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
170
+ act(() => result.current.clearMessages());
171
+ expect(result.current.activeDialogId).toBeNull();
172
+ expect(result.current.messages).toEqual([]);
173
+ expect(window.localStorage.getItem(CONVERSATION_KEY)).toBeNull();
174
+ });
175
+
176
+ it('first send: captures the minted id WITHOUT hydrating it, and re-reads the list at end of turn', async () => {
177
+ let listed = 0;
178
+ const { calls } = mockFetch({
179
+ list: () => {
180
+ listed += 1;
181
+ return listed === 1 ? listPayload([]) : listPayload(['conv-new']);
182
+ },
183
+ streams: [wireTurn('conv-new', 'Hello there.')],
184
+ });
185
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
186
+ await waitFor(() => expect(listed).toBe(1));
187
+
188
+ await act(async () => {
189
+ await result.current.sendMessage('first question');
190
+ });
191
+ expect(result.current.activeDialogId).toBe('conv-new');
192
+ expect(urlsOf(calls, '/api/docs/chat/history')).toEqual([]);
193
+ await waitFor(() => expect(listed).toBe(2));
194
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['conv-new']);
195
+ // The streamed turn is the thread — nothing was prepended by hydration.
196
+ expect(result.current.messages.map(m => m.role)).toEqual(['user', 'assistant']);
197
+ });
198
+
199
+ it('rename / archive / restore hit the PATCH wire; archiving the open chat drops to draft', async () => {
200
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
201
+ const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
202
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
203
+ await waitFor(() => expect(result.current.dialogs.length).toBe(2));
204
+
205
+ await act(async () => {
206
+ await result.current.renameDialog('b', 'Renamed B');
207
+ });
208
+ expect(result.current.dialogs.find(d => d.id === 'b')?.title).toBe('Renamed B');
209
+
210
+ await act(async () => {
211
+ await result.current.archiveDialog('a');
212
+ });
213
+ expect(result.current.dialogs.map(d => d.id)).toEqual(['b']);
214
+ expect(result.current.activeDialogId).toBeNull();
215
+
216
+ await act(async () => {
217
+ await result.current.dialogCapabilities?.unarchiveDialog?.('a');
218
+ });
219
+
220
+ const patches = calls.filter(c => c.url.startsWith(CONVERSATIONS_URL + '/'));
221
+ const parseBody = (c: Call): unknown => JSON.parse(String(c.init.body));
222
+ expect(patches.map(c => [c.url, c.init.method, parseBody(c)])).toEqual([
223
+ [`${CONVERSATIONS_URL}/b`, 'PATCH', { title: 'Renamed B' }],
224
+ [`${CONVERSATIONS_URL}/a`, 'PATCH', { archived: true }],
225
+ [`${CONVERSATIONS_URL}/a`, 'PATCH', { archived: false }],
226
+ ]);
227
+ // Restore re-reads the active list.
228
+ expect(urlsOf(calls, `${CONVERSATIONS_URL}?`).length).toBeGreaterThanOrEqual(2);
229
+ });
230
+
231
+ it('search term change re-reads page 1 with `search`', async () => {
232
+ const { calls } = mockFetch({ list: () => listPayload(['a']) });
233
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
234
+ await waitFor(() => expect(result.current.dialogs.length).toBe(1));
235
+ act(() => result.current.dialogCapabilities?.onSearchChange?.('print'));
236
+ await waitFor(() =>
237
+ expect(urlsOf(calls, `${CONVERSATIONS_URL}?`)).toEqual([
238
+ `${CONVERSATIONS_URL}?status=active&limit=20`,
239
+ `${CONVERSATIONS_URL}?status=active&limit=20&search=print`,
240
+ ]),
241
+ );
242
+ expect(result.current.dialogCapabilities?.searchQuery).toBe('print');
243
+ });
244
+
245
+ it('ZERO-REGRESSION: without chatConversationsUrl the single-thread stubs are returned', async () => {
246
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
247
+ const { calls } = mockFetch({});
248
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(plainRuntime) });
249
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
250
+ expect(result.current.dialogs).toEqual([]);
251
+ expect(result.current.dialogsManaged).toBe(false);
252
+ expect(result.current.dialogCapabilities).toBeUndefined();
253
+ expect(result.current.activeDialogId).toBeNull();
254
+ expect(urlsOf(calls, CONVERSATIONS_URL)).toEqual([]);
255
+ });
256
+ });
@@ -27,6 +27,8 @@ export * from './use-sse';
27
27
  // access is needed. `useEmbeddedChat` is the legacy SSE alias.
28
28
  export * from './use-sse-chat-adapter';
29
29
  export * from './use-nats-chat-adapter';
30
+ // Shared dialog-list state machine behind both adapters' managed modes.
31
+ export * from './use-managed-dialog-list';
30
32
  export * from './use-unified-chat';
31
33
  export * from './use-embedded-chat';
32
34
 
@@ -35,8 +35,10 @@ export interface UseChatHistoryHydrationArgs {
35
35
  source: string;
36
36
  /** Resolved history endpoint (`<chatStreamUrl>/history` by default). */
37
37
  historyUrl: string;
38
- /** The server-issued conversation id (null = nothing to hydrate). */
39
- conversationIdRef: MutableRefObject<string | null>;
38
+ /** The server-issued conversation id (null = nothing to hydrate). A VALUE,
39
+ * not a ref: switching conversations (`selectDialog`) must re-run the
40
+ * fetch, so the id is an effect dependency. */
41
+ conversationId: string | null;
40
42
  /** User-send counter — set to the hydrated user-turn count so the next
41
43
  * live send lands on the following `sendIdx`. */
42
44
  sendCountRef: MutableRefObject<number>;
@@ -64,7 +66,7 @@ export function useChatHistoryHydration({
64
66
  active,
65
67
  source,
66
68
  historyUrl,
67
- conversationIdRef,
69
+ conversationId,
68
70
  sendCountRef,
69
71
  hydrateMessages,
70
72
  bumpMetaTick,
@@ -76,7 +78,6 @@ export function useChatHistoryHydration({
76
78
  if (!active) return undefined;
77
79
  // No stored conversation id → nothing to hydrate (fresh visitor / after
78
80
  // "new chat"); the first send establishes the conversation server-side.
79
- const conversationId = conversationIdRef.current;
80
81
  if (!conversationId) return undefined;
81
82
  const key = `${source}:${conversationId}`;
82
83
  if (hydratedKeyRef.current === key) return undefined;
@@ -146,9 +147,9 @@ export function useChatHistoryHydration({
146
147
  return () => {
147
148
  cancelled = true;
148
149
  };
149
- // `conversationIdRef`/`sendCountRef` are refs: stable identities, so
150
- // listing them costs nothing and the effect still keys on the real inputs.
151
- }, [active, source, historyUrl, hydrateMessages, bumpMetaTick, conversationIdRef, sendCountRef]);
150
+ // `sendCountRef` is a ref: a stable identity, so listing it costs nothing;
151
+ // `conversationId` is the real re-run trigger (dialog switch).
152
+ }, [active, source, historyUrl, conversationId, hydrateMessages, bumpMetaTick, sendCountRef]);
152
153
 
153
154
  return { isHydratingHistory, hydratedKeyRef };
154
155
  }