@fish-under-sea/magpie-purge 0.3.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/page/app.js CHANGED
@@ -28,10 +28,15 @@
28
28
  replace: '人设放最前,宿主 system 里「自称 + 点名模型/厂商」的行删掉。',
29
29
  append: '人设放最前,宿主 system 原样保留。',
30
30
  }
31
- /** NOT_INJECTABLE 说清「这条为什么不会进 system」,并指出下一步:导入的是素材,不是人设。 */
32
- const NOT_INJECTABLE =
33
- '素材条目:可查、可归档,不会写进 system。要注入请导入人设或技能(.md / .markdown / .txt),' +
34
- '或在下方「从本机选文件」里挑一个 md。'
31
+ /** MODE_SHORT 是下拉里模式名后面那一截:只够一格,别写成整句。 */
32
+ const MODE_SHORT = {
33
+ off: '不动请求',
34
+ strict: '只留人设',
35
+ replace: '去自称',
36
+ append: '原样保留',
37
+ }
38
+ /** NOT_INJECTABLE 只说「它是什么」,下一步交给详情里的 callout,别两处都指路。 */
39
+ const NOT_INJECTABLE = '素材条目:能查看、能归档,但不会写进 system。'
35
40
 
36
41
  let options = {}
37
42
  let catalog = window.PURGE_CATALOG ?? null
@@ -41,6 +46,16 @@
41
46
  let saveTimer = 0
42
47
  let pendingSave = null
43
48
  let busy = false
49
+ /** showingText 是「查看原文」的展开态;换条目时要收回去,否则新条目一进来就是展开的。 */
50
+ let showingText = false
51
+ /** pendingFile 是「点过选择、还没点导入」的那个文件;两步导入靠它接上。 */
52
+ let pendingFile = null
53
+ /** importKind 是导入时选的类型:auto 交给判定,persona/skill 覆盖它。 */
54
+ let importKind = 'auto'
55
+ /** confirmedSig 记「用户按下确认时的那套配置」;配置一变就失效,退回「确认注入」。 */
56
+ let confirmedSig = ''
57
+ /** modeMenuOpen 是模式下拉面板是否展开;每次重画都要记住,否则点一下就收。 */
58
+ let modeMenuOpen = false
44
59
 
45
60
  // ---------- 小工具 ----------
46
61
 
@@ -58,11 +73,16 @@
58
73
  say.timer = setTimeout(() => { el.hidden = true }, 6000)
59
74
  }
60
75
 
