chatluna-plugin-kb 0.1.1 → 0.1.3

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.
package/web/client.js CHANGED
@@ -28,10 +28,17 @@ import {
28
28
  CardFooter,
29
29
  CardHeader,
30
30
  CardTitle,
31
+ Checkbox,
31
32
  CodeValue,
32
33
  Collapsible,
33
34
  CollapsibleContent,
34
35
  CollapsibleTrigger,
36
+ Combobox,
37
+ ComboboxContent,
38
+ ComboboxEmpty,
39
+ ComboboxInput,
40
+ ComboboxItem,
41
+ ComboboxList,
35
42
  CopyButton,
36
43
  Dialog,
37
44
  DialogContent,
@@ -49,6 +56,8 @@ import {
49
56
  Input,
50
57
  PageHeader,
51
58
  Progress,
59
+ RadioGroup,
60
+ RadioGroupItem,
52
61
  SearchBox,
53
62
  Section,
54
63
  Select,
@@ -61,6 +70,8 @@ import {
61
70
  TabsContent,
62
71
  TabsList,
63
72
  TabsTrigger,
73
+ ToggleGroup,
74
+ ToggleGroupItem,
64
75
  Tooltip,
65
76
  TooltipContent,
66
77
  TooltipTrigger,
@@ -509,6 +520,22 @@ export const RULE_SCENES = [
509
520
  ]
510
521
  const RULE_LEVEL_MAX = 5
511
522
 
523
+ /** 规则编辑器的候选目录;获取失败时仍可用手动输入。 */
524
+ export const EMPTY_RULE_OPTIONS = {
525
+ platforms: [],
526
+ guilds: [],
527
+ users: [],
528
+ kbs: [],
529
+ levels: [
530
+ { value: 0, label: '0 · 访客' },
531
+ { value: 1, label: '1 · 普通用户' },
532
+ { value: 2, label: '2 · 成员' },
533
+ { value: 3, label: '3 · 群管' },
534
+ { value: 4, label: '4 · 管理员' },
535
+ { value: 5, label: '5 · 主人' }
536
+ ]
537
+ }
538
+
512
539
  /** 新建规则的空白草稿:默认兜底规则(all + 无匹配条件)。 */
513
540
  export function emptyRuleDraft() {
514
541
  return {
@@ -549,6 +576,61 @@ export function parseSpecText(value) {
549
576
  return specList(raw)
550
577
  }
551
578
 
579
+ /** 权限矩阵里某一列是否已勾选指定知识库;'*' 通配时不代表单库命中。 */
580
+ export function specHasValue(text, value) {
581
+ const key = draftText(value).toLowerCase()
582
+ if (key === '') return false
583
+ return parseSpecText(text).some((item) => item !== WILDCARD && item.toLowerCase() === key)
584
+ }
585
+
586
+ /**
587
+ * 勾选/取消矩阵里的单个知识库,保持草稿仍是一段逗号分隔文本。
588
+ * - 已存在 '*' 时保持通配,绝不把宽权限悄悄收敛成单库。
589
+ * - 取消后列表为空则回退到空字符串(序列化为 [])。
590
+ */
591
+ export function toggleSpecValue(text, value, checked) {
592
+ const item = draftText(value)
593
+ const list = parseSpecText(text)
594
+ if (item === '' || item === WILDCARD) return list.join(', ')
595
+ if (list[0] === WILDCARD) return WILDCARD
596
+ const key = item.toLowerCase()
597
+ const has = list.some((entry) => entry.toLowerCase() === key)
598
+ if (checked === true) return has ? list.join(', ') : [...list, item].join(', ')
599
+ return has ? list.filter((entry) => entry.toLowerCase() !== key).join(', ') : list.join(', ')
600
+ }
601
+
602
+ /** 「全部 (*)」列开关:打开写入 '*',关闭只移除通配符并保留其余显式项。 */
603
+ export function setSpecWildcard(text, all) {
604
+ if (all === true) return WILDCARD
605
+ return parseSpecText(text).filter((item) => item !== WILDCARD).join(', ')
606
+ }
607
+
608
+ /**
609
+ * 权限矩阵需要渲染的库:目录中的库在前,再合并草稿里已引用但目录缺失的 ID。
610
+ * 顺序稳定、按小写去重;'*' 不是库,跳过。
611
+ */
612
+ export function ruleKbMatrixRows(kbs, draft) {
613
+ const source = draft !== null && typeof draft === 'object' ? draft : {}
614
+ const out = []
615
+ const seen = new Set()
616
+ const add = (id, name, known = false) => {
617
+ const text = draftText(id)
618
+ if (text === '' || text === WILDCARD) return
619
+ const key = text.toLowerCase()
620
+ if (seen.has(key)) return
621
+ seen.add(key)
622
+ out.push({ id: text, name: draftText(name), known: known === true })
623
+ }
624
+ for (const kb of Array.isArray(kbs) ? kbs : []) {
625
+ if (kb === null || typeof kb !== 'object') continue
626
+ add(kb.id, kb.name, true)
627
+ }
628
+ for (const field of ['readableKbs', 'writableKbs', 'manageableKbs', 'defaultKb']) {
629
+ for (const id of parseSpecText(source[field])) add(id, '')
630
+ }
631
+ return out
632
+ }
633
+
552
634
  const draftText = (value) => (typeof value === 'string' ? value.trim() : '')
553
635
 
554
636
  /** 字段级校验;只报告错误,绝不静默改写用户输入。 */
@@ -1045,7 +1127,23 @@ function engineOfflineCard(status, actions, options) {
1045
1127
 
1046
1128
  // ---- 从 ChatLuna 复制模型配置 ---------------------------------------------
1047
1129
  // 列表只来自服务端脱敏元数据;页面从不接收、保存或展示 API Key。
1048
- const MODEL_TYPE_LABELS = { embedding: 'Embedding 模型', vlm: '视觉模型(VLM)' }
1130
+ const MODEL_TYPE_LABELS = {
1131
+ chat: '对话模型',
1132
+ embedding: 'Embedding 模型',
1133
+ vlm: '视觉模型(VLM)',
1134
+ rerank: 'ReRank 模型'
1135
+ }
1136
+ const MODEL_TYPE_ORDER = ['chat', 'embedding', 'vlm', 'rerank']
1137
+
1138
+ function modelRoleLabel(role) {
1139
+ return role === 'vlm' ? 'VLM' : role === 'chat' ? '对话' : role === 'rerank' ? 'ReRank' : 'Embedding'
1140
+ }
1141
+
1142
+ function importRolesFor(item) {
1143
+ const roles = [item?.type]
1144
+ if (item?.type === 'chat' && item?.supportsVision === true) roles.push('vlm')
1145
+ return roles.filter((role) => MODEL_TYPE_LABELS[role] !== undefined)
1146
+ }
1049
1147
 
1050
1148
  function shortenUrl(value, max = 52) {
1051
1149
  const text = typeof value === 'string' ? value : ''
@@ -1057,6 +1155,84 @@ function modelSelectionKey(item) {
1057
1155
  return `${item?.providerId ?? ''}\u0000${item?.modelId ?? ''}\u0000${item?.type ?? ''}`
1058
1156
  }
1059
1157
 
1158
+ const MODEL_FILTER_LABELS = {
1159
+ chat: '对话',
1160
+ embedding: 'Embedding',
1161
+ vlm: 'VLM',
1162
+ rerank: 'ReRank'
1163
+ }
1164
+ const MODEL_GROUP_LIMIT = 5
1165
+
1166
+ const providerGroupOf = (item) => {
1167
+ const label = typeof item?.providerLabel === 'string' ? item.providerLabel.trim() : ''
1168
+ if (label !== '') return label
1169
+ const id = typeof item?.providerId === 'string' ? item.providerId.trim() : ''
1170
+ return id === '' ? '—' : id
1171
+ }
1172
+
1173
+ /**
1174
+ * 模型复制列表的搜索/类型筛选/厂商分组(纯函数,SSR 与单测共用)。
1175
+ * - 类型计数与 chips 基于完整目录,只展示有模型的类型;
1176
+ * - 每个厂商默认最多 5 行;选中项所在厂商自动展开到选中行,保证始终可见。
1177
+ * @returns {{matched: object[], counts: Record<string, number>, typeOptions: object[], activeType: string, groups: object[], empty: boolean}}
1178
+ */
1179
+ export function modelCopyReport(models, options = {}) {
1180
+ const list = Array.isArray(models) ? models.filter((item) => item !== null && typeof item === 'object') : []
1181
+ const query = typeof options.query === 'string' ? options.query.trim() : ''
1182
+ const requestedType = typeof options.type === 'string' && options.type !== '' ? options.type : 'all'
1183
+ const selectedKey = typeof options.selectedKey === 'string' ? options.selectedKey : ''
1184
+ const expanded = options.expanded !== null && typeof options.expanded === 'object' ? options.expanded : {}
1185
+ const matched =
1186
+ query === ''
1187
+ ? list
1188
+ : list.filter((item) =>
1189
+ matchesQuery(query, item.providerLabel, item.providerId, item.modelId, item.baseUrl)
1190
+ )
1191
+ // 计数基于完整目录,chips 在搜索过程中保持稳定;只展示有模型的类型。
1192
+ const counts = { all: list.length }
1193
+ for (const item of list) {
1194
+ if (MODEL_TYPE_LABELS[item.type] === undefined) continue
1195
+ counts[item.type] = (counts[item.type] ?? 0) + 1
1196
+ }
1197
+ const typeOptions = [
1198
+ { value: 'all', label: '全部', count: counts.all },
1199
+ ...MODEL_TYPE_ORDER.filter((type) => (counts[type] ?? 0) > 0).map((type) => ({
1200
+ value: type,
1201
+ label: MODEL_FILTER_LABELS[type] ?? type,
1202
+ count: counts[type]
1203
+ }))
1204
+ ]
1205
+ const activeType = requestedType === 'all' || counts[requestedType] > 0 ? requestedType : 'all'
1206
+ const typed = activeType === 'all' ? matched : matched.filter((item) => item.type === activeType)
1207
+ const groupMap = new Map()
1208
+ for (const item of typed) {
1209
+ const key = providerGroupOf(item)
1210
+ if (!groupMap.has(key)) groupMap.set(key, [])
1211
+ groupMap.get(key).push(item)
1212
+ }
1213
+ const groups = []
1214
+ for (const [key, items] of groupMap) {
1215
+ const selectedIndex = items.findIndex((item) => modelSelectionKey(item) === selectedKey)
1216
+ const isExpanded = expanded[key] === true
1217
+ const limit = isExpanded
1218
+ ? items.length
1219
+ : selectedIndex >= MODEL_GROUP_LIMIT
1220
+ ? selectedIndex + 1
1221
+ : Math.min(items.length, MODEL_GROUP_LIMIT)
1222
+ const visible = items.slice(0, limit)
1223
+ groups.push({
1224
+ key,
1225
+ label: key,
1226
+ items: visible,
1227
+ total: items.length,
1228
+ hidden: items.length - visible.length,
1229
+ expanded: isExpanded,
1230
+ hasSelected: selectedIndex >= 0
1231
+ })
1232
+ }
1233
+ return { matched, counts, typeOptions, activeType, groups, empty: typed.length === 0 }
1234
+ }
1235
+
1060
1236
  /**
1061
1237
  * 纯渲染层:所有状态与请求都在 ModelCopyPanel 里,便于 SSR 桩测试直接喂模型。
1062
1238
  * @param {{
@@ -1065,12 +1241,18 @@ function modelSelectionKey(item) {
1065
1241
  * models: Array<object>,
1066
1242
  * error?: string,
1067
1243
  * selectedKey?: string,
1244
+ * query?: string,
1245
+ * type?: string,
1246
+ * expanded?: object,
1068
1247
  * importing?: boolean,
1069
1248
  * copyError?: string,
1070
1249
  * result?: object|null,
1071
1250
  * onToggle?: Function,
1072
1251
  * onLoad?: Function,
1073
1252
  * onSelect?: Function,
1253
+ * onQueryChange?: Function,
1254
+ * onTypeChange?: Function,
1255
+ * onToggleGroup?: Function,
1074
1256
  * onCopy?: Function
1075
1257
  * }} m
1076
1258
  */
@@ -1078,10 +1260,15 @@ export function modelCopyView(m = {}) {
1078
1260
  const models = Array.isArray(m.models) ? m.models : []
1079
1261
  const selectedKey = typeof m.selectedKey === 'string' ? m.selectedKey : ''
1080
1262
  const selected = models.find((item) => modelSelectionKey(item) === selectedKey) ?? null
1081
- const groups = [
1082
- { type: 'embedding', items: models.filter((item) => item?.type === 'embedding') },
1083
- { type: 'vlm', items: models.filter((item) => item?.type === 'vlm') }
1084
- ].filter((group) => group.items.length > 0)
1263
+ const query = typeof m.query === 'string' ? m.query : ''
1264
+ const report = modelCopyReport(models, {
1265
+ query,
1266
+ type: m.type,
1267
+ expanded: m.expanded,
1268
+ selectedKey
1269
+ })
1270
+ const selectedRoles = selected === null ? [] : importRolesFor(selected)
1271
+ const activeImportRole = selectedRoles.includes(m.importRole) ? m.importRole : selected?.type
1085
1272
  const result = m.result !== null && typeof m.result === 'object' ? m.result : null
1086
1273
  const open = m.open === true
1087
1274
  const state = typeof m.state === 'string' ? m.state : 'idle'
@@ -1140,58 +1327,137 @@ export function modelCopyView(m = {}) {
1140
1327
  ? errorAlert(m.error, '读取模型列表失败')
1141
1328
  : null,
1142
1329
  state === 'idle'
1143
- ? h('p', { className: 'kb-muted-text' }, '点击「加载模型列表」查看可复制的 Embedding / VLM 模型。')
1330
+ ? h('p', { className: 'kb-muted-text' }, '点击「加载模型列表」查看可复制的对话 / Embedding / VLM / ReRank 模型。')
1144
1331
  : null,
1145
1332
  state === 'ready' && models.length === 0
1146
- ? h('p', { className: 'kb-muted-text' }, 'ChatLuna 暂无可用于复制的 Embedding / VLM 模型。')
1333
+ ? h('p', { className: 'kb-muted-text' }, 'ChatLuna 暂无可用于复制的知识库模型。')
1147
1334
  : null,
1148
- groups.map((group) =>
1149
- h(
1150
- 'div',
1151
- { key: group.type, className: 'kb-model-group' },
1152
- h('p', { className: 'kb-model-group-title' }, MODEL_TYPE_LABELS[group.type] ?? group.type),
1153
- h(
1154
- 'ul',
1155
- { className: 'kb-model-list' },
1156
- group.items.map((item) => {
1157
- const key = modelSelectionKey(item)
1158
- const active = key === selectedKey
1159
- const role = item.type === 'vlm' ? 'VLM' : 'Embedding'
1160
- return h(
1161
- 'li',
1162
- { key },
1335
+ state === 'ready' && models.length > 0
1336
+ ? h(
1337
+ 'div',
1338
+ { className: 'kb-model-toolbar' },
1339
+ h(SearchBox, {
1340
+ value: query,
1341
+ onChange: (value) =>
1342
+ typeof m.onQueryChange === 'function' ? m.onQueryChange(value) : undefined,
1343
+ placeholder: '搜索厂商、模型或 baseUrl…',
1344
+ clearLabel: '清除搜索'
1345
+ }),
1346
+ h(FilterChips, {
1347
+ options: report.typeOptions,
1348
+ value: report.activeType,
1349
+ onChange: (value) =>
1350
+ typeof m.onTypeChange === 'function' ? m.onTypeChange(value) : undefined,
1351
+ label: '按模型类型筛选'
1352
+ })
1353
+ )
1354
+ : null,
1355
+ state === 'ready' && models.length > 0 && report.empty
1356
+ ? h('p', { className: 'kb-muted-text' }, '没有匹配的模型;调整搜索关键词或类型筛选。')
1357
+ : null,
1358
+ state === 'ready' && report.groups.length > 0
1359
+ ? h(
1360
+ 'div',
1361
+ { className: 'kb-model-scroll' },
1362
+ report.groups.map((group) =>
1363
+ h(
1364
+ 'div',
1365
+ { key: group.key, className: 'kb-model-group' },
1163
1366
  h(
1164
- 'button',
1165
- {
1166
- type: 'button',
1167
- className: 'kb-model-item',
1168
- 'aria-pressed': active,
1169
- onClick: typeof m.onSelect === 'function' ? () => m.onSelect(key) : undefined
1170
- },
1171
- h(
1172
- 'span',
1173
- { className: 'kb-model-main' },
1174
- h(
1175
- 'span',
1176
- { className: 'kb-model-title' },
1177
- `${item.providerLabel || item.providerId || '—'} · ${item.modelId || '—'}`,
1178
- h(Badge, { variant: item.type === 'vlm' ? 'outline' : 'secondary' }, role)
1179
- ),
1180
- h(
1181
- 'span',
1182
- { className: 'kb-model-url', title: item.baseUrl || '' },
1183
- shortenUrl(item.baseUrl)
1367
+ 'div',
1368
+ { className: 'kb-model-group-head' },
1369
+ h('p', { className: 'kb-model-group-title' }, group.label),
1370
+ h(Badge, { variant: 'outline' }, String(group.total))
1371
+ ),
1372
+ h(
1373
+ 'ul',
1374
+ { className: 'kb-model-list' },
1375
+ group.items.map((item) => {
1376
+ const key = modelSelectionKey(item)
1377
+ const active = key === selectedKey
1378
+ const role = modelRoleLabel(item.type)
1379
+ return h(
1380
+ 'li',
1381
+ { key },
1382
+ h(
1383
+ 'button',
1384
+ {
1385
+ type: 'button',
1386
+ className: 'kb-model-item',
1387
+ 'aria-pressed': active,
1388
+ onClick: typeof m.onSelect === 'function' ? () => m.onSelect(key) : undefined
1389
+ },
1390
+ h(
1391
+ 'span',
1392
+ { className: 'kb-model-main' },
1393
+ h(
1394
+ 'span',
1395
+ { className: 'kb-model-title' },
1396
+ `${item.providerLabel || item.providerId || '—'} · ${item.modelId || '—'}`,
1397
+ h(Badge, { variant: item.type === 'embedding' ? 'secondary' : 'outline' }, role),
1398
+ item.supportsVision === true
1399
+ ? h(Badge, { variant: 'secondary' }, '支持视觉')
1400
+ : null,
1401
+ item.protocolHint ? h(Badge, { variant: 'outline' }, '原生协议') : null
1402
+ ),
1403
+ h(
1404
+ 'span',
1405
+ { className: 'kb-model-url', title: item.baseUrl || '' },
1406
+ shortenUrl(item.baseUrl)
1407
+ ),
1408
+ item.protocolHint
1409
+ ? h(
1410
+ 'span',
1411
+ { className: 'kb-muted-text' },
1412
+ '该路由使用非 OpenAI 原生协议,复制后可能需要在 WeKnora 中调整接口类型。'
1413
+ )
1414
+ : null
1415
+ ),
1416
+ active
1417
+ ? h(
1418
+ 'span',
1419
+ { className: 'kb-model-check', 'aria-hidden': true },
1420
+ h(UiIcon, { name: 'check' })
1421
+ )
1422
+ : null
1423
+ )
1184
1424
  )
1185
- ),
1186
- active
1187
- ? h('span', { className: 'kb-model-check', 'aria-hidden': true }, h(UiIcon, { name: 'check' }))
1188
- : null
1189
- )
1425
+ })
1426
+ ),
1427
+ group.hidden > 0
1428
+ ? h(
1429
+ Button,
1430
+ {
1431
+ variant: 'ghost',
1432
+ size: 'sm',
1433
+ className: 'kb-model-more',
1434
+ onClick: () =>
1435
+ typeof m.onToggleGroup === 'function'
1436
+ ? m.onToggleGroup(group.key)
1437
+ : undefined
1438
+ },
1439
+ `显示更多 ${group.hidden}`
1440
+ )
1441
+ : null,
1442
+ group.expanded && group.total > MODEL_GROUP_LIMIT
1443
+ ? h(
1444
+ Button,
1445
+ {
1446
+ variant: 'ghost',
1447
+ size: 'sm',
1448
+ className: 'kb-model-more',
1449
+ onClick: () =>
1450
+ typeof m.onToggleGroup === 'function'
1451
+ ? m.onToggleGroup(group.key)
1452
+ : undefined
1453
+ },
1454
+ '收起'
1455
+ )
1456
+ : null
1190
1457
  )
1191
- })
1458
+ )
1192
1459
  )
1193
- )
1194
- ),
1460
+ : null,
1195
1461
  m.copyError ? errorAlert(m.copyError, '复制失败') : null,
1196
1462
  result !== null
1197
1463
  ? h(
@@ -1210,6 +1476,33 @@ export function modelCopyView(m = {}) {
1210
1476
  ? h(
1211
1477
  'div',
1212
1478
  { className: 'kb-model-footer' },
1479
+ selectedRoles.length > 1
1480
+ ? h(
1481
+ Select,
1482
+ {
1483
+ value: activeImportRole,
1484
+ disabled: m.importing === true,
1485
+ onValueChange: (next) =>
1486
+ typeof m.onImportRole === 'function' ? m.onImportRole(String(next)) : undefined
1487
+ },
1488
+ h(
1489
+ SelectTrigger,
1490
+ { id: 'kb-model-import-role', className: 'kb-rule-select', 'aria-label': '导入为' },
1491
+ h(SelectValue, null, activeImportRole === 'vlm' ? '仅作为视觉模型 (VLLM)' : '对话模型(含视觉)')
1492
+ ),
1493
+ h(
1494
+ SelectContent,
1495
+ null,
1496
+ selectedRoles.map((role) =>
1497
+ h(
1498
+ SelectItem,
1499
+ { key: role, value: role },
1500
+ role === 'vlm' ? '仅作为视觉模型 (VLLM)' : '对话模型(含视觉)'
1501
+ )
1502
+ )
1503
+ )
1504
+ )
1505
+ : null,
1213
1506
  h(
1214
1507
  Button,
1215
1508
  {
@@ -1234,6 +1527,10 @@ function ModelCopyPanel() {
1234
1527
  const [models, setModels] = useState([])
1235
1528
  const [error, setError] = useState('')
1236
1529
  const [selectedKey, setSelectedKey] = useState('')
1530
+ const [importRole, setImportRole] = useState('')
1531
+ const [query, setQuery] = useState('')
1532
+ const [modelType, setModelType] = useState('all')
1533
+ const [expanded, setExpanded] = useState({})
1237
1534
  const [importing, setImporting] = useState(false)
1238
1535
  const [copyError, setCopyError] = useState('')
1239
1536
  const [result, setResult] = useState(null)
@@ -1246,6 +1543,9 @@ function ModelCopyPanel() {
1246
1543
  const list = Array.isArray(response?.models) ? response.models : []
1247
1544
  setModels(list)
1248
1545
  setSelectedKey('')
1546
+ setQuery('')
1547
+ setModelType('all')
1548
+ setExpanded({})
1249
1549
  setState('ready')
1250
1550
  } catch (err) {
1251
1551
  setError(apiErrorMessage(err))
@@ -1260,8 +1560,9 @@ function ModelCopyPanel() {
1260
1560
  setCopyError('')
1261
1561
  setResult(null)
1262
1562
  try {
1563
+ const role = importRolesFor(selected).includes(importRole) ? importRole : selected.type
1263
1564
  const response = await callAction('kb.models.import', {
1264
- role: selected.type,
1565
+ role,
1265
1566
  providerId: selected.providerId,
1266
1567
  modelId: selected.modelId
1267
1568
  })
@@ -1272,7 +1573,7 @@ function ModelCopyPanel() {
1272
1573
  } finally {
1273
1574
  setImporting(false)
1274
1575
  }
1275
- }, [models, selectedKey])
1576
+ }, [models, selectedKey, importRole])
1276
1577
 
1277
1578
  return modelCopyView({
1278
1579
  open,
@@ -1280,6 +1581,10 @@ function ModelCopyPanel() {
1280
1581
  models,
1281
1582
  error,
1282
1583
  selectedKey,
1584
+ query,
1585
+ type: modelType,
1586
+ expanded,
1587
+ importRole,
1283
1588
  importing,
1284
1589
  copyError,
1285
1590
  result,
@@ -1287,9 +1592,14 @@ function ModelCopyPanel() {
1287
1592
  onLoad: load,
1288
1593
  onSelect: (key) => {
1289
1594
  setSelectedKey(key)
1595
+ setImportRole('')
1290
1596
  setCopyError('')
1291
1597
  setResult(null)
1292
1598
  },
1599
+ onQueryChange: (value) => setQuery(value),
1600
+ onTypeChange: (value) => setModelType(value === '' ? 'all' : value),
1601
+ onToggleGroup: (key) =>
1602
+ setExpanded((current) => ({ ...current, [key]: current[key] !== true })),
1293
1603
  onCopy: copy
1294
1604
  })
1295
1605
  }
@@ -2377,20 +2687,284 @@ function RuleField({ id, label, error, hint, children }) {
2377
2687
  )
2378
2688
  }
2379
2689
 
2380
- function RuleSceneSelect({ value, disabled, onChange }) {
2381
- const selected = RULE_SCENES.find((option) => option.value === value) ?? RULE_SCENES[0]
2690
+ function RuleSceneToggle({ value, disabled, onChange }) {
2691
+ return h(
2692
+ ToggleGroup,
2693
+ {
2694
+ id: 'kb-rule-scene',
2695
+ value: [value],
2696
+ disabled,
2697
+ variant: 'outline',
2698
+ size: 'sm',
2699
+ spacing: 0,
2700
+ 'aria-label': '场景',
2701
+ onValueChange: (next) => {
2702
+ const picked = RULE_SCENES.find((option) => next.includes(option.value) && option.value !== value)
2703
+ if (picked !== undefined) onChange(picked.value)
2704
+ }
2705
+ },
2706
+ RULE_SCENES.map((option) => h(ToggleGroupItem, { key: option.value, value: option.value }, option.label))
2707
+ )
2708
+ }
2709
+
2710
+ function RuleLevelSelect({ value, options, disabled, onChange }) {
2711
+ const levels = Array.isArray(options?.levels) ? options.levels : EMPTY_RULE_OPTIONS.levels
2712
+ const selected = value === '' ? 'none' : value
2382
2713
  return h(
2383
2714
  Select,
2384
- { value, disabled, onValueChange: (next) => onChange(String(next)) },
2715
+ { value: selected, disabled, onValueChange: (next) => onChange(next === 'none' ? '' : String(next)) },
2385
2716
  h(
2386
2717
  SelectTrigger,
2387
- { id: 'kb-rule-scene', className: 'kb-rule-select', 'aria-label': '场景' },
2388
- h(SelectValue, null, selected.label)
2718
+ { id: 'kb-rule-minLevel', className: 'kb-rule-select', 'aria-label': '最低权限等级' },
2719
+ h(
2720
+ SelectValue,
2721
+ null,
2722
+ value === ''
2723
+ ? '不限'
2724
+ : levels.find((level) => String(level.value) === String(value))?.label ?? `${value} 级`
2725
+ )
2389
2726
  ),
2390
2727
  h(
2391
2728
  SelectContent,
2392
2729
  null,
2393
- RULE_SCENES.map((option) => h(SelectItem, { key: option.value, value: option.value }, option.label))
2730
+ h(SelectItem, { value: 'none' }, '不限'),
2731
+ levels.map((level) =>
2732
+ h(SelectItem, { key: String(level.value), value: String(level.value) }, level.label)
2733
+ )
2734
+ )
2735
+ )
2736
+ }
2737
+
2738
+ /**
2739
+ * 可搜索 + 可手输的候选选择器:Combobox 提供真实下拉列表,输入框本身负责手输兜底。
2740
+ * 目录为空时仍可输入任意 ID,留空表示不限;已选旧值不在目录中时照常回显。
2741
+ */
2742
+ function RulePicker({ id, value, options, placeholder, emptyLabel, disabled, onChange }) {
2743
+ const items = []
2744
+ const labels = new Map()
2745
+ for (const item of Array.isArray(options) ? options : []) {
2746
+ const raw = String(item.id)
2747
+ if (labels.has(raw)) continue
2748
+ items.push(raw)
2749
+ const name = typeof item.name === 'string' ? item.name.trim() : ''
2750
+ labels.set(raw, name === '' ? raw : `${name} · ${raw}`)
2751
+ }
2752
+ return h(
2753
+ Combobox,
2754
+ {
2755
+ items,
2756
+ // 只有命中目录的值才算选中;手输的任意 ID 依靠 inputValue 回显。
2757
+ value: items.includes(value) ? value : null,
2758
+ inputValue: value ?? '',
2759
+ disabled,
2760
+ onInputValueChange: (next) => onChange(typeof next === 'string' ? next : ''),
2761
+ onValueChange: (next) => onChange(next === null || next === undefined ? '' : String(next))
2762
+ },
2763
+ h(ComboboxInput, {
2764
+ id,
2765
+ className: 'kb-rule-picker-input',
2766
+ placeholder,
2767
+ disabled,
2768
+ autoComplete: 'off',
2769
+ 'aria-label': placeholder
2770
+ }),
2771
+ h(
2772
+ ComboboxContent,
2773
+ null,
2774
+ h(ComboboxEmpty, null, emptyLabel ?? '无匹配,可直接输入 ID'),
2775
+ h(ComboboxList, null, (raw) =>
2776
+ h(
2777
+ ComboboxItem,
2778
+ { key: raw, value: raw },
2779
+ h('span', { className: 'kb-rule-picker-name' }, labels.get(String(raw)) ?? String(raw))
2780
+ )
2781
+ )
2782
+ )
2783
+ )
2784
+ }
2785
+
2786
+ const RULE_PLATFORM_NONE = '__platform_none__'
2787
+ const RULE_PLATFORM_MANUAL = '__platform_manual__'
2788
+
2789
+ /** 平台优先从已知目录里选;选「其他平台」后回到 Input 手输,自定义值也保持可编辑。 */
2790
+ function RulePlatformSelect({ value, options, disabled, onChange }) {
2791
+ const platforms = (Array.isArray(options) ? options : []).map((item) => String(item.id))
2792
+ const known = value !== '' && platforms.includes(value)
2793
+ const custom = value !== '' && !known
2794
+ const [manual, setManual] = useState(custom)
2795
+ // 自定义值始终可编辑;已进入已知目录的值优先回到下拉项。
2796
+ const showManual = !known && (manual || custom)
2797
+ const selected = showManual ? RULE_PLATFORM_MANUAL : value === '' ? RULE_PLATFORM_NONE : value
2798
+ return h(
2799
+ 'div',
2800
+ { className: 'kb-rule-picker' },
2801
+ h(
2802
+ Select,
2803
+ {
2804
+ value: selected,
2805
+ disabled,
2806
+ onValueChange: (next) => {
2807
+ const picked = String(next)
2808
+ if (picked === RULE_PLATFORM_MANUAL) {
2809
+ setManual(true)
2810
+ if (!custom) onChange('')
2811
+ return
2812
+ }
2813
+ setManual(false)
2814
+ onChange(picked === RULE_PLATFORM_NONE ? '' : picked)
2815
+ }
2816
+ },
2817
+ h(
2818
+ SelectTrigger,
2819
+ { id: 'kb-rule-platform', className: 'kb-rule-select', 'aria-label': '平台' },
2820
+ h(SelectValue, null, showManual ? '其他平台(手动输入)' : value === '' ? '不限' : value)
2821
+ ),
2822
+ h(
2823
+ SelectContent,
2824
+ null,
2825
+ h(SelectItem, { value: RULE_PLATFORM_NONE }, '不限'),
2826
+ platforms.map((platform) => h(SelectItem, { key: platform, value: platform }, platform)),
2827
+ h(SelectItem, { value: RULE_PLATFORM_MANUAL }, '其他平台(手动输入)')
2828
+ )
2829
+ ),
2830
+ showManual
2831
+ ? h(Input, {
2832
+ id: 'kb-rule-platform-manual',
2833
+ type: 'text',
2834
+ value: value ?? '',
2835
+ placeholder: '输入平台名,例如 onebot',
2836
+ disabled,
2837
+ autoComplete: 'off',
2838
+ 'aria-label': '自定义平台',
2839
+ onChange: (event) => onChange(event.target.value)
2840
+ })
2841
+ : null
2842
+ )
2843
+ }
2844
+
2845
+ const RULE_DEFAULT_GLOBAL = '__default_global__'
2846
+
2847
+ function RulePermissionMatrix({ draft, options, disabled, onChange }) {
2848
+ // 目录中的库 + 草稿已引用但目录缺失的 ID,保证旧规则里的库仍可逐项调整。
2849
+ const rows = ruleKbMatrixRows(options?.kbs, draft)
2850
+ const columns = [
2851
+ { key: 'readableKbs', label: '可读' },
2852
+ { key: 'writableKbs', label: '可写' },
2853
+ { key: 'manageableKbs', label: '可管理' }
2854
+ ]
2855
+ const wildcardOf = (key) => parseSpecText(draft[key]).includes(WILDCARD)
2856
+ const currentDefault = draft.defaultKb ?? ''
2857
+ return h(
2858
+ 'div',
2859
+ { className: 'kb-rule-matrix' + (disabled ? ' kb-rule-matrix-disabled' : '') },
2860
+ h(
2861
+ 'div',
2862
+ { className: 'kb-rule-matrix-global' },
2863
+ h('span', { className: 'kb-rule-matrix-title' }, '全部知识库 (*)'),
2864
+ columns.map((column) =>
2865
+ h(
2866
+ 'label',
2867
+ { key: column.key, className: 'kb-rule-check' },
2868
+ h(Checkbox, {
2869
+ checked: wildcardOf(column.key),
2870
+ disabled,
2871
+ 'aria-label': `${column.label}全部`,
2872
+ onCheckedChange: (next) => onChange(column.key, setSpecWildcard(draft[column.key], next === true))
2873
+ }),
2874
+ h('span', null, column.label)
2875
+ )
2876
+ )
2877
+ ),
2878
+ rows.length === 0
2879
+ ? h('p', { className: 'kb-muted-text' }, '引擎离线或暂无知识库;可在下方手动填写 ID。')
2880
+ : null,
2881
+ h(
2882
+ RadioGroup,
2883
+ {
2884
+ className: 'kb-rule-matrix-body',
2885
+ value: currentDefault === '' ? RULE_DEFAULT_GLOBAL : currentDefault,
2886
+ disabled,
2887
+ onValueChange: (next) => onChange('defaultKb', next === RULE_DEFAULT_GLOBAL ? '' : String(next))
2888
+ },
2889
+ rows.length === 0
2890
+ ? null
2891
+ : h(
2892
+ 'div',
2893
+ { className: 'kb-rule-matrix-row kb-rule-matrix-head' },
2894
+ h('span', null, '知识库'),
2895
+ columns.map((column) => h('span', { key: column.key }, column.label)),
2896
+ h('span', null, '默认')
2897
+ ),
2898
+ rows.map((kb) =>
2899
+ h(
2900
+ 'div',
2901
+ { key: kb.id, className: 'kb-rule-matrix-row' },
2902
+ h(
2903
+ 'span',
2904
+ { className: 'kb-rule-matrix-kb', title: kb.id },
2905
+ h('span', { className: 'kb-rule-matrix-name' }, kb.known ? kb.name || kb.id : '(目录外知识库)'),
2906
+ h('code', { className: 'kb-rule-matrix-id' }, kb.id)
2907
+ ),
2908
+ columns.map((column) => {
2909
+ const wildcard = wildcardOf(column.key)
2910
+ return h(
2911
+ 'label',
2912
+ { key: column.key, className: 'kb-rule-check' },
2913
+ h(Checkbox, {
2914
+ checked: wildcard || specHasValue(draft[column.key], kb.id),
2915
+ disabled: disabled || wildcard,
2916
+ 'aria-label': `${column.label} ${kb.id}`,
2917
+ onCheckedChange: (next) =>
2918
+ onChange(column.key, toggleSpecValue(draft[column.key], kb.id, next === true))
2919
+ })
2920
+ )
2921
+ }),
2922
+ h(
2923
+ 'span',
2924
+ { className: 'kb-rule-matrix-cell' },
2925
+ h(RadioGroupItem, { value: kb.id, 'aria-label': `默认知识库 ${kb.name || kb.id}` })
2926
+ )
2927
+ )
2928
+ ),
2929
+ h(
2930
+ 'div',
2931
+ { className: 'kb-rule-matrix-row kb-rule-matrix-default-row' },
2932
+ h('span', { className: 'kb-rule-matrix-default-label' }, '默认知识库沿用全局默认'),
2933
+ h(
2934
+ 'span',
2935
+ { className: 'kb-rule-matrix-cell' },
2936
+ h(RadioGroupItem, { value: RULE_DEFAULT_GLOBAL, 'aria-label': '默认知识库沿用全局默认' })
2937
+ )
2938
+ )
2939
+ ),
2940
+ h(
2941
+ 'details',
2942
+ { className: 'kb-rule-advanced' },
2943
+ h('summary', null, '自定义知识库 ID(兜底)'),
2944
+ columns.map((column) =>
2945
+ h(
2946
+ RuleField,
2947
+ { key: column.key, id: `kb-rule-${column.key}`, label: column.label },
2948
+ h(RuleInput, {
2949
+ id: `kb-rule-${column.key}`,
2950
+ value: draft[column.key] ?? '',
2951
+ placeholder: '逗号分隔;* 表示全部',
2952
+ disabled,
2953
+ onChange: (next) => onChange(column.key, next)
2954
+ })
2955
+ )
2956
+ ),
2957
+ h(
2958
+ RuleField,
2959
+ { id: 'kb-rule-defaultKb', label: '默认知识库 ID / 名称' },
2960
+ h(RuleInput, {
2961
+ id: 'kb-rule-defaultKb',
2962
+ value: draft.defaultKb ?? '',
2963
+ placeholder: '留空使用全局默认',
2964
+ disabled,
2965
+ onChange: (next) => onChange('defaultKb', next)
2966
+ })
2967
+ )
2394
2968
  )
2395
2969
  )
2396
2970
  }
@@ -2418,6 +2992,7 @@ export function RuleEditor({
2418
2992
  errors = {},
2419
2993
  formError = '',
2420
2994
  saving = false,
2995
+ options = EMPTY_RULE_OPTIONS,
2421
2996
  onChange,
2422
2997
  onClose,
2423
2998
  onSubmit
@@ -2425,19 +3000,20 @@ export function RuleEditor({
2425
3000
  const change = (key) => (value) => {
2426
3001
  if (typeof onChange === 'function') onChange(key, value)
2427
3002
  }
2428
- const field = (key, label, options = {}) =>
2429
- h(
2430
- RuleField,
2431
- { id: `kb-rule-${key}`, label, error: errors[key], hint: options.hint },
2432
- h(RuleInput, {
2433
- id: `kb-rule-${key}`,
2434
- value: draft[key] ?? '',
2435
- placeholder: options.placeholder,
2436
- type: options.type,
2437
- disabled: saving,
2438
- onChange: change(key)
2439
- })
2440
- )
3003
+ const scene = draft.scene ?? 'all'
3004
+ const platforms = (Array.isArray(options?.platforms) ? options.platforms : []).map((platform) => ({
3005
+ id: String(platform),
3006
+ name: String(platform)
3007
+ }))
3008
+ // 未选平台时展示全部候选;选了平台才按平台收窄。
3009
+ const byPlatform = (items) =>
3010
+ draft.platform === ''
3011
+ ? items
3012
+ : items.filter(
3013
+ (item) => item?.platform === undefined || item.platform === '' || item.platform === draft.platform
3014
+ )
3015
+ const guilds = byPlatform(Array.isArray(options?.guilds) ? options.guilds : [])
3016
+ const users = byPlatform(Array.isArray(options?.users) ? options.users : [])
2441
3017
  return h(
2442
3018
  Dialog,
2443
3019
  {
@@ -2448,7 +3024,7 @@ export function RuleEditor({
2448
3024
  },
2449
3025
  h(
2450
3026
  DialogContent,
2451
- { className: 'kb-rule-dialog' },
3027
+ { className: 'kb-rule-dialog kb-rule-dialog-wide' },
2452
3028
  h(
2453
3029
  DialogHeader,
2454
3030
  null,
@@ -2456,7 +3032,7 @@ export function RuleEditor({
2456
3032
  h(
2457
3033
  DialogDescription,
2458
3034
  null,
2459
- '场景「私聊」保存为后端 direct;知识库可填 ID 或名称,多个用逗号分隔,* 表示全部。保存后以实时规则为准。'
3035
+ '能选的都不用手填;需要离线对象时仍可直接输入 ID。私聊保存为后端 direct,保存后以实时规则为准。'
2460
3036
  )
2461
3037
  ),
2462
3038
  formError !== '' ? errorAlert(formError, '保存失败') : null,
@@ -2469,17 +3045,74 @@ export function RuleEditor({
2469
3045
  h(
2470
3046
  RuleField,
2471
3047
  { id: 'kb-rule-scene', label: '场景' },
2472
- h(RuleSceneSelect, { value: draft.scene, disabled: saving, onChange: change('scene') })
3048
+ h(RuleSceneToggle, {
3049
+ value: scene,
3050
+ disabled: saving,
3051
+ onChange: (next) => {
3052
+ change('scene')(next)
3053
+ if (next === 'private' && (draft.guildId ?? '') !== '') change('guildId')('')
3054
+ }
3055
+ })
2473
3056
  ),
2474
- field('platform', '平台', { placeholder: '例如 onebot;留空为不限' }),
2475
- field('guildId', '群 ID', { placeholder: '留空为不限' }),
2476
- field('userId', '用户 ID', { placeholder: '留空为不限' }),
2477
- field('minLevel', '最低权限等级', { type: 'number', placeholder: '0-5;留空为不限' }),
2478
- field('defaultKb', '默认知识库', { placeholder: '知识库 ID 或名称;留空用全局默认' })
3057
+ h(
3058
+ RuleField,
3059
+ { id: 'kb-rule-minLevel', label: '最低权限等级', error: errors.minLevel },
3060
+ h(RuleLevelSelect, {
3061
+ value: draft.minLevel ?? '',
3062
+ options,
3063
+ disabled: saving,
3064
+ onChange: change('minLevel')
3065
+ })
3066
+ ),
3067
+ h(
3068
+ RuleField,
3069
+ { id: 'kb-rule-platform', label: '平台', error: errors.platform },
3070
+ h(RulePlatformSelect, {
3071
+ value: draft.platform ?? '',
3072
+ options: platforms,
3073
+ disabled: saving,
3074
+ onChange: change('platform')
3075
+ })
3076
+ ),
3077
+ scene !== 'private'
3078
+ ? h(
3079
+ RuleField,
3080
+ { id: 'kb-rule-guildId', label: '群', error: errors.guildId },
3081
+ h(RulePicker, {
3082
+ id: 'kb-rule-guildId',
3083
+ value: draft.guildId ?? '',
3084
+ options: guilds,
3085
+ placeholder: '不限;搜索群名称或直接输入群 ID',
3086
+ emptyLabel: '引擎离线或暂无群,可直接输入群 ID',
3087
+ disabled: saving,
3088
+ onChange: change('guildId')
3089
+ })
3090
+ )
3091
+ : null,
3092
+ h(
3093
+ RuleField,
3094
+ { id: 'kb-rule-userId', label: '用户', error: errors.userId },
3095
+ h(RulePicker, {
3096
+ id: 'kb-rule-userId',
3097
+ value: draft.userId ?? '',
3098
+ options: users,
3099
+ placeholder: '不限;搜索昵称或直接输入用户 ID',
3100
+ emptyLabel: '引擎离线或暂无用户,可直接输入用户 ID',
3101
+ disabled: saving,
3102
+ onChange: change('userId')
3103
+ })
3104
+ )
2479
3105
  ),
2480
- field('readableKbs', '可读知识库', { placeholder: '逗号分隔;* 表示全部' }),
2481
- field('writableKbs', '可写知识库', { placeholder: '逗号分隔;* 表示全部' }),
2482
- field('manageableKbs', '可管理知识库', { placeholder: '逗号分隔;* 表示全部' })
3106
+ h(
3107
+ RuleField,
3108
+ { id: 'kb-rule-permissions', label: '知识库权限', error: errors.readableKbs || errors.writableKbs || errors.manageableKbs },
3109
+ h(RulePermissionMatrix, {
3110
+ draft,
3111
+ options,
3112
+ disabled: saving,
3113
+ onChange: (key, value) => change(key)(value)
3114
+ })
3115
+ )
2483
3116
  ),
2484
3117
  h(
2485
3118
  DialogFooter,
@@ -2499,8 +3132,10 @@ export function RulesTab({ snapshot }) {
2499
3132
  const [formError, setFormError] = useState('')
2500
3133
  const [saving, setSaving] = useState(false)
2501
3134
  const [confirmTarget, setConfirmTarget] = useState(null)
3135
+ const [ruleOptions, setRuleOptions] = useState(EMPTY_RULE_OPTIONS)
2502
3136
  // React 的 setState 不是同步生效的;用 ref 拦住同一帧内的重复提交。
2503
3137
  const savingRef = useRef(false)
3138
+ const optionsRequestedRef = useRef(false)
2504
3139
  const rules = rulesOf(snapshot)
2505
3140
  const live = snapshot?.status ?? 'loading'
2506
3141
  const report = rulesReport(rules, query, scene)
@@ -2514,6 +3149,30 @@ export function RulesTab({ snapshot }) {
2514
3149
  const ready = !broken && live !== 'loading'
2515
3150
  const busy = saving
2516
3151
 
3152
+ // 候选目录只用于选择题供数;ready 后只请求一次,失败保持空数组,手动输入始终可用。
3153
+ useEffect(() => {
3154
+ if (!ready || optionsRequestedRef.current) return undefined
3155
+ optionsRequestedRef.current = true
3156
+ let current = true
3157
+ callAction('kb.ruleOptions', {})
3158
+ .then((response) => {
3159
+ const options = response?.options ?? response
3160
+ if (current && options !== null && typeof options === 'object') {
3161
+ setRuleOptions({
3162
+ platforms: Array.isArray(options.platforms) ? options.platforms : [],
3163
+ guilds: Array.isArray(options.guilds) ? options.guilds : [],
3164
+ users: Array.isArray(options.users) ? options.users : [],
3165
+ kbs: Array.isArray(options.kbs) ? options.kbs : [],
3166
+ levels: Array.isArray(options.levels) && options.levels.length > 0 ? options.levels : EMPTY_RULE_OPTIONS.levels
3167
+ })
3168
+ }
3169
+ })
3170
+ .catch(() => {})
3171
+ return () => {
3172
+ current = false
3173
+ }
3174
+ }, [ready])
3175
+
2517
3176
  // 写入只走 kb.saveRules;保存前重读实时规则,列表与顺序永远以 live 为准。
2518
3177
  const persist = async (nextRules, message) => {
2519
3178
  if (savingRef.current) return false
@@ -2730,6 +3389,7 @@ export function RulesTab({ snapshot }) {
2730
3389
  errors,
2731
3390
  formError,
2732
3391
  saving,
3392
+ options: ruleOptions,
2733
3393
  onChange: updateDraft,
2734
3394
  onClose: closeEditor,
2735
3395
  onSubmit: submitEditor