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