chatluna-plugin-onebot-sandbox 1.0.0

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -0
  3. package/client/app.tsx +306 -0
  4. package/client/chat/chat-pane.tsx +303 -0
  5. package/client/chat/composer.css +635 -0
  6. package/client/chat/composer.tsx +646 -0
  7. package/client/chat/details-panel.tsx +196 -0
  8. package/client/chat/emoji-picker.tsx +70 -0
  9. package/client/chat/extension-mark.tsx +16 -0
  10. package/client/chat/forward.tsx +257 -0
  11. package/client/chat/image-preview.tsx +93 -0
  12. package/client/chat/member-menu.tsx +64 -0
  13. package/client/chat/message-list.tsx +617 -0
  14. package/client/chat/messages.css +1018 -0
  15. package/client/chat/notifications.tsx +83 -0
  16. package/client/chat/reactions.tsx +52 -0
  17. package/client/chat/search-panel.tsx +231 -0
  18. package/client/chat/sidebar.tsx +424 -0
  19. package/client/chat/webqq-view.tsx +71 -0
  20. package/client/environment/avatar-picker.tsx +92 -0
  21. package/client/environment/create-popover.tsx +228 -0
  22. package/client/environment/directory-model.ts +63 -0
  23. package/client/environment/entity-dialog.css +383 -0
  24. package/client/environment/entity-dialog.tsx +442 -0
  25. package/client/environment/page.css +14 -0
  26. package/client/environment/page.tsx +280 -0
  27. package/client/i18n.ts +19 -0
  28. package/client/index.ts +17 -0
  29. package/client/locales/en.yml +617 -0
  30. package/client/locales/zh.yml +617 -0
  31. package/client/mcp/capability-catalog.tsx +277 -0
  32. package/client/mcp/credential-manager.tsx +257 -0
  33. package/client/onebot-debug/page.tsx +329 -0
  34. package/client/records/record-layout.tsx +429 -0
  35. package/client/records/records.css +259 -0
  36. package/client/settings/about.tsx +43 -0
  37. package/client/settings/draft.ts +47 -0
  38. package/client/settings/localize.ts +76 -0
  39. package/client/settings/page.tsx +210 -0
  40. package/client/settings/settings.css +47 -0
  41. package/client/shared/avatar.tsx +35 -0
  42. package/client/shared/confirm-dialog.tsx +44 -0
  43. package/client/shared/controls.css +17 -0
  44. package/client/shared/discard-confirm.tsx +45 -0
  45. package/client/shared/floating-panel.ts +40 -0
  46. package/client/shared/format-duration.ts +22 -0
  47. package/client/shared/format-time.ts +49 -0
  48. package/client/shared/glass.css +150 -0
  49. package/client/shared/implementation.ts +12 -0
  50. package/client/shared/overlay-scrollbar.css +45 -0
  51. package/client/shared/overlay-scrollbar.tsx +123 -0
  52. package/client/shared/use-element-width.ts +19 -0
  53. package/client/shared/use-retained.ts +12 -0
  54. package/client/test-call/page.tsx +260 -0
  55. package/client/test-space/agent-visuals.tsx +121 -0
  56. package/client/test-space/observe-overlay.tsx +42 -0
  57. package/client/test-space/overview.tsx +267 -0
  58. package/client/test-space/spaces.css +201 -0
  59. package/client/test-space/thumbnail-capture.ts +63 -0
  60. package/client/test-space/thumbnail-scale.ts +21 -0
  61. package/client/test-space/use-space-list.ts +35 -0
  62. package/client/test-space/zoom.ts +197 -0
  63. package/client/webqq/composer-draft-host.ts +578 -0
  64. package/client/webqq/composer-draft.ts +81 -0
  65. package/client/webqq/conversation-tree.ts +155 -0
  66. package/client/webqq/emoji-catalog.ts +78 -0
  67. package/client/webqq/fork-boundary.ts +28 -0
  68. package/client/webqq/forward-cluster.ts +20 -0
  69. package/client/webqq/forward-dialog-stack.ts +74 -0
  70. package/client/webqq/forward-preview.ts +40 -0
  71. package/client/webqq/friend-menu.ts +17 -0
  72. package/client/webqq/group-display.ts +18 -0
  73. package/client/webqq/group-menu.ts +25 -0
  74. package/client/webqq/mention.ts +4 -0
  75. package/client/webqq/message-capabilities.ts +37 -0
  76. package/client/webqq/message-cluster.ts +68 -0
  77. package/client/webqq/message-presentation.ts +197 -0
  78. package/client/webqq/message-reveal.ts +31 -0
  79. package/client/webqq/message-search-date.ts +40 -0
  80. package/client/webqq/message-selection.ts +85 -0
  81. package/client/webqq/notification-requests.ts +20 -0
  82. package/client/webqq/participant-presentation.ts +128 -0
  83. package/client/webqq/profile-card.ts +199 -0
  84. package/client/webqq/relationship-directory.ts +62 -0
  85. package/client/webqq/thinking-panel.ts +7 -0
  86. package/client/webqq/user-stack.ts +53 -0
  87. package/client/workspace/agent-overlay-effect.ts +238 -0
  88. package/client/workspace/context.tsx +117 -0
  89. package/client/workspace/overlay-host.tsx +299 -0
  90. package/client/workspace/profile-card.css +164 -0
  91. package/client/workspace/state.ts +28 -0
  92. package/client/workspace/store.ts +388 -0
  93. package/client/workspace/use-test-spaces.ts +21 -0
  94. package/dist/.vite/manifest.json +21 -0
  95. package/dist/app-63rfTh6w.js +85 -0
  96. package/dist/client.css +4 -0
  97. package/dist/client.js +1 -0
  98. package/lib/account-profile.d.ts +17 -0
  99. package/lib/account-profile.d.ts.map +1 -0
  100. package/lib/base-dir.d.ts +4 -0
  101. package/lib/base-dir.d.ts.map +1 -0
  102. package/lib/bot.d.ts +185 -0
  103. package/lib/bot.d.ts.map +1 -0
  104. package/lib/builtin-avatar-options.d.ts +11 -0
  105. package/lib/builtin-avatar-options.d.ts.map +1 -0
  106. package/lib/builtin-avatars.d.ts +6 -0
  107. package/lib/builtin-avatars.d.ts.map +1 -0
  108. package/lib/channel-assignee.d.ts +52 -0
  109. package/lib/channel-assignee.d.ts.map +1 -0
  110. package/lib/chatluna/conversation-lines.d.ts +46 -0
  111. package/lib/chatluna/conversation-lines.d.ts.map +1 -0
  112. package/lib/chatluna/runtime.d.ts +26 -0
  113. package/lib/chatluna/runtime.d.ts.map +1 -0
  114. package/lib/chatluna/state.d.ts +67 -0
  115. package/lib/chatluna/state.d.ts.map +1 -0
  116. package/lib/chatluna/thinking.d.ts +10 -0
  117. package/lib/chatluna/thinking.d.ts.map +1 -0
  118. package/lib/chatluna/tools.d.ts +36 -0
  119. package/lib/chatluna/tools.d.ts.map +1 -0
  120. package/lib/chatluna/wakeup.d.ts +143 -0
  121. package/lib/chatluna/wakeup.d.ts.map +1 -0
  122. package/lib/console-contract.d.ts +131 -0
  123. package/lib/console-contract.d.ts.map +1 -0
  124. package/lib/console.d.ts +31 -0
  125. package/lib/console.d.ts.map +1 -0
  126. package/lib/control-service.d.ts +425 -0
  127. package/lib/control-service.d.ts.map +1 -0
  128. package/lib/conversation-resolution.d.ts +157 -0
  129. package/lib/conversation-resolution.d.ts.map +1 -0
  130. package/lib/error-detail.d.ts +3 -0
  131. package/lib/error-detail.d.ts.map +1 -0
  132. package/lib/inbound-delivery.d.ts +156 -0
  133. package/lib/inbound-delivery.d.ts.map +1 -0
  134. package/lib/index.d.ts +76 -0
  135. package/lib/index.d.ts.map +1 -0
  136. package/lib/index.js +12834 -0
  137. package/lib/index.js.map +1 -0
  138. package/lib/lifecycle.d.ts +8 -0
  139. package/lib/lifecycle.d.ts.map +1 -0
  140. package/lib/mcp/arguments.d.ts +71 -0
  141. package/lib/mcp/arguments.d.ts.map +1 -0
  142. package/lib/mcp/call-records.d.ts +32 -0
  143. package/lib/mcp/call-records.d.ts.map +1 -0
  144. package/lib/mcp/http-api.d.ts +147 -0
  145. package/lib/mcp/http-api.d.ts.map +1 -0
  146. package/lib/mcp/page-cursor.d.ts +37 -0
  147. package/lib/mcp/page-cursor.d.ts.map +1 -0
  148. package/lib/mcp/server.d.ts +60 -0
  149. package/lib/mcp/server.d.ts.map +1 -0
  150. package/lib/mcp/service.d.ts +219 -0
  151. package/lib/mcp/service.d.ts.map +1 -0
  152. package/lib/mcp/tool-registry.d.ts +113 -0
  153. package/lib/mcp/tool-registry.d.ts.map +1 -0
  154. package/lib/mcp/types.d.ts +144 -0
  155. package/lib/mcp/types.d.ts.map +1 -0
  156. package/lib/media-storage.d.ts +33 -0
  157. package/lib/media-storage.d.ts.map +1 -0
  158. package/lib/message-capabilities.d.ts +78 -0
  159. package/lib/message-capabilities.d.ts.map +1 -0
  160. package/lib/onebot-debug.d.ts +115 -0
  161. package/lib/onebot-debug.d.ts.map +1 -0
  162. package/lib/onebot-message.d.ts +23 -0
  163. package/lib/onebot-message.d.ts.map +1 -0
  164. package/lib/onebot-profiles.d.ts +45 -0
  165. package/lib/onebot-profiles.d.ts.map +1 -0
  166. package/lib/persistence.d.ts +148 -0
  167. package/lib/persistence.d.ts.map +1 -0
  168. package/lib/random.d.ts +5 -0
  169. package/lib/random.d.ts.map +1 -0
  170. package/lib/record-store.d.ts +80 -0
  171. package/lib/record-store.d.ts.map +1 -0
  172. package/lib/relationship-actions.d.ts +157 -0
  173. package/lib/relationship-actions.d.ts.map +1 -0
  174. package/lib/scope-directory.d.ts +105 -0
  175. package/lib/scope-directory.d.ts.map +1 -0
  176. package/lib/settings.d.ts +33 -0
  177. package/lib/settings.d.ts.map +1 -0
  178. package/lib/test-spaces.d.ts +69 -0
  179. package/lib/test-spaces.d.ts.map +1 -0
  180. package/lib/types.d.ts +739 -0
  181. package/lib/types.d.ts.map +1 -0
  182. package/lib/webui.d.ts +26 -0
  183. package/lib/webui.d.ts.map +1 -0
  184. package/package.json +112 -0
