@djangocfg/ui-tools 2.1.335 → 2.1.337

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 (194) hide show
  1. package/README.md +68 -2
  2. package/dist/ChatRoot-PNNGQCYF.css +7 -0
  3. package/dist/ChatRoot-PNNGQCYF.css.map +1 -0
  4. package/dist/ChatRoot-XV2QXMV4.mjs +5 -0
  5. package/dist/ChatRoot-XV2QXMV4.mjs.map +1 -0
  6. package/dist/ChatRoot-YX4RLHQX.cjs +14 -0
  7. package/dist/ChatRoot-YX4RLHQX.cjs.map +1 -0
  8. package/dist/{CronScheduler.client-3O3VU4CI.mjs → CronScheduler.client-DLMXCPAJ.mjs} +4 -4
  9. package/dist/{CronScheduler.client-3O3VU4CI.mjs.map → CronScheduler.client-DLMXCPAJ.mjs.map} +1 -1
  10. package/dist/{CronScheduler.client-A4GO6YBY.cjs → CronScheduler.client-WEJF4PWQ.cjs} +14 -14
  11. package/dist/{CronScheduler.client-A4GO6YBY.cjs.map → CronScheduler.client-WEJF4PWQ.cjs.map} +1 -1
  12. package/dist/{DocsLayout-XLDB6CJ2.cjs → DocsLayout-N5ZJZPBY.cjs} +200 -199
  13. package/dist/DocsLayout-N5ZJZPBY.cjs.map +1 -0
  14. package/dist/{DocsLayout-CTJINVBM.mjs → DocsLayout-VFPPNKSQ.mjs} +7 -6
  15. package/dist/DocsLayout-VFPPNKSQ.mjs.map +1 -0
  16. package/dist/JsonSchemaForm-DD7CLRIG.cjs +13 -0
  17. package/dist/{JsonSchemaForm-6WMS4CIY.cjs.map → JsonSchemaForm-DD7CLRIG.cjs.map} +1 -1
  18. package/dist/JsonSchemaForm-XKUIVELK.mjs +4 -0
  19. package/dist/{JsonSchemaForm-KX4JT3M4.mjs.map → JsonSchemaForm-XKUIVELK.mjs.map} +1 -1
  20. package/dist/JsonTree-55625VVH.mjs +5 -0
  21. package/dist/{JsonTree-F27RMYSI.cjs.map → JsonTree-55625VVH.mjs.map} +1 -1
  22. package/dist/JsonTree-DCM5QGWF.cjs +11 -0
  23. package/dist/{JsonTree-QTJYSHCV.mjs.map → JsonTree-DCM5QGWF.cjs.map} +1 -1
  24. package/dist/{LottiePlayer.client-6WVWDO75.cjs → LottiePlayer.client-2S7ISJ2S.cjs} +6 -6
  25. package/dist/{LottiePlayer.client-6WVWDO75.cjs.map → LottiePlayer.client-2S7ISJ2S.cjs.map} +1 -1
  26. package/dist/{LottiePlayer.client-B4I6WNZM.mjs → LottiePlayer.client-5LDSSJWS.mjs} +4 -4
  27. package/dist/{LottiePlayer.client-B4I6WNZM.mjs.map → LottiePlayer.client-5LDSSJWS.mjs.map} +1 -1
  28. package/dist/{MapContainer-RYG4HPH4.cjs → MapContainer-76YL2JXL.cjs} +8 -8
  29. package/dist/{MapContainer-RYG4HPH4.cjs.map → MapContainer-76YL2JXL.cjs.map} +1 -1
  30. package/dist/{MapContainer-GXQLP5WY.mjs → MapContainer-7HXBI3OH.mjs} +3 -3
  31. package/dist/{MapContainer-GXQLP5WY.mjs.map → MapContainer-7HXBI3OH.mjs.map} +1 -1
  32. package/dist/{Mermaid.client-SXRRI2YW.mjs → Mermaid.client-NL4SVR7F.mjs} +4 -4
  33. package/dist/{Mermaid.client-SXRRI2YW.mjs.map → Mermaid.client-NL4SVR7F.mjs.map} +1 -1
  34. package/dist/{Mermaid.client-W76R5AKJ.cjs → Mermaid.client-NNTI6DFX.cjs} +26 -26
  35. package/dist/{Mermaid.client-W76R5AKJ.cjs.map → Mermaid.client-NNTI6DFX.cjs.map} +1 -1
  36. package/dist/Player-BRV7XTWR.mjs +4 -0
  37. package/dist/{Player-M3GC3VPE.mjs.map → Player-BRV7XTWR.mjs.map} +1 -1
  38. package/dist/Player-PM7F7DD7.cjs +13 -0
  39. package/dist/{Player-ZL2X5LGG.cjs.map → Player-PM7F7DD7.cjs.map} +1 -1
  40. package/dist/{PrettyCode.client-RPDIE5CH.cjs → PrettyCode.client-KOHDVPPN.cjs} +13 -13
  41. package/dist/{PrettyCode.client-RPDIE5CH.cjs.map → PrettyCode.client-KOHDVPPN.cjs.map} +1 -1
  42. package/dist/{PrettyCode.client-SPMTQEG4.mjs → PrettyCode.client-ZGYGKE7G.mjs} +4 -4
  43. package/dist/{PrettyCode.client-SPMTQEG4.mjs.map → PrettyCode.client-ZGYGKE7G.mjs.map} +1 -1
  44. package/dist/TreeRoot-N72OYKXU.cjs +19 -0
  45. package/dist/{TreeRoot-A3J65L6F.mjs.map → TreeRoot-N72OYKXU.cjs.map} +1 -1
  46. package/dist/TreeRoot-VGAIXCUA.mjs +4 -0
  47. package/dist/{TreeRoot-DSK5JILT.cjs.map → TreeRoot-VGAIXCUA.mjs.map} +1 -1
  48. package/dist/chunk-2ZLKZ5VR.mjs +631 -0
  49. package/dist/chunk-2ZLKZ5VR.mjs.map +1 -0
  50. package/dist/{chunk-LFWQ36LJ.mjs → chunk-5G5YBFS6.mjs} +4 -4
  51. package/dist/{chunk-LFWQ36LJ.mjs.map → chunk-5G5YBFS6.mjs.map} +1 -1
  52. package/dist/{chunk-IHAY6FO6.cjs → chunk-5I5QNGUG.cjs} +17 -17
  53. package/dist/{chunk-IHAY6FO6.cjs.map → chunk-5I5QNGUG.cjs.map} +1 -1
  54. package/dist/{chunk-F2CMIIOH.cjs → chunk-76NNDZH6.cjs} +42 -42
  55. package/dist/{chunk-F2CMIIOH.cjs.map → chunk-76NNDZH6.cjs.map} +1 -1
  56. package/dist/chunk-B5AWZOHJ.cjs +649 -0
  57. package/dist/chunk-B5AWZOHJ.cjs.map +1 -0
  58. package/dist/{chunk-KR6B3LVY.mjs → chunk-B6IR5KSC.mjs} +3 -3
  59. package/dist/{chunk-KR6B3LVY.mjs.map → chunk-B6IR5KSC.mjs.map} +1 -1
  60. package/dist/{chunk-5LBDYFWH.mjs → chunk-C6GXVH5J.mjs} +3 -3
  61. package/dist/{chunk-5LBDYFWH.mjs.map → chunk-C6GXVH5J.mjs.map} +1 -1
  62. package/dist/{chunk-NRKD4F5X.cjs → chunk-FEN5S772.cjs} +36 -36
  63. package/dist/{chunk-NRKD4F5X.cjs.map → chunk-FEN5S772.cjs.map} +1 -1
  64. package/dist/{chunk-2SMCH62O.cjs → chunk-FP2RLYQZ.cjs} +11 -11
  65. package/dist/{chunk-2SMCH62O.cjs.map → chunk-FP2RLYQZ.cjs.map} +1 -1
  66. package/dist/{chunk-MOME6KYD.mjs → chunk-G5IEC7SR.mjs} +3 -3
  67. package/dist/{chunk-MOME6KYD.mjs.map → chunk-G5IEC7SR.mjs.map} +1 -1
  68. package/dist/{chunk-SE5IERVH.mjs → chunk-GYIO7W7M.mjs} +3 -3
  69. package/dist/{chunk-SE5IERVH.mjs.map → chunk-GYIO7W7M.mjs.map} +1 -1
  70. package/dist/{chunk-3Z3A7FHA.cjs → chunk-IEEAENLX.cjs} +48 -48
  71. package/dist/{chunk-3Z3A7FHA.cjs.map → chunk-IEEAENLX.cjs.map} +1 -1
  72. package/dist/{chunk-DFTVB66S.cjs → chunk-KNDLV4PI.cjs} +85 -85
  73. package/dist/{chunk-DFTVB66S.cjs.map → chunk-KNDLV4PI.cjs.map} +1 -1
  74. package/dist/{chunk-SSUOENAZ.mjs → chunk-KNEQRUBA.mjs} +3 -3
  75. package/dist/{chunk-SSUOENAZ.mjs.map → chunk-KNEQRUBA.mjs.map} +1 -1
  76. package/dist/{chunk-CGILA3WO.mjs → chunk-N2XQF2OL.mjs} +5 -3
  77. package/dist/{chunk-CGILA3WO.mjs.map → chunk-N2XQF2OL.mjs.map} +1 -1
  78. package/dist/{chunk-EUADAUBQ.mjs → chunk-N4MZYNR4.mjs} +4 -4
  79. package/dist/{chunk-EUADAUBQ.mjs.map → chunk-N4MZYNR4.mjs.map} +1 -1
  80. package/dist/{chunk-GGKGH5PM.mjs → chunk-OBRSGM64.mjs} +4 -4
  81. package/dist/{chunk-GGKGH5PM.mjs.map → chunk-OBRSGM64.mjs.map} +1 -1
  82. package/dist/{chunk-6JTB2X72.mjs → chunk-ODO4GMW7.mjs} +3 -3
  83. package/dist/{chunk-6JTB2X72.mjs.map → chunk-ODO4GMW7.mjs.map} +1 -1
  84. package/dist/{chunk-WGEGR3DF.cjs → chunk-OLISEQHS.cjs} +5 -2
  85. package/dist/{chunk-WGEGR3DF.cjs.map → chunk-OLISEQHS.cjs.map} +1 -1
  86. package/dist/{chunk-PZKAH7WQ.mjs → chunk-PVAX67JG.mjs} +3 -3
  87. package/dist/{chunk-PZKAH7WQ.mjs.map → chunk-PVAX67JG.mjs.map} +1 -1
  88. package/dist/{chunk-PRPG2T2E.cjs → chunk-QJ6GTUCO.cjs} +6 -6
  89. package/dist/{chunk-PRPG2T2E.cjs.map → chunk-QJ6GTUCO.cjs.map} +1 -1
  90. package/dist/chunk-QW4RBGHN.cjs +961 -0
  91. package/dist/chunk-QW4RBGHN.cjs.map +1 -0
  92. package/dist/{chunk-33AMWFBZ.cjs → chunk-SGP7V2UW.cjs} +15 -15
  93. package/dist/{chunk-33AMWFBZ.cjs.map → chunk-SGP7V2UW.cjs.map} +1 -1
  94. package/dist/{chunk-FX2QFYWF.mjs → chunk-VWQ5WOIL.mjs} +3 -3
  95. package/dist/{chunk-FX2QFYWF.mjs.map → chunk-VWQ5WOIL.mjs.map} +1 -1
  96. package/dist/{chunk-ZLQHUZDU.cjs → chunk-YDPDTOSP.cjs} +139 -139
  97. package/dist/{chunk-ZLQHUZDU.cjs.map → chunk-YDPDTOSP.cjs.map} +1 -1
  98. package/dist/{chunk-77HQWEQ6.cjs → chunk-YW5IVWHQ.cjs} +33 -33
  99. package/dist/{chunk-77HQWEQ6.cjs.map → chunk-YW5IVWHQ.cjs.map} +1 -1
  100. package/dist/chunk-YWSQDBNU.mjs +2339 -0
  101. package/dist/chunk-YWSQDBNU.mjs.map +1 -0
  102. package/dist/{chunk-YXBOAGIM.cjs → chunk-YXZ6GU7H.cjs} +7 -7
  103. package/dist/{chunk-YXBOAGIM.cjs.map → chunk-YXZ6GU7H.cjs.map} +1 -1
  104. package/dist/{chunk-62Y65TGK.mjs → chunk-ZUFTH5IR.mjs} +8 -631
  105. package/dist/chunk-ZUFTH5IR.mjs.map +1 -0
  106. package/dist/chunk-ZWPBBAR2.cjs +2379 -0
  107. package/dist/chunk-ZWPBBAR2.cjs.map +1 -0
  108. package/dist/components-EHOGXATG.cjs +22 -0
  109. package/dist/{components-5UXYNAKR.cjs.map → components-EHOGXATG.cjs.map} +1 -1
  110. package/dist/components-MQ6DR7TX.cjs +26 -0
  111. package/dist/{components-CFXOEVPN.mjs.map → components-MQ6DR7TX.cjs.map} +1 -1
  112. package/dist/components-XRX7QGLB.mjs +5 -0
  113. package/dist/{components-WYEZL5TE.cjs.map → components-XRX7QGLB.mjs.map} +1 -1
  114. package/dist/components-YATKRWLH.mjs +5 -0
  115. package/dist/{components-ZAGG2PBO.mjs.map → components-YATKRWLH.mjs.map} +1 -1
  116. package/dist/file-icon/index.cjs +6 -6
  117. package/dist/file-icon/index.mjs +1 -1
  118. package/dist/index.cjs +739 -215
  119. package/dist/index.cjs.map +1 -1
  120. package/dist/index.d.cts +1025 -39
  121. package/dist/index.d.ts +1025 -39
  122. package/dist/index.mjs +387 -31
  123. package/dist/index.mjs.map +1 -1
  124. package/dist/tree/index.cjs +38 -38
  125. package/dist/tree/index.d.cts +2 -2
  126. package/dist/tree/index.d.ts +2 -2
  127. package/dist/tree/index.mjs +3 -3
  128. package/package.json +6 -6
  129. package/src/index.ts +5 -0
  130. package/src/stories/index.ts +3 -1
  131. package/src/tools/Chat/Chat.story.tsx +1006 -0
  132. package/src/tools/Chat/README.md +528 -0
  133. package/src/tools/Chat/components/Attachments.tsx +192 -0
  134. package/src/tools/Chat/components/ChatRoot.tsx +208 -0
  135. package/src/tools/Chat/components/Composer.tsx +134 -0
  136. package/src/tools/Chat/components/EmptyState.tsx +47 -0
  137. package/src/tools/Chat/components/ErrorBanner.tsx +47 -0
  138. package/src/tools/Chat/components/JumpToLatest.tsx +30 -0
  139. package/src/tools/Chat/components/MessageActions.tsx +72 -0
  140. package/src/tools/Chat/components/MessageBubble.tsx +228 -0
  141. package/src/tools/Chat/components/MessageList.tsx +82 -0
  142. package/src/tools/Chat/components/Sources.tsx +55 -0
  143. package/src/tools/Chat/components/StreamingIndicator.tsx +29 -0
  144. package/src/tools/Chat/components/ToolCalls.tsx +172 -0
  145. package/src/tools/Chat/components/index.ts +24 -0
  146. package/src/tools/Chat/config.ts +55 -0
  147. package/src/tools/Chat/context/ChatProvider.tsx +126 -0
  148. package/src/tools/Chat/context/index.ts +9 -0
  149. package/src/tools/Chat/core/audio/audioBus.ts +172 -0
  150. package/src/tools/Chat/core/audio/index.ts +8 -0
  151. package/src/tools/Chat/core/audio/preferences.ts +68 -0
  152. package/src/tools/Chat/core/audio/types.ts +49 -0
  153. package/src/tools/Chat/core/ids.ts +16 -0
  154. package/src/tools/Chat/core/index.ts +5 -0
  155. package/src/tools/Chat/core/logger.ts +73 -0
  156. package/src/tools/Chat/core/markdown.ts +56 -0
  157. package/src/tools/Chat/core/payload-dispatch.ts +54 -0
  158. package/src/tools/Chat/core/persona.ts +35 -0
  159. package/src/tools/Chat/core/reducer.ts +335 -0
  160. package/src/tools/Chat/core/transport/http.ts +167 -0
  161. package/src/tools/Chat/core/transport/index.ts +13 -0
  162. package/src/tools/Chat/core/transport/mock.ts +134 -0
  163. package/src/tools/Chat/core/transport/sse.ts +116 -0
  164. package/src/tools/Chat/core/transport/types.ts +24 -0
  165. package/src/tools/Chat/hooks/index.ts +26 -0
  166. package/src/tools/Chat/hooks/useChat.ts +555 -0
  167. package/src/tools/Chat/hooks/useChatAudio.ts +191 -0
  168. package/src/tools/Chat/hooks/useChatComposer.ts +227 -0
  169. package/src/tools/Chat/hooks/useChatHistory.ts +59 -0
  170. package/src/tools/Chat/hooks/useChatLayout.ts +111 -0
  171. package/src/tools/Chat/hooks/useChatLightbox.ts +34 -0
  172. package/src/tools/Chat/hooks/useChatScroll.ts +132 -0
  173. package/src/tools/Chat/index.ts +161 -0
  174. package/src/tools/Chat/lazy.tsx +14 -0
  175. package/src/tools/Chat/types.ts +237 -0
  176. package/src/tools/Chat/utils/collectImageAttachments.ts +13 -0
  177. package/src/tools/Map/README.md +384 -0
  178. package/dist/DocsLayout-CTJINVBM.mjs.map +0 -1
  179. package/dist/DocsLayout-XLDB6CJ2.cjs.map +0 -1
  180. package/dist/JsonSchemaForm-6WMS4CIY.cjs +0 -13
  181. package/dist/JsonSchemaForm-KX4JT3M4.mjs +0 -4
  182. package/dist/JsonTree-F27RMYSI.cjs +0 -11
  183. package/dist/JsonTree-QTJYSHCV.mjs +0 -5
  184. package/dist/Player-M3GC3VPE.mjs +0 -4
  185. package/dist/Player-ZL2X5LGG.cjs +0 -13
  186. package/dist/TreeRoot-A3J65L6F.mjs +0 -4
  187. package/dist/TreeRoot-DSK5JILT.cjs +0 -19
  188. package/dist/chunk-62Y65TGK.mjs.map +0 -1
  189. package/dist/chunk-TKSFZHCG.cjs +0 -1597
  190. package/dist/chunk-TKSFZHCG.cjs.map +0 -1
  191. package/dist/components-5UXYNAKR.cjs +0 -22
  192. package/dist/components-CFXOEVPN.mjs +0 -5
  193. package/dist/components-WYEZL5TE.cjs +0 -26
  194. package/dist/components-ZAGG2PBO.mjs +0 -5
