chatluna-plugin-kb 0.1.0 → 0.1.2

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,6 +28,7 @@ import {
28
28
  CardFooter,
29
29
  CardHeader,
30
30
  CardTitle,
31
+ Checkbox,
31
32
  CodeValue,
32
33
  Collapsible,
33
34
  CollapsibleContent,
@@ -49,6 +50,8 @@ import {
49
50
  Input,
50
51
  PageHeader,
51
52
  Progress,
53
+ RadioGroup,
54
+ RadioGroupItem,
52
55
  SearchBox,
53
56
  Section,
54
57
  Select,
@@ -61,6 +64,8 @@ import {
61
64
  TabsContent,
62
65
  TabsList,
63
66
  TabsTrigger,
67
+ ToggleGroup,
68
+ ToggleGroupItem,
64
69
  Tooltip,
65
70
  TooltipContent,
66
71
  TooltipTrigger,
@@ -509,6 +514,22 @@ export const RULE_SCENES = [
509
514
  ]
510
515
  const RULE_LEVEL_MAX = 5
511
516
 
517
+ /** 规则编辑器的候选目录;获取失败时仍可用手动输入。 */
518
+ export const EMPTY_RULE_OPTIONS = {
519
+ platforms: [],
520
+ guilds: [],
521
+ users: [],
522
+ kbs: [],
523
+ levels: [
524
+ { value: 0, label: '0 · 访客' },
525
+ { value: 1, label: '1 · 普通用户' },
526
+ { value: 2, label: '2 · 成员' },
527
+ { value: 3, label: '3 · 群管' },
528
+ { value: 4, label: '4 · 管理员' },
529
+ { value: 5, label: '5 · 主人' }
530
+ ]
531
+ }
532
+
512
533
  /** 新建规则的空白草稿:默认兜底规则(all + 无匹配条件)。 */
513
534
  export function emptyRuleDraft() {
514
535
  return {
@@ -549,6 +570,61 @@ export function parseSpecText(value) {
549
570
  return specList(raw)
550
571
  }
551
572
 
573
+ /** 权限矩阵里某一列是否已勾选指定知识库;'*' 通配时不代表单库命中。 */
574
+ export function specHasValue(text, value) {
575
+ const key = draftText(value).toLowerCase()
576
+ if (key === '') return false
577
+ return parseSpecText(text).some((item) => item !== WILDCARD && item.toLowerCase() === key)
578
+ }
579
+
580
+ /**
581
+ * 勾选/取消矩阵里的单个知识库,保持草稿仍是一段逗号分隔文本。
582
+ * - 已存在 '*' 时保持通配,绝不把宽权限悄悄收敛成单库。
583
+ * - 取消后列表为空则回退到空字符串(序列化为 [])。
584
+ */
585
+ export function toggleSpecValue(text, value, checked) {
586
+ const item = draftText(value)
587
+ const list = parseSpecText(text)
588
+ if (item === '' || item === WILDCARD) return list.join(', ')
589
+ if (list[0] === WILDCARD) return WILDCARD
590
+ const key = item.toLowerCase()
591
+ const has = list.some((entry) => entry.toLowerCase() === key)
592
+ if (checked === true) return has ? list.join(', ') : [...list, item].join(', ')
593
+ return has ? list.filter((entry) => entry.toLowerCase() !== key).join(', ') : list.join(', ')
594
+ }
595
+
596
+ /** 「全部 (*)」列开关:打开写入 '*',关闭只移除通配符并保留其余显式项。 */
597
+ export function setSpecWildcard(text, all) {
598
+ if (all === true) return WILDCARD
599
+ return parseSpecText(text).filter((item) => item !== WILDCARD).join(', ')
600
+ }
601
+
602
+ /**
603
+ * 权限矩阵需要渲染的库:目录中的库在前,再合并草稿里已引用但目录缺失的 ID。
604
+ * 顺序稳定、按小写去重;'*' 不是库,跳过。
605
+ */
606
+ export function ruleKbMatrixRows(kbs, draft) {
607
+ const source = draft !== null && typeof draft === 'object' ? draft : {}
608
+ const out = []
609
+ const seen = new Set()
610
+ const add = (id, name, known = false) => {
611
+ const text = draftText(id)
612
+ if (text === '' || text === WILDCARD) return
613
+ const key = text.toLowerCase()
614
+ if (seen.has(key)) return
615
+ seen.add(key)
616
+ out.push({ id: text, name: draftText(name), known: known === true })
617
+ }
618
+ for (const kb of Array.isArray(kbs) ? kbs : []) {
619
+ if (kb === null || typeof kb !== 'object') continue
620
+ add(kb.id, kb.name, true)
621
+ }
622
+ for (const field of ['readableKbs', 'writableKbs', 'manageableKbs', 'defaultKb']) {
623
+ for (const id of parseSpecText(source[field])) add(id, '')
624
+ }
625
+ return out
626
+ }
627
+
552
628
  const draftText = (value) => (typeof value === 'string' ? value.trim() : '')
553
629
 
554
630
  /** 字段级校验;只报告错误,绝不静默改写用户输入。 */
@@ -1045,7 +1121,23 @@ function engineOfflineCard(status, actions, options) {
1045
1121
 
1046
1122
  // ---- 从 ChatLuna 复制模型配置 ---------------------------------------------
1047
1123
  // 列表只来自服务端脱敏元数据;页面从不接收、保存或展示 API Key。
1048
- const MODEL_TYPE_LABELS = { embedding: 'Embedding 模型', vlm: '视觉模型(VLM)' }
1124
+ const MODEL_TYPE_LABELS = {
1125
+ chat: '对话模型',
1126
+ embedding: 'Embedding 模型',
1127
+ vlm: '视觉模型(VLM)',
1128
+ rerank: 'ReRank 模型'
1129
+ }
1130
+ const MODEL_TYPE_ORDER = ['chat', 'embedding', 'vlm', 'rerank']
1131
+
1132
+ function modelRoleLabel(role) {
1133
+ return role === 'vlm' ? 'VLM' : role === 'chat' ? '对话' : role === 'rerank' ? 'ReRank' : 'Embedding'
1134
+ }
1135
+
1136
+ function importRolesFor(item) {
1137
+ const roles = [item?.type]
1138
+ if (item?.type === 'chat' && item?.supportsVision === true) roles.push('vlm')
1139
+ return roles.filter((role) => MODEL_TYPE_LABELS[role] !== undefined)
1140
+ }
1049
1141
 
1050
1142
  function shortenUrl(value, max = 52) {
1051
1143
  const text = typeof value === 'string' ? value : ''
@@ -1078,10 +1170,12 @@ export function modelCopyView(m = {}) {
1078
1170
  const models = Array.isArray(m.models) ? m.models : []
1079
1171
  const selectedKey = typeof m.selectedKey === 'string' ? m.selectedKey : ''
1080
1172
  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)
1173
+ const groups = MODEL_TYPE_ORDER.map((type) => ({
1174
+ type,
1175
+ items: models.filter((item) => item?.type === type)
1176
+ })).filter((group) => group.items.length > 0)
1177
+ const selectedRoles = selected === null ? [] : importRolesFor(selected)
1178
+ const activeImportRole = selectedRoles.includes(m.importRole) ? m.importRole : selected?.type
1085
1179
  const result = m.result !== null && typeof m.result === 'object' ? m.result : null
1086
1180
  const open = m.open === true
1087
1181
  const state = typeof m.state === 'string' ? m.state : 'idle'
@@ -1140,10 +1234,10 @@ export function modelCopyView(m = {}) {
1140
1234
  ? errorAlert(m.error, '读取模型列表失败')
1141
1235
  : null,
1142
1236
  state === 'idle'
1143
- ? h('p', { className: 'kb-muted-text' }, '点击「加载模型列表」查看可复制的 Embedding / VLM 模型。')
1237
+ ? h('p', { className: 'kb-muted-text' }, '点击「加载模型列表」查看可复制的对话 / Embedding / VLM / ReRank 模型。')
1144
1238
  : null,
1145
1239
  state === 'ready' && models.length === 0
1146
- ? h('p', { className: 'kb-muted-text' }, 'ChatLuna 暂无可用于复制的 Embedding / VLM 模型。')
1240
+ ? h('p', { className: 'kb-muted-text' }, 'ChatLuna 暂无可用于复制的知识库模型。')
1147
1241
  : null,
1148
1242
  groups.map((group) =>
1149
1243
  h(
@@ -1156,7 +1250,8 @@ export function modelCopyView(m = {}) {
1156
1250
  group.items.map((item) => {
1157
1251
  const key = modelSelectionKey(item)
1158
1252
  const active = key === selectedKey
1159
- const role = item.type === 'vlm' ? 'VLM' : 'Embedding'
1253
+ const role = modelRoleLabel(item.type)
1254
+ const roles = importRolesFor(item)
1160
1255
  return h(
1161
1256
  'li',
1162
1257
  { key },
@@ -1175,13 +1270,23 @@ export function modelCopyView(m = {}) {
1175
1270
  'span',
1176
1271
  { className: 'kb-model-title' },
1177
1272
  `${item.providerLabel || item.providerId || '—'} · ${item.modelId || '—'}`,
1178
- h(Badge, { variant: item.type === 'vlm' ? 'outline' : 'secondary' }, role)
1273
+ h(Badge, { variant: item.type === 'embedding' ? 'secondary' : 'outline' }, role),
1274
+ item.supportsVision === true ? h(Badge, { variant: 'secondary' }, '支持视觉') : null,
1275
+ item.protocolHint ? h(Badge, { variant: 'outline' }, '原生协议') : null
1179
1276
  ),
1180
1277
  h(
1181
1278
  'span',
1182
1279
  { className: 'kb-model-url', title: item.baseUrl || '' },
1183
1280
  shortenUrl(item.baseUrl)
1184
- )
1281
+ ),
1282
+ item.protocolHint
1283
+ ? h(
1284
+ 'span',
1285
+ { className: 'kb-muted-text' },
1286
+ '该路由使用非 OpenAI 原生协议,复制后可能需要在 WeKnora 中调整接口类型。'
1287
+ )
1288
+ : null
1289
+
1185
1290
  ),
1186
1291
  active
1187
1292
  ? h('span', { className: 'kb-model-check', 'aria-hidden': true }, h(UiIcon, { name: 'check' }))
@@ -1210,6 +1315,33 @@ export function modelCopyView(m = {}) {
1210
1315
  ? h(
1211
1316
  'div',
1212
1317
  { className: 'kb-model-footer' },
1318
+ selectedRoles.length > 1
1319
+ ? h(
1320
+ Select,
1321
+ {
1322
+ value: activeImportRole,
1323
+ disabled: m.importing === true,
1324
+ onValueChange: (next) =>
1325
+ typeof m.onImportRole === 'function' ? m.onImportRole(String(next)) : undefined
1326
+ },
1327
+ h(
1328
+ SelectTrigger,
1329
+ { id: 'kb-model-import-role', className: 'kb-rule-select', 'aria-label': '导入为' },
1330
+ h(SelectValue, null, activeImportRole === 'vlm' ? '仅作为视觉模型 (VLLM)' : '对话模型(含视觉)')
1331
+ ),
1332
+ h(
1333
+ SelectContent,
1334
+ null,
1335
+ selectedRoles.map((role) =>
1336
+ h(
1337
+ SelectItem,
1338
+ { key: role, value: role },
1339
+ role === 'vlm' ? '仅作为视觉模型 (VLLM)' : '对话模型(含视觉)'
1340
+ )
1341
+ )
1342
+ )
1343
+ )
1344
+ : null,
1213
1345
  h(
1214
1346
  Button,
1215
1347
  {
@@ -1234,6 +1366,7 @@ function ModelCopyPanel() {
1234
1366
  const [models, setModels] = useState([])
1235
1367
  const [error, setError] = useState('')
1236
1368
  const [selectedKey, setSelectedKey] = useState('')
1369
+ const [importRole, setImportRole] = useState('')
1237
1370
  const [importing, setImporting] = useState(false)
1238
1371
  const [copyError, setCopyError] = useState('')
1239
1372
  const [result, setResult] = useState(null)
@@ -1260,8 +1393,9 @@ function ModelCopyPanel() {
1260
1393
  setCopyError('')
1261
1394
  setResult(null)
1262
1395
  try {
1396
+ const role = importRolesFor(selected).includes(importRole) ? importRole : selected.type
1263
1397
  const response = await callAction('kb.models.import', {
1264
- role: selected.type,
1398
+ role,
1265
1399
  providerId: selected.providerId,
1266
1400
  modelId: selected.modelId
1267
1401
  })
@@ -1272,7 +1406,7 @@ function ModelCopyPanel() {
1272
1406
  } finally {
1273
1407
  setImporting(false)
1274
1408
  }
1275
- }, [models, selectedKey])
1409
+ }, [models, selectedKey, importRole])
1276
1410
 
1277
1411
  return modelCopyView({
1278
1412
  open,
@@ -1280,6 +1414,7 @@ function ModelCopyPanel() {
1280
1414
  models,
1281
1415
  error,
1282
1416
  selectedKey,
1417
+ importRole,
1283
1418
  importing,
1284
1419
  copyError,
1285
1420
  result,
@@ -1287,6 +1422,7 @@ function ModelCopyPanel() {
1287
1422
  onLoad: load,
1288
1423
  onSelect: (key) => {
1289
1424
  setSelectedKey(key)
1425
+ setImportRole('')
1290
1426
  setCopyError('')
1291
1427
  setResult(null)
1292
1428
  },
@@ -2377,20 +2513,272 @@ function RuleField({ id, label, error, hint, children }) {
2377
2513
  )
2378
2514
  }
2379
2515
 
2380
- function RuleSceneSelect({ value, disabled, onChange }) {
2381
- const selected = RULE_SCENES.find((option) => option.value === value) ?? RULE_SCENES[0]
2516
+ function RuleSceneToggle({ value, disabled, onChange }) {
2517
+ return h(
2518
+ ToggleGroup,
2519
+ {
2520
+ id: 'kb-rule-scene',
2521
+ value: [value],
2522
+ disabled,
2523
+ variant: 'outline',
2524
+ size: 'sm',
2525
+ spacing: 0,
2526
+ 'aria-label': '场景',
2527
+ onValueChange: (next) => {
2528
+ const picked = RULE_SCENES.find((option) => next.includes(option.value) && option.value !== value)
2529
+ if (picked !== undefined) onChange(picked.value)
2530
+ }
2531
+ },
2532
+ RULE_SCENES.map((option) => h(ToggleGroupItem, { key: option.value, value: option.value }, option.label))
2533
+ )
2534
+ }
2535
+
2536
+ function RuleLevelSelect({ value, options, disabled, onChange }) {
2537
+ const levels = Array.isArray(options?.levels) ? options.levels : EMPTY_RULE_OPTIONS.levels
2538
+ const selected = value === '' ? 'none' : value
2382
2539
  return h(
2383
2540
  Select,
2384
- { value, disabled, onValueChange: (next) => onChange(String(next)) },
2541
+ { value: selected, disabled, onValueChange: (next) => onChange(next === 'none' ? '' : String(next)) },
2385
2542
  h(
2386
2543
  SelectTrigger,
2387
- { id: 'kb-rule-scene', className: 'kb-rule-select', 'aria-label': '场景' },
2388
- h(SelectValue, null, selected.label)
2544
+ { id: 'kb-rule-minLevel', className: 'kb-rule-select', 'aria-label': '最低权限等级' },
2545
+ h(
2546
+ SelectValue,
2547
+ null,
2548
+ value === ''
2549
+ ? '不限'
2550
+ : levels.find((level) => String(level.value) === String(value))?.label ?? `${value} 级`
2551
+ )
2389
2552
  ),
2390
2553
  h(
2391
2554
  SelectContent,
2392
2555
  null,
2393
- RULE_SCENES.map((option) => h(SelectItem, { key: option.value, value: option.value }, option.label))
2556
+ h(SelectItem, { value: 'none' }, '不限'),
2557
+ levels.map((level) =>
2558
+ h(SelectItem, { key: String(level.value), value: String(level.value) }, level.label)
2559
+ )
2560
+ )
2561
+ )
2562
+ }
2563
+
2564
+ /**
2565
+ * 可搜索 + 可手输:ui-kit Input 加原生 datalist(value=ID,label 带名称)。
2566
+ * 目录为空时仍可输入任意 ID,留空表示不限。
2567
+ */
2568
+ function RulePicker({ id, value, options, placeholder, disabled, onChange }) {
2569
+ const listId = `${id}-options`
2570
+ return h(
2571
+ 'div',
2572
+ { className: 'kb-rule-picker' },
2573
+ h(Input, {
2574
+ id,
2575
+ type: 'text',
2576
+ value: value ?? '',
2577
+ placeholder,
2578
+ disabled,
2579
+ autoComplete: 'off',
2580
+ list: listId,
2581
+ 'aria-label': placeholder,
2582
+ onChange: (event) => onChange(event.target.value)
2583
+ }),
2584
+ h(
2585
+ 'datalist',
2586
+ { id: listId },
2587
+ (Array.isArray(options) ? options : []).map((item) => {
2588
+ const raw = String(item.id)
2589
+ const name = typeof item.name === 'string' ? item.name.trim() : ''
2590
+ return h('option', {
2591
+ key: `${item.platform ?? ''}\u0000${raw}`,
2592
+ value: raw,
2593
+ label: name === '' ? raw : `${name} · ${raw}`
2594
+ })
2595
+ })
2596
+ )
2597
+ )
2598
+ }
2599
+
2600
+ const RULE_PLATFORM_NONE = '__platform_none__'
2601
+ const RULE_PLATFORM_MANUAL = '__platform_manual__'
2602
+
2603
+ /** 平台优先从已知目录里选;选「其他平台」后回到 Input 手输,自定义值也保持可编辑。 */
2604
+ function RulePlatformSelect({ value, options, disabled, onChange }) {
2605
+ const platforms = (Array.isArray(options) ? options : []).map((item) => String(item.id))
2606
+ const known = value !== '' && platforms.includes(value)
2607
+ const custom = value !== '' && !known
2608
+ const [manual, setManual] = useState(custom)
2609
+ // 自定义值始终可编辑;已进入已知目录的值优先回到下拉项。
2610
+ const showManual = !known && (manual || custom)
2611
+ const selected = showManual ? RULE_PLATFORM_MANUAL : value === '' ? RULE_PLATFORM_NONE : value
2612
+ return h(
2613
+ 'div',
2614
+ { className: 'kb-rule-picker' },
2615
+ h(
2616
+ Select,
2617
+ {
2618
+ value: selected,
2619
+ disabled,
2620
+ onValueChange: (next) => {
2621
+ const picked = String(next)
2622
+ if (picked === RULE_PLATFORM_MANUAL) {
2623
+ setManual(true)
2624
+ if (!custom) onChange('')
2625
+ return
2626
+ }
2627
+ setManual(false)
2628
+ onChange(picked === RULE_PLATFORM_NONE ? '' : picked)
2629
+ }
2630
+ },
2631
+ h(
2632
+ SelectTrigger,
2633
+ { id: 'kb-rule-platform', className: 'kb-rule-select', 'aria-label': '平台' },
2634
+ h(SelectValue, null, showManual ? '其他平台(手动输入)' : value === '' ? '不限' : value)
2635
+ ),
2636
+ h(
2637
+ SelectContent,
2638
+ null,
2639
+ h(SelectItem, { value: RULE_PLATFORM_NONE }, '不限'),
2640
+ platforms.map((platform) => h(SelectItem, { key: platform, value: platform }, platform)),
2641
+ h(SelectItem, { value: RULE_PLATFORM_MANUAL }, '其他平台(手动输入)')
2642
+ )
2643
+ ),
2644
+ showManual
2645
+ ? h(Input, {
2646
+ id: 'kb-rule-platform-manual',
2647
+ type: 'text',
2648
+ value: value ?? '',
2649
+ placeholder: '输入平台名,例如 onebot',
2650
+ disabled,
2651
+ autoComplete: 'off',
2652
+ 'aria-label': '自定义平台',
2653
+ onChange: (event) => onChange(event.target.value)
2654
+ })
2655
+ : null
2656
+ )
2657
+ }
2658
+
2659
+ const RULE_DEFAULT_GLOBAL = '__default_global__'
2660
+
2661
+ function RulePermissionMatrix({ draft, options, disabled, onChange }) {
2662
+ // 目录中的库 + 草稿已引用但目录缺失的 ID,保证旧规则里的库仍可逐项调整。
2663
+ const rows = ruleKbMatrixRows(options?.kbs, draft)
2664
+ const columns = [
2665
+ { key: 'readableKbs', label: '可读' },
2666
+ { key: 'writableKbs', label: '可写' },
2667
+ { key: 'manageableKbs', label: '可管理' }
2668
+ ]
2669
+ const wildcardOf = (key) => parseSpecText(draft[key]).includes(WILDCARD)
2670
+ const currentDefault = draft.defaultKb ?? ''
2671
+ return h(
2672
+ 'div',
2673
+ { className: 'kb-rule-matrix' + (disabled ? ' kb-rule-matrix-disabled' : '') },
2674
+ h(
2675
+ 'div',
2676
+ { className: 'kb-rule-matrix-global' },
2677
+ h('span', { className: 'kb-rule-matrix-title' }, '全部知识库 (*)'),
2678
+ columns.map((column) =>
2679
+ h(
2680
+ 'label',
2681
+ { key: column.key, className: 'kb-rule-check' },
2682
+ h(Checkbox, {
2683
+ checked: wildcardOf(column.key),
2684
+ disabled,
2685
+ 'aria-label': `${column.label}全部`,
2686
+ onCheckedChange: (next) => onChange(column.key, setSpecWildcard(draft[column.key], next === true))
2687
+ }),
2688
+ h('span', null, column.label)
2689
+ )
2690
+ )
2691
+ ),
2692
+ rows.length === 0
2693
+ ? h('p', { className: 'kb-muted-text' }, '引擎离线或暂无知识库;可在下方手动填写 ID。')
2694
+ : null,
2695
+ h(
2696
+ RadioGroup,
2697
+ {
2698
+ className: 'kb-rule-matrix-body',
2699
+ value: currentDefault === '' ? RULE_DEFAULT_GLOBAL : currentDefault,
2700
+ disabled,
2701
+ onValueChange: (next) => onChange('defaultKb', next === RULE_DEFAULT_GLOBAL ? '' : String(next))
2702
+ },
2703
+ rows.length === 0
2704
+ ? null
2705
+ : h(
2706
+ 'div',
2707
+ { className: 'kb-rule-matrix-row kb-rule-matrix-head' },
2708
+ h('span', null, '知识库'),
2709
+ columns.map((column) => h('span', { key: column.key }, column.label)),
2710
+ h('span', null, '默认')
2711
+ ),
2712
+ rows.map((kb) =>
2713
+ h(
2714
+ 'div',
2715
+ { key: kb.id, className: 'kb-rule-matrix-row' },
2716
+ h(
2717
+ 'span',
2718
+ { className: 'kb-rule-matrix-kb', title: kb.id },
2719
+ h('span', { className: 'kb-rule-matrix-name' }, kb.known ? kb.name || kb.id : '(目录外知识库)'),
2720
+ h('code', { className: 'kb-rule-matrix-id' }, kb.id)
2721
+ ),
2722
+ columns.map((column) => {
2723
+ const wildcard = wildcardOf(column.key)
2724
+ return h(
2725
+ 'label',
2726
+ { key: column.key, className: 'kb-rule-check' },
2727
+ h(Checkbox, {
2728
+ checked: wildcard || specHasValue(draft[column.key], kb.id),
2729
+ disabled: disabled || wildcard,
2730
+ 'aria-label': `${column.label} ${kb.id}`,
2731
+ onCheckedChange: (next) =>
2732
+ onChange(column.key, toggleSpecValue(draft[column.key], kb.id, next === true))
2733
+ })
2734
+ )
2735
+ }),
2736
+ h(
2737
+ 'span',
2738
+ { className: 'kb-rule-matrix-cell' },
2739
+ h(RadioGroupItem, { value: kb.id, 'aria-label': `默认知识库 ${kb.name || kb.id}` })
2740
+ )
2741
+ )
2742
+ ),
2743
+ h(
2744
+ 'div',
2745
+ { className: 'kb-rule-matrix-row kb-rule-matrix-default-row' },
2746
+ h('span', { className: 'kb-rule-matrix-default-label' }, '默认知识库沿用全局默认'),
2747
+ h(
2748
+ 'span',
2749
+ { className: 'kb-rule-matrix-cell' },
2750
+ h(RadioGroupItem, { value: RULE_DEFAULT_GLOBAL, 'aria-label': '默认知识库沿用全局默认' })
2751
+ )
2752
+ )
2753
+ ),
2754
+ h(
2755
+ 'details',
2756
+ { className: 'kb-rule-advanced' },
2757
+ h('summary', null, '自定义知识库 ID(兜底)'),
2758
+ columns.map((column) =>
2759
+ h(
2760
+ RuleField,
2761
+ { key: column.key, id: `kb-rule-${column.key}`, label: column.label },
2762
+ h(RuleInput, {
2763
+ id: `kb-rule-${column.key}`,
2764
+ value: draft[column.key] ?? '',
2765
+ placeholder: '逗号分隔;* 表示全部',
2766
+ disabled,
2767
+ onChange: (next) => onChange(column.key, next)
2768
+ })
2769
+ )
2770
+ ),
2771
+ h(
2772
+ RuleField,
2773
+ { id: 'kb-rule-defaultKb', label: '默认知识库 ID / 名称' },
2774
+ h(RuleInput, {
2775
+ id: 'kb-rule-defaultKb',
2776
+ value: draft.defaultKb ?? '',
2777
+ placeholder: '留空使用全局默认',
2778
+ disabled,
2779
+ onChange: (next) => onChange('defaultKb', next)
2780
+ })
2781
+ )
2394
2782
  )
2395
2783
  )
2396
2784
  }
@@ -2418,6 +2806,7 @@ export function RuleEditor({
2418
2806
  errors = {},
2419
2807
  formError = '',
2420
2808
  saving = false,
2809
+ options = EMPTY_RULE_OPTIONS,
2421
2810
  onChange,
2422
2811
  onClose,
2423
2812
  onSubmit
@@ -2425,19 +2814,20 @@ export function RuleEditor({
2425
2814
  const change = (key) => (value) => {
2426
2815
  if (typeof onChange === 'function') onChange(key, value)
2427
2816
  }
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
- )
2817
+ const scene = draft.scene ?? 'all'
2818
+ const platforms = (Array.isArray(options?.platforms) ? options.platforms : []).map((platform) => ({
2819
+ id: String(platform),
2820
+ name: String(platform)
2821
+ }))
2822
+ // 未选平台时展示全部候选;选了平台才按平台收窄。
2823
+ const byPlatform = (items) =>
2824
+ draft.platform === ''
2825
+ ? items
2826
+ : items.filter(
2827
+ (item) => item?.platform === undefined || item.platform === '' || item.platform === draft.platform
2828
+ )
2829
+ const guilds = byPlatform(Array.isArray(options?.guilds) ? options.guilds : [])
2830
+ const users = byPlatform(Array.isArray(options?.users) ? options.users : [])
2441
2831
  return h(
2442
2832
  Dialog,
2443
2833
  {
@@ -2448,7 +2838,7 @@ export function RuleEditor({
2448
2838
  },
2449
2839
  h(
2450
2840
  DialogContent,
2451
- { className: 'kb-rule-dialog' },
2841
+ { className: 'kb-rule-dialog kb-rule-dialog-wide' },
2452
2842
  h(
2453
2843
  DialogHeader,
2454
2844
  null,
@@ -2456,7 +2846,7 @@ export function RuleEditor({
2456
2846
  h(
2457
2847
  DialogDescription,
2458
2848
  null,
2459
- '场景「私聊」保存为后端 direct;知识库可填 ID 或名称,多个用逗号分隔,* 表示全部。保存后以实时规则为准。'
2849
+ '能选的都不用手填;需要离线对象时仍可直接输入 ID。私聊保存为后端 direct,保存后以实时规则为准。'
2460
2850
  )
2461
2851
  ),
2462
2852
  formError !== '' ? errorAlert(formError, '保存失败') : null,
@@ -2469,17 +2859,72 @@ export function RuleEditor({
2469
2859
  h(
2470
2860
  RuleField,
2471
2861
  { id: 'kb-rule-scene', label: '场景' },
2472
- h(RuleSceneSelect, { value: draft.scene, disabled: saving, onChange: change('scene') })
2862
+ h(RuleSceneToggle, {
2863
+ value: scene,
2864
+ disabled: saving,
2865
+ onChange: (next) => {
2866
+ change('scene')(next)
2867
+ if (next === 'private' && (draft.guildId ?? '') !== '') change('guildId')('')
2868
+ }
2869
+ })
2870
+ ),
2871
+ h(
2872
+ RuleField,
2873
+ { id: 'kb-rule-minLevel', label: '最低权限等级', error: errors.minLevel },
2874
+ h(RuleLevelSelect, {
2875
+ value: draft.minLevel ?? '',
2876
+ options,
2877
+ disabled: saving,
2878
+ onChange: change('minLevel')
2879
+ })
2473
2880
  ),
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 或名称;留空用全局默认' })
2881
+ h(
2882
+ RuleField,
2883
+ { id: 'kb-rule-platform', label: '平台', error: errors.platform },
2884
+ h(RulePlatformSelect, {
2885
+ value: draft.platform ?? '',
2886
+ options: platforms,
2887
+ disabled: saving,
2888
+ onChange: change('platform')
2889
+ })
2890
+ ),
2891
+ scene !== 'private'
2892
+ ? h(
2893
+ RuleField,
2894
+ { id: 'kb-rule-guildId', label: '群', error: errors.guildId },
2895
+ h(RulePicker, {
2896
+ id: 'kb-rule-guildId',
2897
+ value: draft.guildId ?? '',
2898
+ options: guilds,
2899
+ placeholder: '不限;搜索群名称或直接输入群 ID',
2900
+ disabled: saving,
2901
+ onChange: change('guildId')
2902
+ })
2903
+ )
2904
+ : null,
2905
+ h(
2906
+ RuleField,
2907
+ { id: 'kb-rule-userId', label: '用户', error: errors.userId },
2908
+ h(RulePicker, {
2909
+ id: 'kb-rule-userId',
2910
+ value: draft.userId ?? '',
2911
+ options: users,
2912
+ placeholder: '不限;搜索昵称或直接输入用户 ID',
2913
+ disabled: saving,
2914
+ onChange: change('userId')
2915
+ })
2916
+ )
2479
2917
  ),
2480
- field('readableKbs', '可读知识库', { placeholder: '逗号分隔;* 表示全部' }),
2481
- field('writableKbs', '可写知识库', { placeholder: '逗号分隔;* 表示全部' }),
2482
- field('manageableKbs', '可管理知识库', { placeholder: '逗号分隔;* 表示全部' })
2918
+ h(
2919
+ RuleField,
2920
+ { id: 'kb-rule-permissions', label: '知识库权限', error: errors.readableKbs || errors.writableKbs || errors.manageableKbs },
2921
+ h(RulePermissionMatrix, {
2922
+ draft,
2923
+ options,
2924
+ disabled: saving,
2925
+ onChange: (key, value) => change(key)(value)
2926
+ })
2927
+ )
2483
2928
  ),
2484
2929
  h(
2485
2930
  DialogFooter,
@@ -2499,8 +2944,10 @@ export function RulesTab({ snapshot }) {
2499
2944
  const [formError, setFormError] = useState('')
2500
2945
  const [saving, setSaving] = useState(false)
2501
2946
  const [confirmTarget, setConfirmTarget] = useState(null)
2947
+ const [ruleOptions, setRuleOptions] = useState(EMPTY_RULE_OPTIONS)
2502
2948
  // React 的 setState 不是同步生效的;用 ref 拦住同一帧内的重复提交。
2503
2949
  const savingRef = useRef(false)
2950
+ const optionsRequestedRef = useRef(false)
2504
2951
  const rules = rulesOf(snapshot)
2505
2952
  const live = snapshot?.status ?? 'loading'
2506
2953
  const report = rulesReport(rules, query, scene)
@@ -2514,6 +2961,30 @@ export function RulesTab({ snapshot }) {
2514
2961
  const ready = !broken && live !== 'loading'
2515
2962
  const busy = saving
2516
2963
 
2964
+ // 候选目录只用于选择题供数;ready 后只请求一次,失败保持空数组,手动输入始终可用。
2965
+ useEffect(() => {
2966
+ if (!ready || optionsRequestedRef.current) return undefined
2967
+ optionsRequestedRef.current = true
2968
+ let current = true
2969
+ callAction('kb.ruleOptions', {})
2970
+ .then((response) => {
2971
+ const options = response?.options ?? response
2972
+ if (current && options !== null && typeof options === 'object') {
2973
+ setRuleOptions({
2974
+ platforms: Array.isArray(options.platforms) ? options.platforms : [],
2975
+ guilds: Array.isArray(options.guilds) ? options.guilds : [],
2976
+ users: Array.isArray(options.users) ? options.users : [],
2977
+ kbs: Array.isArray(options.kbs) ? options.kbs : [],
2978
+ levels: Array.isArray(options.levels) && options.levels.length > 0 ? options.levels : EMPTY_RULE_OPTIONS.levels
2979
+ })
2980
+ }
2981
+ })
2982
+ .catch(() => {})
2983
+ return () => {
2984
+ current = false
2985
+ }
2986
+ }, [ready])
2987
+
2517
2988
  // 写入只走 kb.saveRules;保存前重读实时规则,列表与顺序永远以 live 为准。
2518
2989
  const persist = async (nextRules, message) => {
2519
2990
  if (savingRef.current) return false
@@ -2730,6 +3201,7 @@ export function RulesTab({ snapshot }) {
2730
3201
  errors,
2731
3202
  formError,
2732
3203
  saving,
3204
+ options: ruleOptions,
2733
3205
  onChange: updateDraft,
2734
3206
  onClose: closeEditor,
2735
3207
  onSubmit: submitEditor