@@ -0,0 +1,646 @@
1
+ import * as React from 'react'
2
+ import { createLayout, type AutoLayout } from 'animejs'
3
+ import { FileIcon, PaperclipIcon, PencilIcon, PlusIcon, SendIcon, Trash2Icon, XIcon } from 'lucide-react'
4
+ import {
5
+ cn,
6
+ ContextMenu,
7
+ ContextMenuContent,
8
+ ContextMenuItem,
9
+ ContextMenuTrigger,
10
+ Tooltip,
11
+ TooltipContent,
12
+ TooltipTrigger,
13
+ } from '@chatluna/ui-kit'
14
+ import type { SendMediaFileInput } from '../../src/types'
15
+ import { useT } from '../i18n'
16
+ import { SandboxAvatar } from '../shared/avatar'
17
+ import { CreateEntityPopover } from '../environment/create-popover'
18
+ import type { MentionCandidate } from '../webqq/composer-draft'
19
+ import {
20
+ createComposerDraftHost,
21
+ resolveComposerHostTextOffset,
22
+ type ComposerHostCaretReading,
23
+ type ComposerHostCaretTarget,
24
+ type ComposerHostNodePlan,
25
+ type ComposerHostNodeReading,
26
+ } from '../webqq/composer-draft-host'
27
+ import {
28
+ getUserStackLayoutMetrics,
29
+ getUserStackMetrics,
30
+ orderUsersByActive,
31
+ USER_AVATAR_SIZE,
32
+ USER_STACK_COLLAPSED_STEP,
33
+ USER_STACK_EXPANDED_STEP,
34
+ } from '../webqq/user-stack'
35
+ import { errorText } from '../workspace/store'
36
+ import { useSandbox, useWorkspace } from '../workspace/context'
37
+ import { ExtensionMark } from './extension-mark'
38
+ import './composer.css'
39
+
40
+ export interface ComposerHandle {
41
+ focus(): void
42
+ insertMention(mention: { id: string, name: string }): void
43
+ }
44
+
45
+ export interface ComposerSendIntent {
46
+ conversationId: string
47
+ content: string
48
+ replyToMessageId?: string
49
+ media?: SendMediaFileInput[]
50
+ }
51
+
52
+ interface Attachment {
53
+ id: string
54
+ file: File
55
+ previewUrl?: string
56
+ baseName: string
57
+ extension: string
58
+ }
59
+
60
+ const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024
61
+ // 胶囊内 padding(8) + 三个 gap(12) + 附件按钮(32) + 发送按钮(36)。
62
+ const COMPOSER_FIXED_WIDTH = 88
63
+ // 输入区可压缩到 0(min-width: 0),低于这个宽度就该省略头像而不是压扁输入框。
64
+ const COMPOSER_MIN_INPUT_WIDTH = 100
65
+ const ACCEPT = 'image/png,image/jpeg,image/gif,image/webp,audio/*,video/mp4,video/webm,video/quicktime,.txt,.csv,.json,.pdf,.zip,.doc,.docx,.xls,.xlsx,.ppt,.pptx'
66
+
67
+ function splitFileName(name: string) {
68
+ const dot = name.lastIndexOf('.')
69
+ return dot <= 0 ? { baseName: name, extension: '' } : { baseName: name.slice(0, dot), extension: name.slice(dot) }
70
+ }
71
+
72
+ function readDataUrl(file: File) {
73
+ return new Promise<string>((resolve, reject) => {
74
+ const reader = new FileReader()
75
+ reader.addEventListener('load', () => resolve(typeof reader.result === 'string' ? reader.result : ''))
76
+ reader.addEventListener('error', () => reject(reader.error ?? new Error('unreadable')))
77
+ reader.readAsDataURL(file)
78
+ })
79
+ }
80
+
81
+ /**
82
+ * 发送框:悬浮在消息区底部的胶囊。左侧是可切换的发送者头像堆叠(用户与机器人都能作为当前操作者),
83
+ * 中间是支持 @ 成员胶囊的富文本草稿,右侧是附件与发送。Enter 发送、Shift+Enter 换行,输入法组字期间不提交。
84
+ *
85
+ * 外观与动画逐条对齐源插件:折叠时只露当前操作者与最近两位、其余并成 "+N",悬停或聚焦时展开;
86
+ * 切换发送者时当前操作者移到最前,由 Anime.js 的布局 FLIP 补间重排。消息区底部留白经 `onSpaceChange` 回报。
87
+ */
88
+ export const Composer = React.forwardRef<ComposerHandle, {
89
+ replyingTo?: { id: string, authorName: string, content: string }
90
+ mentionCandidates: MentionCandidate[]
91
+ onClearReply(): void
92
+ onSend(intent: ComposerSendIntent): Promise<void>
93
+ onOpenImage?(url: string): void
94
+ onSpaceChange?(space: number): void
95
+ }>(function Composer({ replyingTo, mentionCandidates, onClearReply, onSend, onOpenImage, onSpaceChange }, ref) {
96
+ const t = useT()
97
+ const { store, dialogs } = useSandbox()
98
+ const { conversation, operatorId, snapshot, resolveAvatar } = useWorkspace()
99
+ const editor = React.useRef<HTMLDivElement>(null)
100
+ const fileInput = React.useRef<HTMLInputElement>(null)
101
+ const [, rerender] = React.useReducer((value: number) => value + 1, 0)
102
+ const [attachments, setAttachments] = React.useState<Attachment[]>([])
103
+ const [sending, setSending] = React.useState(false)
104
+ const [error, setError] = React.useState('')
105
+ const [stackExpanded, setStackExpanded] = React.useState(false)
106
+ const [overflowMotion, setOverflowMotion] = React.useState<'idle' | 'expanding' | 'collapsing'>('idle')
107
+ const [compactStack, setCompactStack] = React.useState(false)
108
+ const layoutRoot = React.useRef<HTMLDivElement>(null)
109
+ const form = React.useRef<HTMLFormElement>(null)
110
+ const context = React.useRef<HTMLDivElement>(null)
111
+ const stackRoot = React.useRef<HTMLDivElement>(null)
112
+ const layout = React.useRef<AutoLayout>(undefined)
113
+ const pendingLayout = React.useRef<AutoLayout>(undefined)
114
+ const transitionUntil = React.useRef(0)
115
+ const timers = React.useRef<{ motion?: ReturnType<typeof setTimeout>, suppress?: ReturnType<typeof setTimeout> }>({})
116
+ const pointer = React.useRef({ hovered: false, focused: false, creating: false, suppress: false })
117
+ const stack = React.useRef({ hasOverflow: false, expanded: false })
118
+ const candidates = React.useRef(mentionCandidates)
119
+ candidates.current = mentionCandidates
120
+ const current = React.useRef({ conversationId: conversation?.id, operatorId })
121
+ current.current = { conversationId: conversation?.id, operatorId }
122
+
123
+ const host = React.useMemo(() => createComposerDraftHost({
124
+ readNodes: () => {
125
+ const root = editor.current
126
+ if (!root) return undefined
127
+ const map = (node: Node): ComposerHostNodeReading => {
128
+ if (node.nodeType === Node.TEXT_NODE) return { kind: 'text', text: node.textContent ?? '' }
129
+ if (!(node instanceof HTMLElement)) return { kind: 'container', children: [] }
130
+ if (node.dataset['mentionId']) {
131
+ return { kind: 'mention', id: node.dataset['mentionId'], name: node.dataset['mentionName'] || node.textContent?.replace(/^@/, '') || node.dataset['mentionId'] }
132
+ }
133
+ if (node.tagName === 'BR') return { kind: 'line-break' }
134
+ return { kind: 'container', children: Array.from(node.childNodes).map(map) }
135
+ }
136
+ return Array.from(root.childNodes).map(map)
137
+ },
138
+ renderNodes: (plan: readonly ComposerHostNodePlan[]) => {
139
+ const root = editor.current
140
+ if (!root) return
141
+ root.replaceChildren()
142
+ for (const node of plan) {
143
+ if (node.kind === 'text') {
144
+ root.appendChild(document.createTextNode(node.text))
145
+ continue
146
+ }
147
+ const chip = document.createElement('span')
148
+ chip.className = 'sandbox-composer-mention'
149
+ chip.contentEditable = 'false'
150
+ chip.dataset['mentionId'] = node.id
151
+ chip.dataset['mentionName'] = node.name
152
+ chip.textContent = `@${node.name}`
153
+ root.appendChild(chip)
154
+ }
155
+ },
156
+ readCaret: (): ComposerHostCaretReading | undefined => {
157
+ const root = editor.current
158
+ const selection = window.getSelection()
159
+ if (!root || !selection || selection.rangeCount === 0) return undefined
160
+ const range = selection.getRangeAt(0)
161
+ if (!root.contains(range.startContainer)) return undefined
162
+ if (range.startContainer === root) return { kind: 'editor', childOffset: range.startOffset }
163
+ let childIndex = 0
164
+ for (const child of Array.from(root.childNodes)) {
165
+ if (child === range.startContainer || child.contains(range.startContainer)) return { kind: 'child', childIndex, offset: range.startOffset }
166
+ if (child.nodeType === Node.TEXT_NODE || (child instanceof HTMLElement && child.dataset['mentionId'])) childIndex += 1
167
+ }
168
+ return { kind: 'editor', childOffset: root.childNodes.length }
169
+ },
170
+ writeCaret: (target: ComposerHostCaretTarget) => {
171
+ const root = editor.current
172
+ const selection = window.getSelection()
173
+ if (!root || !selection) return
174
+ let node: Node = root
175
+ let offset = root.childNodes.length
176
+ if (target.kind === 'child') {
177
+ const child = root.childNodes[target.childIndex]
178
+ if (child) {
179
+ node = child
180
+ offset = resolveComposerHostTextOffset(child.textContent ?? '', target.offset)
181
+ }
182
+ }
183
+ try {
184
+ const range = document.createRange()
185
+ range.setStart(node, offset)
186
+ range.collapse(true)
187
+ selection.removeAllRanges()
188
+ selection.addRange(range)
189
+ } catch {
190
+ // 节点在本帧被替换时放弃这次定位,下一次输入会重新同步。
191
+ }
192
+ },
193
+ nextTick: () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),
194
+ focus: () => editor.current?.focus(),
195
+ readMentionCandidates: () => candidates.current,
196
+ }, rerender), [])
197
+
198
+ React.useImperativeHandle(ref, () => ({
199
+ focus: () => host.focus(),
200
+ insertMention: (mention) => host.insertMention(mention),
201
+ }), [host])
202
+
203
+ React.useEffect(() => {
204
+ host.render()
205
+ }, [host])
206
+
207
+ // 换会话或换操作者时草稿作废;附件一并清掉,避免把上一个身份的附件发到新会话。
208
+ React.useEffect(() => {
209
+ host.reset()
210
+ setError('')
211
+ setAttachments((list) => {
212
+ for (const item of list) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)
213
+ return []
214
+ })
215
+ }, [conversation?.id, operatorId, host])
216
+
217
+ React.useEffect(() => () => {
218
+ setAttachments((list) => {
219
+ for (const item of list) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)
220
+ return list
221
+ })
222
+ }, [])
223
+
224
+ const addFiles = (files: Iterable<File>) => {
225
+ const next: Attachment[] = []
226
+ let oversize = false
227
+ for (const file of files) {
228
+ if (file.size > MAX_ATTACHMENT_SIZE) {
229
+ oversize = true
230
+ continue
231
+ }
232
+ next.push({
233
+ id: `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2, 8)}`,
234
+ file,
235
+ previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined,
236
+ ...splitFileName(file.name),
237
+ })
238
+ }
239
+ if (oversize) setError(t('sandbox.composer.oversize'))
240
+ if (next.length) setAttachments((list) => [...list, ...next])
241
+ }
242
+
243
+ const removeAttachment = (id: string) => setAttachments((list) => list.filter((item) => {
244
+ if (item.id !== id) return true
245
+ if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)
246
+ return false
247
+ }))
248
+
249
+ const disabled = sending || !conversation
250
+ const submit = async () => {
251
+ host.closeMentionMenu()
252
+ const content = host.serialize()
253
+ const request = { ...current.current }
254
+ if (sending || host.composing.value || (!content && !attachments.length) || !request.conversationId || !request.operatorId) return
255
+ setSending(true)
256
+ setError('')
257
+ try {
258
+ const media = attachments.length
259
+ ? await Promise.all(attachments.map(async ({ file }) => {
260
+ const dataUrl = await readDataUrl(file)
261
+ return { fileName: file.name, mimeType: file.type, dataBase64: dataUrl.slice(dataUrl.indexOf(',') + 1) }
262
+ }))
263
+ : undefined
264
+ await onSend({ conversationId: request.conversationId, content, replyToMessageId: replyingTo?.id, media })
265
+ host.reset()
266
+ for (const item of attachments) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)
267
+ setAttachments([])
268
+ onClearReply()
269
+ } catch (failure) {
270
+ setError(errorText(failure, t('sandbox.composer.failed')))
271
+ } finally {
272
+ refocus.current = request
273
+ setSending(false)
274
+ }
275
+ }
276
+
277
+ // 发送期间编辑器是 contentEditable=false,focus() 无效,要等 sending 复位的提交完成后再还焦点。
278
+ // 只有请求期间没换会话、没换身份时才还,避免抢走用户已经转移的焦点。
279
+ const refocus = React.useRef<{ conversationId?: string, operatorId?: string }>(undefined)
280
+ React.useLayoutEffect(() => {
281
+ const request = refocus.current
282
+ if (sending || !request) return
283
+ refocus.current = undefined
284
+ if (current.current.conversationId !== request.conversationId || current.current.operatorId !== request.operatorId) return
285
+ const root = editor.current
286
+ if (!root) return
287
+ root.focus()
288
+ const range = document.createRange()
289
+ range.selectNodeContents(root)
290
+ range.collapse(false)
291
+ const selection = window.getSelection()
292
+ selection?.removeAllRanges()
293
+ selection?.addRange(range)
294
+ }, [sending])
295
+
296
+ const senders = orderUsersByActive(
297
+ snapshot.participants.map((participant) => ({ ...participant, avatar: resolveAvatar(participant.avatar) })),
298
+ operatorId,
299
+ )
300
+ const metrics = getUserStackMetrics(senders.length, compactStack)
301
+ const layoutMetrics = getUserStackLayoutMetrics(senders.length, compactStack)
302
+ const hasOverflow = metrics.overflowCount > 0
303
+ const expanded = stackExpanded && hasOverflow
304
+ const visualExpanded = expanded || !hasOverflow
305
+ const overflowPreview = senders[metrics.collapsedVisibleCount]
306
+ const isCollapsedExtra = (index: number) => hasOverflow && index >= metrics.collapsedVisibleCount
307
+ const isCollapsedHidden = (index: number) => !expanded && isCollapsedExtra(index)
308
+ stack.current = { hasOverflow, expanded }
309
+
310
+ const setExpanded = (next: boolean) => {
311
+ if (!stack.current.hasOverflow || stack.current.expanded === next) return
312
+ setOverflowMotion(next ? 'expanding' : 'collapsing')
313
+ clearTimeout(timers.current.motion)
314
+ timers.current.motion = setTimeout(() => setOverflowMotion('idle'), 280)
315
+ stack.current.expanded = next
316
+ setStackExpanded(next)
317
+ transitionUntil.current = performance.now() + 180
318
+ }
319
+
320
+ // Chrome 会在 keyed 按钮重排时短暂触发 focusout,切换动画完成前不能据此折叠头像堆叠。
321
+ const syncExpanded = () => {
322
+ if (pointer.current.suppress) return
323
+ setExpanded(pointer.current.hovered || pointer.current.focused || pointer.current.creating)
324
+ }
325
+
326
+ // 人数减少到不再溢出时收起,下次溢出从折叠态开始。
327
+ React.useEffect(() => {
328
+ if (!hasOverflow) setStackExpanded(false)
329
+ }, [hasOverflow])
330
+
331
+ // 只记录头像区;把发送框正文加入 FLIP 会让整个控件在切换发送者时横向跳动。
332
+ const recordLayout = () => {
333
+ if (!layout.current && stackRoot.current) {
334
+ layout.current = createLayout(stackRoot.current, {
335
+ children: ['.sandbox-composer-user-capsule', '.sandbox-composer-user-stack', '.sandbox-composer-user-switch', '.sandbox-composer-user-overflow', '.sandbox-composer-user-add'],
336
+ })
337
+ }
338
+ layout.current?.record()
339
+ return layout.current
340
+ }
341
+
342
+ // 新顺序提交到 DOM 后、绘制之前从记录的旧位置补间过去,等价于原版 nextTick 之后的 animate。
343
+ React.useLayoutEffect(() => {
344
+ const pending = pendingLayout.current
345
+ if (!pending) return
346
+ pendingLayout.current = undefined
347
+ pending.animate({ duration: 260, ease: 'out(3)' })
348
+ }, [operatorId])
349
+
350
+ React.useEffect(() => () => {
351
+ layout.current?.revert()
352
+ clearTimeout(timers.current.motion)
353
+ clearTimeout(timers.current.suppress)
354
+ }, [])
355
+
356
+ const switchOperator = async (participantId: string) => {
357
+ if (participantId === operatorId) return
358
+ pointer.current.suppress = true
359
+ clearTimeout(timers.current.suppress)
360
+ const remaining = transitionUntil.current - performance.now()
361
+ if (remaining > 0) await new Promise((resolve) => setTimeout(resolve, remaining))
362
+ pendingLayout.current = recordLayout()
363
+ try {
364
+ await store.selectOperator(participantId)
365
+ setError('')
366
+ } catch (failure) {
367
+ pendingLayout.current = undefined
368
+ setError(errorText(failure, t('sandbox.composer.switchFailed')))
369
+ } finally {
370
+ timers.current.suppress = setTimeout(() => {
371
+ pointer.current.suppress = false
372
+ pointer.current.focused = !!layoutRoot.current?.contains(document.activeElement)
373
+ syncExpanded()
374
+ }, 280)
375
+ }
376
+ }
377
+
378
+ // 极限窄屏:胶囊被 max-width 钳住后头像堆叠会把附件、发送图标挤出胶囊背景,宽度不足时折叠态只留
379
+ // 当前操作者 + "+N"。阈值恒按完整(非 compact)堆叠宽度计算,compact 与否不影响判定,无反馈循环。
380
+ const senderCount = senders.length
381
+ React.useLayoutEffect(() => {
382
+ const element = form.current
383
+ if (!element || typeof ResizeObserver === 'undefined') return
384
+ const update = () => {
385
+ const fullWidth = getUserStackLayoutMetrics(senderCount).collapsedWidth
386
+ setCompactStack(element.clientWidth < fullWidth + COMPOSER_FIXED_WIDTH + COMPOSER_MIN_INPUT_WIDTH)
387
+ // 回复与附件共用一个浮动包络,消息区底部留白按包络真实高度计算。28 = 胶囊距底 20px + 置底时
388
+ // 末条消息与输入区的可视间隙 8px;包络与胶囊之间的 8px 已计入包络高度。
389
+ const formHeight = Math.ceil(element.getBoundingClientRect().height)
390
+ const overlay = context.current ? Math.ceil(context.current.getBoundingClientRect().height) + 8 : 0
391
+ onSpaceChange?.(formHeight + overlay + 28)
392
+ }
393
+ const observer = new ResizeObserver(update)
394
+ observer.observe(element)
395
+ if (context.current) observer.observe(context.current)
396
+ update()
397
+ return () => observer.disconnect()
398
+ }, [senderCount, !!replyingTo, attachments.length, onSpaceChange])
399
+
400
+ const extraWidth = Math.max(0, layoutMetrics.collapsedWidth - USER_AVATAR_SIZE)
401
+ const visualExtension = visualExpanded ? Math.max(0, layoutMetrics.expandedWidth - layoutMetrics.collapsedWidth) : 0
402
+ const coveredByExpanded = expanded || overflowMotion === 'expanding'
403
+ const vars = (values: Record<string, string | number>) => values as React.CSSProperties
404
+
405
+ const mentionOpen = host.mentionMenuOpen.value
406
+ const mentionList = host.mentionCandidates.value
407
+ const mentionIndex = host.mentionMenuIndex.value
408
+
409
+ return (
410
+ <div ref={layoutRoot} className="sandbox-composer-layout-root">
411
+ <form
412
+ ref={form}
413
+ className="sandbox-composer"
414
+ style={vars({ width: `${460 + extraWidth}px`, '--sandbox-composer-visual-extension': `${visualExtension}px` })}
415
+ onSubmit={(event) => {
416
+ event.preventDefault()
417
+ void submit()
418
+ }}
419
+ >
420
+ {error && <span role="alert" className="sandbox-composer-error">{error}</span>}
421
+ {(replyingTo || attachments.length > 0) && (
422
+ <div ref={context} className="sandbox-composer-context">
423
+ {replyingTo && (
424
+ <div className="sandbox-composer-reply">
425
+ <span>{t('sandbox.composer.replyTo', { name: replyingTo.authorName, content: replyingTo.content })}</span>
426
+ <button type="button" aria-label={t('sandbox.composer.clearReply')} onClick={onClearReply}><XIcon className="size-[15px]" aria-hidden /></button>
427
+ </div>
428
+ )}
429
+ {attachments.map((item) => item.previewUrl ? (
430
+ <span key={item.id} className="sandbox-composer-attachment-image">
431
+ <button type="button" className="sandbox-composer-attachment-preview" aria-label={t('sandbox.composer.preview', { name: item.file.name })} onClick={() => onOpenImage?.(item.previewUrl!)}>
432
+ <img src={item.previewUrl} alt={item.file.name} />
433
+ </button>
434
+ <button type="button" className="sandbox-composer-attachment-remove" aria-label={t('sandbox.composer.remove', { name: item.file.name })} onClick={() => removeAttachment(item.id)}>
435
+ <XIcon className="size-3" aria-hidden />
436
+ </button>
437
+ </span>
438
+ ) : (
439
+ <span key={item.id} className="sandbox-composer-attachment-file">
440
+ <FileIcon className="size-3.5" strokeWidth={2} aria-hidden />
441
+ <span className="sandbox-composer-attachment-name">
442
+ <span className="sandbox-composer-attachment-base">{item.baseName}</span><span>{item.extension}</span>
443
+ </span>
444
+ <button type="button" aria-label={t('sandbox.composer.remove', { name: item.file.name })} onClick={() => removeAttachment(item.id)}>
445
+ <XIcon className="size-3.5" aria-hidden />
446
+ </button>
447
+ </span>
448
+ ))}
449
+ </div>
450
+ )}
451
+ <div ref={stackRoot} className="sandbox-composer-user-layout-root" style={vars({ '--sandbox-user-layout-width': `${layoutMetrics.collapsedWidth}px` })}>
452
+ <div
453
+ className={cn('sandbox-composer-user-capsule', visualExpanded && 'is-expanded')}
454
+ style={vars({
455
+ '--sandbox-user-capsule-collapsed-width': `${layoutMetrics.collapsedWidth}px`,
456
+ '--sandbox-user-capsule-expanded-width': `${layoutMetrics.expandedWidth}px`,
457
+ })}
458
+ onPointerEnter={() => {
459
+ pointer.current.hovered = true
460
+ syncExpanded()
461
+ }}
462
+ onPointerLeave={() => {
463
+ pointer.current.hovered = false
464
+ syncExpanded()
465
+ }}
466
+ onFocus={() => {
467
+ pointer.current.focused = true
468
+ syncExpanded()
469
+ }}
470
+ onBlur={(event) => {
471
+ pointer.current.focused = event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)
472
+ syncExpanded()
473
+ }}
474
+ >
475
+ <div
476
+ className={cn(
477
+ 'sandbox-composer-user-stack',
478
+ visualExpanded && 'is-expanded',
479
+ overflowMotion === 'expanding' && 'is-overflow-expanding',
480
+ overflowMotion === 'collapsing' && 'is-overflow-collapsing',
481
+ )}
482
+ style={vars({
483
+ '--sandbox-user-stack-collapsed-width': `${layoutMetrics.collapsedWidth}px`,
484
+ '--sandbox-user-stack-expanded-width': `${layoutMetrics.expandedWidth}px`,
485
+ })}
486
+ >
487
+ {senders.map((sender, index) => {
488
+ const active = sender.id === operatorId
489
+ const label = sender.kind === 'bot' ? `${sender.name}(${t('sandbox.kind.bot')})` : sender.name
490
+ return (
491
+ <Tooltip key={sender.id}>
492
+ {/* Tooltip 挂在外层定位节点,ContextMenu 直接绑定内部按钮,两者的锚点互不干扰。 */}
493
+ <TooltipTrigger render={(
494
+ <span
495
+ className={cn('sandbox-composer-user-switch', index > 0 && 'is-overlapped', isCollapsedExtra(index) && 'is-collapsed-extra')}
496
+ aria-hidden={isCollapsedHidden(index) || undefined}
497
+ style={vars({
498
+ '--sandbox-user-collapsed-right': `${(isCollapsedExtra(index) ? metrics.collapsedVisibleCount : index) * USER_STACK_COLLAPSED_STEP}px`,
499
+ '--sandbox-user-expanded-right': `${index * USER_STACK_EXPANDED_STEP}px`,
500
+ zIndex: senders.length - index,
501
+ })}
502
+ />
503
+ )}>
504
+ <ContextMenu>
505
+ <ContextMenuTrigger render={(
506
+ <button
507
+ type="button"
508
+ className="sandbox-composer-user-button"
509
+ aria-pressed={active}
510
+ aria-label={t(active ? 'sandbox.composer.currentSender' : 'sandbox.composer.switchSender', { name: label })}
511
+ tabIndex={isCollapsedHidden(index) ? -1 : undefined}
512
+ onClick={() => void switchOperator(sender.id)}
513
+ />
514
+ )}>
515
+ <SandboxAvatar kind={sender.kind} name={sender.name} src={sender.avatar} badge={false} className="sandbox-composer-user-avatar" />
516
+ </ContextMenuTrigger>
517
+ <ContextMenuContent className="sandbox-glass">
518
+ <ContextMenuItem onClick={() => dialogs.openEntity('edit', { type: sender.kind, id: sender.id })}>
519
+ <PencilIcon />{t('sandbox.menu.editEntity', { kind: t(`sandbox.kind.${sender.kind}`) })}<ExtensionMark />
520
+ </ContextMenuItem>
521
+ <ContextMenuItem variant="destructive" onClick={() => dialogs.openEntity('delete', { type: sender.kind, id: sender.id })}>
522
+ <Trash2Icon />{t('sandbox.menu.deleteEntity', { kind: t(`sandbox.kind.${sender.kind}`) })}<ExtensionMark />
523
+ </ContextMenuItem>
524
+ </ContextMenuContent>
525
+ </ContextMenu>
526
+ </TooltipTrigger>
527
+ <TooltipContent side="top">{sender.name}</TooltipContent>
528
+ </Tooltip>
529
+ )
530
+ })}
531
+ {hasOverflow && (
532
+ <span
533
+ className="sandbox-composer-user-overflow"
534
+ aria-hidden
535
+ style={vars({
536
+ '--sandbox-user-overflow-right': `${metrics.collapsedVisibleCount * USER_STACK_COLLAPSED_STEP}px`,
537
+ '--sandbox-user-overflow-expanded-right': `${metrics.collapsedVisibleCount * USER_STACK_EXPANDED_STEP}px`,
538
+ '--sandbox-user-overflow-z-index': `${senders.length - metrics.collapsedVisibleCount - (coveredByExpanded ? 1 : 0)}`,
539
+ })}
540
+ >
541
+ {overflowPreview && (
542
+ <SandboxAvatar kind={overflowPreview.kind} name={overflowPreview.name} src={overflowPreview.avatar} badge={false} className="sandbox-composer-user-overflow-avatar" />
543
+ )}
544
+ <span className="sandbox-composer-user-overflow-label">
545
+ <span className="sandbox-composer-user-overflow-plus">+</span>
546
+ <span className="sandbox-composer-user-overflow-count">{metrics.overflowCount}</span>
547
+ </span>
548
+ </span>
549
+ )}
550
+ <CreateEntityPopover
551
+ type="participant"
552
+ side="top"
553
+ onOpenChange={(open) => {
554
+ pointer.current.creating = open
555
+ syncExpanded()
556
+ }}
557
+ trigger={(
558
+ <button
559
+ type="button"
560
+ className={cn('sandbox-composer-user-add', hasOverflow && !visualExpanded && 'is-collapsed-hidden')}
561
+ style={vars({
562
+ '--sandbox-user-add-collapsed-right': `${layoutMetrics.addCollapsedRight}px`,
563
+ '--sandbox-user-add-expanded-right': `${layoutMetrics.addExpandedRight}px`,
564
+ })}
565
+ aria-label={t('sandbox.composer.addAccount')}
566
+ >
567
+ <PlusIcon className="size-[18px]" strokeWidth={2} aria-hidden />
568
+ </button>
569
+ )}
570
+ />
571
+ </div>
572
+ </div>
573
+ </div>
574
+ <div className="sandbox-composer-main">
575
+ {host.isEmpty.value && <span aria-hidden className="sandbox-composer-placeholder">{t('sandbox.composer.placeholder')}</span>}
576
+ <div
577
+ ref={editor}
578
+ role="textbox"
579
+ aria-multiline="true"
580
+ aria-label={t('sandbox.composer.input')}
581
+ aria-disabled={disabled || undefined}
582
+ contentEditable={!disabled}
583
+ suppressContentEditableWarning
584
+ className="sandbox-composer-editor"
585
+ onKeyDown={(event) => {
586
+ const action = host.routeKey({ key: event.key, shiftKey: event.shiftKey, disabled })
587
+ if (action.kind !== 'none') event.preventDefault()
588
+ if (action.kind === 'submit') void submit()
589
+ }}
590
+ onInput={() => void host.handleInput()}
591
+ onCompositionStart={() => host.startComposition()}
592
+ onCompositionEnd={() => void host.endComposition()}
593
+ onPaste={(event) => {
594
+ const files = Array.from(event.clipboardData?.files ?? [])
595
+ if (files.length) {
596
+ event.preventDefault()
597
+ addFiles(files)
598
+ return
599
+ }
600
+ // 只接受纯文本粘贴,避免把外部富文本结构带进草稿宿主。
601
+ event.preventDefault()
602
+ document.execCommand('insertText', false, event.clipboardData.getData('text/plain'))
603
+ }}
604
+ onMouseUp={() => host.syncCaretFromHost()}
605
+ onKeyUp={() => host.syncCaretFromHost()}
606
+ />
607
+ {mentionOpen && (
608
+ <div className="sandbox-glass absolute right-0 bottom-[calc(100%+8px)] left-0 z-30 flex max-h-[220px] flex-col gap-0.5 overflow-y-auto rounded-[14px] bg-popover p-1.5 text-popover-foreground shadow-popup ring-1 ring-border" role="listbox" aria-label={t('sandbox.composer.mention')}>
609
+ {mentionList.map((candidate, index) => (
610
+ <button
611
+ key={candidate.id}
612
+ type="button"
613
+ role="option"
614
+ aria-selected={index === mentionIndex}
615
+ className={cn('flex min-w-0 items-center gap-2 rounded-[10px] px-2 py-1.5 text-left hover:bg-accent', index === mentionIndex && 'bg-accent')}
616
+ onMouseDown={(event) => {
617
+ event.preventDefault()
618
+ host.selectMentionCandidate(candidate)
619
+ }}
620
+ onMouseEnter={() => host.setMentionSelection(index)}
621
+ >
622
+ <SandboxAvatar kind={candidate.kind} name={candidate.name} src={candidate.avatar} className="size-7" />
623
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
624
+ <strong className="truncate text-[13px] leading-4 font-semibold">{candidate.name}</strong>
625
+ <small className="truncate text-[11px] leading-[14px] text-muted-foreground">{candidate.id}</small>
626
+ </span>
627
+ </button>
628
+ ))}
629
+ {!mentionList.length && <p className="px-2 py-2.5 text-center text-xs text-muted-foreground">{t('sandbox.composer.noMention')}</p>}
630
+ </div>
631
+ )}
632
+ </div>
633
+ <input ref={fileInput} type="file" multiple accept={ACCEPT} className="sr-only" onChange={(event) => {
634
+ if (event.target.files) addFiles(Array.from(event.target.files))
635
+ event.target.value = ''
636
+ }} />
637
+ <button type="button" className="sandbox-composer-action" aria-label={t('sandbox.composer.attach')} disabled={disabled} onClick={() => fileInput.current?.click()}>
638
+ <PaperclipIcon className="size-[19px]" strokeWidth={2} aria-hidden />
639
+ </button>
640
+ <button type="submit" className="sandbox-composer-action is-primary" aria-label={t('sandbox.composer.send')} disabled={disabled || (host.isEmpty.value && !attachments.length)}>
641
+ <SendIcon className="size-[19px]" strokeWidth={2} aria-hidden />
642
+ </button>
643
+ </form>
644
+ </div>
645
+ )
646
+ })