76
+ /** SVG_NS 是 svg 元素的命名空间:用 createElement 造出来的 <svg> 是 HTML 未知元素,不会渲染。 */
77
+ const SVG_NS = 'http://www.w3.org/2000/svg'
78
+
61
79
  function el(tag, attrs = {}, ...kids) {
62
- const node = document.createElement(tag)
80
+ const node = tag === 'svg' || tag === 'path'
81
+ ? document.createElementNS(SVG_NS, tag)
82
+ : document.createElement(tag)
63
83
  for (const [k, v] of Object.entries(attrs)) {
64
84
  if (v === null || v === undefined || v === false) continue
65
- if (k === 'class') node.className = v
85
+ if (k === 'class') node.setAttribute('class', v)
66
86
  else if (k === 'text') node.textContent = v
67
87
  else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v)
68
88
  else node.setAttribute(k, v === true ? '' : String(v))
@@ -78,6 +98,12 @@
78
98
  const inlineEntries = () => (Array.isArray(options.inline) ? options.inline : [])
79
99
  const findEntry = (id) => entries().find((e) => e.id === id) || inlineEntries().find((e) => e.id === id) || null
80
100
  const isEnabled = (id) => (options.enabled?.[id] !== undefined ? options.enabled[id] : findEntry(id)?.kind === 'persona')
101
+ /** defaultPersona 是「现在最能顶上的人设」:内置底座优先,其次第一个可用的人设。 */
102
+ const defaultPersona = () =>
103
+ entries().find((e) => e.kind === 'persona' && e.default === true) ||
104
+ entries().find((e) => e.kind === 'persona') ||
105
+ inlineEntries().find((e) => e.kind !== 'skill') ||
106
+ null
81
107
 
82
108
  // ---------- 与宿主说话 ----------
83
109
 
@@ -94,11 +120,18 @@
94
120
 
95
121
  async function flush() {
96
122
  if (!pendingSave || !bridge?.options?.set) return
123
+ // 记住这一轮自己刚写下去的键:宿主回包只用来「补全它规范化的字段」,
124
+ // 不许它把我们刚设的值盖回去——否则「选了模式又被换回」会反复发生。
125
+ const sent = { ...(pendingSave || {}) }
97
126
  const body = { ...options }
98
127
  pendingSave = null
99
128
  try {
100
129
  const saved = await bridge.options.set(body)
101
- if (saved && typeof saved === 'object') options = { ...body, ...saved }
130
+ if (saved && typeof saved === 'object') {
131
+ const merged = { ...body, ...saved }
132
+ for (const key of Object.keys(sent)) merged[key] = body[key]
133
+ options = merged
134
+ }
102
135
  } catch (error) {
103
136
  say(`保存失败:${error?.message || error}`, 'bad')
104
137
  }
@@ -186,7 +219,13 @@
186
219
  class: 'row',
187
220
  role: 'option',
188
221
  'aria-selected': selected === e.id,
189
- onclick: () => { selected = selected === e.id ? '' : e.id; render() },
222
+ onclick: () => {
223
+ const next = selected === e.id ? '' : e.id
224
+ // 换条目就收起原文:从一条展开着的详情跳到另一条,不该自动展示别人的正文。
225
+ if (next !== selected) showingText = false
226
+ selected = next
227
+ render()
228
+ },
190
229
  },
191
230
  el('span', { class: 'spine', style: `--spine:var(--kind-${kindClass(e.kind)})` }),
192
231
  el('span', {},
@@ -298,18 +337,23 @@
298
337
  const e = findEntry(selected)
299
338
  if (!e) {
300
339
  // 没选中时让位给「组装预览」:右栏不留一片空白,那是最浪费的一屏。
340
+ showingText = false
301
341
  host.replaceChildren()
302
342
  return
303
343
  }
304
344
  const kind = KINDS[e.kind] || { label: e.kind }
305
345
  const kindCls = kindClass(e.kind)
306
346
  const inline = e.source?.root === 'inline' || e.meta?.format === 'inline'
307
- // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:来源目录里的原件不动。
308
- const imported = Boolean(e.source?.root && /[\\/]state[\\/]imports\/?$/.test(e.source.root))
347
+ // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:原件不动。
348
+ // root 可能是绝对路径(真机)也可能是相对路径(演示快照),所以不要求前导分隔符。
349
+ const imported = Boolean(e.source?.root && /(^|[\\/])state[\\/]imports\/?$/.test(e.source.root))
309
350
  const enabled = isEnabled(e.id)
310
351
  const pinned = options.pinned?.[e.id]
311
352
  const history = Array.isArray(e.history) ? e.history : []
312
- const text = inline ? String(e.text || '') : ''
353
+ // 可注入条目的正文现在随快照下来(inventory.snapshotOf 带 text),
354
+ // 所以「看原文」对内置技能也成立,不再只限页面里贴进来的那几条。
355
+ const text = typeof e.text === 'string' ? e.text : ''
356
+ const canShowText = Boolean(text.trim())
313
357
 
314
358
  const actions = []
315
359
  // 人设才有「设为当前人设」;技能是「启用/停用」。混着写会让人以为技能能当人设用。
@@ -326,6 +370,15 @@
326
370
  onclick: () => save({ enabled: { ...(options.enabled || {}), [e.id]: !enabled } }, enabled ? `已停用「${e.name}」` : `已启用「${e.name}」`),
327
371
  }, enabled ? '停用' : '启用'))
328
372
  }
373
+ // 「它到底写了什么」是判断要不要启用它的唯一依据:进来就看得到,不用去磁盘翻文件。
374
+ if (canShowText) {
375
+ actions.push(el('button', {
376
+ type: 'button',
377
+ class: showingText ? 'quiet' : '',
378
+ 'aria-expanded': showingText ? 'true' : 'false',
379
+ onclick: () => { showingText = !showingText; renderInspector() },
380
+ }, showingText ? '收起原文' : '查看原文'))
381
+ }
329
382
  if (pinned) {
330
383
  actions.push(el('button', {
331
384
  type: 'button',
@@ -342,18 +395,53 @@
342
395
  type: 'button',
343
396
  class: 'danger',
344
397
  onclick: () => {
398
+ // 删掉导入的条目时,指向它的引用也要一起清:否则 plan 会卡在 persona-missing,
399
+ // 用户还得再点一次「改用」才能恢复注入。
345
400
  const kept = inlineEntries().filter((x) => x.id !== e.id)
346
401
  const enabledNext = { ...(options.enabled || {}) }
347
402
  delete enabledNext[e.id]
348
- save({ inline: kept, enabled: enabledNext, persona: options.persona === e.id ? '' : options.persona }, '已从页面导入里删掉')
403
+ const pinnedNext = { ...(options.pinned || {}) }
404
+ delete pinnedNext[e.id]
405
+ const fallback = kept.find((x) => x.kind !== 'skill')
406
+ save({
407
+ inline: kept,
408
+ enabled: enabledNext,
409
+ pinned: pinnedNext,
410
+ persona: options.persona === e.id ? (fallback?.id || '') : options.persona,
411
+ }, `已删除「${e.name}」`)
349
412
  if (selected === e.id) selected = ''
413
+ render()
414
+ },
415
+ }, '删除导入'))
416
+ // 类型选错时能就地改:重扫猜出来的类型不一定对,硬编码成「人设」更糟。
417
+ actions.push(el('button', {
418
+ type: 'button',
419
+ class: 'quiet',
420
+ onclick: () => {
421
+ const nextKind = e.kind === 'skill' ? 'persona' : 'skill'
422
+ const next = inlineEntries().map((x) => (x.id === e.id ? { ...x, kind: nextKind } : x))
423
+ save({ inline: next }, `已改判为${nextKind === 'skill' ? '技能' : '人设'}`)
424
+ render()
350
425
  },
351
- }, '删除'))
426
+ }, e.kind === 'skill' ? '改判为人设' : '改判为技能'))
352
427
  } else if (imported) {
353
428
  actions.push(el('button', {
354
429
  type: 'button',
355
430
  class: 'danger',
356
- onclick: () => importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`),
431
+ onclick: () => {
432
+ // 删副本同时把指向它的引用清掉:留着会让 plan 卡在 persona-missing。
433
+ const enabledNext = { ...(options.enabled || {}) }
434
+ delete enabledNext[e.id]
435
+ const pinnedNext = { ...(options.pinned || {}) }
436
+ delete pinnedNext[e.id]
437
+ save({
438
+ enabled: enabledNext,
439
+ pinned: pinnedNext,
440
+ persona: options.persona === e.id ? '' : options.persona,
441
+ })
442
+ importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`)
443
+ if (selected === e.id) selected = ''
444
+ },
357
445
  }, '删除副本'))
