@flamingo-stack/openframe-frontend-core 0.0.598 → 0.0.599-2039.5717.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 (206) 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-BK6CCQG6.js → chunk-2R6F56U5.js} +12 -12
  11. package/dist/{chunk-STYNZ4QM.cjs → chunk-3IXDZI3R.cjs} +3 -3
  12. package/dist/{chunk-STYNZ4QM.cjs.map → chunk-3IXDZI3R.cjs.map} +1 -1
  13. package/dist/{chunk-QIKBISZM.cjs → chunk-4ZAQSPCQ.cjs} +242 -242
  14. package/dist/{chunk-QIKBISZM.cjs.map → chunk-4ZAQSPCQ.cjs.map} +1 -1
  15. package/dist/{chunk-JVZVVZOZ.cjs → chunk-5DORSDXA.cjs} +9 -9
  16. package/dist/{chunk-JVZVVZOZ.cjs.map → chunk-5DORSDXA.cjs.map} +1 -1
  17. package/dist/{chunk-YWBAIFI2.cjs → chunk-6D4DUONA.cjs} +105 -105
  18. package/dist/{chunk-YWBAIFI2.cjs.map → chunk-6D4DUONA.cjs.map} +1 -1
  19. package/dist/{chunk-KHOZ52NR.js → chunk-7654NDQB.js} +6 -6
  20. package/dist/{chunk-DI3SVVY5.cjs → chunk-AC5SWE3S.cjs} +85 -85
  21. package/dist/{chunk-DI3SVVY5.cjs.map → chunk-AC5SWE3S.cjs.map} +1 -1
  22. package/dist/{chunk-R4UV366K.js → chunk-AJU3NYAA.js} +6 -6
  23. package/dist/{chunk-GHYFVT52.js → chunk-B23ID4DM.js} +5 -5
  24. package/dist/{chunk-SE3PVN64.js → chunk-B6HSRLC5.js} +2 -2
  25. package/dist/{chunk-EVMHJB6X.js → chunk-BLUL2TE3.js} +4 -4
  26. package/dist/{chunk-GGQZBSFN.js → chunk-BVQEU5JB.js} +2 -2
  27. package/dist/{chunk-75YW6ET4.js → chunk-C4APMQWW.js} +4 -4
  28. package/dist/{chunk-H64ZHSYR.cjs → chunk-CCWI3622.cjs} +4 -4
  29. package/dist/{chunk-H64ZHSYR.cjs.map → chunk-CCWI3622.cjs.map} +1 -1
  30. package/dist/{chunk-WPN545FW.js → chunk-CVYVYSP2.js} +12 -12
  31. package/dist/{chunk-YH6IQTPI.cjs → chunk-EHAYNUOL.cjs} +3 -3
  32. package/dist/{chunk-YH6IQTPI.cjs.map → chunk-EHAYNUOL.cjs.map} +1 -1
  33. package/dist/{chunk-VIRTMRS4.js → chunk-EZOI5UR3.js} +7 -7
  34. package/dist/{chunk-WZJOILPU.js → chunk-F2KBCLUG.js} +2 -2
  35. package/dist/{chunk-MYBXCWEI.js → chunk-FKBM6U43.js} +2 -2
  36. package/dist/{chunk-2SYX2Z7R.cjs → chunk-GIG3WQTF.cjs} +34 -34
  37. package/dist/{chunk-2SYX2Z7R.cjs.map → chunk-GIG3WQTF.cjs.map} +1 -1
  38. package/dist/{chunk-LRQCKSZC.js → chunk-IW746HJ7.js} +2 -2
  39. package/dist/{chunk-YBPFIXV4.cjs → chunk-IYEKAU4X.cjs} +801 -482
  40. package/dist/chunk-IYEKAU4X.cjs.map +1 -0
  41. package/dist/{chunk-VLJTJAHJ.cjs → chunk-J3ODLFCA.cjs} +25 -25
  42. package/dist/{chunk-VLJTJAHJ.cjs.map → chunk-J3ODLFCA.cjs.map} +1 -1
  43. package/dist/{chunk-UE7OFLLS.cjs → chunk-J4RRF2EP.cjs} +14 -14
  44. package/dist/{chunk-UE7OFLLS.cjs.map → chunk-J4RRF2EP.cjs.map} +1 -1
  45. package/dist/{chunk-M4YQUHOR.cjs → chunk-JJUV7Z4L.cjs} +15 -15
  46. package/dist/{chunk-M4YQUHOR.cjs.map → chunk-JJUV7Z4L.cjs.map} +1 -1
  47. package/dist/{chunk-UG7JNQZY.cjs → chunk-JKFWKPHW.cjs} +37 -37
  48. package/dist/{chunk-UG7JNQZY.cjs.map → chunk-JKFWKPHW.cjs.map} +1 -1
  49. package/dist/{chunk-3WSS7C2V.cjs → chunk-KAHI4QWA.cjs} +15 -15
  50. package/dist/{chunk-3WSS7C2V.cjs.map → chunk-KAHI4QWA.cjs.map} +1 -1
  51. package/dist/{chunk-VNSRNVPD.js → chunk-KJ5EQ6P6.js} +728 -409
  52. package/dist/chunk-KJ5EQ6P6.js.map +1 -0
  53. package/dist/{chunk-V2QK5W3O.cjs → chunk-L64FTMML.cjs} +3 -3
  54. package/dist/{chunk-V2QK5W3O.cjs.map → chunk-L64FTMML.cjs.map} +1 -1
  55. package/dist/{chunk-P24VPJTT.cjs → chunk-LT6GIGMZ.cjs} +15 -15
  56. package/dist/{chunk-P24VPJTT.cjs.map → chunk-LT6GIGMZ.cjs.map} +1 -1
  57. package/dist/{chunk-WDWCQD75.js → chunk-LVVDTK5X.js} +9 -9
  58. package/dist/{chunk-HWAYIK4U.cjs → chunk-MSPYY2F4.cjs} +22 -22
  59. package/dist/{chunk-HWAYIK4U.cjs.map → chunk-MSPYY2F4.cjs.map} +1 -1
  60. package/dist/{chunk-QD64Q4I2.cjs → chunk-N7LOLURS.cjs} +9 -9
  61. package/dist/{chunk-QD64Q4I2.cjs.map → chunk-N7LOLURS.cjs.map} +1 -1
  62. package/dist/{chunk-TZPVRWPU.js → chunk-O33JVUR5.js} +5 -5
  63. package/dist/{chunk-HLPAVYK7.js → chunk-ODPN724R.js} +4 -4
  64. package/dist/{chunk-NIAMPMKV.js → chunk-OQNKAF4F.js} +4 -4
  65. package/dist/{chunk-SAEJGTCI.cjs → chunk-QPAPUIF3.cjs} +35 -35
  66. package/dist/{chunk-SAEJGTCI.cjs.map → chunk-QPAPUIF3.cjs.map} +1 -1
  67. package/dist/{chunk-BPVHDDNY.cjs → chunk-R2VBMBPJ.cjs} +8 -8
  68. package/dist/{chunk-BPVHDDNY.cjs.map → chunk-R2VBMBPJ.cjs.map} +1 -1
  69. package/dist/{chunk-UAAXUFK6.js → chunk-RU3IKVY2.js} +3 -3
  70. package/dist/{chunk-EZM5DNII.js → chunk-S6WBBSII.js} +3 -3
  71. package/dist/{chunk-2JNCZDJR.js → chunk-TSCIVH7T.js} +2 -2
  72. package/dist/{chunk-PX4IPM7Q.js → chunk-TYY6HOTI.js} +3 -3
  73. package/dist/{chunk-RDTOMWDN.cjs → chunk-UPKZU6QU.cjs} +1 -1
  74. package/dist/chunk-UPKZU6QU.cjs.map +1 -0
  75. package/dist/{chunk-WCBRZCU4.cjs → chunk-UQEOAPAI.cjs} +9 -9
  76. package/dist/{chunk-WCBRZCU4.cjs.map → chunk-UQEOAPAI.cjs.map} +1 -1
  77. package/dist/{chunk-O4VZOA2Q.cjs → chunk-UXOOVP77.cjs} +3 -3
  78. package/dist/{chunk-O4VZOA2Q.cjs.map → chunk-UXOOVP77.cjs.map} +1 -1
  79. package/dist/{chunk-PTK3CINU.js → chunk-VELZVF3F.js} +5 -5
  80. package/dist/{chunk-BZEWPW5A.cjs → chunk-VIBREYUK.cjs} +3 -3
  81. package/dist/{chunk-BZEWPW5A.cjs.map → chunk-VIBREYUK.cjs.map} +1 -1
  82. package/dist/{chunk-RYXIRVDC.js → chunk-YB6FI2G3.js} +1 -1
  83. package/dist/chunk-YB6FI2G3.js.map +1 -0
  84. package/dist/{chunk-DAPOBLAK.cjs → chunk-YEO6W4CT.cjs} +39 -39
  85. package/dist/{chunk-DAPOBLAK.cjs.map → chunk-YEO6W4CT.cjs.map} +1 -1
  86. package/dist/{chunk-XNPAVMPB.js → chunk-YUELNVD5.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 +12 -1
  101. package/dist/components/chat/hooks/use-unified-chat.d.ts.map +1 -1
  102. package/dist/components/chat/index.cjs +11 -5
  103. package/dist/components/chat/index.cjs.map +1 -1
  104. package/dist/components/chat/index.js +10 -4
  105. package/dist/components/chat/types/unified-chat-state.types.d.ts +86 -6
  106. package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
  107. package/dist/components/chat/utils/chat-conversations-api.d.ts +29 -0
  108. package/dist/components/chat/utils/chat-conversations-api.d.ts.map +1 -0
  109. package/dist/components/chat/utils/index.d.ts +1 -0
  110. package/dist/components/chat/utils/index.d.ts.map +1 -1
  111. package/dist/components/contact/index.cjs +9 -9
  112. package/dist/components/contact/index.js +8 -8
  113. package/dist/components/docs/index.cjs +12 -12
  114. package/dist/components/docs/index.js +11 -11
  115. package/dist/components/embeds/index.cjs +9 -9
  116. package/dist/components/embeds/index.js +8 -8
  117. package/dist/components/faq/index.cjs +10 -10
  118. package/dist/components/faq/index.js +9 -9
  119. package/dist/components/features/index.cjs +8 -8
  120. package/dist/components/features/index.js +7 -7
  121. package/dist/components/help-center-pages/index.cjs +31 -31
  122. package/dist/components/help-center-pages/index.js +22 -22
  123. package/dist/components/index.cjs +72 -66
  124. package/dist/components/index.cjs.map +1 -1
  125. package/dist/components/index.js +28 -22
  126. package/dist/components/index.js.map +1 -1
  127. package/dist/components/meeting-scheduler/index.cjs +49 -49
  128. package/dist/components/meeting-scheduler/index.js +9 -9
  129. package/dist/components/navigation/index.cjs +11 -11
  130. package/dist/components/navigation/index.js +10 -10
  131. package/dist/components/onboarding-guides/index.cjs +12 -12
  132. package/dist/components/onboarding-guides/index.js +11 -11
  133. package/dist/components/related-content/index.cjs +7 -7
  134. package/dist/components/related-content/index.js +6 -6
  135. package/dist/components/tickets/index.cjs +13 -13
  136. package/dist/components/tickets/index.js +12 -12
  137. package/dist/components/ui/index.cjs +14 -8
  138. package/dist/components/ui/index.cjs.map +1 -1
  139. package/dist/components/ui/index.js +13 -7
  140. package/dist/contexts/chat-runtime-context.d.ts +12 -0
  141. package/dist/contexts/chat-runtime-context.d.ts.map +1 -1
  142. package/dist/contexts/index.cjs +2 -2
  143. package/dist/contexts/index.js +1 -1
  144. package/dist/hooks/index.cjs +5 -5
  145. package/dist/hooks/index.js +4 -4
  146. package/dist/index.cjs +18 -12
  147. package/dist/index.cjs.map +1 -1
  148. package/dist/index.js +17 -11
  149. package/dist/index.js.map +1 -1
  150. package/package.json +1 -1
  151. package/src/chat-protocol/index.ts +1 -0
  152. package/src/chat-protocol/nats-decoder.ts +1 -5
  153. package/src/chat-protocol/wire-narrow.ts +22 -0
  154. package/src/components/chat/.embeddable-chat.md +4 -2
  155. package/src/components/chat/embeddable-chat.tsx +131 -87
  156. package/src/components/chat/hooks/.index.md +1 -1
  157. package/src/components/chat/hooks/.use-managed-dialog-list.md +31 -0
  158. package/src/components/chat/hooks/.use-nats-chat-adapter.md +3 -1
  159. package/src/components/chat/hooks/.use-sse-chat-adapter.md +8 -1
  160. package/src/components/chat/hooks/.use-unified-chat.md +2 -2
  161. package/src/components/chat/hooks/__tests__/managed-dialog-list.test.ts +280 -0
  162. package/src/components/chat/hooks/__tests__/nats-adapter-managed-dialogs.test.ts +193 -0
  163. package/src/components/chat/hooks/__tests__/sse-managed-dialogs.test.ts +310 -0
  164. package/src/components/chat/hooks/__tests__/unified-chat-dialog-capabilities.test.ts +129 -0
  165. package/src/components/chat/hooks/index.ts +2 -0
  166. package/src/components/chat/hooks/use-chat-history-hydration.ts +67 -24
  167. package/src/components/chat/hooks/use-managed-dialog-list.ts +339 -0
  168. package/src/components/chat/hooks/use-nats-chat-adapter.ts +64 -150
  169. package/src/components/chat/hooks/use-sse-chat-adapter.ts +238 -59
  170. package/src/components/chat/hooks/use-unified-chat.ts +26 -2
  171. package/src/components/chat/types/.unified-chat-state.types.md +13 -1
  172. package/src/components/chat/types/unified-chat-state.types.ts +93 -6
  173. package/src/components/chat/utils/.chat-conversations-api.md +16 -0
  174. package/src/components/chat/utils/.index.md +1 -1
  175. package/src/components/chat/utils/__tests__/chat-conversations-api-golden.test.ts +105 -0
  176. package/src/components/chat/utils/chat-conversations-api.ts +83 -0
  177. package/src/components/chat/utils/index.ts +7 -0
  178. package/src/contexts/.chat-runtime-context.md +3 -1
  179. package/src/contexts/chat-runtime-context.tsx +12 -0
  180. package/dist/chunk-RDTOMWDN.cjs.map +0 -1
  181. package/dist/chunk-RYXIRVDC.js.map +0 -1
  182. package/dist/chunk-VNSRNVPD.js.map +0 -1
  183. package/dist/chunk-YBPFIXV4.cjs.map +0 -1
  184. /package/dist/{chunk-BK6CCQG6.js.map → chunk-2R6F56U5.js.map} +0 -0
  185. /package/dist/{chunk-KHOZ52NR.js.map → chunk-7654NDQB.js.map} +0 -0
  186. /package/dist/{chunk-R4UV366K.js.map → chunk-AJU3NYAA.js.map} +0 -0
  187. /package/dist/{chunk-GHYFVT52.js.map → chunk-B23ID4DM.js.map} +0 -0
  188. /package/dist/{chunk-SE3PVN64.js.map → chunk-B6HSRLC5.js.map} +0 -0
  189. /package/dist/{chunk-EVMHJB6X.js.map → chunk-BLUL2TE3.js.map} +0 -0
  190. /package/dist/{chunk-GGQZBSFN.js.map → chunk-BVQEU5JB.js.map} +0 -0
  191. /package/dist/{chunk-75YW6ET4.js.map → chunk-C4APMQWW.js.map} +0 -0
  192. /package/dist/{chunk-WPN545FW.js.map → chunk-CVYVYSP2.js.map} +0 -0
  193. /package/dist/{chunk-VIRTMRS4.js.map → chunk-EZOI5UR3.js.map} +0 -0
  194. /package/dist/{chunk-WZJOILPU.js.map → chunk-F2KBCLUG.js.map} +0 -0
  195. /package/dist/{chunk-MYBXCWEI.js.map → chunk-FKBM6U43.js.map} +0 -0
  196. /package/dist/{chunk-LRQCKSZC.js.map → chunk-IW746HJ7.js.map} +0 -0
  197. /package/dist/{chunk-WDWCQD75.js.map → chunk-LVVDTK5X.js.map} +0 -0
  198. /package/dist/{chunk-TZPVRWPU.js.map → chunk-O33JVUR5.js.map} +0 -0
  199. /package/dist/{chunk-HLPAVYK7.js.map → chunk-ODPN724R.js.map} +0 -0
  200. /package/dist/{chunk-NIAMPMKV.js.map → chunk-OQNKAF4F.js.map} +0 -0
  201. /package/dist/{chunk-UAAXUFK6.js.map → chunk-RU3IKVY2.js.map} +0 -0
  202. /package/dist/{chunk-EZM5DNII.js.map → chunk-S6WBBSII.js.map} +0 -0
  203. /package/dist/{chunk-2JNCZDJR.js.map → chunk-TSCIVH7T.js.map} +0 -0
  204. /package/dist/{chunk-PX4IPM7Q.js.map → chunk-TYY6HOTI.js.map} +0 -0
  205. /package/dist/{chunk-PTK3CINU.js.map → chunk-VELZVF3F.js.map} +0 -0
  206. /package/dist/{chunk-XNPAVMPB.js.map → chunk-YUELNVD5.js.map} +0 -0
@@ -0,0 +1,310 @@
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
+ * `dialogCapabilities` is `undefined` 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.dialogCapabilities).toBeDefined();
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('never wedges on the message skeleton when a hydration is superseded', async () => {
246
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
247
+ mockFetch({ list: () => listPayload(['a', 'b']) });
248
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
249
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
250
+
251
+ // "New chat" while a hydration could still be in flight: the loading flag
252
+ // must clear, or `hasConversation` pins the panel on a skeleton forever.
253
+ act(() => result.current.clearMessages());
254
+ await waitFor(() => expect(result.current.isMessagesLoading).toBe(false));
255
+ expect(result.current.activeDialogId).toBeNull();
256
+
257
+ // Same for selecting away mid-flight.
258
+ act(() => result.current.selectDialog('b'));
259
+ act(() => result.current.selectDialog(null));
260
+ await waitFor(() => expect(result.current.isMessagesLoading).toBe(false));
261
+ });
262
+
263
+ it('keeps a stored id whose thread is legitimately empty but owned', async () => {
264
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'empty-but-mine' }));
265
+ const { fetchMock } = mockFetch({ list: () => listPayload([]) });
266
+ fetchMock.mockImplementation((url: string) => {
267
+ const u = String(url);
268
+ const json = (body: unknown) =>
269
+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) } as unknown as Response);
270
+ // Owned, just has no rows yet — the id must SURVIVE.
271
+ if (u.includes('/history')) return json({ conversationId: 'empty-but-mine', messages: [], found: true });
272
+ if (u.startsWith(CONVERSATIONS_URL)) return json(listPayload([]));
273
+ return json({ commands: [] });
274
+ });
275
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
276
+ await waitFor(() => expect(result.current.dialogCapabilities).toBeDefined());
277
+ await new Promise(resolve => setTimeout(resolve, 20));
278
+ expect(window.localStorage.getItem(CONVERSATION_KEY)).not.toBeNull();
279
+ expect(result.current.activeDialogId).toBe('empty-but-mine');
280
+ });
281
+
282
+ it('drops a stored id the server reports as not ours (found: false)', async () => {
283
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'gone' }));
284
+ const { fetchMock } = mockFetch({ list: () => listPayload([]) });
285
+ fetchMock.mockImplementation((url: string) => {
286
+ const u = String(url);
287
+ const json = (body: unknown) =>
288
+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) } as unknown as Response);
289
+ // `found: false` = the server does not recognize this id for us.
290
+ if (u.includes('/history')) return json({ conversationId: 'gone', messages: [], found: false });
291
+ if (u.startsWith(CONVERSATIONS_URL)) return json(listPayload([]));
292
+ return json({ commands: [] });
293
+ });
294
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
295
+ await waitFor(() => expect(window.localStorage.getItem(CONVERSATION_KEY)).toBeNull());
296
+ expect(result.current.activeDialogId).toBeNull();
297
+ });
298
+
299
+ it('ZERO-REGRESSION: without chatConversationsUrl the single-thread stubs are returned', async () => {
300
+ window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
301
+ const { calls } = mockFetch({});
302
+ const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(plainRuntime) });
303
+ await waitFor(() => expect(result.current.messages.length).toBe(2));
304
+ expect(result.current.dialogs).toEqual([]);
305
+ // The ABSENT capability object is what keeps this panel single-thread.
306
+ expect(result.current.dialogCapabilities).toBeUndefined();
307
+ expect(result.current.activeDialogId).toBeNull();
308
+ expect(urlsOf(calls, CONVERSATIONS_URL)).toEqual([]);
309
+ });
310
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * GOLDEN CONTRACT TEST — how `useUnifiedChat` resolves THE conversation-list
3
+ * signal, `dialogCapabilities`.
4
+ *
5
+ * `EmbeddableChat` gates its entire history surface (rail, stacked list,
6
+ * archive page, rename/archive menus, header search) on the presence of this
7
+ * ONE object, and never on a transport name. This file pins the resolution
8
+ * rule so that gate can never silently change meaning:
9
+ *
10
+ * - GUIDE mode reports whatever the SSE adapter reports — `undefined`
11
+ * without `chatConversationsUrl`, so a plain Guide panel stays
12
+ * single-thread even when a Mingo config is also present;
13
+ * - MINGO mode reports the NATS adapter's object, which is always present;
14
+ * - a HOST-INJECTED state (`mingoStateOverride`) that carries no
15
+ * capabilities of its own falls back to the `injectedDialogCapabilities`
16
+ * companion, and to an EMPTY object when the host passes neither — so
17
+ * injecting a state never costs a host its list surface;
18
+ * - capabilities ON the injected state win over the companion prop.
19
+ */
20
+
21
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
22
+ import { renderHook } from '@testing-library/react';
23
+ import { createElement, type ReactNode } from 'react';
24
+ import { describe, it, expect, vi } from 'vitest';
25
+ import { ChatRuntimeContext, type ChatRuntime } from '../../../../contexts/chat-runtime-context';
26
+ import type { ChatDialogCapabilities, UnifiedChatState } from '../../types/unified-chat-state.types';
27
+ import { useUnifiedChat, type UseUnifiedChatModes } from '../use-unified-chat';
28
+
29
+ const endpoints: ChatRuntime['endpoints'] = {
30
+ chatStreamUrl: '/api/docs/chat',
31
+ approvalToolUrl: '/api/chat/agent/confirm-tool',
32
+ commandsUrl: '/api/docs/commands',
33
+ buildListUrl: () => null,
34
+ attachmentUploadUrl: '/api/storage/generate-upload-url',
35
+ attachmentViewUrlPrefix: '/api/storage/view/chat-attachments/',
36
+ identityUrl: '/api/chat/identity',
37
+ };
38
+
39
+ function wrapperFor(runtime: ChatRuntime) {
40
+ return function wrapper({ children }: { children: ReactNode }) {
41
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
42
+ return createElement(
43
+ QueryClientProvider,
44
+ { client: queryClient },
45
+ createElement(ChatRuntimeContext.Provider, { value: runtime }, children),
46
+ );
47
+ };
48
+ }
49
+
50
+ const plainRuntime: ChatRuntime = { endpoints, navigation: { mode: 'host' }, source: 'unifiedsrc' };
51
+ const managedRuntime: ChatRuntime = {
52
+ endpoints: { ...endpoints, chatConversationsUrl: '/api/docs/chat/conversations' },
53
+ navigation: { mode: 'host' },
54
+ source: 'unifiedsrc',
55
+ };
56
+
57
+ /** A Mingo mode config that is structurally valid but never opens a socket. */
58
+ const mingoMode: UseUnifiedChatModes['mingo'] = {
59
+ dialogId: null,
60
+ getNatsWsUrl: () => null,
61
+ publishUserMessage: vi.fn(),
62
+ };
63
+
64
+ /** Minimal host-built state — only the fields this contract reads. */
65
+ function injectedState(overrides: Partial<UnifiedChatState> = {}): UnifiedChatState {
66
+ return { dialogs: [], activeDialogId: null, ...overrides } as unknown as UnifiedChatState;
67
+ }
68
+
69
+ function capsOf(options: Parameters<typeof useUnifiedChat>[0], runtime = plainRuntime) {
70
+ const { result } = renderHook(() => useUnifiedChat(options), { wrapper: wrapperFor(runtime) });
71
+ return result.current.dialogCapabilities;
72
+ }
73
+
74
+ describe('useUnifiedChat — dialogCapabilities resolution', () => {
75
+ it('guide mode without a conversations endpoint has NO list, even beside a mingo config', () => {
76
+ expect(capsOf({ modes: { guide: {}, mingo: mingoMode }, activeMode: 'guide' })).toBeUndefined();
77
+ });
78
+
79
+ it('guide mode WITH the endpoint reports the SSE adapter capabilities', () => {
80
+ const caps = capsOf({ modes: { guide: {} }, activeMode: 'guide' }, managedRuntime);
81
+ expect(caps).toMatchObject({ canRename: true, canArchive: true, emptyListSkipsToCompose: true });
82
+ });
83
+
84
+ it('mingo mode reports the NATS adapter object — the Mingo panel always owns a list', () => {
85
+ const caps = capsOf({ modes: { mingo: mingoMode }, activeMode: 'mingo' }, managedRuntime);
86
+ // Present despite the runtime endpoint, which belongs to the OTHER transport.
87
+ expect(caps).toBeDefined();
88
+ expect(caps?.emptyListSkipsToCompose).toBeUndefined();
89
+ });
90
+
91
+ it('an injected state with no capabilities falls back to the companion prop', () => {
92
+ const injected: ChatDialogCapabilities = { canRename: true, canArchive: true, searchQuery: 'q' };
93
+ const caps = capsOf({
94
+ modes: {},
95
+ activeMode: 'mingo',
96
+ mingoStateOverride: injectedState(),
97
+ injectedDialogCapabilities: injected,
98
+ });
99
+ expect(caps).toBe(injected);
100
+ });
101
+
102
+ it('an injected state with NEITHER still owns a list (empty, not undefined)', () => {
103
+ // Injecting a state must never cost a host its list surface — this is the
104
+ // case the removed `activeMode === 'mingo'` check used to carry.
105
+ const caps = capsOf({ modes: {}, activeMode: 'mingo', mingoStateOverride: injectedState() });
106
+ expect(caps).toEqual({});
107
+ });
108
+
109
+ it('capabilities ON the injected state win over the companion prop', () => {
110
+ const own: ChatDialogCapabilities = { canRename: true };
111
+ const caps = capsOf({
112
+ modes: {},
113
+ activeMode: 'mingo',
114
+ mingoStateOverride: injectedState({ dialogCapabilities: own }),
115
+ injectedDialogCapabilities: { canArchive: true },
116
+ });
117
+ expect(caps).toBe(own);
118
+ });
119
+
120
+ it('the companion prop is ignored when the injected state is NOT active', () => {
121
+ const caps = capsOf({
122
+ modes: { guide: {} },
123
+ activeMode: 'guide',
124
+ mingoStateOverride: injectedState(),
125
+ injectedDialogCapabilities: { canRename: true },
126
+ });
127
+ expect(caps).toBeUndefined();
128
+ });
129
+ });
@@ -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
 
