chatluna-plugin-onebot-sandbox 1.1.5 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/client/chat/chat-pane.tsx +19 -7
  2. package/client/chat/composer.tsx +4 -4
  3. package/client/chat/forward.tsx +11 -12
  4. package/client/chat/media-attachments.tsx +236 -0
  5. package/client/chat/message-list.tsx +54 -37
  6. package/client/chat/messages.css +207 -20
  7. package/client/environment/avatar-picker.tsx +4 -0
  8. package/client/locales/en.yml +10 -3
  9. package/client/locales/zh.yml +10 -3
  10. package/client/mcp/credential-manager.tsx +5 -9
  11. package/client/test-space/spaces.css +2 -0
  12. package/client/webqq/composer-draft.ts +0 -1
  13. package/client/webqq/forward-dialog-stack.ts +11 -3
  14. package/client/webqq/media-attachment.ts +72 -0
  15. package/client/webqq/message-cluster.ts +9 -29
  16. package/client/workspace/context.tsx +1 -1
  17. package/client/workspace/overlay-host.tsx +26 -17
  18. package/client/workspace/store.ts +75 -39
  19. package/dist/.vite/manifest.json +1 -1
  20. package/dist/app-BZMBUgjR.js +85 -0
  21. package/dist/client.css +2 -2
  22. package/dist/client.js +1 -1
  23. package/lib/base64.d.ts +3 -0
  24. package/lib/base64.d.ts.map +1 -0
  25. package/lib/bot.d.ts.map +1 -1
  26. package/lib/builtin-avatar-png.d.ts +0 -1
  27. package/lib/builtin-avatar-png.d.ts.map +1 -1
  28. package/lib/builtin-avatars.d.ts +0 -1
  29. package/lib/builtin-avatars.d.ts.map +1 -1
  30. package/lib/chatluna/state.d.ts.map +1 -1
  31. package/lib/chatluna/thinking.d.ts.map +1 -1
  32. package/lib/console-contract.d.ts +5 -5
  33. package/lib/console-contract.d.ts.map +1 -1
  34. package/lib/console.d.ts +1 -3
  35. package/lib/console.d.ts.map +1 -1
  36. package/lib/control-service.d.ts +4 -3
  37. package/lib/control-service.d.ts.map +1 -1
  38. package/lib/conversation-resolution.d.ts +0 -2
  39. package/lib/conversation-resolution.d.ts.map +1 -1
  40. package/lib/inbound-delivery.d.ts.map +1 -1
  41. package/lib/index.d.ts +1 -0
  42. package/lib/index.d.ts.map +1 -1
  43. package/lib/index.js +529 -549
  44. package/lib/index.js.map +1 -1
  45. package/lib/mcp/call-records.d.ts.map +1 -1
  46. package/lib/mcp/http-api.d.ts +3 -4
  47. package/lib/mcp/http-api.d.ts.map +1 -1
  48. package/lib/mcp/server.d.ts.map +1 -1
  49. package/lib/mcp/service.d.ts +8 -7
  50. package/lib/mcp/service.d.ts.map +1 -1
  51. package/lib/mcp/types.d.ts +1 -4
  52. package/lib/mcp/types.d.ts.map +1 -1
  53. package/lib/media-download.d.ts +3 -0
  54. package/lib/media-download.d.ts.map +1 -0
  55. package/lib/media-limits.d.ts +6 -0
  56. package/lib/media-limits.d.ts.map +1 -0
  57. package/lib/media-preview.d.ts +4 -0
  58. package/lib/media-preview.d.ts.map +1 -0
  59. package/lib/media-storage.d.ts +2 -3
  60. package/lib/media-storage.d.ts.map +1 -1
  61. package/lib/onebot-debug.d.ts.map +1 -1
  62. package/lib/record-store.d.ts +0 -2
  63. package/lib/record-store.d.ts.map +1 -1
  64. package/lib/test-spaces.d.ts +1 -0
  65. package/lib/test-spaces.d.ts.map +1 -1
  66. package/lib/types.d.ts +16 -3
  67. package/lib/types.d.ts.map +1 -1
  68. package/lib/user-authority.d.ts +1 -1
  69. package/lib/user-authority.d.ts.map +1 -1
  70. package/package.json +5 -2
  71. package/dist/app-CpJLSY0S.js +0 -85
@@ -49,6 +49,7 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
49
49
  const [selection, setSelection] = React.useState<MessageSelectionState>(exitMessageSelection())