358
446
  }
359
447
 
@@ -375,42 +463,75 @@
375
463
  )
376
464
  : null
377
465
 
466
+ // 详情不再是一张平铺的规格表:主栏说「它是什么、怎么用、占多少」,侧栏放技术事实,
467
+ // 底部单独一条操作栏。原来六行 dl + 一条细预算条全堆在一起,看不出主次。
468
+ const desc = e.meta?.description || (e.injectable ? '可写进 system 段的人设/技能文本。' : NOT_INJECTABLE)
469
+ const pct = Math.min(100, ((e.chars || 0) / 65536) * 100)
470
+ const facts = [
471
+ ['来源', e.source?.root === 'inline' ? '页面导入(存在 options 里)' : e.builtin ? `插件内置 ${builtinFolder(e)}/` : e.source?.root || '—'],
472
+ ['路径', null, 'code', e.source?.rel || '—'],
473
+ ['摘要', null, 'code', short(e.digest)],
474
+ ['版本', `v${e.version ?? 1}${history.length ? ` · 留 ${history.length} 个旧版` : ''}`],
475
+ ['导入', e.builtin ? '随插件' : fmtTime(e.importedAt)],
476
+ ...(e.meta?.sessions !== undefined ? [['会话数', String(e.meta.sessions)]] : []),
477
+ ...(e.meta?.turns !== undefined ? [['选定轮次', String(e.meta.turns)]] : []),
478
+ ]
479
+
378
480
  // replaceChildren 会把 null 变成 "null" 字符串,所以先过滤。