@@ -18,16 +18,11 @@
18
18
  */
19
19
 
20
20
  import { useEffect, useRef, useState, type MutableRefObject } from 'react';
21
+ import { isRecord, unwrapEnvelope } from '../../../chat-protocol/wire-narrow';
21
22
  import { embedAuthedFetch } from '../../../utils/embed-authed-fetch';
22
23
  import { AUTO_CONTINUATION_DIRECTIVE_PREFIX } from '../utils/auto-continuation-directive';
23
24
  import type { Message } from './use-chat';
24
25
 
25
- /** Narrow one hop of an untrusted JSON body to something with readable keys.
26
- * `typeof null === 'object'`, so the null check is the whole point. */
27
- function isRecord(value: unknown): value is Record<string, unknown> {
28
- return typeof value === 'object' && value !== null;
29
- }
30
-
31
26
  export interface UseChatHistoryHydrationArgs {
32
27
  /** Mirrors the adapter's `active` gate — an idle (Mingo-mode) mount never fetches. */
33
28
  active: boolean;
@@ -35,8 +30,10 @@ export interface UseChatHistoryHydrationArgs {
35
30
  source: string;
36
31
  /** Resolved history endpoint (`<chatStreamUrl>/history` by default). */
37
32
  historyUrl: string;
38
- /** The server-issued conversation id (null = nothing to hydrate). */
39
- conversationIdRef: MutableRefObject<string | null>;
33
+ /** The server-issued conversation id (null = nothing to hydrate). A VALUE,
34
+ * not a ref: switching conversations (`selectDialog`) must re-run the
35
+ * fetch, so the id is an effect dependency. */
36
+ conversationId: string | null;
40
37
  /** User-send counter — set to the hydrated user-turn count so the next
41
38
  * live send lands on the following `sendIdx`. */
42
39
  sendCountRef: MutableRefObject<number>;
@@ -49,6 +46,14 @@ export interface UseChatHistoryHydrationArgs {
49
46
  ) => void;
50
47
  /** Invalidates the adapter's `latestMeta` memo after hydration lands. */
51
48
  bumpMetaTick: () => void;
49
+ /** The server answered OK and reported the id as NOT READABLE by this caller
50
+ * (`found: false`) — it no longer exists, or is no longer ours (e.g. the
51
+ * thread was claimed by an account and this browser is now signed out).
52
+ * Distinct from a fetch FAILURE, which keeps the id so a transient outage
53
+ * never loses context, and from a legitimately EMPTY but owned thread, which
54
+ * also keeps it. A host that persists the id should drop it here — otherwise
55
+ * every later turn streams an answer the server refuses to record. */
56
+ onOrphanedConversation?: (conversationId: string) => void;
52
57
  }
53
58
 
54
59
  export interface UseChatHistoryHydrationResult {
@@ -64,24 +69,34 @@ export function useChatHistoryHydration({
64
69
  active,
65
70
  source,
66
71
  historyUrl,
67
- conversationIdRef,
72
+ conversationId,
68
73
  sendCountRef,
69
74
  hydrateMessages,
70
75
  bumpMetaTick,
76
+ onOrphanedConversation,
71
77
  }: UseChatHistoryHydrationArgs): UseChatHistoryHydrationResult {
72
78
  const [isHydratingHistory, setIsHydratingHistory] = useState(false);
73
79
  const hydratedKeyRef = useRef<string | null>(null);
80
+ // Monotonic run id: only the LATEST hydration owns the loading flag, so a
81
+ // slow superseded run resolving after a newer one started cannot clear the
82
+ // skeleton out from under it. (Same guard `useManagedDialogList` uses.)
83
+ const runIdRef = useRef(0);
74
84
 
75
85
  useEffect(() => {
76
- if (!active) return undefined;
77
- // No stored conversation id → nothing to hydrate (fresh visitor / after
78
- // "new chat"); the first send establishes the conversation server-side.
79
- const conversationId = conversationIdRef.current;
80
- if (!conversationId) return undefined;
86
+ // The flag is owned by the fetch below and released in its `finally`; the
87
+ // CLEANUP releases it for every early exit and for a superseded run.
88
+ // `conversationId` is a DEPENDENCY (a dialog switch must re-fetch), so that
89
+ // path is reachable in normal use: before this, "new chat" or archiving the
90
+ // open thread mid-fetch left the flag stuck true forever and the panel
91
+ // wedged on a message skeleton.
92
+ if (!active || !conversationId) return () => setIsHydratingHistory(false);
81
93
  const key = `${source}:${conversationId}`;
82
- if (hydratedKeyRef.current === key) return undefined;
94
+ if (hydratedKeyRef.current === key) return () => setIsHydratingHistory(false);
83
95
  hydratedKeyRef.current = key;
84
96
  let cancelled = false;
97
+ let completed = false;
98
+ const runId = ++runIdRef.current;
99
+ const isCurrentRun = () => runIdRef.current === runId;
85
100
  setIsHydratingHistory(true);
86
101
  // Self-contained: try/catch/finally below, and every state write is gated
87
102
  // on `cancelled` so a superseded effect can't hydrate the new conversation.
@@ -90,13 +105,19 @@ export function useChatHistoryHydration({
90
105
  const res = await embedAuthedFetch(`${historyUrl}?conversationId=${encodeURIComponent(conversationId)}`, {
91
106
  method: 'GET',
92
107
  });
93
- if (!res.ok) return;
108
+ if (!res.ok) {
109
+ // Releases the once-guard exactly like the catch below — this path
110
+ // returns BEFORE it, and a transient 429/5xx must not mark the
111
+ // conversation hydrated for the rest of the mount. `isCurrentRun` so
112
+ // a superseded run can't release a key its replacement re-claimed
113
+ // (same key string, different run).
114
+ if (isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
115
+ return;
116
+ }
94
117
  // `.json()` is `any` — this is untrusted wire, so narrow it rather than
95
118
  // asserting the shape we hope for.
96
119
  const payload: unknown = await res.json().catch(() => null);
97
- // route-base successResponse envelope ({ data }) with a raw-body fallback.
98
- const envelope = isRecord(payload) ? payload.data : undefined;
99
- const body = envelope ?? payload;
120
+ const body = unwrapEnvelope(payload);
100
121
  const rawRows = isRecord(body) ? body.messages : undefined;
101
122
  // Non-object rows are DROPPED, not carried into the loop below. The
102
123
  // loop reads `row.role` unguarded, so a single `null` row threw a
@@ -104,7 +125,15 @@ export function useChatHistoryHydration({
104
125
  // hydration wholesale and rendering an EMPTY conversation on refresh.
105
126
  // Skipping the bad row keeps every good one.
106
127
  const rows: Array<Record<string, unknown>> = Array.isArray(rawRows) ? rawRows.filter(isRecord) : [];
107
- if (cancelled || rows.length === 0) return;
128
+ if (cancelled) return;
129
+ if (rows.length === 0) {
130
+ // `found === false` = unknown or foreign id → the stored id is dead.
131
+ // An owned-but-empty thread (`found === true`, or a server that
132
+ // predates the flag) keeps it.
133
+ const found = isRecord(body) ? body.found : undefined;
134
+ if (found === false) onOrphanedConversation?.(conversationId);
135
+ return;
136
+ }
108
137
  const hydrated: Message[] = [];
109
138
  // Per-send "Sources used" chips, restored from the persisted audit
110
139
  // copy the history route projects as `sources` on assistant rows —
@@ -139,16 +168,30 @@ export function useChatHistoryHydration({
139
168
  bumpMetaTick();
140
169
  } catch {
141
170
  // Fetch failed — start empty; the server still owns history (above).
171
+ // Release the once-guard so re-selecting the conversation retries
172
+ // (a transient 429/5xx must not mark it hydrated for the mount).
173
+ if (isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
142
174
  } finally {
143
- if (!cancelled) setIsHydratingHistory(false);
175
+ completed = true;
176
+ // Only the latest run owns the flag (React no-ops updates after unmount).
177
+ if (isCurrentRun()) setIsHydratingHistory(false);
144
178
  }
145
179
  })();
146
180
  return () => {
147
181
  cancelled = true;
182
+ // An INCOMPLETE run must hand the key back, or a re-run for the SAME key
183
+ // (a mode toggle flipping `active`, a StrictMode remount) early-returns
184
+ // on the guard, drops the in-flight response and never refetches — the
185
+ // thread would render empty for the rest of the mount while the server
186
+ // keeps answering from history the user cannot see.
187
+ if (!completed && isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
188
+ // Release the skeleton unless a newer run has already claimed it (that
189
+ // run raises the flag itself and owns clearing it).
190
+ if (isCurrentRun()) setIsHydratingHistory(false);
148
191
  };
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]);
192
+ // `sendCountRef` is a ref: a stable identity, so listing it costs nothing;
193
+ // `conversationId` is the real re-run trigger (dialog switch).
194
+ }, [active, source, historyUrl, conversationId, hydrateMessages, bumpMetaTick, onOrphanedConversation, sendCountRef]);
152
195
 
153
196
  return { isHydratingHistory, hydratedKeyRef };
154
197
  }