@djangocfg/ui-tools 2.1.381 → 2.1.383

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