379
481
  host.replaceChildren(...[
380
- el('div', {},
381
- el('h2', {}, e.name, el('span', { class: `kind ${kindCls}` }, kind.label)),
382
- el('p', { class: 'sub-note', text: e.meta?.description || (e.injectable ? '可写进 system 段的人设/技能文本。' : NOT_INJECTABLE) }),
482
+ // ---- 头:名字 + 类型 + 一句话定位 ----
483
+ el('header', { class: 'ins-head' },
484
+ el('div', { class: 'ins-title' },
485
+ el('h2', {}, e.name),
486
+ el('span', { class: `kind ${kindCls}` }, kind.label),
487
+ e.builtin ? el('span', { class: 'ins-badge', text: '内置' }) : null,
488
+ ),
489
+ el('p', { class: 'ins-lede', text: desc }),
383
490
  ),
384
- // 内置专家:说清它是随包来的,不是用户导入的,所以没有「删除」只有「停用」。
385
- // 「何时用」与「提炼自」分两行:一行里塞两件事读起来像免责声明。
386
- e.builtin && e.meta?.whenToUse
387
- ? el('p', { class: 'sub-note', text: `何时用:${e.meta.whenToUse}` })
388
- : null,
389
- e.builtin && e.meta?.source
390
- ? el('p', { class: 'sub-note', text: `提炼自 ${e.meta.source}` })
391
- : null,
392
- el('dl', { class: 'facts' },
393
- el('dt', { text: '来源' }), el('dd', { text: e.source?.root === 'inline' ? '页面导入(存在 options 里)' : e.builtin ? `插件内置 ${builtinFolder(e)}/` : e.source?.root || '—' }),
394
- el('dt', { text: '路径' }), el('dd', {}, el('code', { text: e.source?.rel || '—' })),
395
- el('dt', { text: '大小' }), el('dd', { text: e.injectable ? `${e.chars || 0} 字符(上限 64 KB)` : fmtSize(e.size || 0) }),
396
- el('dt', { text: '摘要' }), el('dd', {}, el('code', { text: short(e.digest) })),
397
- el('dt', { text: '版本' }), el('dd', { text: `v${e.version ?? 1}${history.length ? ` · 保留 ${history.length} 个旧版` : ''}` }),
398
- el('dt', { text: '导入于' }), el('dd', { text: e.builtin ? '随插件' : fmtTime(e.importedAt) }),
399
- e.meta?.sessions !== undefined ? el('dt', { text: '会话数' }) : null,
400
- e.meta?.sessions !== undefined ? el('dd', { text: String(e.meta.sessions) }) : null,
401
- e.meta?.turns !== undefined ? el('dt', { text: '选定轮次' }) : null,
402
- e.meta?.turns !== undefined ? el('dd', { text: String(e.meta.turns) }) : null,
491
+
492
+ // ---- 主体:主栏(何时用 / 体量)+ 侧栏(技术事实)----
493
+ el('div', { class: 'ins-body' },
494
+ el('div', { class: 'ins-main' },
495
+ e.meta?.whenToUse
496
+ ? el('section', { class: 'ins-callout' },
497
+ el('h3', { text: '何时用' }),
498
+ el('p', { text: e.meta.whenToUse }),
499
+ )
500
+ : null,
501
+ e.injectable
502
+ ? el('section', { class: 'ins-meter' },
503
+ el('h3', {}, '进入 system 的体量',
504
+ el('span', { class: 'ins-pct', text: pct < 1 ? '<1%' : `${pct.toFixed(pct < 10 ? 1 : 0)}%` })),
505
+ el('div', { class: 'meter-track' }, el('div', { class: 'meter-fill', style: `width:${Math.max(pct, 0.6)}%` })),
506
+ el('p', { class: 'ins-meter-note', text: `${(e.chars || 0).toLocaleString('zh-CN')} / 65,536 字符 · 与人设一起拼进 system` }),
507
+ )
508
+ : el('section', { class: 'ins-callout is-material' },
509
+ el('h3', { text: '下一步' }),
510
+ el('p', { text: '把它当资料翻;要注入的话,从「导入与来源」里选一份 .md 人设或技能。' }),
511
+ ),
512
+ // 「出处」比「提炼自」中性:技能是从 dsh-purge 提炼的,人设是新写的,一个前缀套不住两种。
513
+ e.builtin && e.meta?.source
514
+ ? el('p', { class: 'ins-origin', text: `出处:${e.meta.source}` })
515
+ : null,
516
+ ),
517
+ el('aside', { class: 'ins-facts' },
518
+ ...facts.flatMap(([k, v, tag, code]) => [
519
+ el('dt', { text: k }),
520
+ el('dd', {}, v !== null ? String(v) : el(tag || 'code', { text: code })),
521
+ ]),
522
+ ),
403
523
  ),
404
- e.injectable
405
- ? el('div', { class: 'budget' },
406
- el('div', { class: 'track' }, el('div', { class: 'fill', style: `width:${Math.min(100, Math.round((e.chars || 0) / 65536 * 100))}%` })),
407
- el('div', { class: 'label', text: `${(e.chars || 0).toLocaleString('zh-CN')} / 65,536 字符会进入 system` }),
408
- )
524
+
525
+ // ---- 底:操作栏 ----
526
+ actions.length
527
+ ? el('footer', { class: 'ins-actions' }, ...actions)
409
528
  : null,
410
- el('div', { class: 'actions' }, ...actions),
411
529
  versionPicker,
412
530
  pinned ? el('p', { class: 'note', text: `当前固定到 ${short(pinned)}:网关用那一版的正文,不是最新的。` }) : null,
413
- inline && text ? el('pre', { class: 'text', text: text.slice(0, 3200) + (text.length > 3200 ? '\n…' : '') }) : null,
531
+ // 原文按注入形态显示:前面出现的技能段,正文会以「## 技能:<名字>」为界拼进去。
532
+ showingText && canShowText
533
+ ? el('pre', { class: 'text', text: text.length > 8000 ? `${text.slice(0, 8000)}\n…(共 ${text.length.toLocaleString('zh-CN')} 字符,后面省略)` : text })
534
+ : null,
414
535
  ].filter(Boolean))
415
536
  }
416
537
 
@@ -460,8 +581,6 @@
460
581
  const shown = visible().length
461
582
  $('count').textContent = `${shown} / ${entries().length + inlineEntries().length} 条 · 快照 v${catalog.version} · ${fmtTime(catalog.generatedAt)}`
462
583
  }
463
- $('mode').value = MODES().includes(options.mode) ? options.mode : ''
464
- $('mode-help').textContent = modeHelp($('mode').value)
465
584
  renderPlan()
466
585
  renderFilters()
467
586
  renderList()
@@ -473,19 +592,15 @@
473
592
  $('inspect').hidden = !picked