50
50
  const [forwardTargetOpen, setForwardTargetOpen] = React.useState(false)
51
51
  const [forwardStack, setForwardStack] = React.useState<ForwardDialogFrame[]>([])
52
+ const forwardRequest = React.useRef(0)
52
53
  const [imageUrl, setImageUrl] = React.useState('')
53
54
  // 悬浮发送框回报的占位高度,初值按单行胶囊估算(44 + 28),首帧不至于让末条消息被遮住。
54
55
  const [composerSpace, setComposerSpace] = React.useState(72)
@@ -62,7 +63,7 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
62
63
  return reply ? [[reply.id, reply] as const] : []
63
64
  })) as Record<string, SandboxMessage>
64
65
  }, [messages, snapshot.messages])
65
- const forwardPreviews = React.useMemo(() => buildForwardPreviewMap(messages, snapshot.forwards ?? []), [messages, snapshot.forwards])
66
+ const forwardPreviews = React.useMemo(() => buildForwardPreviewMap(messages, snapshot.forwards), [messages, snapshot.forwards])
66
67
  const capabilities = React.useMemo(() => buildMessageCapabilityMap({ messages, conversation, operatorId, group }), [messages, conversation, operatorId, group])
67
68
  const friendMenuStates = React.useMemo<Record<string, FriendMenuState>>(() => {
68
69
  if (!operatorId) return {}
@@ -103,7 +104,7 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
103
104
  }), [snapshot, workspace.conversations, operatorId, resolveAvatar, t])
104
105
  const chatLunaStates = workspace.workspace.chatLunaStates.filter(({ conversationId }) => conversationId === conversation?.id)
105
106
 
106
- // 换会话时清掉与上一个会话绑定的临时状态。
107
+ // 换会话或操作者时清掉旧视角的临时状态;卸载也使在途转发请求失效。
107
108
  React.useEffect(() => {
108
109
  setReplyTo('')
109
110
  setReactionTarget('')
@@ -111,7 +112,8 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
111
112
  setForwardTargetOpen(false)
112
113
  setForwardStack(closeForwardStack())
113
114
  setSearchOpen(false)
114
- }, [conversation?.id])
115
+ return () => { forwardRequest.current++ }
116
+ }, [conversation?.id, operatorId])
115
117
 
116
118
  // Esc 的优先级:先关转发目标,再退出多选,最后关闭查找。
