chatluna-plugin-onebot-sandbox 1.1.0 → 1.2.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 (81) hide show
  1. package/client/chat/chat-pane.tsx +19 -7
  2. package/client/chat/composer.tsx +8 -5
  3. package/client/chat/forward.tsx +11 -12
  4. package/client/chat/media-attachments.tsx +236 -0
  5. package/client/chat/message-list.tsx +60 -37
  6. package/client/chat/messages.css +203 -19
  7. package/client/environment/avatar-picker.tsx +6 -5
  8. package/client/environment/entity-dialog.css +5 -0
  9. package/client/environment/entity-dialog.tsx +41 -3
  10. package/client/locales/en.yml +17 -3
  11. package/client/locales/zh.yml +17 -3
  12. package/client/mcp/credential-manager.tsx +5 -9
  13. package/client/settings/localize.ts +2 -2
  14. package/client/settings/page.tsx +2 -2
  15. package/client/test-space/spaces.css +2 -0
  16. package/client/webqq/composer-draft.ts +0 -1
  17. package/client/webqq/forward-dialog-stack.ts +11 -3
  18. package/client/webqq/media-attachment.ts +72 -0
  19. package/client/webqq/message-cluster.ts +9 -29
  20. package/client/workspace/context.tsx +1 -1
  21. package/client/workspace/media-cache.ts +1 -1
  22. package/client/workspace/overlay-host.tsx +26 -17
  23. package/client/workspace/store.ts +104 -51
  24. package/dist/.vite/manifest.json +1 -1
  25. package/dist/app-Cubeh6IM.js +85 -0
  26. package/dist/client.css +2 -2
  27. package/dist/client.js +1 -1
  28. package/lib/base64.d.ts +3 -0
  29. package/lib/base64.d.ts.map +1 -0
  30. package/lib/bot.d.ts.map +1 -1
  31. package/lib/builtin-avatar-options.d.ts.map +1 -1
  32. package/lib/builtin-avatar-png.d.ts +14 -0
  33. package/lib/builtin-avatar-png.d.ts.map +1 -0
  34. package/lib/builtin-avatars.d.ts +1 -2
  35. package/lib/builtin-avatars.d.ts.map +1 -1
  36. package/lib/chatluna/state.d.ts.map +1 -1
  37. package/lib/chatluna/thinking.d.ts.map +1 -1
  38. package/lib/chatluna/user-permissions.d.ts +15 -0
  39. package/lib/chatluna/user-permissions.d.ts.map +1 -0
  40. package/lib/console-contract.d.ts +5 -5
  41. package/lib/console-contract.d.ts.map +1 -1
  42. package/lib/console.d.ts +1 -3
  43. package/lib/console.d.ts.map +1 -1
  44. package/lib/control-service.d.ts +10 -9
  45. package/lib/control-service.d.ts.map +1 -1
  46. package/lib/conversation-resolution.d.ts +0 -2
  47. package/lib/conversation-resolution.d.ts.map +1 -1
  48. package/lib/inbound-delivery.d.ts.map +1 -1
  49. package/lib/index.d.ts +2 -0
  50. package/lib/index.d.ts.map +1 -1
  51. package/lib/index.js +948 -666
  52. package/lib/index.js.map +1 -1
  53. package/lib/mcp/call-records.d.ts.map +1 -1
  54. package/lib/mcp/http-api.d.ts +3 -4
  55. package/lib/mcp/http-api.d.ts.map +1 -1
  56. package/lib/mcp/server.d.ts.map +1 -1
  57. package/lib/mcp/service.d.ts +11 -7
  58. package/lib/mcp/service.d.ts.map +1 -1
  59. package/lib/mcp/tool-registry.d.ts +1 -0
  60. package/lib/mcp/tool-registry.d.ts.map +1 -1
  61. package/lib/mcp/types.d.ts +1 -4
  62. package/lib/mcp/types.d.ts.map +1 -1
  63. package/lib/media-download.d.ts +3 -0
  64. package/lib/media-download.d.ts.map +1 -0
  65. package/lib/media-limits.d.ts +6 -0
  66. package/lib/media-limits.d.ts.map +1 -0
  67. package/lib/media-preview.d.ts +4 -0
  68. package/lib/media-preview.d.ts.map +1 -0
  69. package/lib/media-storage.d.ts +2 -3
  70. package/lib/media-storage.d.ts.map +1 -1
  71. package/lib/onebot-debug.d.ts.map +1 -1
  72. package/lib/record-store.d.ts +0 -2
  73. package/lib/record-store.d.ts.map +1 -1
  74. package/lib/test-spaces.d.ts +1 -0
  75. package/lib/test-spaces.d.ts.map +1 -1
  76. package/lib/types.d.ts +23 -4
  77. package/lib/types.d.ts.map +1 -1
  78. package/lib/user-authority.d.ts +6 -0
  79. package/lib/user-authority.d.ts.map +1 -0
  80. package/package.json +10 -3
  81. package/dist/app-SGdVOART.js +0 -85