474
593
  renderRejects()
475
594
  renderLast()
476
- renderSources()
477
595
  }
478
596
 
479
- /** MODES 是模式下拉的全部取值:空串 = 跟随 agent-purge。 */
480
- const MODES = () => ['', 'off', 'strict', 'replace', 'append']
597
+ /** MODES 是模式下拉的全部取值:没有「跟随上游」这一档,模式必须自己选。 */
598
+ const MODES = () => ['off', 'strict', 'replace', 'append']
481
599
 
482
- /** modeHelp 说清当前值到底意味着什么,尤其是「跟随 agent-purge」时用的是它的什么值。 */
600
+ /** modeHelp 说清当前值到底意味着什么;未选时说清未选就是不动请求。 */
483
601
  function modeHelp(value) {
484
602
  if (value) return MODE_HELP[value] || ''
485
- const p = catalog?.purge
486
- if (!p?.bound) return '没装 agent-purge 或读不到它的 state.json:等价于 off,不会改请求。'
487
- if (p.error) return `agent-purge 的 state.json 有问题:${p.error};等价于 off。`
488
- return `跟随 agent-purge:当前 ${p.mode || '未设置'}${p.persona ? ` · 人设 ${p.persona}` : ''}`
603
+ return '还没选模式:请求原样放行。选一个(比如 replace)才开始注入。'
489
604
  }
490
605
 