117
119
  React.useEffect(() => {
@@ -134,8 +136,15 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
134
136
  const conversationId = conversation?.id
135
137
 
136
138
  const openForward = async (input: { forwardId?: string, messageId?: string }, mode: 'replace' | 'push') => {
137
- const frame = await loadForwardDialogFrame({ input, load: (request) => store.getForwardMessage(request) })
138
- if (frame) setForwardStack((stack) => pushForwardFrame(stack, frame, mode))
139
+ const requestId = ++forwardRequest.current
140
+ const isCurrent = () => requestId === forwardRequest.current
141
+ && store.getView().currentOperatorId === operatorId
142
+ && store.getView().activeConversationId === conversationId
143
+ const frame = await loadForwardDialogFrame({
144
+ input,
145
+ load: (request) => isCurrent() ? store.getForwardMessage(request) : Promise.resolve(undefined),
146
+ })
147
+ if (frame && isCurrent()) setForwardStack((stack) => pushForwardFrame(stack, frame, mode))
139
148
  }
140
149
 
141
150
  const title = conversation?.title ?? group?.name ?? peer?.name ?? conversation?.id ?? t('sandbox.chat.pick')
@@ -287,7 +296,10 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
287
296
  <ForwardViewer
288
297
  stack={forwardStack}
289
298
  imageOpen={!!imageUrl}
290
- onCloseFrom={(depth) => setForwardStack((stack) => depth ? stack.slice(0, depth) : closeForwardStack())}
299
+ onCloseFrom={(depth) => {
300
+ forwardRequest.current++
301
+ setForwardStack((stack) => depth ? stack.slice(0, depth) : closeForwardStack())
302
+ }}
291
303
  onOpenForward={(forwardId) => void openForward({ forwardId }, 'push')}
292
304
  onOpenImage={setImageUrl}
293
305
  />
@@ -299,5 +311,5 @@ export function ChatPane({ detailsVisible, onToggleDetails, onBack, mentionBridg
299
311
  function visibleConversation(store: ReturnType<typeof useSandbox>['store'], conversationId: string | undefined) {
300
312
  const snapshot = store.snapshot
301
313
  if (!snapshot || !conversationId) return undefined
302
- return [...snapshot.conversations, ...(snapshot.conversationInstances ?? [])].find(({ id }) => id === conversationId)
314
+ return [...snapshot.conversations, ...snapshot.conversationInstances].find(({ id }) => id === conversationId)
303
315
  }
@@ -12,6 +12,7 @@ import {
12
12
  TooltipTrigger,
13
13
  } from '@chatluna/ui-kit'
14
14
  import type { SendMediaFileInput } from '../../src/types'
15
+ import { MEBIBYTE } from '../../src/media-limits'
15
16
  import { useT } from '../i18n'
16
17
  import { SandboxAvatar } from '../shared/avatar'
17
18
  import { CreateEntityPopover } from '../environment/create-popover'
@@ -57,7 +58,6 @@ interface Attachment {
57
58
  extension: string
58
59
  }
59
60
 
60
- const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024
61
61
  // 胶囊内 padding(8) + 三个 gap(12) + 附件按钮(32) + 发送按钮(36)。
62
62
  const COMPOSER_FIXED_WIDTH = 88
63
63
  // 输入区可压缩到 0(min-width: 0),低于这个宽度就该省略头像而不是压扁输入框。
@@ -95,7 +95,7 @@ export const Composer = React.forwardRef<ComposerHandle, {
95
95
  }>(function Composer({ replyingTo, mentionCandidates, onClearReply, onSend, onOpenImage, onSpaceChange }, ref) {
96
96
  const t = useT()
97
97
  const { store, dialogs } = useSandbox()
98
- const { conversation, operatorId, snapshot, resolveAvatar } = useWorkspace()
98
+ const { conversation, operatorId, snapshot, resolveAvatar, workspace } = useWorkspace()
99
99
  const editor = React.useRef<HTMLDivElement>(null)
100
100
  const fileInput = React.useRef<HTMLInputElement>(null)
101
101
  const [, rerender] = React.useReducer((value: number) => value + 1, 0)
@@ -225,7 +225,7 @@ export const Composer = React.forwardRef<ComposerHandle, {
225
225
  const next: Attachment[] = []
226
226
  let oversize = false
227
227
  for (const file of files) {
228
- if (file.size > MAX_ATTACHMENT_SIZE) {
228
+ if (file.size > workspace.mediaMaxSize) {
229
229
  oversize = true
230
230
  continue
231
231
  }
@@ -236,7 +236,7 @@ export const Composer = React.forwardRef<ComposerHandle, {
236
236
  ...splitFileName(file.name),
237
237
  })
238
238
  }
239
- if (oversize) setError(t('sandbox.composer.oversize'))
239
+ if (oversize) setError(t('sandbox.composer.oversize', { size: workspace.mediaMaxSize / MEBIBYTE }))
240
240
  if (next.length) setAttachments((list) => [...list, ...next])
241
241
  }
242
242
 
@@ -1,5 +1,5 @@
1
1
  import * as React from 'react'
2
- import { ChevronRightIcon, PaperclipIcon, SearchIcon } from 'lucide-react'
2
+ import { ChevronRightIcon, SearchIcon } from 'lucide-react'
3
3
  import {
4
4
  Button,
5
5
  cn,
@@ -21,9 +21,10 @@ import { useRetained } from '../shared/use-retained'
21
21
  import type { ForwardDialogFrame } from '../webqq/forward-dialog-stack'
22
22
  import { getForwardNodeClusterClass, isMergedForwardNode } from '../webqq/forward-cluster'
23
23
  import { buildForwardPreview } from '../webqq/forward-preview'
24
- import { formatMediaSize, getMediaLabel } from '../webqq/message-presentation'
24
+ import { getMediaLabel } from '../webqq/message-presentation'
25
25
  import { useWorkspace } from '../workspace/context'
26
26
  import { errorText } from '../workspace/store'
27
+ import { FileMessage, VoiceMessage } from './media-attachments'
27
28
  import './messages.css'
28
29
 
29
30
  export interface ForwardTargetOption {
@@ -217,23 +218,21 @@ function ForwardFrameDialog({ stack, depth, imageOpen, onCloseFrom, onOpenForwar
217
218
  )}
218
219
  {item.media?.map((entry) => {
219
220
  const source = media[entry.id]
221
+ const failed = !source && !!mediaFailures[entry.id]
220
222
  return (
221
223
  <div key={entry.id} className="sandbox-message-media">
222
- {!source ? (
223
- <span className="sandbox-message-media-loading">{mediaFailures[entry.id] ? t('sandbox.media.unavailable') : t('sandbox.media.loading')}</span>
224
+ {entry.type === 'audio' ? (
225
+ <VoiceMessage media={entry} source={source} failed={failed} />
226
+ ) : entry.type === 'file' ? (
227
+ <FileMessage media={entry} source={source} failed={failed} />
228
+ ) : !source ? (
229
+ <span className="sandbox-message-media-loading">{failed ? t('sandbox.media.unavailable') : t('sandbox.media.loading')}</span>
224
230
  ) : entry.type === 'image' ? (
225
231
  <button type="button" className="sandbox-message-image" aria-label={t('sandbox.media.viewImage')} onClick={() => onOpenImage(source)}>
226
232
  <img src={source} alt={entry.name} />
227
233
  </button>
228
- ) : entry.type === 'audio' ? (
229
- <audio src={source} controls preload="metadata" />
230
- ) : entry.type === 'video' ? (
231
- <video src={source} controls preload="metadata" />
232
234
  ) : (
233
- <a href={source} download={entry.name} className="sandbox-message-file">
234
- <PaperclipIcon className="size-[18px]" />
235
- <span><strong>{entry.name}</strong><small>{formatMediaSize(entry.size)}</small></span>
236
- </a>
235
+ <video src={source} controls preload="metadata" />
237
236
  )}
238
237
  </div>
239
238
  )
@@ -0,0 +1,236 @@
1
+ import * as React from 'react'
2
+ import {
3
+ DownloadIcon,
4
+ FileArchiveIcon,
5
+ FileCodeIcon,
6
+ FileIcon,
7
+ FileImageIcon,
8
+ FileMusicIcon,
9
+ FileSpreadsheetIcon,
10
+ FileTextIcon,
11
+ FileVideoCameraIcon,
12
+ PauseIcon,
13
+ PlayIcon,
14
+ type LucideIcon,
15
+ } from 'lucide-react'
16
+ import { cn } from '@chatluna/ui-kit'
17
+ import type { SandboxMedia } from '../../src/types'
18
+ import { useT } from '../i18n'
19
+ import { formatMediaSize } from '../webqq/message-presentation'
20
+ import {
21
+ computeWaveformPeaks,
22
+ fallbackWaveformPeaks,
23
+ formatPlaybackTime,
24
+ getFileExtension,
25
+ getFileKind,
26
+ type FileKind,
27
+ } from '../webqq/media-attachment'
28
+
29
+ interface Waveform {
30
+ peaks: number[]
31
+ duration: number
32
+ }
33
+
34
+ /** 超过这个体积不在浏览器里解码波形,改用按 ID 生成的形状,免得长音频占住主线程。 */
35
+ const WAVEFORM_DECODE_LIMIT = 16 * 1024 * 1024
36
+ /** 解码结果按媒体 ID 缓存:媒体 ID 是内容哈希,切换会话再回来不重新解码。 */
37
+ const waveforms = new Map<string, Promise<Waveform | undefined>>()
38
+
39
+ function loadWaveform(media: SandboxMedia, source: string) {
40
+ let task = waveforms.get(media.id)
41
+ if (!task) {
42
+ task = media.size > WAVEFORM_DECODE_LIMIT ? Promise.resolve(undefined) : decodeWaveform(source).catch(() => undefined)
43
+ waveforms.set(media.id, task)
44
+ }
45
+ return task
46
+ }
47
+
48
+ async function decodeWaveform(source: string): Promise<Waveform> {
49
+ const data = await (await fetch(source)).arrayBuffer()
50
+ // 只需要包络:解码到 8 kHz 单声道,Firefox 支持的最低采样率,内存占用最小。
51
+ const buffer = await new OfflineAudioContext(1, 1, 8000).decodeAudioData(data)
52
+ return { peaks: computeWaveformPeaks(buffer.getChannelData(0)), duration: buffer.duration }
53
+ }
54
+
55
+ /** 同一时刻只播一条语音,开始播放时停掉上一条。 */
56
+ let activeAudio: HTMLAudioElement | undefined
57
+
58
+ export function VoiceMessage(props: { media: SandboxMedia; source?: string; failed?: boolean; disabled?: boolean }) {
59
+ const t = useT()
60
+ const { media, source } = props
61
+ const audio = React.useRef<HTMLAudioElement>(null)
62
+ const [peaks, setPeaks] = React.useState(() => fallbackWaveformPeaks(media.id))
63
+ const [duration, setDuration] = React.useState(Number.NaN)
64
+ const [current, setCurrent] = React.useState(0)
65
+ const [playing, setPlaying] = React.useState(false)
66
+
67
+ React.useEffect(() => {
68
+ if (!source) return
69
+ let alive = true
70
+ void loadWaveform(media, source).then((waveform) => {
71
+ if (!alive || !waveform) return
72
+ setPeaks(waveform.peaks)
73
+ setDuration((value) => Number.isFinite(value) ? value : waveform.duration)
74
+ })
75
+ return () => {
76
+ alive = false
77
+ }
78
+ }, [media, source])
79
+
80
+ // timeupdate 每秒只派发几次,播放中按帧读进度,波形填色才连贯。
81
+ React.useEffect(() => {
82
+ if (!playing) return
83
+ let frame = requestAnimationFrame(function tick() {
84
+ if (audio.current) setCurrent(audio.current.currentTime)
85
+ frame = requestAnimationFrame(tick)
86
+ })
87
+ return () => cancelAnimationFrame(frame)
88
+ }, [playing])
89
+
90
+ React.useEffect(() => {
91
+ const element = audio.current
92
+ return () => {
93
+ element?.pause()
94
+ if (activeAudio === element) activeAudio = undefined
95
+ }
96
+ }, [source])
97
+
98
+ const ready = !!source && !props.disabled
99
+ const progress = Number.isFinite(duration) && duration > 0 ? Math.min(1, current / duration) : 0
100
+
101
+ const toggle = () => {
102
+ const element = audio.current
103
+ if (!element || !source) return
104
+ if (!element.paused) {
105
+ element.pause()
106
+ return
107
+ }
108
+ if (activeAudio && activeAudio !== element) activeAudio.pause()
109
+ activeAudio = element
110
+ void element.play().catch(() => setPlaying(false))
111
+ }
112
+
113
+ const seek = (seconds: number) => {
114
+ const element = audio.current
115
+ if (!element || !Number.isFinite(duration)) return
116
+ const value = Math.max(0, Math.min(duration, seconds))
117
+ element.currentTime = value
118
+ setCurrent(value)
119
+ }
120
+
121
+ const seekToPointer = (event: React.PointerEvent<HTMLDivElement>) => {
122
+ const rect = event.currentTarget.getBoundingClientRect()
123
+ seek((event.clientX - rect.left) / rect.width * duration)
124
+ }
125
+
126
+ const status = props.failed ? t('sandbox.media.unavailable') : !source ? t('sandbox.media.loading') : undefined
127
+ const bars = peaks.map((peak, index) => <span key={index} style={{ height: `${Math.round(peak * 100)}%` }} />)
128
+
129
+ return (
130
+ <div className={cn('sandbox-message-voice', playing && 'is-playing')}>
131
+ {source && (
132
+ <audio
133
+ ref={audio}
134
+ src={source}
135
+ preload="metadata"
136
+ onLoadedMetadata={(event) => {
137
+ const value = event.currentTarget.duration
138
+ if (Number.isFinite(value)) setDuration(value)
139
+ }}
140
+ onPlay={() => setPlaying(true)}
141
+ onPause={(event) => {
142
+ setPlaying(false)
143
+ setCurrent(event.currentTarget.currentTime)
144
+ }}
145
+ onEnded={(event) => {
146
+ event.currentTarget.currentTime = 0
147
+ setCurrent(0)
148
+ }}
149
+ />
150
+ )}
151
+ <button
152
+ type="button"
153
+ className="sandbox-message-voice-toggle"
154
+ disabled={!ready}
155
+ aria-label={playing ? t('sandbox.media.pauseVoice') : t('sandbox.media.playVoice')}
156
+ onClick={(event) => {
157
+ event.stopPropagation()
158
+ toggle()
159
+ }}
160
+ >
161
+ {playing ? <PauseIcon className="size-3.5" fill="currentColor" /> : <PlayIcon className="size-3.5 translate-x-px" fill="currentColor" />}
162
+ </button>
163
+ <div
164
+ className="sandbox-message-voice-wave"
165
+ role="slider"
166
+ tabIndex={ready ? 0 : -1}
167
+ aria-label={t('sandbox.media.voiceProgress')}
168
+ aria-disabled={!ready}
169
+ aria-valuemin={0}
170
+ aria-valuemax={Number.isFinite(duration) ? Math.round(duration) : 0}
171
+ aria-valuenow={Math.round(current)}
172
+ aria-valuetext={`${formatPlaybackTime(current)} / ${formatPlaybackTime(duration)}`}
173
+ onPointerDown={(event) => {
174
+ if (!ready || event.button !== 0) return
175
+ event.currentTarget.setPointerCapture(event.pointerId)
176
+ seekToPointer(event)
177
+ }}
178
+ onPointerMove={(event) => {
179
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) seekToPointer(event)
180
+ }}
181
+ onKeyDown={(event) => {
182
+ if (!ready) return
183
+ const step = { ArrowLeft: -5, ArrowDown: -5, ArrowRight: 5, ArrowUp: 5 }[event.key]
184
+ if (step !== undefined) seek(current + step)
185
+ else if (event.key === 'Home') seek(0)
186
+ else if (event.key === 'End') seek(duration)
187
+ else return
188
+ event.preventDefault()
189
+ }}
190
+ >
191
+ <span className="sandbox-message-voice-bars" aria-hidden>{bars}</span>
192
+ {/* 已播放的部分是同一组竖条的填色副本,按进度裁剪,播放中逐帧推进而不是逐根跳变。 */}
193
+ <span className="sandbox-message-voice-bars is-played" aria-hidden style={{ clipPath: `inset(0 ${(1 - progress) * 100}% 0 0)` }}>{bars}</span>
194
+ </div>
195
+ <span className="sandbox-message-voice-time">
196
+ {status ?? formatPlaybackTime(playing || current > 0 ? current : duration)}
197
+ </span>
198
+ </div>
199
+ )
200
+ }
201
+
202
+ const FILE_ICONS: Record<FileKind, LucideIcon> = {
203
+ archive: FileArchiveIcon,
204
+ audio: FileMusicIcon,
205
+ code: FileCodeIcon,
206
+ document: FileTextIcon,
207
+ image: FileImageIcon,
208
+ sheet: FileSpreadsheetIcon,
209
+ video: FileVideoCameraIcon,
210
+ other: FileIcon,
211
+ }
212
+
213
+ export function FileMessage(props: { media: SandboxMedia; source?: string; failed?: boolean }) {
214
+ const t = useT()
215
+ const { media, source } = props
216
+ const kind = getFileKind(media.name, media.mimeType)
217
+ const Icon = FILE_ICONS[kind]
218
+ const extension = getFileExtension(media.name).toUpperCase()
219
+ const meta = props.failed ? t('sandbox.media.unavailable') : !source ? t('sandbox.media.loading') : [formatMediaSize(media.size), extension].filter(Boolean).join(' · ')
220
+ const content = (
221
+ <>
222
+ <span className="sandbox-message-file-icon" data-kind={kind}><Icon className="size-5" /></span>
223
+ <span className="sandbox-message-file-info">
224
+ <strong title={media.name}>{media.name}</strong>
225
+ <small>{meta}</small>
226
+ </span>
227
+ {source && <span className="sandbox-message-file-download" aria-hidden><DownloadIcon className="size-4" /></span>}
228
+ </>
229
+ )
230
+ // 媒体未就绪时先占好卡片位置,读到内容后原位变成下载链接,不出现「加载中」一行再撑开。
231
+ return source ? (
232
+ <a href={source} download={media.name} className="sandbox-message-file" aria-label={t('sandbox.media.downloadFile', { name: media.name })}>{content}</a>
233
+ ) : (
234
+ <div className="sandbox-message-file is-pending">{content}</div>
235
+ )
236
+ }
@@ -13,7 +13,6 @@ import {
13
13
  HandIcon,
14
14
  IdCardIcon,
15
15
  ListChecksIcon,
16
- PaperclipIcon,
17
16
  PencilIcon,
18
17
  ReplyIcon,
19
18
  SmilePlusIcon,
@@ -43,7 +42,6 @@ import { formatSandboxTimeOfDay } from '../shared/format-time'
43
42
  import { OverlayScrollbar } from '../shared/overlay-scrollbar'
44
43
  import { getMessageClusterClass, isMergedMessage } from '../webqq/message-cluster'
45
44
  import {
46
- formatMediaSize,
47
45
  getEventMessageText,
48
46
  getForwardPreview,
49
47
  getMessageText,
@@ -74,6 +72,7 @@ import type { SandboxChatLunaState, SandboxForwardPreview } from '../../src/type
74
72
  import type { FriendMenuState } from '../webqq/friend-menu'
75
73
  import { useSandbox, useWorkspace } from '../workspace/context'
76
74
  import { ExtensionMark } from './extension-mark'
75
+ import { FileMessage, VoiceMessage } from './media-attachments'
77
76
  import { GroupMemberMenuItems } from './member-menu'
78
77
  import { MessageReactions } from './reactions'
79
78
  import './messages.css'
@@ -233,6 +232,11 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
233
232
  React.useEffect(() => () => clearTimeout(highlightTimer.current), [])
234
233
 
235
234
  const thinkingStates = props.chatLunaStates.filter(({ thinking }) => thinking)
235
+ // 等待气泡按实际显示顺序参与分组,复用连续消息的头像、间距与圆角规则。
236
+ const clusterMessages = [...props.messages, ...thinkingStates.map((state) => ({
237
+ authorId: state.botParticipantId,
238
+ conversationId: state.conversationId,
239
+ }))]
236
240
  const empty = !props.messages.length && !thinkingStates.length
237
241
  const peerKind = group ? 'group' : participants[conversation?.participantIds?.find((id) => id !== operatorId) ?? '']?.isBot ? 'bot' : 'user'
238
242
 
@@ -240,10 +244,15 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
240
244
 
241
245
  const renderMedia = (message: SandboxMessage) => message.media?.map((item) => {
242
246
  const source = media[item.id]
247
+ const failed = !source && !!mediaFailures[item.id]
243
248
  return (
244
249
  <div key={item.id} className="sandbox-message-media">
245
- {!source ? (
246
- <span className="sandbox-message-media-loading">{mediaFailures[item.id] ? t('sandbox.media.unavailable') : t('sandbox.media.loading')}</span>
250
+ {item.type === 'audio' ? (
251
+ <VoiceMessage media={item} source={source} failed={failed} disabled={props.selectionMode} />
252
+ ) : item.type === 'file' ? (
253
+ <FileMessage media={item} source={source} failed={failed} />
254
+ ) : !source ? (
255
+ <span className="sandbox-message-media-loading">{failed ? t('sandbox.media.unavailable') : t('sandbox.media.loading')}</span>
247
256
  ) : item.type === 'image' ? (
248
257
  <button type="button" className="sandbox-message-image" aria-label={t('sandbox.media.viewImage')} onClick={(event) => {
249
258
  if (props.selectionMode) return
@@ -252,15 +261,8 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
252
261
  }}>
253
262
  <img src={source} alt={item.name} />
254
263
  </button>
255
- ) : item.type === 'audio' ? (
256
- <audio src={source} controls preload="metadata" />
257
- ) : item.type === 'video' ? (
258
- <video src={source} controls preload="metadata" />
259
264
  ) : (
260
- <a href={source} download={item.name} className="sandbox-message-file">
261
- <PaperclipIcon className="size-[18px]" />
262
- <span><strong>{item.name}</strong><small>{formatMediaSize(item.size)}</small></span>
263
- </a>
265
+ <video src={source} controls preload="metadata" />
264
266
  )}
265
267
  </div>
266
268
  )
@@ -308,8 +310,8 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
308
310
  const outgoing = message.authorId === operatorId
309
311
  const direction = outgoing ? 'is-outgoing' : 'is-incoming'
310
312
  const capabilities = readMessageCapabilities(message, presentation)
311
- const merged = isMergedMessage(props.messages, index, operatorId)
312
- const cluster = getMessageClusterClass(props.messages, index, operatorId)
313
+ const merged = isMergedMessage(clusterMessages, index, operatorId)
314
+ const cluster = getMessageClusterClass(clusterMessages, index, operatorId)
313
315
  const recalled = isRecalledMessage(message)
314
316
  const inherited = isInheritedMessage(message, presentation)
315
317
  const selected = props.selectedIds.includes(message.id)
@@ -363,6 +365,11 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
363
365
  <PencilIcon />{t('sandbox.menu.editEntity', { kind: t(isBot ? 'sandbox.kind.bot' : 'sandbox.kind.user') })}<ExtensionMark />
364
366
  </ContextMenuItem>
365
367
  )}
368
+ {group && getCurrentGroupMember(message.authorId, presentation) && (
369
+ <ContextMenuItem onClick={() => dialogs.openGroupAction('sandbox-card', message.authorId, group.id)}>
370
+ <TagIcon />{t('sandbox.member.setCard')}<ExtensionMark />
371
+ </ContextMenuItem>
372
+ )}
366
373
  {!outgoing && (
367
374
  <>
368
375
  {getMessageGroupMemberActions(message.authorId, presentation).includes('mention') && (
@@ -492,7 +499,7 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
492
499
  if (!selectable) return
493
500
  // 右键菜单经 Portal 渲染,React 事件仍沿组件树冒泡到这里:点「多选」进入多选后,同一次点击会把刚选中的这条切回未选。
494
501
  if (!event.currentTarget.contains(event.target as Node)) return
495
- if ((event.target as HTMLElement).closest('a,button,audio,video')) return
502
+ if ((event.target as HTMLElement).closest('a,button,audio,video,[role="slider"]')) return
496
503
  props.onToggleSelection(message.id)
497
504
  }}
498
505
  >
@@ -565,30 +572,40 @@ export const MessageList = React.forwardRef<MessageListHandle, MessageListProps>
565
572
  </React.Fragment>
566
573
  )
567
574
  })}
568
- {thinkingStates.map((state) => (
569
- <li
570
- key={`${state.botParticipantId}:${state.conversationId}`}
571
- className={cn('sandbox-message-row', state.botParticipantId === operatorId ? 'is-outgoing' : 'is-incoming')}
572
- >
573
- <span className="sandbox-message-avatar-wrap">
574
- <SandboxAvatar kind="bot" name={participants[state.botParticipantId]?.name} src={participants[state.botParticipantId]?.avatar} className="size-8" />
575
- </span>
576
- <div className="sandbox-message-content">
577
- {/* 等待气泡复用普通消息的 sender-line + body 结构:少了包裹层会丢掉两者之间的 6px 间距,
578
- 被替换成真实消息时会整体下跳。 */}
579
- <div className="sandbox-message-sender-line">
580
- <span>{participants[state.botParticipantId]?.name ?? state.botParticipantId}</span>
581
- </div>
582
- <div className="sandbox-message-body">
583
- <div className="sandbox-message-bubble" aria-label={t('sandbox.chat.thinking')}>
584
- <span className="sandbox-message-thinking-dots">
585
- {[0, 1, 2].map((dot) => <span key={dot} className="sandbox-message-thinking-dot" />)}
586
- </span>
575
+ {thinkingStates.map((state, index) => {
576
+ const clusterIndex = props.messages.length + index
577
+ const merged = isMergedMessage(clusterMessages, clusterIndex, operatorId)
578
+ return (
579
+ <li
580
+ key={`${state.botParticipantId}:${state.conversationId}`}
581
+ className={cn(
582
+ 'sandbox-message-row',
583
+ state.botParticipantId === operatorId ? 'is-outgoing' : 'is-incoming',
584
+ getMessageClusterClass(clusterMessages, clusterIndex, operatorId),
585
+ merged && 'is-merged',
586
+ )}
587
+ >
588
+ <span className="sandbox-message-avatar-wrap">
589
+ <SandboxAvatar kind="bot" name={participants[state.botParticipantId]?.name} src={participants[state.botParticipantId]?.avatar} className="size-8" />
590
+ </span>
591
+ <div className="sandbox-message-content">
592
+ {/* 等待气泡复用普通消息的 sender-line + body 结构;合并时省略昵称,头像由 is-merged 隐藏并保留占位。 */}
593
+ {!merged && (
594
+ <div className="sandbox-message-sender-line">
595
+ <span>{participants[state.botParticipantId]?.name ?? state.botParticipantId}</span>
596
+ </div>
597
+ )}
598
+ <div className="sandbox-message-body">
599
+ <div className="sandbox-message-bubble" aria-label={t('sandbox.chat.thinking')}>
600
+ <span className="sandbox-message-thinking-dots">
601
+ {[0, 1, 2].map((dot) => <span key={dot} className="sandbox-message-thinking-dot" />)}
602
+ </span>
603
+ </div>
587
604
  </div>
588
605
  </div>
589
- </div>
590
- </li>
591
- ))}
606
+ </li>
607
+ )
608
+ })}
592
609
  </ol>
593
610
  )}
594
611
  </ContextMenuTrigger>