@@ -5,7 +5,6 @@ export interface ComposerDraft { tokens: ComposerDraftToken[], tokenIndex: numbe
5
5
  export interface MentionCandidate { id: string, name: string, avatar?: string, kind: 'user' | 'bot', keywords?: string[] }
6
6
 
7
7
  export function createEmptyComposerDraft(): ComposerDraft { return { tokens: [{ type: 'text', text: '' }], tokenIndex: 0, offset: 0 } }
8
- export function draftText(tokens: readonly ComposerDraftToken[]): string { return tokens.map((token) => token.type === 'text' ? token.text : `@${token.name}`).join('') }
9
8
  export function isComposerDraftEmpty(tokens: readonly ComposerDraftToken[]): boolean { return !tokens.some((token) => token.type === 'mention' || !!token.text.trim()) }
10
9
  export function serializeComposerDraft(tokens: readonly ComposerDraftToken[]): string { return tokens.map((token) => token.type === 'mention' ? `<at id="${token.id}"/>` : token.text.replace(/ /g, ' ')).join('').trim() }
11
10
 
@@ -41,27 +41,35 @@ export function closeForwardStack(): ForwardDialogFrame[] {
41
41
  */
42
42
  export async function loadForwardDialogFrame(input: {
43
43
  readonly input: { forwardId?: string, messageId?: string }
44
- readonly load: (input: { forwardId?: string, messageId?: string }) => Promise<SandboxForward>
44
+ readonly load: (input: { forwardId?: string, messageId?: string }) => Promise<SandboxForward | undefined>
45
45
  }): Promise<ForwardDialogFrame | undefined> {
46
- let forward: SandboxForward
46
+ let forward: SandboxForward | undefined
47
47
  try {
48
48
  forward = await input.load(input.input)
49
49
  } catch {
50
50
  return
51
51
  }
52
52
 
53
+ if (!forward) return
54
+ let cancelled = false
53
55
  const nestedEntries = await Promise.all(
54
56
  forward.nodes
55
57
  .map((node) => node.forwardId)
56
58
  .filter((forwardId): forwardId is string => !!forwardId)
57
59
  .map(async (forwardId) => {
58
60
  try {
59
- return [forwardId, await input.load({ forwardId })] as const
61
+ const nested = await input.load({ forwardId })
62
+ if (!nested) {
63
+ cancelled = true
64
+ return
65
+ }
66
+ return [forwardId, nested] as const
60
67
  } catch {
61
68
  return undefined
62
69
  }
63
70
  }),
64
71
  )
72
+ if (cancelled) return
65
73
 
66
74
  return {
67
75
  // 没有可推断的标题时留空,由界面按当前语言显示「合并转发」。
@@ -0,0 +1,72 @@
1
+ /** 语音条与文件卡片的纯逻辑:文件归类、波形采样与时长格式。 */
2
+
3
+ export type FileKind = 'archive' | 'audio' | 'code' | 'document' | 'image' | 'sheet' | 'video' | 'other'
4
+
5
+ const EXTENSION_KINDS: Record<string, FileKind> = {
6
+ '7z': 'archive', bz2: 'archive', gz: 'archive', rar: 'archive', tar: 'archive', tgz: 'archive', xz: 'archive', zip: 'archive', zst: 'archive',
7
+ aac: 'audio', amr: 'audio', flac: 'audio', m4a: 'audio', mp3: 'audio', ogg: 'audio', opus: 'audio', silk: 'audio', wav: 'audio', wma: 'audio',
8
+ avi: 'video', flv: 'video', m4v: 'video', mkv: 'video', mov: 'video', mp4: 'video', webm: 'video', wmv: 'video',
9
+ avif: 'image', bmp: 'image', gif: 'image', heic: 'image', ico: 'image', jpeg: 'image', jpg: 'image', png: 'image', svg: 'image', webp: 'image',
10
+ csv: 'sheet', numbers: 'sheet', ods: 'sheet', tsv: 'sheet', xls: 'sheet', xlsx: 'sheet',
11
+ doc: 'document', docx: 'document', epub: 'document', key: 'document', md: 'document', odt: 'document', pages: 'document', pdf: 'document',
12
+ ppt: 'document', pptx: 'document', rtf: 'document', txt: 'document',
13
+ c: 'code', cpp: 'code', css: 'code', go: 'code', h: 'code', html: 'code', java: 'code', js: 'code', json: 'code', jsx: 'code', kt: 'code',
14
+ mjs: 'code', php: 'code', py: 'code', rb: 'code', rs: 'code', sh: 'code', sql: 'code', ts: 'code', tsx: 'code', xml: 'code', yaml: 'code', yml: 'code',
15
+ }
16
+
17
+ /** 不含点的小写扩展名;没有扩展名、以点开头的隐藏文件名或过长的尾段返回空串。 */
18
+ export function getFileExtension(name: string): string {
19
+ const index = name.lastIndexOf('.')
20
+ if (index <= 0 || index === name.length - 1) return ''
21
+ const extension = name.slice(index + 1).toLowerCase()
22
+ return /^[a-z0-9]{1,8}$/.test(extension) ? extension : ''
23
+ }
24
+
25
+ /** 扩展名优先,认不出时退回 MIME 主类型;`application/octet-stream` 之类归为 other。 */
26
+ export function getFileKind(name: string, mimeType: string): FileKind {
27
+ const byExtension = EXTENSION_KINDS[getFileExtension(name)]
28
+ if (byExtension) return byExtension
29
+ const major = mimeType.split('/')[0]
30
+ if (major === 'audio' || major === 'video' || major === 'image') return major
31
+ if (major === 'text') return 'document'
32
+ return 'other'
33
+ }
34
+
35
+ export const WAVEFORM_BARS = 32
36
+ /** 静音段也保留一截竖条,语音条不会出现空洞。 */
37
+ const MIN_BAR = 0.16
38
+
39
+ /** 按段取均方根并归一化到 [MIN_BAR, 1]。 */
40
+ export function computeWaveformPeaks(samples: ArrayLike<number>, bars = WAVEFORM_BARS): number[] {
41
+ const size = Math.floor(samples.length / bars)
42
+ if (size < 1) return fallbackWaveformPeaks('', bars)
43
+ const levels: number[] = []
44
+ for (let bar = 0; bar < bars; bar++) {
45
+ let sum = 0
46
+ for (let index = bar * size; index < (bar + 1) * size; index++) sum += samples[index]! * samples[index]!
47
+ levels.push(Math.sqrt(sum / size))
48
+ }
49
+ const max = Math.max(...levels)
50
+ if (!(max > 0)) return levels.map(() => MIN_BAR)
51
+ return levels.map((level) => MIN_BAR + (1 - MIN_BAR) * (level / max))
52
+ }
53
+
54
+ /** 解码失败时按媒体 ID 生成稳定的起伏,同一条语音每次渲染形状一致。 */
55
+ export function fallbackWaveformPeaks(seed: string, bars = WAVEFORM_BARS): number[] {
56
+ let state = 2166136261
57
+ for (let index = 0; index < seed.length; index++) state = Math.imul(state ^ seed.charCodeAt(index), 16777619)
58
+ return Array.from({ length: bars }, (_, bar) => {
59
+ state = Math.imul(state ^ (state >>> 15), 2246822507) >>> 0
60
+ const noise = (state % 1000) / 1000
61
+ // 两端收窄、中段饱满,接近人声的包络。
62
+ const envelope = Math.sin(Math.PI * (bar + 0.5) / bars)
63
+ return MIN_BAR + (1 - MIN_BAR) * Math.min(1, 0.25 + 0.75 * envelope * (0.45 + 0.55 * noise))
64
+ })
65
+ }
66
+
67
+ /** `m:ss`;时长未知时返回 `-:--`。 */
68
+ export function formatPlaybackTime(seconds: number): string {
69
+ if (!Number.isFinite(seconds) || seconds < 0) return '-:--'
70
+ const total = Math.floor(seconds)
71
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`
72
+ }
@@ -1,21 +1,16 @@
1
1
  import type { SandboxMessage } from '../../src/types'
2
2
 
3
- export function isImageOnlyMessage(message: SandboxMessage | undefined) {
4
- const media = message?.media
5
- return !!message
6
- && media?.length === 1
7
- && media[0].type === 'image'
8
- && message.content === `[图片] ${media[0].name}`
9
- }
3
+ // 分组只读取呈现字段,等待气泡无需伪造消息 ID 或写入历史。
4
+ type MessageClusterItem = Pick<SandboxMessage, 'authorId' | 'conversationId' | 'event'>
10
5
 
11
- function getDirection(message: SandboxMessage | undefined, currentOperatorId: string | undefined) {
6
+ function getDirection(message: MessageClusterItem | undefined, currentOperatorId: string | undefined) {
12
7
  if (!message) return
13
8
  return message.authorId === currentOperatorId ? 'outgoing' : 'incoming'
14
9
  }
15
10
 
16
11
  function isSameClusterSender(
17
- left: SandboxMessage | undefined,
18
- right: SandboxMessage | undefined,
12
+ left: MessageClusterItem | undefined,
13
+ right: MessageClusterItem | undefined,
19
14
  currentOperatorId: string | undefined,
20
15
  ) {
21
16
  return !!left
@@ -30,23 +25,8 @@ function isSameClusterSender(
30
25
  && getDirection(left, currentOperatorId) === getDirection(right, currentOperatorId)
31
26
  }
32
27
 
33
- function getClusterBubbleMessage(
34
- messages: SandboxMessage[],
35
- index: number,
36
- step: 1 | -1,
37
- currentOperatorId: string | undefined,
38
- ) {
39
- const message = messages[index]
40
- if (!message) return
41
- for (let cursor = index + step; cursor >= 0 && cursor < messages.length; cursor += step) {
42
- const candidate = messages[cursor]
43
- if (!isSameClusterSender(message, candidate, currentOperatorId)) return
44
- if (!isImageOnlyMessage(candidate)) return candidate
45
- }
46
- }
47
-
48
28
  export function isMergedMessage(
49
- messages: SandboxMessage[],
29
+ messages: MessageClusterItem[],
50
30
  index: number,
51
31
  currentOperatorId: string | undefined,
52
32
  ) {
@@ -54,13 +34,13 @@ export function isMergedMessage(
54
34
  }
55
35
 
56
36
  export function getMessageClusterClass(
57
- messages: SandboxMessage[],
37
+ messages: MessageClusterItem[],
58
38
  index: number,
59
39
  currentOperatorId: string | undefined,
60
40
  ) {
61
41
  if (!messages[index]) return ''
62
- const hasPrevious = !!getClusterBubbleMessage(messages, index, -1, currentOperatorId)
63
- const hasNext = !!getClusterBubbleMessage(messages, index, 1, currentOperatorId)
42
+ const hasPrevious = isMergedMessage(messages, index, currentOperatorId)
43
+ const hasNext = isMergedMessage(messages, index + 1, currentOperatorId)
64
44
  if (hasPrevious && hasNext) return 'is-cluster-middle'
65
45
  if (hasNext) return 'is-cluster-first'
66
46
  if (hasPrevious) return 'is-cluster-last'
@@ -42,7 +42,7 @@ interface SandboxContextValue {
42
42
  export interface SandboxDialogs {
43
43
  openEntity(mode: 'edit' | 'delete', target: { type: 'user' | 'bot' | 'group', id: string }): void
44
44
  openRemark(targetId: string): void
45
- openGroupAction(mode: 'card' | 'name' | 'title', targetId: string, groupId?: string): void
45
+ openGroupAction(mode: 'card' | 'sandbox-card' | 'name' | 'title', targetId: string, groupId?: string): void
46
46
  openConversationRename(conversationId: string): void
47
47
  openProfile(participantId: string, anchor?: { x: number, y: number }): void
48
48
  openGroupProfile(groupId: string, anchor?: { x: number, y: number }): void
@@ -5,7 +5,7 @@
5
5
  * 先闪名字首字再出图片。媒体 ID 是内容的 sha256(`src/media-storage.ts`),同一个 ID 的内容不变,
6
6
  * 所以缓存不会过期,插件重启、切换空间与操作者都照用。只在内存里,刷新页面后重新拉取。
7
7
  *
8
- * 头像是几 KB 的 SVG,数量有限,长期保留;消息里的图片可能有几 MB,只保留最近用到的
8
+ * 内置头像是预生成的 PNG,数量有限,长期保留;消息里的图片可能有几 MB,只保留最近用到的
9
9
  * {@link MESSAGE_MEDIA_LIMIT} 张,按最近使用淘汰。
10
10
  */
11
11
 
@@ -12,6 +12,7 @@ import {
12
12
  Input,
13
13
  } from '@chatluna/ui-kit'
14
14
  import { toast } from '@chatluna/ui-client/client'
15
+ import { resolveConversation } from '../../src/conversation-resolution'
15
16
  import { useT } from '../i18n'
16
17
  import { EntityDialog, type EntityDialogTarget } from '../environment/entity-dialog'
17
18
  import { SandboxAvatar } from '../shared/avatar'
@@ -27,7 +28,7 @@ import { useSandbox, useWorkspace } from './context'
27
28
 
28
29
  type TextDialog =
29
30
  | { kind: 'remark', targetId: string, value: string }
30
- | { kind: 'card' | 'name' | 'title', targetId: string, groupId: string, value: string }
31
+ | { kind: 'card' | 'sandbox-card' | 'name' | 'title', targetId: string, groupId: string, value: string }
31
32
  | { kind: 'rename', conversationId: string, value: string }
32
33
 
33
34
  export interface OverlayState {
@@ -58,15 +59,15 @@ export function useOverlayState(store: WorkspaceStore) {
58
59
  setState((current) => ({ ...current, text: { kind, targetId, groupId: group.id, value } }))
59
60
  },
60
61
  openConversationRename: (conversationId) => {
61
- const instance = store.snapshot?.conversationInstances?.find(({ id }) => id === conversationId)
62
+ const instance = store.snapshot?.conversationInstances.find(({ id }) => id === conversationId)
62
63
  if (instance) setState((value) => ({ ...value, text: { kind: 'rename', conversationId, value: instance.title ?? '' } }))
63
64
  },
64
65
  openProfile: (participantId, anchor) => {
65
66
  const snapshot = store.snapshot
66
67
  if (!snapshot) return
67
68
  const view = store.getView()
68
- const conversation = [...snapshot.conversations, ...(snapshot.conversationInstances ?? [])].find(({ id }) => id === view.activeConversationId)
69
- const groupId = conversation && 'groupId' in conversation ? conversation.groupId : undefined
69
+ const conversation = view.activeConversationId ? resolveConversation(snapshot, view.activeConversationId) : undefined
70
+ const groupId = conversation?.groupId
70
71
  const card = buildProfileCardModel(t, { snapshot, participantId, viewerId: view.currentOperatorId, groupId })
71
72
  if (card) setState((value) => ({ ...value, profile: { card, ...anchorOf(anchor) } }))
72
73
  },
@@ -106,6 +107,7 @@ function TextActionDialog({ dialog, onClose }: { dialog?: TextDialog, onClose():
106
107
  const [busy, setBusy] = React.useState(false)
107
108
  const [error, setError] = React.useState('')
108
109
  const shown = useRetained(dialog)
110
+ const scroller = React.useRef<HTMLDivElement>(null)
109
111
  const { requestClose, confirm } = useDiscardConfirm(!!dialog && value !== dialog.value, onClose)
110
112
 
111
113
  // 布局阶段回填:打开的首帧就是本次的值,不闪出上一次输入的内容。
@@ -124,6 +126,7 @@ function TextActionDialog({ dialog, onClose }: { dialog?: TextDialog, onClose():
124
126
  else if (dialog.kind === 'rename') await store.renameConversationInstance({ conversationId: dialog.conversationId, title: value })
125
127
  else if (dialog.kind === 'name') await store.performGroupAction({ action: 'set-name', groupId: dialog.groupId, name: value })
126
128
  else if (dialog.kind === 'title') await store.performGroupAction({ action: 'set-title', groupId: dialog.groupId, targetId: dialog.targetId, title: value })
129
+ else if (dialog.kind === 'sandbox-card') await store.manageEnvironment({ action: 'set-group-card', data: { groupId: dialog.groupId, targetId: dialog.targetId, card: value } })
127
130
  else await store.performGroupAction({ action: 'set-card', groupId: dialog.groupId, targetId: dialog.targetId, card: value })
128
131
  onClose()
129
132
  } catch (failure) {
@@ -133,24 +136,30 @@ function TextActionDialog({ dialog, onClose }: { dialog?: TextDialog, onClose():
133
136
  }
134
137
  }
135
138
 
136
- const kind = shown?.kind ?? 'remark'
139
+ const kind = shown?.kind === 'sandbox-card' ? 'card' : shown?.kind ?? 'remark'
137
140
  return (
138
141
  <Dialog open={!!dialog} onOpenChange={(open) => !open && requestClose()}>
139
- <DialogContent>
142
+ <DialogContent className="flex flex-col overflow-hidden text-sm leading-6">
140
143
  <DialogHeader>
141
144
  <DialogTitle>{t(`sandbox.text.${kind}.title`)}</DialogTitle>
142
- <DialogDescription>{t(`sandbox.text.${kind}.description`)}</DialogDescription>
145
+ <DialogDescription>{t(shown?.kind === 'sandbox-card' ? 'sandbox.text.card.sandboxDescription' : `sandbox.text.${kind}.description`)}</DialogDescription>
143
146
  </DialogHeader>
144
- <Input
145
- autoFocus
146
- value={value}
147
- placeholder={t(`sandbox.text.${kind}.placeholder`)}
148
- onChange={(event) => setValue(event.target.value)}
149
- onKeyDown={(event) => {
150
- if (event.key === 'Enter' && !event.nativeEvent.isComposing) void submit()
151
- }}
152
- />
153
- {error && <p role="alert" className="text-xs text-destructive">{error}</p>}
147
+ <div className="relative -mx-5 flex min-h-0 flex-col">
148
+ <div ref={scroller} className="min-h-0 space-y-2 overflow-y-auto px-5 py-0.5" style={{ scrollbarWidth: 'none' }}>
149
+ <Input
150
+ autoFocus
151
+ value={value}
152
+ aria-label={t(`sandbox.text.${kind}.placeholder`)}
153
+ placeholder={t(`sandbox.text.${kind}.placeholder`)}
154
+ onChange={(event) => setValue(event.target.value)}
155
+ onKeyDown={(event) => {
156
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing) void submit()
157
+ }}
158
+ />
159
+ {error && <p role="alert" className="text-xs text-destructive">{error}</p>}
160
+ </div>
161
+ <OverlayScrollbar target={scroller} className="inset-y-0" />
162
+ </div>
154
163
  <DialogFooter>
155
164
  <Button variant="outline" onClick={requestClose}>{t('sandbox.common.cancel')}</Button>
156
165
  <Button disabled={busy} onClick={submit}>{busy ? t('sandbox.common.saving') : t('sandbox.common.save')}</Button>
@@ -85,9 +85,12 @@ export interface WorkspaceView {
85
85
  export class WorkspaceStore {
86
86
  private view: WorkspaceView = { media: {}, mediaFailures: {} }
87
87
  private listeners = new Set<() => void>()
88
+ private loadTask: Promise<void> | undefined
88
89
  private refreshTask: Promise<void> | undefined
89
90
  private pendingRefresh = false
90
91
  private mediaLoading = new Set<string>()
92
+ private readEpoch = 0
93
+ private historyTasks = new Map<string, Promise<void>>()
91
94
  private disposed = false
92
95
 
93
96
  constructor(readonly spaceId: string | undefined) {}
@@ -107,10 +110,21 @@ export class WorkspaceStore {
107
110
  /** 只停止写入视图;监听器由 `useSyncExternalStore` 自行退订,清空会误删重挂载后的订阅。 */
108
111
  dispose() {
109
112
  this.disposed = true
113
+ this.invalidateReads()
114
+ }
115
+
116
+ private invalidateReads() {
117
+ this.readEpoch++
118
+ this.historyTasks.clear()
119
+ }
120
+
121
+ private isCurrentRead(epoch: number, operatorId: string) {
122
+ return !this.disposed && epoch === this.readEpoch && operatorId === this.view.currentOperatorId
110
123
  }
111
124
 
112
125
  private set(patch: Partial<WorkspaceView>) {
113
126
  if (this.disposed) return
127
+ if ('currentOperatorId' in patch && patch.currentOperatorId !== this.view.currentOperatorId) this.invalidateReads()
114
128
  this.view = { ...this.view, ...patch }
115
129
  for (const listener of this.listeners) listener()
116
130
  }
@@ -137,6 +151,7 @@ export class WorkspaceStore {
137
151
  }
138
152
 
139
153
  private replaceWorkspace(workspace: SandboxWorkspaceState, preferred: SandboxWorkspaceSelection = {}, persist = true) {
154
+ if (this.disposed) return
140
155
  const selection = resolveWorkspaceSelection(workspace.snapshot, {
141
156
  currentOperatorId: preferred.currentOperatorId ?? this.view.currentOperatorId,
142
157
  activeConversationId: preferred.activeConversationId ?? this.view.activeConversationId,
@@ -166,20 +181,28 @@ export class WorkspaceStore {
166
181
  this.replaceWorkspace(workspace, readSelection(this.spaceId), false)
167
182
  }
168
183
 
169
- async load() {
184
+ load() {
185
+ if (this.loadTask) return this.loadTask
170
186
  const stored = readSelection(this.spaceId)
171
- try {
172
- let workspace: SandboxWorkspaceState
187
+ const operatorId = this.view.currentOperatorId
188
+ this.loadTask = (async () => {
173
189
  try {
174
- workspace = await invoke('onebot-sandbox.workspace', this.scoped(stored.currentOperatorId ? { operatorId: stored.currentOperatorId } : {}))
175
- } catch {
176
- // 本地记住的操作者可能已被删除;退回默认视角再解析一次选择。
177
- workspace = await invoke('onebot-sandbox.workspace', this.scoped({}))
190
+ let workspace: SandboxWorkspaceState
191
+ try {
192
+ workspace = await invoke('onebot-sandbox.workspace', this.scoped(stored.currentOperatorId ? { operatorId: stored.currentOperatorId } : {}))
193
+ } catch {
194
+ // 本地记住的操作者可能已被删除;退回默认视角再解析一次选择。
195
+ workspace = await invoke('onebot-sandbox.workspace', this.scoped({}))
196
+ }
197
+ if (operatorId !== this.view.currentOperatorId) return
198
+ this.replaceWorkspace(workspace, stored)
199
+ } catch (error) {
200
+ this.set({ loadError: errorText(error, translate('sandbox.error.loadWorkspace')) })
201
+ } finally {
202
+ this.loadTask = undefined
178
203
  }
179
- this.replaceWorkspace(workspace, stored)
180
- } catch (error) {
181
- this.set({ loadError: errorText(error, translate('sandbox.error.loadWorkspace')) })
182
- }
204
+ })()
205
+ return this.loadTask
183
206
  }
184
207
 
185
208
  /** 场景变更广播只是失效信号;多次信号合并成串行的若干次读取,不会并发打满。 */
@@ -189,10 +212,18 @@ export class WorkspaceStore {
189
212
  this.refreshTask = (async () => {
190
213
  try {
191
214
  while (this.pendingRefresh && !this.disposed) {
215
+ // 初次加载会恢复本地操作者;提前请求会按默认用户裁剪,随后覆盖掉当前用户的私聊。
216
+ await this.loadTask
217
+ if (this.disposed) break
192
218
  this.pendingRefresh = false
219
+ if (!this.view.workspace) continue
193
220
  const operatorId = this.view.currentOperatorId
194
221
  try {
195
222
  const workspace = await invoke('onebot-sandbox.workspace', this.scoped(operatorId ? { operatorId } : {}))
223
+ if (operatorId !== this.view.currentOperatorId) {
224
+ this.pendingRefresh = true
225
+ continue
226
+ }
196
227
  if (workspace.snapshot.revision >= (this.snapshot?.revision ?? 0)) this.replaceWorkspace(workspace)
197
228
  } catch {
198
229
  // 刷新失败保留当前画面,下一次信号会再试。
@@ -211,7 +242,6 @@ export class WorkspaceStore {
211
242
 
212
243
  async selectOperator(participantId: string) {
213
244
  const workspace = await invoke('onebot-sandbox.workspace', this.scoped({ operatorId: participantId }))
214
- this.set({ currentOperatorId: participantId })
215
245
  this.replaceWorkspace(workspace, { currentOperatorId: participantId })
216
246
  }
217
247
 
@@ -304,50 +334,72 @@ export class WorkspaceStore {
304
334
  return invoke('onebot-sandbox.search-conversation-messages', this.scoped({ ...input, operatorId: this.requireOperatorId() }))
305
335
  }
306
336
 
337
+ /** 视角切换或卸载后的结果返回 undefined,调用方不能继续展示旧转发内容。 */
307
338
  async getForwardMessage(input: { forwardId?: string, messageId?: string }) {
308
- const forward = await invoke('onebot-sandbox.get-forward-message', this.scoped({ ...input, operatorId: this.requireOperatorId() }))
309
- const workspace = this.view.workspace
310
- if (workspace && !(workspace.snapshot.forwards ?? []).some(({ id }) => id === forward.id)) {
311
- this.set({ workspace: { ...workspace, snapshot: { ...workspace.snapshot, forwards: [...(workspace.snapshot.forwards ?? []), forward] } } })
312
- void this.loadVisibleMedia()
339
+ if (this.disposed) return
340
+ const operatorId = this.requireOperatorId()
341
+ const epoch = this.readEpoch
342
+ try {
343
+ const forward = await invoke('onebot-sandbox.get-forward-message', this.scoped({ ...input, operatorId }))
344
+ if (!this.isCurrentRead(epoch, operatorId)) return
345
+ const workspace = this.view.workspace
346
+ if (!workspace) return
347
+ if (!workspace.snapshot.forwards.some(({ id }) => id === forward.id)) {
348
+ this.set({ workspace: { ...workspace, snapshot: { ...workspace.snapshot, forwards: [...workspace.snapshot.forwards, forward] } } })
349
+ void this.loadVisibleMedia()
350
+ }
351
+ return forward
352
+ } catch (error) {
353
+ if (this.isCurrentRead(epoch, operatorId)) throw error
313
354
  }
314
- return forward
315
355
  }
316
356
 
317
- /** 向前翻历史:服务端只给最近一段,旧消息按最早一条的 ID 继续取,拼到会话头部。 */
318
- async loadEarlierMessages(conversationId: string) {
357
+ /** 同一视角、同一会话复用在途分页;切换视角或卸载会使旧请求失效。 */
358
+ loadEarlierMessages(conversationId: string): Promise<void> {
319
359
  const workspace = this.view.workspace
320
- if (!workspace) return
360
+ if (this.disposed || !workspace) return Promise.resolve()
361
+ const pending = this.historyTasks.get(conversationId)
362
+ if (pending) return pending
321
363
  const beforeMessageId = readConversationMessageIds(workspace.snapshot, conversationId)[0]
322
- if (!beforeMessageId) return
323
- const history = await invoke('onebot-sandbox.message-history', this.scoped({
324
- operatorId: this.requireOperatorId(),
325
- conversationId,
326
- beforeMessageId,
327
- limit: 50,
328
- }))
329
- const current = this.view.workspace ?? workspace
330
- const snapshot = current.snapshot
331
- const knownIds = new Set(snapshot.messages.map(({ id }) => id))
332
- const knownForwardIds = new Set((snapshot.forwards ?? []).map(({ id }) => id))
333
- const prepend = <T extends { id: string, messageIds: string[] }>(rows: T[]) => rows.map((row) => row.id === conversationId ? {
334
- ...row,
335
- messageIds: [...history.messages.map(({ id }) => id), ...row.messageIds],
336
- hasMoreMessages: !!history.nextBeforeMessageId,
337
- } : row)
338
- this.set({
339
- workspace: {
340
- ...current,
341
- snapshot: {
342
- ...snapshot,
343
- conversations: prepend(snapshot.conversations),
344
- conversationInstances: prepend(snapshot.conversationInstances ?? []),
345
- messages: [...history.messages.filter(({ id }) => !knownIds.has(id)), ...snapshot.messages],
346
- forwards: [...(snapshot.forwards ?? []), ...(history.forwards ?? []).filter(({ id }) => !knownForwardIds.has(id))],
347
- },
348
- },
364
+ if (!beforeMessageId) return Promise.resolve()
365
+ const operatorId = this.requireOperatorId()
366
+ const epoch = this.readEpoch
367
+ const task = (async () => {
368
+ try {
369
+ const history = await invoke('onebot-sandbox.message-history', this.scoped({ operatorId, conversationId, beforeMessageId, limit: 50 }))
370
+ if (!this.isCurrentRead(epoch, operatorId)) return
371
+ const current = this.view.workspace
372
+ // 会话可能已被清空、删除或重新裁剪,不把旧分页接到另一条边界上。
373
+ if (!current || readConversationMessageIds(current.snapshot, conversationId)[0] !== beforeMessageId) return
374
+ const snapshot = current.snapshot
375
+ const knownIds = new Set(snapshot.messages.map(({ id }) => id))
376
+ const knownForwardIds = new Set(snapshot.forwards.map(({ id }) => id))
377
+ const prepend = <T extends { id: string, messageIds: string[] }>(rows: T[]) => rows.map((row) => row.id === conversationId ? {
378
+ ...row,
379
+ messageIds: [...new Set([...history.messages.map(({ id }) => id), ...row.messageIds])],
380
+ hasMoreMessages: !!history.nextBeforeMessageId,
381
+ } : row)
382
+ this.set({
383
+ workspace: {
384
+ ...current,
385
+ snapshot: {
386
+ ...snapshot,
387
+ conversations: prepend(snapshot.conversations),
388
+ conversationInstances: prepend(snapshot.conversationInstances),
389
+ messages: [...history.messages.filter(({ id }) => !knownIds.has(id)), ...snapshot.messages],
390
+ forwards: [...snapshot.forwards, ...(history.forwards ?? []).filter(({ id }) => !knownForwardIds.has(id))],
391
+ },
392
+ },
393
+ })
394
+ void this.loadVisibleMedia()
395
+ } catch (error) {
396
+ if (this.isCurrentRead(epoch, operatorId)) throw error
397
+ }
398
+ })().finally(() => {
399
+ if (this.historyTasks.get(conversationId) === task) this.historyTasks.delete(conversationId)
349
400
  })
350
- void this.loadVisibleMedia()
401
+ this.historyTasks.set(conversationId, task)
402
+ return task
351
403
  }
352
404
 
353
405
  resolveAvatar(reference: string | undefined) {
@@ -369,7 +421,8 @@ export class WorkspaceStore {
369
421
  this.mediaLoading.add(mediaId)
370
422
  try {
371
423
  const content = await invoke('onebot-sandbox.media-content', this.scoped({ operatorId, mediaId }))
372
- const url = `data:${content.mimeType};base64,${content.dataBase64}`
424
+ const playable = content.preview ?? content
425
+ const url = `data:${playable.mimeType};base64,${playable.dataBase64}`
373
426
  rememberMedia(mediaId, url, avatarIds.has(mediaId))
374
427
  const { [mediaId]: _, ...failures } = this.view.mediaFailures
375
428
  this.set({ media: { ...this.view.media, [mediaId]: url }, mediaFailures: failures })
@@ -388,7 +441,7 @@ function visibleMediaIdsOf(snapshot: SandboxSnapshot) {
388
441
  .flatMap((reference) => mediaIdOf(reference) ?? []))
389
442
  const messageMediaIds = new Set([
390
443
  ...snapshot.messages.flatMap(({ media }) => media?.map(({ id }) => id) ?? []),
391
- ...(snapshot.forwards ?? []).flatMap(({ nodes }) => nodes.flatMap(({ media }) => media?.map(({ id }) => id) ?? [])),
444
+ ...snapshot.forwards.flatMap(({ nodes }) => nodes.flatMap(({ media }) => media?.map(({ id }) => id) ?? [])),
392
445
  ])
393
446
  return { avatarIds, messageMediaIds }
394
447
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "client/app.tsx": {
3
- "file": "app-SGdVOART.js",
3
+ "file": "app-Cubeh6IM.js",
4
4
  "name": "app",
5
5
  "src": "client/app.tsx",
6
6
  "isDynamicEntry": true