491
606
  /**
@@ -504,7 +619,9 @@
504
619
  return
505
620
  }
506
621
  const ready = Boolean(plan.ready)
507
- const fromText = { page: '本页设置', 'agent-purge': 'agent-purge', auto: '自动(第一个启用的人设)', default: '默认' }
622
+ // personaFrom 的三种来源,用户一眼要能看懂「谁在顶着」:
623
+ // page = 自己点的、auto = 底座人设自动顶上、default = agent-purge(仅在显式开启时)
624
+ const fromText = { page: '本页设置', auto: '底座人设(没选人设时自动顶上)', default: '默认' }
508
625
  host.dataset.state = ready ? 'ready' : 'blocked'
509
626
 
510
627
  // 没就绪时给一个能点的下一步:光说「不会注入」等于把问题丢回给人。
@@ -518,10 +635,19 @@
518
635
  if (plan.blockedCode === 'no-mode' || plan.blockedCode === 'mode-off') {
519
636
  fix.push(el('button', { type: 'button', class: 'primary', onclick: () => fixed({ mode: 'replace' }, '模式改为 replace') }, '用 replace 开始注入'))
520
637
  }
521
- if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
638
+ // 旧人设被删掉后 options.persona 会一直指着它,卡在 persona-missing:
639
+ // 这个问题点「去看人设」永远绕不出来,得给一个直接改掉它的动作。
640
+ if (plan.blockedCode === 'persona-missing' && defaultPersona()) {
641
+ const next = defaultPersona()
522
642
  fix.push(el('button', {
523
643
  type: 'button',
524
644
  class: 'primary',
645
+ onclick: () => fixed({ persona: next.id }, `人设改为「${next.name}」`),
646
+ }, `改用「${next.name}」`))
647
+ }
648
+ if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
649
+ fix.push(el('button', {
650
+ type: 'button',
525
651
  onclick: () => { filter = 'persona'; query = ''; render() },
526
652
  }, '去看人设'))
527
653
  }
@@ -529,36 +655,148 @@
529
655
  fix.push(el('button', {
530
656
  type: 'button',
531
657
  class: 'primary',
532
- onclick: () => { $('import-file')?.focus(); $('import-file')?.click?.() },
658
+ onclick: () => { filter = 'persona'; query = ''; render() },
533
659
  }, '导入一份人设'))
534
660
  }
535
661
  }
536
662
 
663
+ // 两行文字放进同一列:第一行是结论,第二行是依据;右边的胶囊组跨两行垂直居中。
664
+ // 原来「为什么」那行缩进 20px,看起来像挂件;现在两行左对齐,读起来是一段话。
537
665
  const rows = [
538
666
  el('span', { class: 'dot' }),
539
- el('span', { class: ready ? 'who' : 'who is-empty' }, ready
540
- ? `下一次 agent 请求会注入「${plan.personaName || plan.personaId}」`
541
- : '现在不会注入:请求原样放行'),
542
- el('span', { class: 'actions' },
543
- el('span', { class: 'tag', text: `模式 ${plan.mode} · ${fromText[plan.modeFrom] || plan.modeFrom || '默认'}` }),
544
- ready && plan.skills?.length ? el('span', { class: 'tag', text: `技能 ${plan.skills.length} 条` }) : null,
667
+ el('span', { class: 'plan-text' },
668
+ el('span', { class: ready ? 'who' : 'who is-empty' }, ready
669
+ ? `下一次 agent 请求会注入「${plan.personaName || plan.personaId}」`
670
+ : '现在不会注入:请求原样放行'),
671
+ el('span', { class: 'why', text: ready
672
+ ? `人设来源:${fromText[plan.personaFrom] || plan.personaFrom}`
673
+ : plan.blocked }),
674
+ ),
675
+ el('span', { class: 'plan-controls' },
676
+ modePill(),
545
677
  ...fix,
546
- el('button', { type: 'button', class: 'quiet', onclick: () => refresh() }, '重扫确认'),
678
+ ready ? confirmButton(plan) : null,
547
679
  ),
548
- el('span', { class: 'why', text: ready
549
- ? `人设来源:${fromText[plan.personaFrom] || plan.personaFrom}${catalog?.purge?.bound ? ';agent-purge 的 state.json 已读到' : ';没读到 agent-purge 的 state.json'}`
550
- : `${plan.blocked}${catalog?.purge?.bound ? '' : '(没读到 agent-purge 的 state.json)'}` }),
680
+ // 面板浮在胶囊组下面:.plan-controls 要 overflow:hidden 才能把两段裁成一颗胶囊,
681
+ // 所以面板不能放在它里面,只能挂在 .plan 上做绝对定位。
682
+ modeMenuOpen ? modeMenu() : null,
551
683
  ]
552
684
  host.replaceChildren(...rows.filter(Boolean))
553
685
  }
554
686
 
555
- function renderSources() {
556
- const el2 = $('sources')
557
- if (!el2 || document.activeElement === el2) return
558
- const list = Array.isArray(options.sources) && options.sources.length
559
- ? options.sources
560
- : (catalog?.sources || []).filter((s) => s.path && !/[\\/]state[\\/]imports\/?$/.test(s.path)).map((s) => s.path)
561
- el2.value = list.join('\n')
687
+ /**
688
+ * modePill 是胶囊组的第一段:模式选择器。
689
+ *
690
+ * 不用原生 select:系统的下拉面板是浏览器自己画的,颜色、圆角、间距全都改不了,
691
+ * 深色主题下还会弹出一块浅色板。这里自绘:按钮 + 自绘面板,
692
+ * 键盘(上下键 / Esc / Enter)与 aria 都按 listbox 的模式接好。
693
+ */
694
+ function modePill() {
695
+ const value = MODES().includes(options.mode) ? options.mode : ''
696
+ // 未选模式时不假装跟随谁:直接说「未选」,点开才去挑。
697
+ const label = value === '' ? '未选' : `${value} · ${MODE_SHORT[value] || ''}`
698
+ return el('button', {
699
+ type: 'button',
700
+ class: 'seg seg-mode',
701
+ title: modeHelp(value),
702
+ 'aria-haspopup': 'listbox',
703
+ 'aria-expanded': modeMenuOpen ? 'true' : 'false',
704
+ onclick: (e) => {
705
+ e.stopPropagation()
706
+ modeMenuOpen = !modeMenuOpen
707
+ renderPlan()
708
+ if (modeMenuOpen) document.querySelector('.seg-opt.is-on')?.focus()
709
+ },
710
+ onkeydown: (e) => {
711
+ if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
712
+ e.preventDefault()
713
+ modeMenuOpen = true
714
+ renderPlan()
715
+ document.querySelector('.seg-opt.is-on')?.focus()
716
+ }
717
+ },
718
+ },
719
+ el('span', { class: 'seg-key', text: '模式' }),
720
+ el('span', { class: 'seg-value', text: label }),
721
+ el('svg', { class: 'seg-chev', viewBox: '0 0 12 12', 'aria-hidden': 'true' },
722
+ el('path', { d: 'M2.5 4.5 L6 8 L9.5 4.5', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
723
+ ),
724
+ )
725
+ }
726
+
727
+ /** modeMenu 是自绘的下拉面板:每项两行——模式名 + 一句它到底干什么。 */
728
+ function modeMenu() {
729
+ const value = MODES().includes(options.mode) ? options.mode : ''
730
+ const pick = (m) => {
731
+ modeMenuOpen = false
732
+ save({ mode: m }, `模式改为 ${m}`)
733
+ }
734
+ const move = (delta) => {
735
+ const opts = [...document.querySelectorAll('.seg-opt')]
736
+ const i = opts.indexOf(document.activeElement)
737
+ const next = opts[Math.min(opts.length - 1, Math.max(0, (i < 0 ? 0 : i) + delta))]
738
+ next?.focus()
739
+ }
740
+ return el('div', {
741
+ class: 'seg-menu',
742
+ role: 'listbox',
743
+ 'aria-label': '改写模式',
744
+ onclick: (e) => e.stopPropagation(),
745
+ onkeydown: (e) => {
746
+ if (e.key === 'Escape') { modeMenuOpen = false; renderPlan(); return }
747
+ if (e.key === 'ArrowDown') { e.preventDefault(); move(1) }
748
+ if (e.key === 'ArrowUp') { e.preventDefault(); move(-1) }
749
+ },
750
+ },
751
+ ...MODES().map((m) => el('button', {
752
+ type: 'button',
753
+ class: `seg-opt${m === value ? ' is-on' : ''}`,
754
+ role: 'option',
755
+ 'aria-selected': m === value ? 'true' : 'false',
756
+ tabindex: m === value ? '0' : '-1',
757
+ onclick: () => pick(m),
758
+ },
759
+ el('span', { class: 'seg-opt-body' },
760
+ el('span', { class: 'seg-opt-name', text: m }),
761
+ el('span', { class: 'seg-opt-sub', text: MODE_HELP[m] }),
762
+ ),
763
+ m === value
764
+ ? el('svg', { class: 'seg-check', viewBox: '0 0 12 12', 'aria-hidden': 'true' },
765
+ el('path', { d: 'M2.5 6.2 L5 8.6 L9.5 3.4', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.7', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }))
766
+ : null,
767
+ )),
768
+ )
769
+ }
770
+
771
+ /**
772
+ * confirmButton 是「确认注入」那颗胶囊。
773
+ *
774
+ * 「已注入」有两个来源,都算数:
775
+ * 1. 最近一次真的经过网关的记录(catalog.last)写着同一套人设与模式——这是证据;
776
+ * 2. 用户按下确认,且此后配置没再动过——这是意图。
777
+ * 本地打个勾不叫生效,所以状态里带着「按的是哪一套配置」:改了模式或人设,
778
+ * 签名一变,「已注入」自动退回「确认注入」。
779
+ */
780
+ function confirmButton(plan) {
781
+ const sig = `${plan.mode}|${plan.personaId || ''}`
782
+ const last = catalog?.last
783
+ const evidence = Boolean(last && !last.skipped && last.mode === plan.mode && (last.persona || '') === (plan.personaId || ''))
784
+ const applied = evidence || confirmedSig === sig
785
+ return el('button', {
786
+ type: 'button',
787
+ class: `seg seg-action${applied ? ' is-applied' : ' is-armed'}`,
788
+ title: evidence
789
+ ? `最近一次生效:${fmtTime(last.at)} · ${last.agent || '未知 agent'}`
790
+ : applied
791
+ ? '已按当前配置确认注入;改了模式或人设会退回未确认'
792
+ : '把这套配置推给网关:重扫一次,下一次 agent 请求就按它注入',
793
+ onclick: () => {
794
+ confirmedSig = sig
795
+ renderPlan()
796
+ say('已确认注入:下一次 agent 请求按这套配置走', 'good')
797
+ refresh()
798
+ },
799
+ }, applied ? '已注入' : '确认注入')
562
800
  }
563
801
 
564
802
  // ---------- 动作 ----------
@@ -602,56 +840,105 @@
602
840
  async function refresh() {
603
841
  if (busy) return
604
842
  busy = true
605
- $('refresh').disabled = true
606
843
  try {
607
844
  save({ refreshAt: Date.now() })
608
845
  await flush()
609
846
  pollSnapshot('正在让后端重新扫描…', 25)
610
847
  } finally {
611
848
  busy = false
612
- $('refresh').disabled = false
613
849
  }
614
850
  }
615
851
 
616
852
  function wire() {
617
- $('mode').addEventListener('change', (e) => {
618
- const value = e.target.value
619
- save({ mode: value }, value ? `模式改为 ${value}` : '改为跟随 agent-purge')
620
- })
621
- $('refresh').addEventListener('click', refresh)
853
+ // 模式选择器与「确认注入」都是每次 renderPlan 重建的,监听写在创建处(onclick/onkeydown),
854
+ // 这里只绑那些常驻不动的控件。
622
855
  $('q').addEventListener('input', (e) => { query = e.target.value; render() })
623
856
 
624
- $('import-run').addEventListener('click', () => {
625
- const path = $('import-path').value.trim()
626
- if (!path) return say('先填一个文件路径', 'bad')
627
- importRequest({ op: 'import', path }, '已请求导入')
628
- $('import-path').value = ''
857
+ // 点面板以外的地方就收起。用捕获阶段:面板内部自己 stopPropagation。
858
+ document.addEventListener('click', () => {
859
+ if (!modeMenuOpen) return
860
+ modeMenuOpen = false
861
+ renderPlan()
629
862
  })
630
863
 
631
- $('import-file').addEventListener('change', async (e) => {
632
- const file = e.target.files?.[0]
633
- if (!file) return
864
+ // 导入分两步:先选文件(把路径填进输入框),再点「导入」才真的导入。
865
+ // 一步到底容易误触:浏览器选完就导入,用户还没确认类型就落盘了。
866
+ $('import-pick').addEventListener('click', () => {
867
+ const input = document.createElement('input')
868
+ input.type = 'file'
869
+ input.accept = '.md,.markdown,.txt,.json,.zip'
870
+ input.addEventListener('change', () => {
871
+ const file = input.files?.[0]
872
+ if (!file) return
873
+ // 浏览器出于安全不暴露真实路径,只能拿到文件名。
874
+ // 这一步先把名字填进去,让人看见选中了什么;真正导入走下面那条 inline 通道。
875
+ $('import-path').value = file.name
876
+ pendingFile = file
877
+ say(`已选中「${file.name}」,再点一次「导入」就写入`, 'good')
878
+ })
879
+ input.click()
880
+ })
881
+
882
+ $('import-run').addEventListener('click', async () => {
883
+ const typed = $('import-path').value.trim()
884
+ // 手填的是绝对路径:交给后端复制(原文件不动,副本进 state/imports)。
885
+ if (typed && !pendingFile) {
886
+ importRequest({ op: 'import', path: typed, kind: importKind }, '已请求导入')
887
+ $('import-path').value = ''
888
+ return
889
+ }
890
+ const file = pendingFile
891
+ if (!file) return say('先点「选择」挑一个文件,或在框里填绝对路径', 'bad')
634
892
  try {
635
893
  const raw = await file.text()
636
894
  if (raw.length > 64 * 1024) throw new Error('超过 64 KB:这么大的正文不该塞进 options')
637
895
  const id = (file.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'inline').slice(0, 48)
638
896
  const kept = inlineEntries().filter((x) => x.id !== id)
639
- const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
640
897
  const fm = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
898
+ const declared = fm?.[1]?.match(/^kind:\s*(persona|skill)\s*$/m)?.[1]
641
899
  const name = fm?.[1]?.match(/^name:\s*(.+)$/m)?.[1]?.replace(/^["']|["']$/g, '') || file.name.replace(/\.[^.]+$/, '')
642
- save({ inline: [...kept, { id, name, kind: 'persona', text: body }] }, `已把「${name}」存进 options`)
643
- e.target.value = ''
900
+ const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
901
+ // 类型的优先级:用户明确选的 > 文件自己写的 > 猜。
902
+ const kind = importKind !== 'auto' ? importKind : declared || guessKind(body)
903
+ save({ inline: [...kept, { id, name, kind, text: body }] }, `已导入「${name}」(${kind === 'skill' ? '技能' : '人设'})`)
904
+ pendingFile = null
905
+ $('import-path').value = ''
906
+ refreshAfterImport()
644
907
  } catch (error) {
645
908
  say(`导入失败:${error?.message || error}`, 'bad')
646
909
  }
647
910
  })
648
911
 
649
- const sources = $('sources-save')
650
- sources?.addEventListener('click', () => {
651
- const list = $('sources').value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
652
- save({ sources: list, refreshAt: Date.now() }, '来源目录已保存')
653
- pollSnapshot('等待后端按新来源扫描…', 25)
654
- })
912
+ // 导入类型:三选一,选中项自己管自己的 aria-pressed。
913
+ for (const chip of document.querySelectorAll('#import-kind .chip')) {
914
+ chip.addEventListener('click', () => {
915
+ importKind = chip.dataset.kind || 'auto'
916
+ for (const other of document.querySelectorAll('#import-kind .chip')) {
917
+ other.setAttribute('aria-pressed', other === chip ? 'true' : 'false')
918
+ }
919
+ })
920
+ }
921
+ }
922
+
923
+ /**
924
+ * guessKind 猜一份 .md 是人设还是技能。
925
+ *
926
+ * 判据来自本插件自己的两种文件长相:人设是完整第二人称,通常带 `## 你是什么`/`你是谁`;
927
+ * 技能是「某个领域的专家」,标题一般是 `# X专家`,正文多含命令与表格。
928
+ */
929
+ function guessKind(body) {
930
+ const text = String(body || '')
931
+ if (/^##\s*(你是什么|你是谁|你是谁?)/m.test(text)) return 'persona'
932
+ if (/^(你是|你现在是)/m.test(text) && !/^#\s/m.test(text)) return 'persona'
933
+ if (/^#\s/m.test(text) && /(\||命令|工具|参数)/.test(text)) return 'skill'
934
+ return 'persona'
935
+ }
936
+
937
+ /** refreshAfterImport 让新导入的条目立刻出现在列表里,并让后端按新 options 重扫。 */
938
+ function refreshAfterImport() {
939
+ save({ refreshAt: Date.now() })
940
+ render()
941
+ pollSnapshot('等后端按新导入重扫…', 20)
655
942
  }
656
943
 
657
944
  async function boot() {
@@ -671,6 +958,11 @@
671
958
  }
672
959
  wire()
673
960
  render()
961
+ // 预览用:?menu=1 直接把下拉面板展开,省得截图时还要模拟点击。
962
+ if (new URLSearchParams(location.search).get('menu') === '1') {
963
+ modeMenuOpen = true
964
+ renderPlan()
965
+ }
674
966
  if (!catalog) pollSnapshot('还没有快照,等后端第一次扫描…', 20)
675
967
  }
676
968