@@ -0,0 +1,2379 @@
1
+ 'use strict';
2
+
3
+ var chunkB5AWZOHJ_cjs = require('./chunk-B5AWZOHJ.cjs');
4
+ var chunkOLISEQHS_cjs = require('./chunk-OLISEQHS.cjs');
5
+ var react = require('react');
6
+ var lib = require('@djangocfg/ui-core/lib');
7
+ var consola = require('consola');
8
+ var hooks = require('@djangocfg/ui-core/hooks');
9
+ var zustand = require('zustand');
10
+ var middleware = require('zustand/middleware');
11
+ var jsxRuntime = require('react/jsx-runtime');
12
+ var lucideReact = require('lucide-react');
13
+ var components = require('@djangocfg/ui-core/components');
14
+
15
+ // src/tools/Chat/types.ts
16
+ var DEFAULT_LABELS = {
17
+ send: "Send",
18
+ cancel: "Stop",
19
+ copy: "Copy",
20
+ regenerate: "Regenerate",
21
+ edit: "Edit",
22
+ delete: "Delete",
23
+ retry: "Retry",
24
+ newChat: "New chat",
25
+ loadMore: "Load more",
26
+ jumpToLatest: "Jump to latest",
27
+ attach: "Attach files",
28
+ voice: "Voice input",
29
+ errorGeneric: "Something went wrong",
30
+ cancelledSuffix: "[cancelled]"
31
+ };
32
+
33
+ // src/tools/Chat/config.ts
34
+ var STORAGE_KEYS = {
35
+ mode: "djc-chat-mode",
36
+ sidebarWidth: "djc-chat-sidebar-width",
37
+ composerHistory: "djc-chat-composer-history"
38
+ };
39
+ var CSS_VARS = {
40
+ reserve: "--djc-chat-reserve"
41
+ };
42
+ var DEFAULT_Z_INDEX = 9e3;
43
+ var LIMITS = {
44
+ /** Max characters per single message. */
45
+ messageMaxLength: 8e3,
46
+ /** Max attachments per message. */
47
+ attachmentsMax: 10,
48
+ /** Composer history slots. */
49
+ composerHistorySize: 50,
50
+ /** Coalesce stream tokens within this window before dispatching. */
51
+ streamCoalesceMs: 16,
52
+ /** Default history page size. */
53
+ pageSize: 50,
54
+ /** Virtualize list when >= this many messages (host-controlled threshold). */
55
+ virtualizeThreshold: 50,
56
+ /** SSE idle timeout. */
57
+ sseIdleMs: 45e3
58
+ };
59
+ var DEFAULT_SIDEBAR = {
60
+ width: 420,
61
+ min: 320,
62
+ max: 720
63
+ };
64
+ var HOTKEYS = {
65
+ send: "mod+enter",
66
+ cancel: "esc",
67
+ newChat: "mod+shift+n",
68
+ toggleOpen: "mod+/",
69
+ focusComposer: "mod+l"
70
+ };
71
+ var CHAT_EVENT_NAME = "djc:chat:send";
72
+
73
+ // src/tools/Chat/core/reducer.ts
74
+ var initialState = {
75
+ sessionId: null,
76
+ messages: [],
77
+ isLoading: false,
78
+ isStreaming: false,
79
+ isLoadingMore: false,
80
+ hasMore: true,
81
+ oldestCursor: null,
82
+ error: null
83
+ };
84
+ function updateLastStreaming(messages, patch) {
85
+ const idx = findLastStreamingIndex(messages);
86
+ if (idx === -1) return messages;
87
+ const next = messages.slice();
88
+ next[idx] = patch(messages[idx]);
89
+ return next;
90
+ }
91
+ chunkOLISEQHS_cjs.__name(updateLastStreaming, "updateLastStreaming");
92
+ function findLastStreamingIndex(messages) {
93
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
94
+ if (messages[i].isStreaming) return i;
95
+ }
96
+ return -1;
97
+ }
98
+ chunkOLISEQHS_cjs.__name(findLastStreamingIndex, "findLastStreamingIndex");
99
+ function patchMessageById(messages, id, patch) {
100
+ const idx = messages.findIndex((m) => m.id === id);
101
+ if (idx === -1) return messages;
102
+ const next = messages.slice();
103
+ next[idx] = patch(messages[idx]);
104
+ return next;
105
+ }
106
+ chunkOLISEQHS_cjs.__name(patchMessageById, "patchMessageById");
107
+ function reducer(state, action) {
108
+ switch (action.type) {
109
+ case "SESSION_SET":
110
+ return {
111
+ ...state,
112
+ sessionId: action.sessionId,
113
+ messages: action.messages ?? state.messages,
114
+ hasMore: action.hasMore ?? state.hasMore,
115
+ oldestCursor: action.cursor ?? state.oldestCursor,
116
+ error: null
117
+ };
118
+ case "HISTORY_LOAD_START":
119
+ return { ...state, isLoading: true, error: null };
120
+ case "HISTORY_LOAD_DONE":
121
+ return {
122
+ ...state,
123
+ isLoading: false,
124
+ messages: action.messages,
125
+ hasMore: action.hasMore,
126
+ oldestCursor: action.cursor
127
+ };
128
+ case "HISTORY_MORE_START":
129
+ return { ...state, isLoadingMore: true };
130
+ case "HISTORY_MORE_DONE":
131
+ return {
132
+ ...state,
133
+ isLoadingMore: false,
134
+ // Older messages prepend to the top.
135
+ messages: [...action.messages, ...state.messages],
136
+ hasMore: action.hasMore,
137
+ oldestCursor: action.cursor
138
+ };
139
+ case "MESSAGE_USER_ADD":
140
+ return {
141
+ ...state,
142
+ messages: [...state.messages, action.message],
143
+ error: null
144
+ };
145
+ case "STREAM_START": {
146
+ if (state.isStreaming) {
147
+ if (typeof console !== "undefined") {
148
+ console.warn("[chat] STREAM_START while already streaming, ignoring");
149
+ }
150
+ return state;
151
+ }
152
+ const placeholder = {
153
+ id: action.id,
154
+ role: "assistant",
155
+ content: "",
156
+ createdAt: action.createdAt ?? Date.now(),
157
+ isStreaming: true
158
+ };
159
+ return {
160
+ ...state,
161
+ isStreaming: true,
162
+ messages: [...state.messages, placeholder]
163
+ };
164
+ }
165
+ case "STREAM_CHUNK": {
166
+ const messages = updateLastStreaming(state.messages, (m) => ({
167
+ ...m,
168
+ content: m.content + action.delta
169
+ }));
170
+ return { ...state, messages };
171
+ }
172
+ case "STREAM_TOOL_ACTIVITY": {
173
+ const messages = updateLastStreaming(state.messages, (m) => ({
174
+ ...m,
175
+ toolActivity: action.tool
176
+ }));
177
+ return { ...state, messages };
178
+ }
179
+ case "TOOL_CALL_START": {
180
+ const messages = patchMessageById(state.messages, action.messageId, (m) => ({
181
+ ...m,
182
+ toolCalls: [...m.toolCalls ?? [], action.toolCall]
183
+ }));
184
+ return { ...state, messages };
185
+ }
186
+ case "TOOL_CALL_DELTA": {
187
+ const messages = patchMessageById(state.messages, action.messageId, (m) => {
188
+ if (!m.toolCalls) return m;
189
+ return {
190
+ ...m,
191
+ toolCalls: m.toolCalls.map(
192
+ (tc) => tc.id === action.toolId ? { ...tc, streamingText: (tc.streamingText ?? "") + action.delta } : tc
193
+ )
194
+ };
195
+ });
196
+ return { ...state, messages };
197
+ }
198
+ case "TOOL_CALL_END": {
199
+ const messages = patchMessageById(state.messages, action.messageId, (m) => {
200
+ if (!m.toolCalls) return m;
201
+ return {
202
+ ...m,
203
+ toolCalls: m.toolCalls.map(
204
+ (tc) => tc.id === action.toolId ? {
205
+ ...tc,
206
+ output: action.output,
207
+ status: action.status,
208
+ streamingText: void 0,
209
+ endedAt: Date.now()
210
+ } : tc
211
+ )
212
+ };
213
+ });
214
+ return { ...state, messages };
215
+ }
216
+ case "STREAM_DONE": {
217
+ const messages = patchMessageById(state.messages, action.id, (m) => ({
218
+ ...m,
219
+ isStreaming: false,
220
+ tokensIn: action.tokensIn ?? m.tokensIn,
221
+ tokensOut: action.tokensOut ?? m.tokensOut,
222
+ sources: action.sources ?? m.sources
223
+ }));
224
+ return { ...state, isStreaming: false, messages };
225
+ }
226
+ case "STREAM_CANCELLED": {
227
+ const suffix = action.label ?? "[cancelled]";
228
+ const messages = patchMessageById(state.messages, action.id, (m) => ({
229
+ ...m,
230
+ isStreaming: false,
231
+ content: action.partialText + (action.partialText ? `
232
+
233
+ _${suffix}_` : `_${suffix}_`)
234
+ }));
235
+ return { ...state, isStreaming: false, messages };
236
+ }
237
+ case "STREAM_ERROR": {
238
+ const messages = action.id ? patchMessageById(state.messages, action.id, (m) => ({
239
+ ...m,
240
+ isStreaming: false,
241
+ isError: true
242
+ })) : state.messages;
243
+ return { ...state, isStreaming: false, error: action.message, messages };
244
+ }
245
+ case "MESSAGE_EDIT": {
246
+ const messages = patchMessageById(state.messages, action.id, (m) => ({
247
+ ...m,
248
+ content: action.content,
249
+ version: (m.version ?? 0) + 1
250
+ }));
251
+ return { ...state, messages };
252
+ }
253
+ case "MESSAGE_DELETE":
254
+ return {
255
+ ...state,
256
+ messages: state.messages.filter((m) => m.id !== action.id)
257
+ };
258
+ case "MESSAGES_CLEAR":
259
+ return {
260
+ ...state,
261
+ messages: [],
262
+ isStreaming: false,
263
+ error: null
264
+ };
265
+ case "ERROR_SET":
266
+ return { ...state, error: action.error };
267
+ case "ATTACHMENT_PROGRESS": {
268
+ const messages = patchMessageById(state.messages, action.messageId, (m) => {
269
+ if (!m.attachments) return m;
270
+ return {
271
+ ...m,
272
+ attachments: m.attachments.map(
273
+ (a) => a.id === action.attachmentId ? {
274
+ ...a,
275
+ progress: action.progress ?? a.progress,
276
+ status: action.status ?? a.status
277
+ } : a
278
+ )
279
+ };
280
+ });
281
+ return { ...state, messages };
282
+ }
283
+ default: {
284
+ return state;
285
+ }
286
+ }
287
+ }
288
+ chunkOLISEQHS_cjs.__name(reducer, "reducer");
289
+
290
+ // src/tools/Chat/core/ids.ts
291
+ var counter = 0;
292
+ function createId(prefix = "m") {
293
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
294
+ return `${prefix}_${crypto.randomUUID()}`;
295
+ }
296
+ counter += 1;
297
+ return `${prefix}_${Date.now().toString(36)}_${counter.toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
298
+ }
299
+ chunkOLISEQHS_cjs.__name(createId, "createId");
300
+ var SCOPES = ["bootstrap", "transport", "stream", "lifecycle", "tools", "error"];
301
+ var cache = /* @__PURE__ */ new Map();
302
+ function buildLogger(enabled) {
303
+ const root = consola.consola.withTag("chat");
304
+ const subs = Object.fromEntries(
305
+ SCOPES.map((scope) => [scope, root.withTag(scope)])
306
+ );
307
+ if (!enabled) {
308
+ for (const scope of SCOPES) {
309
+ if (scope === "error") continue;
310
+ subs[scope].level = -999;
311
+ }
312
+ }
313
+ return { ...subs, enabled };
314
+ }
315
+ chunkOLISEQHS_cjs.__name(buildLogger, "buildLogger");
316
+ function getChatLogger(debug) {
317
+ const enabled = debug ?? lib.isDev;
318
+ let logger = cache.get(enabled);
319
+ if (!logger) {
320
+ logger = buildLogger(enabled);
321
+ cache.set(enabled, logger);
322
+ }
323
+ return logger;
324
+ }
325
+ chunkOLISEQHS_cjs.__name(getChatLogger, "getChatLogger");
326
+
327
+ // src/tools/Chat/core/markdown.ts
328
+ function createTokenBuffer(onFlush, windowMs = LIMITS.streamCoalesceMs) {
329
+ let pending = "";
330
+ let timer = null;
331
+ let closed = false;
332
+ const flush = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
333
+ if (timer) {
334
+ clearTimeout(timer);
335
+ timer = null;
336
+ }
337
+ if (pending) {
338
+ const out = pending;
339
+ pending = "";
340
+ onFlush(out);
341
+ }
342
+ }, "flush");
343
+ return {
344
+ push(delta) {
345
+ if (closed || !delta) return;
346
+ pending += delta;
347
+ if (windowMs <= 0) {
348
+ flush();
349
+ return;
350
+ }
351
+ if (timer === null) {
352
+ timer = setTimeout(flush, windowMs);
353
+ }
354
+ },
355
+ flush,
356
+ close() {
357
+ closed = true;
358
+ flush();
359
+ }
360
+ };
361
+ }
362
+ chunkOLISEQHS_cjs.__name(createTokenBuffer, "createTokenBuffer");
363
+
364
+ // src/tools/Chat/hooks/useChat.ts
365
+ function useChat(config) {
366
+ const [state, dispatch] = react.useReducer(reducer, initialState);
367
+ const stateRef = react.useRef(state);
368
+ stateRef.current = state;
369
+ const abortRef = react.useRef(null);
370
+ const lastErrorRef = react.useRef(null);
371
+ const initRef = react.useRef(false);
372
+ const streamingMsgIdRef = react.useRef(null);
373
+ const bootstrapRef = react.useRef(null);
374
+ const { transport, autoCreateSession = true, streaming = true, pageSize = LIMITS.pageSize } = config;
375
+ const log = getChatLogger(config.debug);
376
+ react.useEffect(() => {
377
+ if (initRef.current) return;
378
+ initRef.current = true;
379
+ let cancelled = false;
380
+ if (config.initialSessionId || autoCreateSession) {
381
+ dispatch({ type: "HISTORY_LOAD_START" });
382
+ }
383
+ log.bootstrap.info("start", {
384
+ mode: config.initialSessionId ? "resume" : autoCreateSession ? "create" : "idle",
385
+ initialSessionId: config.initialSessionId
386
+ });
387
+ const run = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(async () => {
388
+ const t0 = performance.now();
389
+ try {
390
+ if (config.initialSessionId) {
391
+ dispatch({
392
+ type: "SESSION_SET",
393
+ sessionId: config.initialSessionId
394
+ });
395
+ const page = await transport.loadHistory(config.initialSessionId, null, pageSize);
396
+ if (cancelled) {
397
+ log.bootstrap.debug("cancelled (post-loadHistory)");
398
+ return null;
399
+ }
400
+ dispatch({
401
+ type: "HISTORY_LOAD_DONE",
402
+ messages: page.messages,
403
+ hasMore: page.hasMore,
404
+ cursor: page.nextCursor
405
+ });
406
+ log.bootstrap.success("resumed", {
407
+ sessionId: config.initialSessionId,
408
+ messages: page.messages.length,
409
+ hasMore: page.hasMore,
410
+ elapsedMs: Math.round(performance.now() - t0)
411
+ });
412
+ return config.initialSessionId;
413
+ }
414
+ if (autoCreateSession) {
415
+ const info = await transport.createSession({ metadata: config.metadata });
416
+ if (cancelled) {
417
+ log.bootstrap.debug("cancelled (post-createSession)");
418
+ return null;
419
+ }
420
+ dispatch({
421
+ type: "SESSION_SET",
422
+ sessionId: info.sessionId,
423
+ messages: info.messages ?? [],
424
+ hasMore: info.hasMore ?? false,
425
+ cursor: info.cursor ?? null
426
+ });
427
+ dispatch({
428
+ type: "HISTORY_LOAD_DONE",
429
+ messages: info.messages ?? [],
430
+ hasMore: info.hasMore ?? false,
431
+ cursor: info.cursor ?? null
432
+ });
433
+ log.bootstrap.success("created", {
434
+ sessionId: info.sessionId,
435
+ resumed: info.resumed ?? false,
436
+ elapsedMs: Math.round(performance.now() - t0)
437
+ });
438
+ return info.sessionId;
439
+ }
440
+ log.bootstrap.debug("idle (no initialSessionId, autoCreateSession=false)");
441
+ return null;
442
+ } catch (err) {
443
+ if (cancelled) {
444
+ log.bootstrap.debug("cancelled (in catch)");
445
+ return null;
446
+ }
447
+ const e = err instanceof Error ? err : new Error(String(err));
448
+ lastErrorRef.current = e;
449
+ dispatch({ type: "ERROR_SET", error: e.message });
450
+ config.onError?.(e);
451
+ log.error.error("bootstrap failed", { message: e.message, elapsedMs: Math.round(performance.now() - t0) });
452
+ return null;
453
+ }
454
+ }, "run");
455
+ bootstrapRef.current = run();
456
+ return () => {
457
+ cancelled = true;
458
+ };
459
+ }, []);
460
+ const awaitSession = react.useCallback(async () => {
461
+ if (stateRef.current.sessionId) return stateRef.current.sessionId;
462
+ if (bootstrapRef.current) {
463
+ const id = await bootstrapRef.current;
464
+ if (id) return id;
465
+ }
466
+ return stateRef.current.sessionId;
467
+ }, []);
468
+ const consumeStream = react.useCallback(
469
+ async (sessionId, content, attachments) => {
470
+ const ctrl = new AbortController();
471
+ abortRef.current = ctrl;
472
+ const assistantId = createId("a");
473
+ streamingMsgIdRef.current = assistantId;
474
+ dispatch({ type: "STREAM_START", id: assistantId });
475
+ config.onStreamStart?.(assistantId);
476
+ log.stream.info("start", { sessionId, assistantId, chars: content.length });
477
+ const tokenBuffer = createTokenBuffer(
478
+ (delta) => dispatch({ type: "STREAM_CHUNK", delta })
479
+ );
480
+ let chunkCount = 0;
481
+ let charsReceived = 0;
482
+ const t0 = performance.now();
483
+ try {
484
+ const iterator = transport.stream(sessionId, content, {
485
+ signal: ctrl.signal,
486
+ attachments,
487
+ metadata: config.metadata
488
+ });
489
+ for await (const ev of iterator) {
490
+ if (ctrl.signal.aborted) break;
491
+ handleEvent(ev);
492
+ }
493
+ tokenBuffer.flush();
494
+ if (stateRef.current.isStreaming) {
495
+ dispatch({ type: "STREAM_DONE", id: assistantId });
496
+ }
497
+ const finalMsg = stateRef.current.messages.find((m) => m.id === assistantId);
498
+ if (finalMsg) config.onMessageEnd?.(finalMsg);
499
+ log.stream.success("done", {
500
+ assistantId,
501
+ chunks: chunkCount,
502
+ chars: charsReceived,
503
+ elapsedMs: Math.round(performance.now() - t0)
504
+ });
505
+ } catch (err) {
506
+ tokenBuffer.close();
507
+ if (ctrl.signal.aborted) {
508
+ const partial = stateRef.current.messages.find((m) => m.id === assistantId)?.content ?? "";
509
+ dispatch({ type: "STREAM_CANCELLED", id: assistantId, partialText: partial });
510
+ log.stream.warn("cancelled", { assistantId, partialChars: partial.length });
511
+ return;
512
+ }
513
+ const e = err instanceof Error ? err : new Error(String(err));
514
+ lastErrorRef.current = e;
515
+ dispatch({ type: "STREAM_ERROR", id: assistantId, message: e.message });
516
+ config.onError?.(e);
517
+ log.error.error("stream failed", { assistantId, message: e.message });
518
+ } finally {
519
+ tokenBuffer.close();
520
+ if (abortRef.current === ctrl) abortRef.current = null;
521
+ streamingMsgIdRef.current = null;
522
+ }
523
+ function handleEvent(ev) {
524
+ switch (ev.type) {
525
+ case "message_start":
526
+ ev.messageId;
527
+ log.stream.debug("message_start", { messageId: ev.messageId });
528
+ return;
529
+ case "chunk":
530
+ tokenBuffer.push(ev.delta);
531
+ chunkCount += 1;
532
+ charsReceived += ev.delta.length;
533
+ return;
534
+ case "tool_activity":
535
+ tokenBuffer.flush();
536
+ dispatch({ type: "STREAM_TOOL_ACTIVITY", tool: ev.tool });
537
+ log.tools.debug("activity", { tool: ev.tool, status: ev.status });
538
+ return;
539
+ case "tool_call_start": {
540
+ tokenBuffer.flush();
541
+ const toolCall = {
542
+ id: ev.toolId,
543
+ name: ev.name,
544
+ input: ev.input,
545
+ status: "running",
546
+ startedAt: Date.now(),
547
+ sourceHostname: ev.sourceHostname
548
+ };
549
+ dispatch({
550
+ type: "TOOL_CALL_START",
551
+ messageId: assistantId,
552
+ toolCall
553
+ });
554
+ log.tools.info("call_start", { toolId: ev.toolId, name: ev.name });
555
+ return;
556
+ }
557
+ case "tool_call_delta":
558
+ dispatch({
559
+ type: "TOOL_CALL_DELTA",
560
+ messageId: assistantId,
561
+ toolId: ev.toolId,
562
+ delta: ev.delta
563
+ });
564
+ return;
565
+ case "tool_call_end":
566
+ dispatch({
567
+ type: "TOOL_CALL_END",
568
+ messageId: assistantId,
569
+ toolId: ev.toolId,
570
+ output: ev.output,
571
+ status: ev.status
572
+ });
573
+ log.tools.info("call_end", { toolId: ev.toolId, status: ev.status });
574
+ return;
575
+ case "message_end":
576
+ tokenBuffer.flush();
577
+ dispatch({
578
+ type: "STREAM_DONE",
579
+ id: assistantId,
580
+ tokensIn: ev.tokensIn,
581
+ tokensOut: ev.tokensOut,
582
+ sources: ev.sources
583
+ });
584
+ log.stream.debug("message_end", {
585
+ tokensIn: ev.tokensIn,
586
+ tokensOut: ev.tokensOut,
587
+ sources: ev.sources?.length ?? 0
588
+ });
589
+ return;
590
+ case "error":
591
+ tokenBuffer.flush();
592
+ dispatch({
593
+ type: "STREAM_ERROR",
594
+ id: assistantId,
595
+ message: ev.message
596
+ });
597
+ log.error.error("stream event error", { code: ev.code, message: ev.message });
598
+ return;
599
+ }
600
+ }
601
+ chunkOLISEQHS_cjs.__name(handleEvent, "handleEvent");
602
+ },
603
+ [transport, config]
604
+ );
605
+ const consumeBuffered = react.useCallback(
606
+ async (sessionId, content, attachments) => {
607
+ const ctrl = new AbortController();
608
+ abortRef.current = ctrl;
609
+ try {
610
+ const reply = await transport.send(sessionId, content, {
611
+ signal: ctrl.signal,
612
+ attachments,
613
+ metadata: config.metadata
614
+ });
615
+ const placeholderId = createId("a");
616
+ dispatch({ type: "STREAM_START", id: placeholderId });
617
+ config.onStreamStart?.(placeholderId);
618
+ dispatch({ type: "STREAM_CHUNK", delta: reply.content });
619
+ dispatch({ type: "STREAM_DONE", id: placeholderId });
620
+ config.onMessageEnd?.(reply);
621
+ } catch (err) {
622
+ const e = err instanceof Error ? err : new Error(String(err));
623
+ lastErrorRef.current = e;
624
+ dispatch({ type: "STREAM_ERROR", message: e.message });
625
+ config.onError?.(e);
626
+ } finally {
627
+ if (abortRef.current === ctrl) abortRef.current = null;
628
+ }
629
+ },
630
+ [transport, config]
631
+ );
632
+ const sendMessage = react.useCallback(
633
+ async (content, attachments) => {
634
+ log.lifecycle.info("sendMessage", {
635
+ chars: content.length,
636
+ attachments: attachments?.length ?? 0,
637
+ hasSession: !!stateRef.current.sessionId
638
+ });
639
+ const sessionId = await awaitSession();
640
+ if (!sessionId) {
641
+ const e = new Error("No active session");
642
+ lastErrorRef.current = e;
643
+ dispatch({ type: "ERROR_SET", error: e.message });
644
+ config.onError?.(e);
645
+ log.error.error("sendMessage aborted: no session");
646
+ return;
647
+ }
648
+ if (!content.trim() && !(attachments && attachments.length > 0)) {
649
+ log.lifecycle.debug("sendMessage skipped (empty)");
650
+ return;
651
+ }
652
+ if (stateRef.current.isStreaming) {
653
+ log.lifecycle.debug("sendMessage skipped (already streaming)");
654
+ return;
655
+ }
656
+ const userMsg = {
657
+ id: createId("u"),
658
+ role: "user",
659
+ content,
660
+ createdAt: Date.now(),
661
+ attachments,
662
+ sender: config.userPersona
663
+ };
664
+ dispatch({ type: "MESSAGE_USER_ADD", message: userMsg });
665
+ config.onMessageSent?.(userMsg);
666
+ if (streaming) {
667
+ await consumeStream(sessionId, content, attachments);
668
+ } else {
669
+ await consumeBuffered(sessionId, content, attachments);
670
+ }
671
+ },
672
+ [streaming, consumeStream, consumeBuffered, config, awaitSession]
673
+ );
674
+ const cancelStream = react.useCallback(() => {
675
+ abortRef.current?.abort();
676
+ }, []);
677
+ const regenerate = react.useCallback(
678
+ async (messageId) => {
679
+ log.lifecycle.info("regenerate", { messageId: messageId ?? "(last)" });
680
+ const messages = stateRef.current.messages;
681
+ let targetUserIdx = -1;
682
+ if (messageId) {
683
+ const idx = messages.findIndex((m) => m.id === messageId);
684
+ if (idx !== -1) {
685
+ targetUserIdx = messages[idx].role === "user" ? idx : findPreviousUserIndex(messages, idx);
686
+ }
687
+ } else {
688
+ targetUserIdx = findLastUserIndex(messages);
689
+ }
690
+ if (targetUserIdx === -1) return;
691
+ const userMsg = messages[targetUserIdx];
692
+ for (let i = messages.length - 1; i > targetUserIdx; i -= 1) {
693
+ dispatch({ type: "MESSAGE_DELETE", id: messages[i].id });
694
+ }
695
+ const sessionId = await awaitSession();
696
+ if (!sessionId) return;
697
+ if (streaming) {
698
+ await consumeStream(sessionId, userMsg.content, userMsg.attachments);
699
+ } else {
700
+ await consumeBuffered(sessionId, userMsg.content, userMsg.attachments);
701
+ }
702
+ },
703
+ [streaming, consumeStream, consumeBuffered, awaitSession]
704
+ );
705
+ const editMessage = react.useCallback(
706
+ async (id, content) => {
707
+ dispatch({ type: "MESSAGE_EDIT", id, content });
708
+ const msg = stateRef.current.messages.find((m) => m.id === id);
709
+ if (msg?.role === "user") {
710
+ await regenerate(id);
711
+ }
712
+ },
713
+ [regenerate]
714
+ );
715
+ const deleteMessage = react.useCallback((id) => {
716
+ dispatch({ type: "MESSAGE_DELETE", id });
717
+ }, []);
718
+ const clearMessages = react.useCallback(() => {
719
+ abortRef.current?.abort();
720
+ dispatch({ type: "MESSAGES_CLEAR" });
721
+ }, []);
722
+ const loadMore = react.useCallback(async () => {
723
+ const sessionId = stateRef.current.sessionId;
724
+ if (!sessionId) return;
725
+ if (stateRef.current.isLoadingMore || !stateRef.current.hasMore) return;
726
+ dispatch({ type: "HISTORY_MORE_START" });
727
+ try {
728
+ const page = await transport.loadHistory(
729
+ sessionId,
730
+ stateRef.current.oldestCursor,
731
+ pageSize
732
+ );
733
+ dispatch({
734
+ type: "HISTORY_MORE_DONE",
735
+ messages: page.messages,
736
+ hasMore: page.hasMore,
737
+ cursor: page.nextCursor
738
+ });
739
+ } catch (err) {
740
+ const e = err instanceof Error ? err : new Error(String(err));
741
+ lastErrorRef.current = e;
742
+ dispatch({ type: "ERROR_SET", error: e.message });
743
+ config.onError?.(e);
744
+ }
745
+ }, [transport, pageSize, config]);
746
+ const newSession = react.useCallback(async () => {
747
+ log.lifecycle.info("newSession", { previous: stateRef.current.sessionId });
748
+ abortRef.current?.abort();
749
+ const previous = stateRef.current.sessionId;
750
+ if (previous) {
751
+ try {
752
+ await transport.closeSession(previous);
753
+ } catch {
754
+ }
755
+ }
756
+ dispatch({ type: "MESSAGES_CLEAR" });
757
+ try {
758
+ const info = await transport.createSession({ metadata: config.metadata });
759
+ dispatch({
760
+ type: "SESSION_SET",
761
+ sessionId: info.sessionId,
762
+ messages: info.messages ?? [],
763
+ hasMore: info.hasMore ?? false,
764
+ cursor: info.cursor ?? null
765
+ });
766
+ log.lifecycle.success("newSession ok", { sessionId: info.sessionId });
767
+ } catch (err) {
768
+ const e = err instanceof Error ? err : new Error(String(err));
769
+ lastErrorRef.current = e;
770
+ dispatch({ type: "ERROR_SET", error: e.message });
771
+ config.onError?.(e);
772
+ log.error.error("newSession failed", { message: e.message });
773
+ }
774
+ }, [transport, config]);
775
+ return {
776
+ ...state,
777
+ sendMessage,
778
+ cancelStream,
779
+ regenerate,
780
+ editMessage,
781
+ deleteMessage,
782
+ clearMessages,
783
+ loadMore,
784
+ newSession,
785
+ lastError: lastErrorRef.current
786
+ };
787
+ }
788
+ chunkOLISEQHS_cjs.__name(useChat, "useChat");
789
+ function findLastUserIndex(messages) {
790
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
791
+ if (messages[i].role === "user") return i;
792
+ }
793
+ return -1;
794
+ }
795
+ chunkOLISEQHS_cjs.__name(findLastUserIndex, "findLastUserIndex");
796
+ function findPreviousUserIndex(messages, from) {
797
+ for (let i = from - 1; i >= 0; i -= 1) {
798
+ if (messages[i].role === "user") return i;
799
+ }
800
+ return -1;
801
+ }
802
+ chunkOLISEQHS_cjs.__name(findPreviousUserIndex, "findPreviousUserIndex");
803
+ var DEFAULT_MOBILE_QUERY = "(max-width: 640px)";
804
+ function useChatLayout(config = {}) {
805
+ const {
806
+ defaultMode = "closed",
807
+ storageKey = STORAGE_KEYS.mode,
808
+ sidebarStorageKey = STORAGE_KEYS.sidebarWidth,
809
+ reserveCssVar = CSS_VARS.reserve,
810
+ defaultSidebarWidth = DEFAULT_SIDEBAR.width,
811
+ minSidebarWidth = DEFAULT_SIDEBAR.min,
812
+ maxSidebarWidth = DEFAULT_SIDEBAR.max,
813
+ mobileQuery = DEFAULT_MOBILE_QUERY
814
+ } = config;
815
+ const [mode, setMode] = hooks.useLocalStorage(storageKey, defaultMode);
816
+ const [sidebarWidthRaw, setSidebarWidthRaw] = hooks.useLocalStorage(
817
+ sidebarStorageKey,
818
+ defaultSidebarWidth
819
+ );
820
+ const isMobile = hooks.useMediaQuery(mobileQuery);
821
+ const setSidebarWidth = react.useCallback(
822
+ (w) => {
823
+ const clamped = Math.max(minSidebarWidth, Math.min(maxSidebarWidth, w));
824
+ setSidebarWidthRaw(clamped);
825
+ },
826
+ [setSidebarWidthRaw, minSidebarWidth, maxSidebarWidth]
827
+ );
828
+ const [previousOpenMode, setPreviousOpenMode] = react.useState(
829
+ mode === "closed" ? "embedded" : mode
830
+ );
831
+ react.useEffect(() => {
832
+ if (mode !== "closed") setPreviousOpenMode(mode);
833
+ }, [mode]);
834
+ const open = react.useCallback(() => {
835
+ setMode(previousOpenMode === "closed" ? "embedded" : previousOpenMode);
836
+ }, [setMode, previousOpenMode]);
837
+ const close = react.useCallback(() => setMode("closed"), [setMode]);
838
+ const toggle = react.useCallback(() => {
839
+ setMode(mode === "closed" ? previousOpenMode : "closed");
840
+ }, [setMode, mode, previousOpenMode]);
841
+ const effectiveMode = react.useMemo(() => {
842
+ if (mode === "closed") return "closed";
843
+ if (isMobile && (mode === "sidebar" || mode === "floating")) return "fullscreen";
844
+ return mode;
845
+ }, [mode, isMobile]);
846
+ react.useEffect(() => {
847
+ if (typeof document === "undefined") return;
848
+ const root = document.documentElement;
849
+ if (effectiveMode === "sidebar") {
850
+ root.style.setProperty(reserveCssVar, `${sidebarWidthRaw}px`);
851
+ } else {
852
+ root.style.removeProperty(reserveCssVar);
853
+ }
854
+ return () => {
855
+ root.style.removeProperty(reserveCssVar);
856
+ };
857
+ }, [effectiveMode, sidebarWidthRaw, reserveCssVar]);
858
+ return {
859
+ mode,
860
+ setMode,
861
+ open,
862
+ close,
863
+ toggle,
864
+ sidebarWidth: sidebarWidthRaw,
865
+ setSidebarWidth,
866
+ isMobile,
867
+ effectiveMode
868
+ };
869
+ }
870
+ chunkOLISEQHS_cjs.__name(useChatLayout, "useChatLayout");
871
+
872
+ // src/tools/Chat/core/audio/audioBus.ts
873
+ var unlocked = false;
874
+ var unlockListeners = /* @__PURE__ */ new Set();
875
+ function setUnlocked(value) {
876
+ if (unlocked === value) return;
877
+ unlocked = value;
878
+ for (const cb of unlockListeners) cb(value);
879
+ }
880
+ chunkOLISEQHS_cjs.__name(setUnlocked, "setUnlocked");
881
+ function createAudioBus(options) {
882
+ if (typeof window === "undefined") {
883
+ return noopBus();
884
+ }
885
+ let sounds = options.sounds;
886
+ const cache2 = /* @__PURE__ */ new Map();
887
+ const getOrCreate = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((url) => {
888
+ const hit = cache2.get(url);
889
+ if (hit) return hit;
890
+ const el = new Audio(url);
891
+ el.preload = "auto";
892
+ el.crossOrigin = "anonymous";
893
+ cache2.set(url, el);
894
+ return el;
895
+ }, "getOrCreate");
896
+ const resolveUrl = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event) => {
897
+ const v = sounds[event];
898
+ if (!v) return null;
899
+ return v;
900
+ }, "resolveUrl");
901
+ const play = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event) => {
902
+ if (options.getMuted()) return;
903
+ if (!options.isEnabled(event)) return;
904
+ const url = resolveUrl(event);
905
+ if (!url) return;
906
+ getOrCreate(url);
907
+ const fresh = new Audio(url);
908
+ fresh.preload = "auto";
909
+ fresh.volume = options.getVolume();
910
+ const p = fresh.play();
911
+ if (p && typeof p.catch === "function") {
912
+ p.catch(() => {
913
+ });
914
+ }
915
+ }, "play");
916
+ const preload = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event) => {
917
+ const url = resolveUrl(event);
918
+ if (!url) return;
919
+ const el = getOrCreate(url);
920
+ try {
921
+ el.load();
922
+ } catch {
923
+ }
924
+ }, "preload");
925
+ const unlock = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
926
+ if (unlocked) return;
927
+ for (const el of cache2.values()) {
928
+ const wasMuted = el.muted;
929
+ el.muted = true;
930
+ const p = el.play();
931
+ if (p && typeof p.then === "function") {
932
+ p.then(() => {
933
+ el.pause();
934
+ el.currentTime = 0;
935
+ el.muted = wasMuted;
936
+ }).catch(() => {
937
+ el.muted = wasMuted;
938
+ });
939
+ } else {
940
+ el.pause();
941
+ el.muted = wasMuted;
942
+ }
943
+ }
944
+ setUnlocked(true);
945
+ }, "unlock");
946
+ return {
947
+ play,
948
+ preload,
949
+ unlock,
950
+ isUnlocked: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => unlocked, "isUnlocked"),
951
+ subscribeUnlock(cb) {
952
+ unlockListeners.add(cb);
953
+ return () => unlockListeners.delete(cb);
954
+ },
955
+ setSounds(next) {
956
+ sounds = next;
957
+ },
958
+ dispose() {
959
+ cache2.clear();
960
+ }
961
+ };
962
+ }
963
+ chunkOLISEQHS_cjs.__name(createAudioBus, "createAudioBus");
964
+ function noopBus() {
965
+ return {
966
+ play: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "play"),
967
+ preload: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "preload"),
968
+ unlock: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "unlock"),
969
+ isUnlocked: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => false, "isUnlocked"),
970
+ subscribeUnlock: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => () => void 0, "subscribeUnlock"),
971
+ setSounds: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "setSounds"),
972
+ dispose: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "dispose")
973
+ };
974
+ }
975
+ chunkOLISEQHS_cjs.__name(noopBus, "noopBus");
976
+ var STORAGE_KEY = "djangocfg-chat-audio:prefs";
977
+ var clamp01 = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((v) => {
978
+ if (!Number.isFinite(v)) return 1;
979
+ return v < 0 ? 0 : v > 1 ? 1 : v;
980
+ }, "clamp01");
981
+ var useChatAudioPrefs = zustand.create()(
982
+ middleware.persist(
983
+ (set) => ({
984
+ volume: 1,
985
+ muted: false,
986
+ enabled: {},
987
+ setVolume: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((v) => set({ volume: clamp01(v) }), "setVolume"),
988
+ setMuted: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((m) => set({ muted: !!m }), "setMuted"),
989
+ setEventEnabled: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event, enabled) => set((s) => ({ enabled: { ...s.enabled, [event]: enabled } })), "setEventEnabled")
990
+ }),
991
+ {
992
+ name: STORAGE_KEY,
993
+ storage: middleware.createJSONStorage(() => {
994
+ if (typeof window === "undefined") {
995
+ return {
996
+ getItem: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => null, "getItem"),
997
+ setItem: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "setItem"),
998
+ removeItem: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => void 0, "removeItem")
999
+ };
1000
+ }
1001
+ return window.localStorage;
1002
+ }),
1003
+ partialize: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((s) => ({ volume: s.volume, muted: s.muted, enabled: s.enabled }), "partialize"),
1004
+ version: 1
1005
+ }
1006
+ )
1007
+ );
1008
+
1009
+ // src/tools/Chat/hooks/useChatAudio.ts
1010
+ var ALL_EVENTS = [
1011
+ "messageSent",
1012
+ "messageReceived",
1013
+ "streamStart",
1014
+ "error",
1015
+ "mention",
1016
+ "notification"
1017
+ ];
1018
+ function readReducedMotion() {
1019
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
1020
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1021
+ }
1022
+ chunkOLISEQHS_cjs.__name(readReducedMotion, "readReducedMotion");
1023
+ function readReducedData() {
1024
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
1025
+ return window.matchMedia("(prefers-reduced-data: reduce)").matches;
1026
+ }
1027
+ chunkOLISEQHS_cjs.__name(readReducedData, "readReducedData");
1028
+ function readVisibilityHidden() {
1029
+ if (typeof document === "undefined") return false;
1030
+ return document.visibilityState === "hidden";
1031
+ }
1032
+ chunkOLISEQHS_cjs.__name(readVisibilityHidden, "readVisibilityHidden");
1033
+ function useChatAudio(config = {}) {
1034
+ const {
1035
+ sounds = {},
1036
+ volume: volumeOverride,
1037
+ muted: mutedOverride,
1038
+ shouldPlay,
1039
+ respectReducedMotion = true,
1040
+ respectReducedData = true,
1041
+ muteWhenHidden = true
1042
+ } = config;
1043
+ const volume = useChatAudioPrefs((s) => volumeOverride != null ? volumeOverride : s.volume);
1044
+ const mutedPersisted = useChatAudioPrefs((s) => s.muted);
1045
+ const muted = mutedOverride != null ? mutedOverride : mutedPersisted;
1046
+ const enabledMap = useChatAudioPrefs((s) => s.enabled);
1047
+ const setVolumePref = useChatAudioPrefs((s) => s.setVolume);
1048
+ const setMutedPref = useChatAudioPrefs((s) => s.setMuted);
1049
+ const setEventEnabledPref = useChatAudioPrefs((s) => s.setEventEnabled);
1050
+ const volumeRef = react.useRef(volume);
1051
+ volumeRef.current = volume;
1052
+ const mutedRef = react.useRef(muted);
1053
+ mutedRef.current = muted;
1054
+ const enabledRef = react.useRef(enabledMap);
1055
+ enabledRef.current = enabledMap;
1056
+ const reducedMotionRef = react.useRef(readReducedMotion());
1057
+ const reducedDataRef = react.useRef(readReducedData());
1058
+ const hiddenRef = react.useRef(readVisibilityHidden());
1059
+ const shouldPlayRef = react.useRef(shouldPlay);
1060
+ shouldPlayRef.current = shouldPlay;
1061
+ react.useEffect(() => {
1062
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
1063
+ const mqMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
1064
+ const mqData = window.matchMedia("(prefers-reduced-data: reduce)");
1065
+ const onMotion = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1066
+ reducedMotionRef.current = mqMotion.matches;
1067
+ }, "onMotion");
1068
+ const onData = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1069
+ reducedDataRef.current = mqData.matches;
1070
+ }, "onData");
1071
+ mqMotion.addEventListener("change", onMotion);
1072
+ mqData.addEventListener("change", onData);
1073
+ return () => {
1074
+ mqMotion.removeEventListener("change", onMotion);
1075
+ mqData.removeEventListener("change", onData);
1076
+ };
1077
+ }, []);
1078
+ react.useEffect(() => {
1079
+ if (!muteWhenHidden || typeof document === "undefined") return;
1080
+ const onVis = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1081
+ hiddenRef.current = document.visibilityState === "hidden";
1082
+ }, "onVis");
1083
+ document.addEventListener("visibilitychange", onVis);
1084
+ return () => document.removeEventListener("visibilitychange", onVis);
1085
+ }, [muteWhenHidden]);
1086
+ const busRef = react.useRef(null);
1087
+ if (busRef.current === null) {
1088
+ busRef.current = createAudioBus({
1089
+ sounds,
1090
+ getVolume: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => volumeRef.current, "getVolume"),
1091
+ getMuted: /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => effectiveMuted(), "getMuted"),
1092
+ isEnabled: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event) => isEnabledImpl(event), "isEnabled")
1093
+ });
1094
+ }
1095
+ function effectiveMuted() {
1096
+ if (mutedRef.current) return true;
1097
+ if (muteWhenHidden && hiddenRef.current) return true;
1098
+ if (respectReducedMotion && reducedMotionRef.current) return true;
1099
+ if (respectReducedData && reducedDataRef.current) return true;
1100
+ return false;
1101
+ }
1102
+ chunkOLISEQHS_cjs.__name(effectiveMuted, "effectiveMuted");
1103
+ function isEnabledImpl(event) {
1104
+ if (shouldPlayRef.current && shouldPlayRef.current(event) === false) return false;
1105
+ const flag = enabledRef.current[event];
1106
+ if (flag === false) return false;
1107
+ return true;
1108
+ }
1109
+ chunkOLISEQHS_cjs.__name(isEnabledImpl, "isEnabledImpl");
1110
+ react.useEffect(() => {
1111
+ busRef.current?.setSounds(sounds);
1112
+ }, [sounds]);
1113
+ react.useEffect(() => {
1114
+ const bus = busRef.current;
1115
+ if (!bus) return;
1116
+ for (const event of ALL_EVENTS) {
1117
+ bus.preload(event);
1118
+ }
1119
+ }, [sounds]);
1120
+ react.useEffect(() => {
1121
+ const bus = busRef.current;
1122
+ return () => {
1123
+ bus?.dispose();
1124
+ };
1125
+ }, []);
1126
+ const isUnlocked = react.useSyncExternalStore(
1127
+ react.useCallback((cb) => busRef.current?.subscribeUnlock(cb) ?? (() => void 0), []),
1128
+ () => busRef.current?.isUnlocked() ?? false,
1129
+ () => false
1130
+ );
1131
+ const play = react.useCallback((event) => {
1132
+ busRef.current?.play(event);
1133
+ }, []);
1134
+ const preload = react.useCallback((event) => {
1135
+ busRef.current?.preload(event);
1136
+ }, []);
1137
+ const unlock = react.useCallback(() => {
1138
+ busRef.current?.unlock();
1139
+ }, []);
1140
+ const isEventEnabled = react.useCallback(
1141
+ (event) => isEnabledImpl(event),
1142
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1143
+ []
1144
+ );
1145
+ const api = react.useMemo(
1146
+ () => ({
1147
+ play,
1148
+ preload,
1149
+ unlock,
1150
+ isUnlocked,
1151
+ muted,
1152
+ setMuted: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((m) => setMutedPref(m), "setMuted"),
1153
+ volume,
1154
+ setVolume: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((v) => setVolumePref(v), "setVolume"),
1155
+ isEventEnabled,
1156
+ setEventEnabled: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((event, enabled) => setEventEnabledPref(event, enabled), "setEventEnabled")
1157
+ }),
1158
+ [play, preload, unlock, isUnlocked, muted, volume, isEventEnabled, setMutedPref, setVolumePref, setEventEnabledPref]
1159
+ );
1160
+ return api;
1161
+ }
1162
+ chunkOLISEQHS_cjs.__name(useChatAudio, "useChatAudio");
1163
+ var Ctx = react.createContext(null);
1164
+ function ChatProvider({
1165
+ transport,
1166
+ config = {},
1167
+ initialSessionId,
1168
+ autoCreateSession,
1169
+ streaming,
1170
+ audio,
1171
+ debug,
1172
+ children
1173
+ }) {
1174
+ const audioApi = useChatAudio(audio ?? {});
1175
+ const audioRef = react.useRef(audioApi);
1176
+ audioRef.current = audioApi;
1177
+ const onMessageSent = react.useCallback(() => audioRef.current.play("messageSent"), []);
1178
+ const onMessageEnd = react.useCallback(() => audioRef.current.play("messageReceived"), []);
1179
+ const onStreamStart = react.useCallback(() => audioRef.current.play("streamStart"), []);
1180
+ const onError = react.useCallback(() => audioRef.current.play("error"), []);
1181
+ const chat = useChat({
1182
+ transport,
1183
+ initialSessionId,
1184
+ autoCreateSession,
1185
+ streaming,
1186
+ debug,
1187
+ metadata: {
1188
+ locale: config.locale ?? config.prefs?.locale,
1189
+ slug: config.slug
1190
+ },
1191
+ userPersona: config.user,
1192
+ onMessageSent,
1193
+ onMessageEnd,
1194
+ onStreamStart,
1195
+ onError
1196
+ });
1197
+ const layout = useChatLayout({ defaultMode: "embedded" });
1198
+ const rootRef = react.useRef(null);
1199
+ react.useEffect(() => {
1200
+ if (audioApi.isUnlocked) return;
1201
+ const root = rootRef.current;
1202
+ if (!root) return;
1203
+ const handler = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1204
+ audioApi.unlock();
1205
+ }, "handler");
1206
+ root.addEventListener("pointerdown", handler, { once: true, capture: true });
1207
+ root.addEventListener("keydown", handler, { once: true, capture: true });
1208
+ return () => {
1209
+ root.removeEventListener("pointerdown", handler, { capture: true });
1210
+ root.removeEventListener("keydown", handler, { capture: true });
1211
+ };
1212
+ }, [audioApi]);
1213
+ const labels = react.useMemo(
1214
+ () => ({ ...DEFAULT_LABELS, ...config.labels ?? {} }),
1215
+ [config.labels]
1216
+ );
1217
+ const value = react.useMemo(
1218
+ () => ({ ...chat, layout, config, labels, audio: audioApi }),
1219
+ [chat, layout, config, labels, audioApi]
1220
+ );
1221
+ return /* @__PURE__ */ jsxRuntime.jsx(Ctx.Provider, { value, children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: rootRef, style: { display: "contents" }, children }) });
1222
+ }
1223
+ chunkOLISEQHS_cjs.__name(ChatProvider, "ChatProvider");
1224
+ function useChatContext() {
1225
+ const v = react.useContext(Ctx);
1226
+ if (!v) throw new Error("useChatContext must be used inside <ChatProvider>");
1227
+ return v;
1228
+ }
1229
+ chunkOLISEQHS_cjs.__name(useChatContext, "useChatContext");
1230
+ function useChatContextOptional() {
1231
+ return react.useContext(Ctx);
1232
+ }
1233
+ chunkOLISEQHS_cjs.__name(useChatContextOptional, "useChatContextOptional");
1234
+ var MAX_TEXTAREA_HEIGHT = 240;
1235
+ function useChatComposer(options) {
1236
+ const {
1237
+ onSubmit,
1238
+ initialValue = "",
1239
+ maxLength = LIMITS.messageMaxLength,
1240
+ maxAttachments = LIMITS.attachmentsMax,
1241
+ disabled = false,
1242
+ submitOn = "enter",
1243
+ history = { enabled: true, size: LIMITS.composerHistorySize },
1244
+ onPasteFiles
1245
+ } = options;
1246
+ const [value, setValueState] = react.useState(initialValue);
1247
+ const [attachments, setAttachments] = react.useState([]);
1248
+ const [isSubmitting, setIsSubmitting] = react.useState(false);
1249
+ const textareaRef = react.useRef(null);
1250
+ const historyRef = react.useRef({ items: [], index: -1 });
1251
+ const setValue = react.useCallback(
1252
+ (next) => {
1253
+ setValueState(next.length > maxLength ? next.slice(0, maxLength) : next);
1254
+ },
1255
+ [maxLength]
1256
+ );
1257
+ react.useEffect(() => {
1258
+ const el = textareaRef.current;
1259
+ if (!el) return;
1260
+ el.style.height = "auto";
1261
+ el.style.height = `${Math.min(el.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;
1262
+ }, [value]);
1263
+ const reset = react.useCallback(() => {
1264
+ setValueState("");
1265
+ setAttachments([]);
1266
+ historyRef.current.index = -1;
1267
+ }, []);
1268
+ const focus = react.useCallback(() => {
1269
+ requestAnimationFrame(() => textareaRef.current?.focus());
1270
+ }, []);
1271
+ const submit = react.useCallback(async () => {
1272
+ const trimmed = value.trim();
1273
+ if (!trimmed && attachments.length === 0 || isSubmitting || disabled) return;
1274
+ setIsSubmitting(true);
1275
+ try {
1276
+ if (history.enabled !== false && trimmed) {
1277
+ const buf = historyRef.current.items;
1278
+ if (buf[buf.length - 1] !== trimmed) {
1279
+ buf.push(trimmed);
1280
+ if (buf.length > (history.size ?? LIMITS.composerHistorySize)) buf.shift();
1281
+ }
1282
+ historyRef.current.index = -1;
1283
+ }
1284
+ const snapshot = [...attachments];
1285
+ const text = value;
1286
+ reset();
1287
+ await onSubmit(text, snapshot);
1288
+ } finally {
1289
+ setIsSubmitting(false);
1290
+ }
1291
+ }, [value, attachments, isSubmitting, disabled, history, onSubmit, reset]);
1292
+ const addAttachment = react.useCallback(
1293
+ (a) => {
1294
+ setAttachments((prev) => {
1295
+ if (prev.some((p) => p.id === a.id)) {
1296
+ return prev.map((p) => p.id === a.id ? a : p);
1297
+ }
1298
+ if (prev.length >= maxAttachments) return prev;
1299
+ return [...prev, a];
1300
+ });
1301
+ },
1302
+ [maxAttachments]
1303
+ );
1304
+ const removeAttachment = react.useCallback((id) => {
1305
+ setAttachments((prev) => prev.filter((a) => a.id !== id));
1306
+ }, []);
1307
+ const recallPrevious = react.useCallback(() => {
1308
+ const { items } = historyRef.current;
1309
+ if (!items.length) return;
1310
+ const next = historyRef.current.index < 0 ? items.length - 1 : Math.max(0, historyRef.current.index - 1);
1311
+ historyRef.current.index = next;
1312
+ setValueState(items[next]);
1313
+ }, []);
1314
+ const recallNext = react.useCallback(() => {
1315
+ const { items } = historyRef.current;
1316
+ if (!items.length || historyRef.current.index < 0) return;
1317
+ const next = historyRef.current.index + 1;
1318
+ if (next >= items.length) {
1319
+ historyRef.current.index = -1;
1320
+ setValueState("");
1321
+ return;
1322
+ }
1323
+ historyRef.current.index = next;
1324
+ setValueState(items[next]);
1325
+ }, []);
1326
+ const onChange = react.useCallback(
1327
+ (e) => {
1328
+ setValue(e.target.value);
1329
+ },
1330
+ [setValue]
1331
+ );
1332
+ const onKeyDown = react.useCallback(
1333
+ (e) => {
1334
+ if (e.key === "Enter") {
1335
+ const isCmd = e.metaKey || e.ctrlKey;
1336
+ const shouldSend = submitOn === "cmd+enter" ? isCmd : !e.shiftKey;
1337
+ if (shouldSend) {
1338
+ e.preventDefault();
1339
+ void submit();
1340
+ }
1341
+ return;
1342
+ }
1343
+ if (history.enabled !== false && value === "" && attachments.length === 0) {
1344
+ if (e.key === "ArrowUp") {
1345
+ e.preventDefault();
1346
+ recallPrevious();
1347
+ } else if (e.key === "ArrowDown" && historyRef.current.index >= 0) {
1348
+ e.preventDefault();
1349
+ recallNext();
1350
+ }
1351
+ }
1352
+ },
1353
+ [submitOn, submit, history, value, attachments.length, recallPrevious, recallNext]
1354
+ );
1355
+ const onPaste = react.useCallback(
1356
+ (e) => {
1357
+ const files = Array.from(e.clipboardData?.files ?? []);
1358
+ if (files.length && onPasteFiles) {
1359
+ e.preventDefault();
1360
+ onPasteFiles(files);
1361
+ }
1362
+ },
1363
+ [onPasteFiles]
1364
+ );
1365
+ const canSubmit = !disabled && !isSubmitting && (value.trim().length > 0 || attachments.length > 0);
1366
+ return {
1367
+ value,
1368
+ setValue,
1369
+ attachments,
1370
+ addAttachment,
1371
+ removeAttachment,
1372
+ isSubmitting,
1373
+ canSubmit,
1374
+ submit,
1375
+ reset,
1376
+ focus,
1377
+ textareaRef,
1378
+ textareaProps: {
1379
+ ref: textareaRef,
1380
+ value,
1381
+ disabled,
1382
+ onChange,
1383
+ onKeyDown,
1384
+ onPaste
1385
+ },
1386
+ recallPrevious,
1387
+ recallNext
1388
+ };
1389
+ }
1390
+ chunkOLISEQHS_cjs.__name(useChatComposer, "useChatComposer");
1391
+ function useChatScroll(options) {
1392
+ const {
1393
+ containerRef,
1394
+ bottomRef,
1395
+ isStreaming = false,
1396
+ bottomThresholdPx = 80,
1397
+ messagesCount = 0
1398
+ } = options;
1399
+ const [isAtBottom, setIsAtBottom] = react.useState(true);
1400
+ const [unreadCount, setUnreadCount] = react.useState(0);
1401
+ const lastCountRef = react.useRef(messagesCount);
1402
+ const stickyRef = react.useRef(true);
1403
+ const wasStreamingRef = react.useRef(isStreaming);
1404
+ const scrollToBottom = react.useCallback(
1405
+ (smooth = false) => {
1406
+ const el = containerRef.current;
1407
+ if (!el) return;
1408
+ el.scrollTo({
1409
+ top: el.scrollHeight,
1410
+ behavior: smooth ? "smooth" : "auto"
1411
+ });
1412
+ stickyRef.current = true;
1413
+ setIsAtBottom(true);
1414
+ setUnreadCount(0);
1415
+ },
1416
+ [containerRef]
1417
+ );
1418
+ const resetUnread = react.useCallback(() => setUnreadCount(0), []);
1419
+ react.useEffect(() => {
1420
+ const el = containerRef.current;
1421
+ if (!el) return;
1422
+ const onScroll = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1423
+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
1424
+ const atBottom = distance <= bottomThresholdPx;
1425
+ stickyRef.current = atBottom;
1426
+ setIsAtBottom(atBottom);
1427
+ if (atBottom) setUnreadCount(0);
1428
+ }, "onScroll");
1429
+ onScroll();
1430
+ el.addEventListener("scroll", onScroll, { passive: true });
1431
+ return () => {
1432
+ el.removeEventListener("scroll", onScroll);
1433
+ };
1434
+ }, [containerRef, bottomThresholdPx]);
1435
+ react.useEffect(() => {
1436
+ const el = containerRef.current;
1437
+ if (!el) return;
1438
+ if (isStreaming) {
1439
+ wasStreamingRef.current = true;
1440
+ if (!stickyRef.current) return;
1441
+ let raf = 0;
1442
+ const tick = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1443
+ if (!stickyRef.current) return;
1444
+ el.scrollTop = el.scrollHeight;
1445
+ raf = requestAnimationFrame(tick);
1446
+ }, "tick");
1447
+ raf = requestAnimationFrame(tick);
1448
+ return () => cancelAnimationFrame(raf);
1449
+ }
1450
+ if (wasStreamingRef.current && stickyRef.current) {
1451
+ wasStreamingRef.current = false;
1452
+ let raf1 = 0;
1453
+ let raf2 = 0;
1454
+ raf1 = requestAnimationFrame(() => {
1455
+ el.scrollTop = el.scrollHeight;
1456
+ raf2 = requestAnimationFrame(() => {
1457
+ el.scrollTop = el.scrollHeight;
1458
+ });
1459
+ });
1460
+ return () => {
1461
+ cancelAnimationFrame(raf1);
1462
+ cancelAnimationFrame(raf2);
1463
+ };
1464
+ }
1465
+ wasStreamingRef.current = false;
1466
+ return;
1467
+ }, [containerRef, isStreaming]);
1468
+ react.useEffect(() => {
1469
+ if (messagesCount > lastCountRef.current) {
1470
+ if (stickyRef.current) {
1471
+ const el = containerRef.current;
1472
+ if (el) el.scrollTop = el.scrollHeight;
1473
+ } else {
1474
+ setUnreadCount((n) => n + (messagesCount - lastCountRef.current));
1475
+ }
1476
+ }
1477
+ lastCountRef.current = messagesCount;
1478
+ }, [containerRef, messagesCount]);
1479
+ react.useEffect(() => {
1480
+ }, [bottomRef]);
1481
+ return { isAtBottom, unreadCount, scrollToBottom, resetUnread };
1482
+ }
1483
+ chunkOLISEQHS_cjs.__name(useChatScroll, "useChatScroll");
1484
+ function useChatHistory(options) {
1485
+ const { enabled = true, containerRef, topSentinelRef, hasMore, isLoadingMore, loadMore } = options;
1486
+ const heightBeforeRef = react.useRef(null);
1487
+ react.useEffect(() => {
1488
+ if (heightBeforeRef.current == null) return;
1489
+ const el = containerRef.current;
1490
+ if (!el) {
1491
+ heightBeforeRef.current = null;
1492
+ return;
1493
+ }
1494
+ if (!isLoadingMore) {
1495
+ const delta = el.scrollHeight - heightBeforeRef.current;
1496
+ if (delta > 0) {
1497
+ el.scrollTop += delta;
1498
+ }
1499
+ heightBeforeRef.current = null;
1500
+ }
1501
+ }, [containerRef, isLoadingMore]);
1502
+ react.useEffect(() => {
1503
+ if (!enabled || !hasMore) return;
1504
+ const sentinel = topSentinelRef.current;
1505
+ const root = containerRef.current;
1506
+ if (!sentinel || !root) return;
1507
+ const observer = new IntersectionObserver(
1508
+ (entries) => {
1509
+ const entry = entries[0];
1510
+ if (!entry?.isIntersecting) return;
1511
+ if (isLoadingMore) return;
1512
+ const el = containerRef.current;
1513
+ if (el) heightBeforeRef.current = el.scrollHeight;
1514
+ void loadMore();
1515
+ },
1516
+ { root, threshold: 0, rootMargin: "200px 0px 0px 0px" }
1517
+ );
1518
+ observer.observe(sentinel);
1519
+ return () => observer.disconnect();
1520
+ }, [enabled, hasMore, isLoadingMore, containerRef, topSentinelRef, loadMore]);
1521
+ }
1522
+ chunkOLISEQHS_cjs.__name(useChatHistory, "useChatHistory");
1523
+ function AttachmentsGrid({
1524
+ attachments,
1525
+ maxVisible,
1526
+ onClick,
1527
+ onRemove,
1528
+ isInComposer = false,
1529
+ layout = "wrap",
1530
+ className
1531
+ }) {
1532
+ if (!attachments?.length) return null;
1533
+ const visible = maxVisible ? attachments.slice(0, maxVisible) : attachments;
1534
+ return /* @__PURE__ */ jsxRuntime.jsx(
1535
+ "div",
1536
+ {
1537
+ className: lib.cn(
1538
+ layout === "grid" ? "grid grid-cols-3 gap-2" : "flex flex-wrap gap-2",
1539
+ className
1540
+ ),
1541
+ children: visible.map((a) => /* @__PURE__ */ jsxRuntime.jsx(
1542
+ AttachmentTile,
1543
+ {
1544
+ attachment: a,
1545
+ isInComposer,
1546
+ onClick: onClick ? () => onClick(a) : void 0,
1547
+ onRemove: onRemove ? () => onRemove(a) : void 0
1548
+ },
1549
+ a.id
1550
+ ))
1551
+ }
1552
+ );
1553
+ }
1554
+ chunkOLISEQHS_cjs.__name(AttachmentsGrid, "AttachmentsGrid");
1555
+ function AttachmentsList({
1556
+ attachments,
1557
+ maxVisible,
1558
+ onClick,
1559
+ onRemove,
1560
+ renderers,
1561
+ isInComposer = false,
1562
+ className
1563
+ }) {
1564
+ if (!attachments?.length) return null;
1565
+ const visible = maxVisible ? attachments.slice(0, maxVisible) : attachments;
1566
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: lib.cn("flex w-full flex-col gap-2", className), children: visible.map((a) => {
1567
+ const renderer = renderers?.[a.type] ?? renderers?.default;
1568
+ const args = {
1569
+ attachment: a,
1570
+ isInComposer,
1571
+ onClick: onClick ? () => onClick(a) : void 0,
1572
+ onRemove: onRemove ? () => onRemove(a) : void 0
1573
+ };
1574
+ if (renderer) {
1575
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative w-full min-w-0", children: [
1576
+ renderer(args),
1577
+ args.onRemove ? /* @__PURE__ */ jsxRuntime.jsx(RemoveBtn, { onRemove: args.onRemove }) : null
1578
+ ] }, a.id);
1579
+ }
1580
+ return /* @__PURE__ */ jsxRuntime.jsx(AttachmentTile, { ...args }, a.id);
1581
+ }) });
1582
+ }
1583
+ chunkOLISEQHS_cjs.__name(AttachmentsList, "AttachmentsList");
1584
+ function Attachments(props) {
1585
+ const { renderers, layout, ...rest } = props;
1586
+ if (renderers) {
1587
+ return /* @__PURE__ */ jsxRuntime.jsx(AttachmentsList, { ...rest, renderers });
1588
+ }
1589
+ return /* @__PURE__ */ jsxRuntime.jsx(AttachmentsGrid, { ...rest, layout: layout === "grid" ? "grid" : "wrap" });
1590
+ }
1591
+ chunkOLISEQHS_cjs.__name(Attachments, "Attachments");
1592
+ function AttachmentTile({ attachment, onClick, onRemove }) {
1593
+ const isImage = attachment.type === "image";
1594
+ const isUploading = attachment.status === "uploading";
1595
+ const inner = isImage ? /* @__PURE__ */ jsxRuntime.jsx(
1596
+ "img",
1597
+ {
1598
+ src: attachment.thumbnailUrl ?? attachment.url,
1599
+ alt: attachment.name ?? "attachment",
1600
+ className: "h-16 w-16 rounded-md object-cover",
1601
+ loading: "lazy"
1602
+ }
1603
+ ) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex max-w-44 items-center gap-2 rounded-md border border-border bg-background/60 px-2 py-1.5 text-xs", children: [
1604
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.File, { "aria-hidden": true, className: "size-4 shrink-0 text-muted-foreground" }),
1605
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "truncate", children: attachment.name ?? "file" })
1606
+ ] });
1607
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", children: [
1608
+ onClick ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick, className: "block", children: inner }) : inner,
1609
+ isUploading ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-background/70 text-[10px] font-medium", children: attachment.progress != null ? `${Math.round(attachment.progress * 100)}%` : "\u2026" }) : null,
1610
+ onRemove ? /* @__PURE__ */ jsxRuntime.jsx(RemoveBtn, { onRemove }) : null
1611
+ ] });
1612
+ }
1613
+ chunkOLISEQHS_cjs.__name(AttachmentTile, "AttachmentTile");
1614
+ function RemoveBtn({ onRemove }) {
1615
+ return /* @__PURE__ */ jsxRuntime.jsx(
1616
+ "button",
1617
+ {
1618
+ type: "button",
1619
+ "aria-label": "Remove attachment",
1620
+ onClick: onRemove,
1621
+ className: "absolute -right-1.5 -top-1.5 grid h-4 w-4 place-items-center rounded-full border border-border bg-background text-muted-foreground hover:bg-destructive hover:text-destructive-foreground",
1622
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { "aria-hidden": true, className: "size-2.5" })
1623
+ }
1624
+ );
1625
+ }
1626
+ chunkOLISEQHS_cjs.__name(RemoveBtn, "RemoveBtn");
1627
+ var Composer = react.forwardRef(/* @__PURE__ */ chunkOLISEQHS_cjs.__name(function Composer2({
1628
+ composer,
1629
+ placeholder = "Type a message...",
1630
+ disabled,
1631
+ showAttachmentButton = false,
1632
+ onPickFiles,
1633
+ toolbarStart,
1634
+ toolbarEnd,
1635
+ attachmentTray,
1636
+ className,
1637
+ textareaClassName,
1638
+ isStreaming: isStreamingProp,
1639
+ onCancel: onCancelProp
1640
+ }, ref) {
1641
+ const ctx = useChatContextOptional();
1642
+ const isStreaming = isStreamingProp ?? ctx?.isStreaming ?? false;
1643
+ const onCancel = onCancelProp ?? ctx?.cancelStream;
1644
+ const isDisabled = disabled ?? isStreaming;
1645
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1646
+ "div",
1647
+ {
1648
+ ref,
1649
+ className: lib.cn(
1650
+ "border-t border-border bg-background/95 px-2.5 pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",
1651
+ className
1652
+ ),
1653
+ children: [
1654
+ composer.attachments.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mb-1.5", children: attachmentTray ?? /* @__PURE__ */ jsxRuntime.jsx(
1655
+ Attachments,
1656
+ {
1657
+ attachments: composer.attachments,
1658
+ onRemove: (a) => composer.removeAttachment(a.id)
1659
+ }
1660
+ ) }) : null,
1661
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-end gap-1.5 [&>:not(textarea)]:shrink-0 [&>:not(textarea)]:h-9", children: [
1662
+ showAttachmentButton ? /* @__PURE__ */ jsxRuntime.jsx(
1663
+ components.Button,
1664
+ {
1665
+ type: "button",
1666
+ variant: "ghost",
1667
+ size: "icon",
1668
+ onClick: onPickFiles,
1669
+ "aria-label": "Attach files",
1670
+ disabled: isDisabled,
1671
+ className: "h-9 w-9",
1672
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Paperclip, { "aria-hidden": true, className: "size-4" })
1673
+ }
1674
+ ) : null,
1675
+ toolbarStart,
1676
+ /* @__PURE__ */ jsxRuntime.jsx(
1677
+ components.Textarea,
1678
+ {
1679
+ ...composer.textareaProps,
1680
+ rows: 1,
1681
+ placeholder,
1682
+ "aria-label": placeholder,
1683
+ "aria-multiline": "true",
1684
+ disabled: isDisabled,
1685
+ className: lib.cn(
1686
+ "min-h-9 max-h-60 flex-1 resize-none rounded-2xl px-3.5 py-2 text-base sm:text-sm",
1687
+ textareaClassName
1688
+ )
1689
+ }
1690
+ ),
1691
+ toolbarEnd,
1692
+ isStreaming ? /* @__PURE__ */ jsxRuntime.jsx(
1693
+ components.Button,
1694
+ {
1695
+ type: "button",
1696
+ variant: "secondary",
1697
+ size: "icon",
1698
+ onClick: onCancel,
1699
+ "aria-label": "Stop",
1700
+ "aria-keyshortcuts": "Escape",
1701
+ className: "h-9 w-9",
1702
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Square, { "aria-hidden": true, className: "size-3.5" })
1703
+ }
1704
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
1705
+ components.Button,
1706
+ {
1707
+ type: "button",
1708
+ size: "icon",
1709
+ onClick: () => void composer.submit(),
1710
+ disabled: !composer.canSubmit,
1711
+ "aria-label": "Send",
1712
+ "aria-keyshortcuts": "Enter",
1713
+ className: "h-9 w-9",
1714
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Send, { "aria-hidden": true, className: "size-4" })
1715
+ }
1716
+ )
1717
+ ] })
1718
+ ]
1719
+ }
1720
+ );
1721
+ }, "Composer"));
1722
+ function EmptyState({
1723
+ greeting,
1724
+ description,
1725
+ suggestions,
1726
+ onPickSuggestion,
1727
+ className
1728
+ }) {
1729
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: lib.cn("flex flex-col items-center gap-3 px-4 py-12 text-center", className), children: [
1730
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "grid size-10 place-items-center rounded-full bg-muted", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Sparkles, { "aria-hidden": true, className: "size-5 text-muted-foreground" }) }),
1731
+ greeting ? /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-base font-semibold", children: greeting }) : null,
1732
+ description ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "max-w-md text-sm text-muted-foreground", children: description }) : null,
1733
+ suggestions?.length ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-2 grid w-full max-w-md grid-cols-1 gap-2 sm:grid-cols-2", children: suggestions.map((s) => /* @__PURE__ */ jsxRuntime.jsx(
1734
+ "button",
1735
+ {
1736
+ type: "button",
1737
+ onClick: () => onPickSuggestion?.(s.prompt),
1738
+ className: "rounded-lg border border-border bg-background/60 px-3 py-2 text-left text-xs hover:bg-accent",
1739
+ children: s.label
1740
+ },
1741
+ s.prompt
1742
+ )) }) : null
1743
+ ] });
1744
+ }
1745
+ chunkOLISEQHS_cjs.__name(EmptyState, "EmptyState");
1746
+ function ErrorBanner({ error, onDismiss, onRetry, className }) {
1747
+ if (!error) return null;
1748
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1749
+ "div",
1750
+ {
1751
+ role: "alert",
1752
+ className: lib.cn(
1753
+ "mx-2.5 my-2 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",
1754
+ className
1755
+ ),
1756
+ children: [
1757
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.AlertCircle, { "aria-hidden": true, className: "mt-0.5 size-3.5 shrink-0" }),
1758
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "min-w-0 flex-1 break-words", children: error }),
1759
+ onRetry ? /* @__PURE__ */ jsxRuntime.jsxs(
1760
+ "button",
1761
+ {
1762
+ type: "button",
1763
+ onClick: onRetry,
1764
+ className: "inline-flex items-center gap-1 rounded px-1.5 py-0.5 hover:bg-destructive/15",
1765
+ children: [
1766
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RefreshCw, { "aria-hidden": true, className: "size-3" }),
1767
+ " Retry"
1768
+ ]
1769
+ }
1770
+ ) : null,
1771
+ onDismiss ? /* @__PURE__ */ jsxRuntime.jsx(
1772
+ "button",
1773
+ {
1774
+ type: "button",
1775
+ "aria-label": "Dismiss",
1776
+ onClick: onDismiss,
1777
+ className: "rounded p-0.5 hover:bg-destructive/15",
1778
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { "aria-hidden": true, className: "size-3" })
1779
+ }
1780
+ ) : null
1781
+ ]
1782
+ }
1783
+ );
1784
+ }
1785
+ chunkOLISEQHS_cjs.__name(ErrorBanner, "ErrorBanner");
1786
+ function JumpToLatest({ visible, unreadCount = 0, onClick, className }) {
1787
+ if (!visible) return null;
1788
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1789
+ "button",
1790
+ {
1791
+ type: "button",
1792
+ onClick,
1793
+ "aria-live": "polite",
1794
+ className: lib.cn(
1795
+ "pointer-events-auto inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-3 py-1 text-xs shadow-md hover:bg-accent",
1796
+ className
1797
+ ),
1798
+ children: [
1799
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ArrowDown, { "aria-hidden": true, className: "size-3.5" }),
1800
+ unreadCount > 0 ? `${unreadCount} new` : "Jump to latest"
1801
+ ]
1802
+ }
1803
+ );
1804
+ }
1805
+ chunkOLISEQHS_cjs.__name(JumpToLatest, "JumpToLatest");
1806
+
1807
+ // src/tools/Chat/core/persona.ts
1808
+ var FALLBACK_USER = { name: "You", initials: "You" };
1809
+ var FALLBACK_ASSISTANT = { name: "AI", initials: "AI" };
1810
+ function resolvePersona(message, user, assistant) {
1811
+ if (message.sender) return message.sender;
1812
+ if (message.role === "user") return user ?? FALLBACK_USER;
1813
+ if (message.role === "assistant") return assistant ?? FALLBACK_ASSISTANT;
1814
+ return { name: message.role };
1815
+ }
1816
+ chunkOLISEQHS_cjs.__name(resolvePersona, "resolvePersona");
1817
+ function deriveInitials(persona, role) {
1818
+ if (persona.initials) return persona.initials;
1819
+ if (persona.name) {
1820
+ const parts = persona.name.trim().split(/\s+/);
1821
+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
1822
+ return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
1823
+ }
1824
+ if (role === "user") return "You";
1825
+ if (role === "assistant") return "AI";
1826
+ return "?";
1827
+ }
1828
+ chunkOLISEQHS_cjs.__name(deriveInitials, "deriveInitials");
1829
+ function StreamingIndicator({ variant = "dots", label, className }) {
1830
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1831
+ "span",
1832
+ {
1833
+ className: lib.cn("inline-flex items-center gap-1.5 text-xs text-muted-foreground", className),
1834
+ "aria-live": "off",
1835
+ children: [
1836
+ variant === "dots" ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex gap-0.5", "aria-hidden": true, children: [
1837
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "size-1 animate-bounce rounded-full bg-current [animation-delay:-0.2s]" }),
1838
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "size-1 animate-bounce rounded-full bg-current [animation-delay:-0.1s]" }),
1839
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "size-1 animate-bounce rounded-full bg-current" })
1840
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-block size-1.5 animate-pulse rounded-full bg-current", "aria-hidden": true }),
1841
+ label ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "italic", children: label }) : null
1842
+ ]
1843
+ }
1844
+ );
1845
+ }
1846
+ chunkOLISEQHS_cjs.__name(StreamingIndicator, "StreamingIndicator");
1847
+ function Sources({ sources, layout = "inline", maxVisible, onClick, className }) {
1848
+ if (!sources?.length) return null;
1849
+ const visible = maxVisible ? sources.slice(0, maxVisible) : sources;
1850
+ const remaining = maxVisible ? Math.max(0, sources.length - maxVisible) : 0;
1851
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1852
+ "div",
1853
+ {
1854
+ className: lib.cn(
1855
+ "mt-2 flex flex-wrap gap-1.5",
1856
+ layout === "grid" && "grid grid-cols-2",
1857
+ className
1858
+ ),
1859
+ children: [
1860
+ visible.map((s, i) => {
1861
+ const handle = onClick ? () => onClick(s) : void 0;
1862
+ const Tag = handle ? "button" : "a";
1863
+ const props = handle ? { type: "button", onClick: handle } : { href: s.url, target: "_blank", rel: "noopener noreferrer" };
1864
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1865
+ Tag,
1866
+ {
1867
+ ...props,
1868
+ className: "inline-flex max-w-full items-center gap-1 rounded-md border border-border bg-background/60 px-2 py-1 text-xs text-foreground/80 hover:bg-accent hover:text-foreground",
1869
+ title: s.snippet ?? s.title,
1870
+ children: [
1871
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "truncate", children: s.title || s.url }),
1872
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ExternalLink, { "aria-hidden": true, className: "size-3 shrink-0 opacity-60" })
1873
+ ]
1874
+ },
1875
+ `${s.url}-${i}`
1876
+ );
1877
+ }),
1878
+ remaining > 0 ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center rounded-md border border-dashed border-border px-2 py-1 text-xs text-muted-foreground", children: [
1879
+ "+",
1880
+ remaining
1881
+ ] }) : null
1882
+ ]
1883
+ }
1884
+ );
1885
+ }
1886
+ chunkOLISEQHS_cjs.__name(Sources, "Sources");
1887
+ function ToolCalls({
1888
+ calls,
1889
+ defaultExpanded = false,
1890
+ expandWhileStreaming = true,
1891
+ renderInput,
1892
+ renderOutput,
1893
+ renderStreaming,
1894
+ renderPayload,
1895
+ className
1896
+ }) {
1897
+ if (!calls?.length) return null;
1898
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: lib.cn("mt-2 space-y-1.5", className), children: calls.map((call) => /* @__PURE__ */ jsxRuntime.jsx(
1899
+ ToolCallItem,
1900
+ {
1901
+ call,
1902
+ defaultExpanded,
1903
+ expandWhileStreaming,
1904
+ renderInput,
1905
+ renderOutput,
1906
+ renderStreaming,
1907
+ renderPayload
1908
+ },
1909
+ call.id
1910
+ )) });
1911
+ }
1912
+ chunkOLISEQHS_cjs.__name(ToolCalls, "ToolCalls");
1913
+ function ToolCallItem({
1914
+ call,
1915
+ defaultExpanded,
1916
+ expandWhileStreaming,
1917
+ renderInput,
1918
+ renderOutput,
1919
+ renderStreaming,
1920
+ renderPayload
1921
+ }) {
1922
+ const isRunning = call.status === "running";
1923
+ const initialOpen = defaultExpanded || expandWhileStreaming && isRunning;
1924
+ const [open, setOpen] = react.useState(initialOpen);
1925
+ const userToggledRef = react.useRef(false);
1926
+ const wasRunningRef = react.useRef(isRunning);
1927
+ react.useEffect(() => {
1928
+ if (wasRunningRef.current && !isRunning) {
1929
+ if (!userToggledRef.current && !defaultExpanded) {
1930
+ setOpen(false);
1931
+ }
1932
+ }
1933
+ wasRunningRef.current = isRunning;
1934
+ }, [isRunning, defaultExpanded]);
1935
+ const handleToggle = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
1936
+ userToggledRef.current = true;
1937
+ setOpen((v) => !v);
1938
+ }, "handleToggle");
1939
+ const Icon = open ? lucideReact.ChevronDown : lucideReact.ChevronRight;
1940
+ const statusColor = call.status === "success" ? "text-emerald-500" : call.status === "error" ? "text-destructive" : call.status === "cancelled" ? "text-muted-foreground" : "text-amber-500";
1941
+ const renderValue = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((value, kind) => {
1942
+ if (kind === "input" && renderInput) return renderInput(value, call);
1943
+ if (kind === "output" && renderOutput) return renderOutput(value, call);
1944
+ if (kind === "streaming" && renderStreaming)
1945
+ return renderStreaming(typeof value === "string" ? value : String(value), call);
1946
+ if (renderPayload) return renderPayload(value, kind, call);
1947
+ return /* @__PURE__ */ jsxRuntime.jsx(DefaultPayload, { value, kind });
1948
+ }, "renderValue");
1949
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "overflow-hidden rounded-md border border-border bg-muted/30", children: [
1950
+ /* @__PURE__ */ jsxRuntime.jsxs(
1951
+ "button",
1952
+ {
1953
+ type: "button",
1954
+ onClick: handleToggle,
1955
+ "aria-expanded": open,
1956
+ className: "flex w-full items-center gap-2 px-2 py-1.5 text-left text-xs hover:bg-muted/60",
1957
+ children: [
1958
+ /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true, className: "size-3 shrink-0 text-muted-foreground" }),
1959
+ isRunning ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { "aria-hidden": true, className: "size-3 shrink-0 animate-spin text-amber-500" }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: lib.cn("size-2 shrink-0 rounded-full", statusColor.replace("text-", "bg-")) }),
1960
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-mono text-foreground", children: call.name }),
1961
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: lib.cn("ml-auto", statusColor), children: call.status })
1962
+ ]
1963
+ }
1964
+ ),
1965
+ open ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1 border-t border-border px-2 py-1.5 text-[11px]", children: [
1966
+ call.input != null ? renderValue(call.input, "input") : null,
1967
+ call.streamingText != null ? renderValue(call.streamingText, "streaming") : call.output !== void 0 ? renderValue(call.output, "output") : null
1968
+ ] }) : null
1969
+ ] });
1970
+ }
1971
+ chunkOLISEQHS_cjs.__name(ToolCallItem, "ToolCallItem");
1972
+ function DefaultPayload({ value, kind }) {
1973
+ const isStreamingOrString = kind === "streaming" || typeof value === "string";
1974
+ const muted = kind === "input";
1975
+ return /* @__PURE__ */ jsxRuntime.jsx(
1976
+ "pre",
1977
+ {
1978
+ className: lib.cn(
1979
+ "overflow-auto rounded bg-background/60 p-1.5 font-mono",
1980
+ kind === "input" ? "max-h-32" : "max-h-48",
1981
+ muted ? "text-muted-foreground" : "text-foreground/90"
1982
+ ),
1983
+ children: isStreamingOrString ? String(value) : safeStringify(value)
1984
+ }
1985
+ );
1986
+ }
1987
+ chunkOLISEQHS_cjs.__name(DefaultPayload, "DefaultPayload");
1988
+ function safeStringify(value) {
1989
+ try {
1990
+ return JSON.stringify(value, null, 2);
1991
+ } catch {
1992
+ return String(value);
1993
+ }
1994
+ }
1995
+ chunkOLISEQHS_cjs.__name(safeStringify, "safeStringify");
1996
+ function MessageActions({
1997
+ role,
1998
+ onCopy,
1999
+ onRegenerate,
2000
+ onEdit,
2001
+ onDelete,
2002
+ hideOn,
2003
+ className
2004
+ }) {
2005
+ if (hideOn?.includes(role)) return null;
2006
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2007
+ "div",
2008
+ {
2009
+ className: lib.cn(
2010
+ "mt-1 flex items-center gap-0.5 opacity-0 transition-opacity group-hover/msg:opacity-100 focus-within:opacity-100",
2011
+ className
2012
+ ),
2013
+ children: [
2014
+ onCopy ? /* @__PURE__ */ jsxRuntime.jsx(ActionButton, { onClick: onCopy, label: "Copy", icon: lucideReact.Copy }) : null,
2015
+ onRegenerate && role === "assistant" ? /* @__PURE__ */ jsxRuntime.jsx(ActionButton, { onClick: onRegenerate, label: "Regenerate", icon: lucideReact.RefreshCw }) : null,
2016
+ onEdit && role === "user" ? /* @__PURE__ */ jsxRuntime.jsx(ActionButton, { onClick: onEdit, label: "Edit", icon: lucideReact.Pencil }) : null,
2017
+ onDelete ? /* @__PURE__ */ jsxRuntime.jsx(ActionButton, { onClick: onDelete, label: "Delete", icon: lucideReact.Trash, destructive: true }) : null
2018
+ ]
2019
+ }
2020
+ );
2021
+ }
2022
+ chunkOLISEQHS_cjs.__name(MessageActions, "MessageActions");
2023
+ function ActionButton({
2024
+ onClick,
2025
+ label,
2026
+ icon: Icon,
2027
+ destructive
2028
+ }) {
2029
+ return /* @__PURE__ */ jsxRuntime.jsx(
2030
+ "button",
2031
+ {
2032
+ type: "button",
2033
+ onClick,
2034
+ "aria-label": label,
2035
+ className: lib.cn(
2036
+ "rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground",
2037
+ destructive && "hover:bg-destructive/15 hover:text-destructive"
2038
+ ),
2039
+ children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true, className: "size-3" })
2040
+ }
2041
+ );
2042
+ }
2043
+ chunkOLISEQHS_cjs.__name(ActionButton, "ActionButton");
2044
+ var MessageBubbleInner = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(({
2045
+ message,
2046
+ isUser: isUserProp,
2047
+ showAvatar = true,
2048
+ avatarSrc,
2049
+ avatarFallback,
2050
+ user,
2051
+ assistant,
2052
+ showTimestamp = false,
2053
+ showActions = true,
2054
+ isCompact = false,
2055
+ className,
2056
+ beforeContent,
2057
+ afterContent,
2058
+ toolCallsRenderer,
2059
+ toolCallsProps,
2060
+ sourcesRenderer,
2061
+ attachmentsRenderer,
2062
+ attachmentRenderers,
2063
+ onAttachmentOpen,
2064
+ onCopy,
2065
+ onRegenerate,
2066
+ onEdit,
2067
+ onDelete
2068
+ }) => {
2069
+ const isUser = isUserProp ?? message.role === "user";
2070
+ const isStreaming = !!message.isStreaming;
2071
+ const isErr = !!message.isError;
2072
+ const ctx = useChatContextOptional();
2073
+ const persona = resolvePersona(
2074
+ message,
2075
+ user ?? ctx?.config.user,
2076
+ assistant ?? ctx?.config.assistant
2077
+ );
2078
+ const initials = deriveInitials(persona, message.role);
2079
+ const personaName = persona.name ?? (isUser ? "You" : "Assistant");
2080
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2081
+ "div",
2082
+ {
2083
+ role: "article",
2084
+ "aria-label": `${personaName} said: ${message.content.slice(0, 80)}`,
2085
+ "aria-busy": isStreaming || void 0,
2086
+ "data-role": message.role,
2087
+ className: lib.cn(
2088
+ "group/msg flex gap-2.5 px-2.5 py-2",
2089
+ isUser ? "flex-row-reverse" : "flex-row",
2090
+ className
2091
+ ),
2092
+ children: [
2093
+ showAvatar ? /* @__PURE__ */ jsxRuntime.jsxs(
2094
+ components.Avatar,
2095
+ {
2096
+ className: "size-7 shrink-0",
2097
+ title: persona.description ?? personaName,
2098
+ children: [
2099
+ avatarSrc || persona.avatarUrl ? /* @__PURE__ */ jsxRuntime.jsx(components.AvatarImage, { src: avatarSrc ?? persona.avatarUrl, alt: personaName }) : null,
2100
+ /* @__PURE__ */ jsxRuntime.jsx(components.AvatarFallback, { className: "text-[10px]", children: avatarFallback ?? initials })
2101
+ ]
2102
+ }
2103
+ ) : null,
2104
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: lib.cn("min-w-0 flex-1", isUser && "flex flex-col items-end"), children: [
2105
+ beforeContent,
2106
+ message.attachments?.length ? attachmentsRenderer ? attachmentsRenderer(message.attachments) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mb-1.5 w-full", children: attachmentRenderers ? /* @__PURE__ */ jsxRuntime.jsx(
2107
+ AttachmentsList,
2108
+ {
2109
+ attachments: message.attachments,
2110
+ renderers: attachmentRenderers,
2111
+ onClick: onAttachmentOpen,
2112
+ className: isUser ? "items-end" : void 0
2113
+ }
2114
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
2115
+ AttachmentsGrid,
2116
+ {
2117
+ attachments: message.attachments,
2118
+ onClick: onAttachmentOpen,
2119
+ className: isUser ? "justify-end" : void 0
2120
+ }
2121
+ ) }) : null,
2122
+ /* @__PURE__ */ jsxRuntime.jsxs(
2123
+ "div",
2124
+ {
2125
+ className: lib.cn(
2126
+ "inline-block max-w-full rounded-2xl px-3.5 py-2 text-sm",
2127
+ isUser ? "bg-primary text-primary-foreground rounded-tr-md" : isErr ? "bg-destructive/10 text-destructive rounded-tl-md border border-destructive/30" : "bg-muted text-foreground rounded-tl-md"
2128
+ ),
2129
+ children: [
2130
+ isStreaming && message.toolActivity ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mb-1.5", children: /* @__PURE__ */ jsxRuntime.jsx(StreamingIndicator, { label: message.toolActivity }) }) : null,
2131
+ message.content || !isStreaming ? /* @__PURE__ */ jsxRuntime.jsx(
2132
+ chunkB5AWZOHJ_cjs.MarkdownMessage,
2133
+ {
2134
+ content: message.content || (isErr ? "*Failed to generate a response.*" : ""),
2135
+ isUser,
2136
+ isCompact,
2137
+ plainText: isStreaming
2138
+ }
2139
+ ) : /* @__PURE__ */ jsxRuntime.jsx(StreamingIndicator, {})
2140
+ ]
2141
+ }
2142
+ ),
2143
+ message.toolCalls?.length ? toolCallsRenderer ? toolCallsRenderer(message.toolCalls) : /* @__PURE__ */ jsxRuntime.jsx(ToolCalls, { calls: message.toolCalls, ...toolCallsProps }) : null,
2144
+ message.sources?.length && !isStreaming ? sourcesRenderer ? sourcesRenderer(message.sources) : /* @__PURE__ */ jsxRuntime.jsx(Sources, { sources: message.sources }) : null,
2145
+ showActions && !isStreaming ? /* @__PURE__ */ jsxRuntime.jsx(
2146
+ MessageActions,
2147
+ {
2148
+ role: message.role,
2149
+ onCopy,
2150
+ onRegenerate,
2151
+ onEdit,
2152
+ onDelete
2153
+ }
2154
+ ) : null,
2155
+ showTimestamp ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-1 text-[10px] text-muted-foreground", children: new Date(message.createdAt).toLocaleTimeString() }) : null,
2156
+ afterContent
2157
+ ] })
2158
+ ]
2159
+ }
2160
+ );
2161
+ }, "MessageBubbleInner");
2162
+ var MessageBubble = react.memo(MessageBubbleInner, (prev, next) => {
2163
+ const a = prev.message;
2164
+ const b = next.message;
2165
+ return a.id === b.id && a.content === b.content && a.isStreaming === b.isStreaming && a.isError === b.isError && (a.version ?? 0) === (b.version ?? 0) && a.toolActivity === b.toolActivity && a.toolCalls === b.toolCalls && a.sources === b.sources && a.attachments === b.attachments;
2166
+ });
2167
+ MessageBubble.displayName = "MessageBubble";
2168
+ var MessageList = react.forwardRef(/* @__PURE__ */ chunkOLISEQHS_cjs.__name(function MessageList2({
2169
+ messages: messagesProp,
2170
+ renderItem,
2171
+ renderEmpty,
2172
+ isLoadingMore: isLoadingMoreProp,
2173
+ topSentinelRef,
2174
+ bottomRef,
2175
+ className,
2176
+ itemClassName
2177
+ }, ref) {
2178
+ const ctx = useChatContextOptional();
2179
+ const messages = messagesProp ?? ctx?.messages ?? [];
2180
+ const isLoadingMore = isLoadingMoreProp ?? ctx?.isLoadingMore ?? false;
2181
+ const defaultRenderItem = react.useCallback(
2182
+ (m) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: itemClassName, children: /* @__PURE__ */ jsxRuntime.jsx(
2183
+ MessageBubble,
2184
+ {
2185
+ message: m,
2186
+ onCopy: () => copy(m.content),
2187
+ onRegenerate: ctx ? () => void ctx.regenerate(m.id) : void 0,
2188
+ onDelete: ctx ? () => ctx.deleteMessage(m.id) : void 0
2189
+ }
2190
+ ) }, m.id),
2191
+ [itemClassName, ctx]
2192
+ );
2193
+ const itemRenderer = renderItem ?? defaultRenderItem;
2194
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2195
+ "div",
2196
+ {
2197
+ ref,
2198
+ role: "log",
2199
+ "aria-live": "polite",
2200
+ "aria-atomic": "false",
2201
+ className: lib.cn("flex-1 overflow-y-auto", className),
2202
+ children: [
2203
+ /* @__PURE__ */ jsxRuntime.jsx("div", { ref: topSentinelRef, "aria-hidden": true }),
2204
+ isLoadingMore ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center py-2", children: /* @__PURE__ */ jsxRuntime.jsx(components.Spinner, { className: "size-4 text-muted-foreground" }) }) : null,
2205
+ messages.length === 0 ? renderEmpty?.() ?? null : messages.map((m, i) => itemRenderer(m, i)),
2206
+ /* @__PURE__ */ jsxRuntime.jsx("div", { ref: bottomRef, "aria-hidden": true })
2207
+ ]
2208
+ }
2209
+ );
2210
+ }, "MessageList"));
2211
+ function copy(text) {
2212
+ if (typeof navigator !== "undefined" && navigator.clipboard) {
2213
+ void navigator.clipboard.writeText(text);
2214
+ }
2215
+ }
2216
+ chunkOLISEQHS_cjs.__name(copy, "copy");
2217
+ function ChatRoot(props) {
2218
+ const { transport, config, initialSessionId, autoCreateSession, streaming, audio, debug, className, ...slots } = props;
2219
+ return /* @__PURE__ */ jsxRuntime.jsx(
2220
+ ChatProvider,
2221
+ {
2222
+ transport,
2223
+ config,
2224
+ initialSessionId,
2225
+ autoCreateSession,
2226
+ streaming,
2227
+ audio,
2228
+ debug,
2229
+ children: /* @__PURE__ */ jsxRuntime.jsx(ChatRootShell, { className, slots })
2230
+ }
2231
+ );
2232
+ }
2233
+ chunkOLISEQHS_cjs.__name(ChatRoot, "ChatRoot");
2234
+ function ChatRootShell({ className, slots }) {
2235
+ const chat = useChatContext();
2236
+ const composer = useChatComposer({
2237
+ onSubmit: /* @__PURE__ */ chunkOLISEQHS_cjs.__name((content, attachments) => chat.sendMessage(content, attachments), "onSubmit"),
2238
+ disabled: chat.isStreaming
2239
+ });
2240
+ const containerRef = react.useRef(null);
2241
+ const bottomRef = react.useRef(null);
2242
+ const topRef = react.useRef(null);
2243
+ const scroll = useChatScroll({
2244
+ containerRef,
2245
+ bottomRef,
2246
+ isStreaming: chat.isStreaming,
2247
+ messagesCount: chat.messages.length
2248
+ });
2249
+ useChatHistory({
2250
+ containerRef,
2251
+ topSentinelRef: topRef,
2252
+ hasMore: chat.hasMore,
2253
+ isLoadingMore: chat.isLoadingMore,
2254
+ loadMore: chat.loadMore
2255
+ });
2256
+ const greeting = chat.config.greeting ?? "How can I help?";
2257
+ const description = chat.config.description;
2258
+ const suggestions = chat.config.suggestions;
2259
+ const headerNode = slots.renderHeader ? slots.renderHeader(chat) : slots.header;
2260
+ const emptyNode = slots.empty ?? (slots.renderEmpty ? slots.renderEmpty({ setValue: composer.setValue, focus: composer.focus }) : /* @__PURE__ */ jsxRuntime.jsx(
2261
+ EmptyState,
2262
+ {
2263
+ greeting,
2264
+ description,
2265
+ suggestions,
2266
+ onPickSuggestion: (prompt) => {
2267
+ composer.setValue(prompt);
2268
+ composer.focus();
2269
+ }
2270
+ }
2271
+ ));
2272
+ const renderItem = slots.renderMessage ?? ((m) => /* @__PURE__ */ jsxRuntime.jsx(
2273
+ MessageBubble,
2274
+ {
2275
+ message: m,
2276
+ toolCallsProps: slots.toolCallsProps,
2277
+ attachmentRenderers: slots.attachmentRenderers,
2278
+ onAttachmentOpen: slots.onAttachmentOpen,
2279
+ onCopy: () => copy2(m.content),
2280
+ onRegenerate: () => void chat.regenerate(m.id),
2281
+ onDelete: () => chat.deleteMessage(m.id)
2282
+ },
2283
+ m.id
2284
+ ));
2285
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: lib.cn("relative flex h-full min-h-0 flex-col overflow-hidden", className), children: [
2286
+ slots.banner ?? null,
2287
+ headerNode ?? null,
2288
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex min-h-0 flex-1 flex-col", children: [
2289
+ /* @__PURE__ */ jsxRuntime.jsx(
2290
+ ErrorBanner,
2291
+ {
2292
+ error: chat.error,
2293
+ onDismiss: chat.error ? () => chat.clearMessages() : void 0,
2294
+ onRetry: chat.error ? () => void chat.regenerate() : void 0
2295
+ }
2296
+ ),
2297
+ /* @__PURE__ */ jsxRuntime.jsx(
2298
+ MessageList,
2299
+ {
2300
+ ref: containerRef,
2301
+ topSentinelRef: topRef,
2302
+ bottomRef,
2303
+ renderItem,
2304
+ renderEmpty: () => /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: emptyNode })
2305
+ }
2306
+ ),
2307
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-none absolute inset-x-0 bottom-2 flex justify-center", children: slots.jumpToLatest ?? /* @__PURE__ */ jsxRuntime.jsx(
2308
+ JumpToLatest,
2309
+ {
2310
+ visible: !scroll.isAtBottom,
2311
+ unreadCount: scroll.unreadCount,
2312
+ onClick: () => scroll.scrollToBottom(true)
2313
+ }
2314
+ ) })
2315
+ ] }),
2316
+ /* @__PURE__ */ jsxRuntime.jsx(
2317
+ Composer,
2318
+ {
2319
+ composer,
2320
+ placeholder: chat.config.placeholder,
2321
+ showAttachmentButton: slots.showAttachmentButton,
2322
+ onPickFiles: slots.onPickFiles,
2323
+ toolbarStart: slots.composerToolbarStart,
2324
+ toolbarEnd: slots.composerToolbarEnd,
2325
+ attachmentTray: slots.composerAttachmentTray
2326
+ }
2327
+ ),
2328
+ slots.footer ?? null
2329
+ ] });
2330
+ }
2331
+ chunkOLISEQHS_cjs.__name(ChatRootShell, "ChatRootShell");
2332
+ function copy2(text) {
2333
+ if (typeof navigator !== "undefined" && navigator.clipboard) {
2334
+ void navigator.clipboard.writeText(text);
2335
+ }
2336
+ }
2337
+ chunkOLISEQHS_cjs.__name(copy2, "copy");
2338
+
2339
+ exports.Attachments = Attachments;
2340
+ exports.AttachmentsGrid = AttachmentsGrid;
2341
+ exports.AttachmentsList = AttachmentsList;
2342
+ exports.CHAT_EVENT_NAME = CHAT_EVENT_NAME;
2343
+ exports.CSS_VARS = CSS_VARS;
2344
+ exports.ChatProvider = ChatProvider;
2345
+ exports.ChatRoot = ChatRoot;
2346
+ exports.Composer = Composer;
2347
+ exports.DEFAULT_LABELS = DEFAULT_LABELS;
2348
+ exports.DEFAULT_SIDEBAR = DEFAULT_SIDEBAR;
2349
+ exports.DEFAULT_Z_INDEX = DEFAULT_Z_INDEX;
2350
+ exports.EmptyState = EmptyState;
2351
+ exports.ErrorBanner = ErrorBanner;
2352
+ exports.HOTKEYS = HOTKEYS;
2353
+ exports.JumpToLatest = JumpToLatest;
2354
+ exports.LIMITS = LIMITS;
2355
+ exports.MessageActions = MessageActions;
2356
+ exports.MessageBubble = MessageBubble;
2357
+ exports.MessageList = MessageList;
2358
+ exports.STORAGE_KEYS = STORAGE_KEYS;
2359
+ exports.Sources = Sources;
2360
+ exports.StreamingIndicator = StreamingIndicator;
2361
+ exports.ToolCalls = ToolCalls;
2362
+ exports.createId = createId;
2363
+ exports.createTokenBuffer = createTokenBuffer;
2364
+ exports.deriveInitials = deriveInitials;
2365
+ exports.getChatLogger = getChatLogger;
2366
+ exports.initialState = initialState;
2367
+ exports.reducer = reducer;
2368
+ exports.resolvePersona = resolvePersona;
2369
+ exports.useChat = useChat;
2370
+ exports.useChatAudio = useChatAudio;
2371
+ exports.useChatAudioPrefs = useChatAudioPrefs;
2372
+ exports.useChatComposer = useChatComposer;
2373
+ exports.useChatContext = useChatContext;
2374
+ exports.useChatContextOptional = useChatContextOptional;
2375
+ exports.useChatHistory = useChatHistory;
2376
+ exports.useChatLayout = useChatLayout;
2377
+ exports.useChatScroll = useChatScroll;
2378
+ //# sourceMappingURL=chunk-ZWPBBAR2.cjs.map
2379
+ //# sourceMappingURL=chunk-ZWPBBAR2.cjs.map