@zifeng1023/dsh-bot 0.3.5 → 0.3.7

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/dsh-plugin.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifestVersion": "0.15",
4
4
  "id": "dsh-bot.core",
5
5
  "name": "dsh-bot",
6
- "version": "0.3.5",
6
+ "version": "0.3.7",
7
7
  "license": "MIT",
8
8
  "facets": {
9
9
  "host": {
package/lib/client.js CHANGED
@@ -21,7 +21,7 @@
21
21
  'use strict';
22
22
 
23
23
  // 构建时由 tsdown 替换为 package.json.version(见 tsdown.config.ts)
24
- const BOT_BUILD = '0.3.5';
24
+ const BOT_BUILD = '0.3.7';
25
25
 
26
26
  // ============================================================
27
27
  // 设计令牌
@@ -487,6 +487,65 @@ function report(status, detail) {
487
487
  }
488
488
  }
489
489
 
490
+ /** 把用户可读的节奏转成 cron(只支持本面板提供的三种模式) */
491
+ function buildCadence(mode, hours, time, days, custom) {
492
+ if (mode === 'none') return '';
493
+ if (mode === 'custom') return custom || '';
494
+ const [hhRaw, mmRaw] = String(time || '09:00').split(':');
495
+ const hh = Math.min(23, Math.max(0, Number(hhRaw) || 0));
496
+ const mm = Math.min(59, Math.max(0, Number(mmRaw) || 0));
497
+ if (mode === 'hours') {
498
+ const n = Math.min(24, Math.max(1, Number(hours) || 12));
499
+ if (n >= 24) return `0 0 * * *`;
500
+ return `0 */${n} * * *`;
501
+ }
502
+ if (mode === 'daily') return `${mm} ${hh} * * *`;
503
+ if (mode === 'weekly') {
504
+ const list = (days && days.length ? days : [1]).join(',');
505
+ return `${mm} ${hh} * * ${list}`;
506
+ }
507
+ return '';
508
+ }
509
+
510
+ /** 反向解析:把已有 cron 还原成可编辑的 UI 状态 */
511
+ function parseCadence(cron) {
512
+ const raw = String(cron || '').trim();
513
+ if (!raw) return { mode: 'none', hours: 12, time: '09:00', days: [1], custom: '' };
514
+ const parts = raw.split(/\s+/);
515
+ if (parts.length !== 5) return { mode: 'custom', hours: 12, time: '09:00', days: [1], custom: raw };
516
+ const [mi, ho, dom, mon, dow] = parts;
517
+ const num = (s) => /^\d+$/.test(s);
518
+ if (mi === '0' && /^\*\/\d+$/.test(ho) && dom === '*' && mon === '*' && dow === '*') {
519
+ return { mode: 'hours', hours: Number(ho.slice(2)), time: '09:00', days: [1], custom: '' };
520
+ }
521
+ if (num(mi) && num(ho) && dom === '*' && mon === '*' && dow === '*') {
522
+ return { mode: 'daily', hours: 12, time: `${ho.padStart(2, '0')}:${mi.padStart(2, '0')}`, days: [1], custom: '' };
523
+ }
524
+ if (num(mi) && num(ho) && dom === '*' && mon === '*' && /^[0-6](,[0-6])*$/.test(dow)) {
525
+ return { mode: 'weekly', hours: 12, time: `${ho.padStart(2, '0')}:${mi.padStart(2, '0')}`, days: dow.split(',').map(Number), custom: '' };
526
+ }
527
+ return { mode: 'custom', hours: 12, time: '09:00', days: [1], custom: raw };
528
+ }
529
+
530
+ /** 人话描述当前节奏 */
531
+ function describeCadence(mode, hours, time, days, custom) {
532
+ if (mode === 'none') return '不自动执行(只手动触发)';
533
+ if (mode === 'custom') return `自定义 cron:${custom || '(空)'}`;
534
+ if (mode === 'hours') {
535
+ const n = Math.min(24, Math.max(1, Number(hours) || 12));
536
+ return n >= 24
537
+ ? '每天 00:00 执行一次'
538
+ : `每 ${n} 小时执行一次(每天 ${Math.floor(24 / n)} 次,整点)`;
539
+ }
540
+ if (mode === 'daily') return `每天 ${time || '09:00'} 执行一次`;
541
+ if (mode === 'weekly') {
542
+ const names = ['日', '一', '二', '三', '四', '五', '六'];
543
+ const list = (days && days.length ? days : [1]).map((d) => `周${names[d]}`).join('、');
544
+ return `每 ${list} 的 ${time || '09:00'} 执行`;
545
+ }
546
+ return '';
547
+ }
548
+
490
549
  report('bundle-executing', 'v2 design-system');
491
550
 
492
551
  // ============================================================
@@ -514,8 +573,28 @@ window.__ModuleLoader__.load({
514
573
  // 必须在 apply 之前就绪,否则渲染时会抛 "h is not a function"。
515
574
  React = require('react');
516
575
  h = React.createElement;
576
+ /** react-dom 可能不存在(旧宿主);拿不到就回退为原地渲染 */
577
+ let ReactDOM = null;
578
+ try {
579
+ ReactDOM = require('react-dom');
580
+ } catch {
581
+ ReactDOM = null;
582
+ }
583
+ /** 渲染到 document.body:绕开聊天输入区里「有 transform 的祖先」对 fixed 的影响 */
584
+ function portal(node) {
585
+ try {
586
+ if (ReactDOM?.createPortal && typeof document !== 'undefined' && document.body) {
587
+ return ReactDOM.createPortal(node, document.body);
588
+ }
589
+ } catch {
590
+ /* 回退 */
591
+ }
592
+ return node;
593
+ }
517
594
 
518
595
  function apply(ctx) {
596
+ /** 侧边栏入口的运行时开关(设置页与首次引导共用;必须在 apply 作用域内) */
597
+ const sidebarController = { apply: (_enabled) => {} };
519
598
  try {
520
599
  injectStyle();
521
600
 
@@ -1970,6 +2049,22 @@ window.__ModuleLoader__.load({
1970
2049
  ),
1971
2050
  ]),
1972
2051
 
2052
+ group('界面', [
2053
+ h(ToggleRow, {
2054
+ label: '侧边栏图标入口',
2055
+ hint: '在左侧边栏显示 Bot 图标,点击打开 Bot 设置页;关闭后仍可从设置页的 Bot 分区进入',
2056
+ value: s.sidebarEntry !== false,
2057
+ onChange: (v) => {
2058
+ patch('sidebarEntry', v);
2059
+ try {
2060
+ sidebarController.apply(v);
2061
+ } catch {
2062
+ /* 注册失败不影响设置保存 */
2063
+ }
2064
+ },
2065
+ }),
2066
+ ]),
2067
+
1973
2068
  group('最近运行', [
1974
2069
  h(RunsSection, { busy }),
1975
2070
  ]),
@@ -2771,6 +2866,16 @@ window.__ModuleLoader__.load({
2771
2866
  const [moreOpen, setMoreOpen] = React.useState(null);
2772
2867
  /** 哪个 Bot 的「配置与危险操作」展开(与「他知道什么」分属两层) */
2773
2868
  const [dangerOpen, setDangerOpen] = React.useState(null);
2869
+ /** 哪个 Bot 正在编辑资料(名称 / 职责 / 附加说明) */
2870
+ const [editOpen, setEditOpen] = React.useState(null);
2871
+ const [editName, setEditName] = React.useState('');
2872
+ const [editRole, setEditRole] = React.useState('');
2873
+ const [editNote, setEditNote] = React.useState('');
2874
+ const [cadenceMode, setCadenceMode] = React.useState('none');
2875
+ const [cadenceHours, setCadenceHours] = React.useState(12);
2876
+ const [cadenceTime, setCadenceTime] = React.useState('09:00');
2877
+ const [cadenceDays, setCadenceDays] = React.useState([1]);
2878
+ const [cadenceCustom, setCadenceCustom] = React.useState('');
2774
2879
  /** 当前视图:bots 列表 / settings 设置页 */
2775
2880
  const [view, setView] = React.useState('bots');
2776
2881
 
@@ -2801,6 +2906,27 @@ window.__ModuleLoader__.load({
2801
2906
  if (open && !data) void refresh();
2802
2907
  }, [open, data, refresh]);
2803
2908
 
2909
+ // 打开编辑时填充「附加说明」:详情异步到达,只填一次,避免覆盖用户输入
2910
+ const editPrefilled = React.useRef(null);
2911
+ React.useEffect(() => {
2912
+ if (!editOpen) {
2913
+ editPrefilled.current = null;
2914
+ return;
2915
+ }
2916
+ if (editPrefilled.current === editOpen) return;
2917
+ if (detail?.bot?.id === editOpen) {
2918
+ setEditNote(detail.bot.systemPromptExtra ?? '');
2919
+ const parsed = parseCadence(detail.goal?.cadence);
2920
+ setCadenceMode(parsed.mode);
2921
+ setCadenceHours(parsed.hours);
2922
+ setCadenceTime(parsed.time);
2923
+ setCadenceDays(parsed.days);
2924
+ setCadenceCustom(parsed.custom);
2925
+ editPrefilled.current = editOpen;
2926
+ }
2927
+ }, [editOpen, detail]);
2928
+
2929
+
2804
2930
  // 展开某个 Bot 的详情时,拉一次完整数据
2805
2931
  // (目标 / 运行史 / 记忆 / 例行流程 / 快照都在这个接口里)
2806
2932
  const loadDetail = React.useCallback(async (botId) => {
@@ -3068,14 +3194,43 @@ window.__ModuleLoader__.load({
3068
3194
  // ⚠️ 之前所有内容平铺在一层,详情区一展开就把面板撑得很高,
3069
3195
  // 超出可视区域后既看不到下面、也没法滚(因为根本没有滚动容器)。
3070
3196
  // 现在用 flex 列布局 + 中部 overflow-y:auto 解决。
3071
- return h(
3197
+ return portal(h(
3072
3198
  'div',
3073
- { className: `${NS}-dock` },
3199
+ {
3200
+ className: `${NS}-dock`,
3201
+ style: {
3202
+ position: 'fixed',
3203
+ inset: 0,
3204
+ zIndex: 9998,
3205
+ background: 'rgba(0, 0, 0, 0.45)',
3206
+ display: 'flex',
3207
+ alignItems: 'center',
3208
+ justifyContent: 'center',
3209
+ padding: 20,
3210
+ },
3211
+ onMouseDown: (e) => {
3212
+ if (e.target === e.currentTarget) setOpen(false);
3213
+ },
3214
+ },
3215
+ h(SidebarEntryPrompt, null),
3074
3216
  h(
3075
3217
  'div',
3076
3218
  {
3077
3219
  className: `${NS}-dock-inner ${NS}-fade ${NS}-expanded`,
3078
- style: card,
3220
+ // v0.3.7 修正:展开态改为视口居中的浮层。
3221
+ // 贴底面板会随输入框高度被挤压,无论怎么算 max-height 都会出现「顶部被挡」;
3222
+ // 浮层用 82vh 上限 + 内部滚动,与输入框高度彻底解耦。
3223
+ style: {
3224
+ ...card,
3225
+ position: 'relative',
3226
+ width: 'min(760px, 94vw)',
3227
+ maxHeight: '82vh',
3228
+ display: 'flex',
3229
+ flexDirection: 'column',
3230
+ overflow: 'hidden',
3231
+ zIndex: 9998,
3232
+ boxShadow: 'var(--dsw-shadow-lv3)',
3233
+ },
3079
3234
  },
3080
3235
  // ---------- 头部(固定) ----------
3081
3236
  h(
@@ -3516,6 +3671,25 @@ window.__ModuleLoader__.load({
3516
3671
  },
3517
3672
  '执行',
3518
3673
  ),
3674
+ h(
3675
+ 'button',
3676
+ {
3677
+ className: `${NS}-row-btn`,
3678
+ onClick: () => {
3679
+ const next = editOpen === b.id ? null : b.id;
3680
+ setEditOpen(next);
3681
+ if (next) {
3682
+ setEditName(b.name ?? '');
3683
+ setEditRole(b.role ?? '');
3684
+ setEditNote('');
3685
+ if (!detail || detail.bot?.id !== b.id) void loadDetail(b.id);
3686
+ }
3687
+ },
3688
+ title: editOpen === b.id ? '收起编辑' : '编辑名称 / 职责 / 附加说明 / 执行周期',
3689
+ type: 'button',
3690
+ },
3691
+ '编辑',
3692
+ ),
3519
3693
  h(
3520
3694
  'button',
3521
3695
  {
@@ -3530,6 +3704,213 @@ window.__ModuleLoader__.load({
3530
3704
  ),
3531
3705
  ),
3532
3706
 
3707
+ // 行内编辑(v0.3.7:入口就在行上,不藏在「配置与危险操作」里)
3708
+ editOpen === b.id
3709
+ ? h(
3710
+ 'div',
3711
+ {
3712
+ className: `${NS}-fade`,
3713
+ style: {
3714
+ padding: '10px 12px 12px',
3715
+ borderTop: `1px solid ${BORDER_L1}`,
3716
+ background: BG_L3,
3717
+ display: 'flex',
3718
+ flexDirection: 'column',
3719
+ gap: 6,
3720
+ },
3721
+ },
3722
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '名称'),
3723
+ h(Input, {
3724
+ value: editName,
3725
+ onChange: setEditName,
3726
+ placeholder: 'Bot 名称',
3727
+ autoFocus: true,
3728
+ }),
3729
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '职责'),
3730
+ h(Input, {
3731
+ value: editRole,
3732
+ onChange: setEditRole,
3733
+ placeholder: '职责(一句话,决定它怎么干活)',
3734
+ multiline: true,
3735
+ }),
3736
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '附加说明'),
3737
+ h(Input, {
3738
+ value: editNote,
3739
+ onChange: setEditNote,
3740
+ placeholder: '附加说明(可选,会写进系统提示)',
3741
+ multiline: true,
3742
+ }),
3743
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '执行周期'),
3744
+ h(
3745
+ 'div',
3746
+ { style: { display: 'flex', gap: 6, flexWrap: 'wrap' } },
3747
+ ...[
3748
+ ['hours', '每 N 小时'],
3749
+ ['daily', '每天'],
3750
+ ['weekly', '每周'],
3751
+ ['none', '不自动跑'],
3752
+ ].map(([mode, label]) =>
3753
+ h(
3754
+ 'button',
3755
+ {
3756
+ key: mode,
3757
+ type: 'button',
3758
+ onClick: () => setCadenceMode(mode),
3759
+ style: {
3760
+ fontSize: 11,
3761
+ border: `1px solid ${cadenceMode === mode ? BRAND : BORDER_L1}`,
3762
+ background: cadenceMode === mode ? BG_L3 : 'transparent',
3763
+ color: cadenceMode === mode ? BRAND : LABEL_3,
3764
+ borderRadius: R_SM,
3765
+ padding: '3px 10px',
3766
+ cursor: 'pointer',
3767
+ },
3768
+ },
3769
+ label,
3770
+ ),
3771
+ ),
3772
+ ),
3773
+ cadenceMode === 'hours'
3774
+ ? h(
3775
+ 'div',
3776
+ { style: { display: 'flex', alignItems: 'center', gap: 8 } },
3777
+ h(
3778
+ 'button',
3779
+ {
3780
+ type: 'button',
3781
+ onClick: () => setCadenceHours((v) => Math.max(1, v - 1)),
3782
+ style: { width: 26, height: 26, borderRadius: R_SM, border: `1px solid ${BORDER_L1}`, background: 'transparent', color: LABEL_2, cursor: 'pointer', fontSize: 14 },
3783
+ },
3784
+ '−',
3785
+ ),
3786
+ h(
3787
+ 'div',
3788
+ { style: { minWidth: 92, textAlign: 'center', fontSize: 12, color: LABEL_1 } },
3789
+ `每 ${cadenceHours} 小时`,
3790
+ ),
3791
+ h(
3792
+ 'button',
3793
+ {
3794
+ type: 'button',
3795
+ onClick: () => setCadenceHours((v) => Math.min(24, v + 1)),
3796
+ style: { width: 26, height: 26, borderRadius: R_SM, border: `1px solid ${BORDER_L1}`, background: 'transparent', color: LABEL_2, cursor: 'pointer', fontSize: 14 },
3797
+ },
3798
+ '+',
3799
+ ),
3800
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '整点触发'),
3801
+ )
3802
+ : null,
3803
+ cadenceMode === 'daily' || cadenceMode === 'weekly'
3804
+ ? h(
3805
+ 'div',
3806
+ { style: { display: 'flex', alignItems: 'center', gap: 8 } },
3807
+ h('div', { style: { fontSize: 10, color: LABEL_3 } }, '时间'),
3808
+ h('input', {
3809
+ type: 'time',
3810
+ value: cadenceTime,
3811
+ onChange: (e) => setCadenceTime(e.target.value || '09:00'),
3812
+ style: {
3813
+ width: 110,
3814
+ boxSizing: 'border-box',
3815
+ fontFamily: FONT,
3816
+ fontSize: 12,
3817
+ color: LABEL_1,
3818
+ background: BG_L1,
3819
+ border: `1px solid ${BORDER_L2}`,
3820
+ borderRadius: R_SM,
3821
+ padding: '4px 8px',
3822
+ outline: 'none',
3823
+ },
3824
+ }),
3825
+ )
3826
+ : null,
3827
+ cadenceMode === 'weekly'
3828
+ ? h(
3829
+ 'div',
3830
+ { style: { fontSize: 10, color: LABEL_3 } },
3831
+ '星期(可多选)',
3832
+ h(
3833
+ 'div',
3834
+ { style: { display: 'flex', gap: 4, marginTop: 4, flexWrap: 'wrap' } },
3835
+ ...['日', '一', '二', '三', '四', '五', '六'].map((label, idx) =>
3836
+ h(
3837
+ 'button',
3838
+ {
3839
+ key: idx,
3840
+ type: 'button',
3841
+ onClick: () =>
3842
+ setCadenceDays((prev) =>
3843
+ prev.includes(idx)
3844
+ ? prev.filter((x) => x !== idx)
3845
+ : [...prev, idx].sort((a, b) => a - b),
3846
+ ),
3847
+ style: {
3848
+ width: 26,
3849
+ height: 24,
3850
+ borderRadius: R_SM,
3851
+ border: `1px solid ${cadenceDays.includes(idx) ? BRAND : BORDER_L1}`,
3852
+ background: cadenceDays.includes(idx) ? BG_L3 : 'transparent',
3853
+ color: cadenceDays.includes(idx) ? BRAND : LABEL_3,
3854
+ fontSize: 11,
3855
+ cursor: 'pointer',
3856
+ },
3857
+ },
3858
+ label,
3859
+ ),
3860
+ ),
3861
+ ),
3862
+ )
3863
+ : null,
3864
+ cadenceMode === 'custom'
3865
+ ? h(
3866
+ 'div',
3867
+ { style: { fontSize: 10, color: WARN } },
3868
+ `当前是自定义 cron(${cadenceCustom});选择上面的模式会覆盖它。`,
3869
+ )
3870
+ : null,
3871
+ h(
3872
+ 'div',
3873
+ { style: { fontSize: 10, color: LABEL_3 } },
3874
+ `将执行:${describeCadence(cadenceMode, cadenceHours, cadenceTime, cadenceDays, cadenceCustom)}`,
3875
+ ),
3876
+ h(
3877
+ 'div',
3878
+ { style: { display: 'flex', gap: 6, justifyContent: 'flex-end' } },
3879
+ h(Btn, { onClick: () => setEditOpen(null) }, '取消'),
3880
+ h(
3881
+ Btn,
3882
+ {
3883
+ kind: 'primary',
3884
+ disabled: busy || !editName.trim() || !editRole.trim(),
3885
+ onClick: async () => {
3886
+ try {
3887
+ const r = await fetch('/_dsh-bot/bot/update', {
3888
+ method: 'POST',
3889
+ headers: { 'content-type': 'application/json' },
3890
+ body: JSON.stringify({
3891
+ botId: b.id,
3892
+ name: editName.trim(),
3893
+ role: editRole.trim(),
3894
+ systemPromptExtra: editNote,
3895
+ cadence: buildCadence(cadenceMode, cadenceHours, cadenceTime, cadenceDays, cadenceCustom),
3896
+ }),
3897
+ });
3898
+ const j = await r.json();
3899
+ if (!j?.ok) throw new Error(j?.message || j?.code || '保存失败');
3900
+ setEditOpen(null);
3901
+ await loadDetail(b.id);
3902
+ await refresh();
3903
+ } catch (err) {
3904
+ setErr(String(err?.message ?? err));
3905
+ }
3906
+ },
3907
+ },
3908
+ '保存',
3909
+ ),
3910
+ ),
3911
+ )
3912
+ : null,
3913
+
3533
3914
  // 详情
3534
3915
  //
3535
3916
  // A 方案(三层折叠)+ D 方案(状态驱动)
@@ -3916,7 +4297,7 @@ window.__ModuleLoader__.load({
3916
4297
 
3917
4298
  // 关闭滚动容器
3918
4299
  ),
3919
- );
4300
+ ));
3920
4301
  } catch (e) {
3921
4302
  report('render-error', String(e?.message ?? e));
3922
4303
  return null;
@@ -4061,6 +4442,155 @@ window.__ModuleLoader__.load({
4061
4442
  );
4062
4443
  }
4063
4444
 
4445
+ /** 侧边栏图标(只画字形,颜色跟随 currentColor) */
4446
+ function BotSidebarIcon({ size = 16 }) {
4447
+ return h(
4448
+ 'svg',
4449
+ { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
4450
+ h('rect', { x: 4, y: 6.5, width: 16, height: 12, rx: 3, stroke: 'currentColor', strokeWidth: 1.6 }),
4451
+ h('circle', { cx: 9, cy: 12.5, r: 1.4, fill: 'currentColor' }),
4452
+ h('circle', { cx: 15, cy: 12.5, r: 1.4, fill: 'currentColor' }),
4453
+ h('path', { d: 'M12 6.5V4', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round' }),
4454
+ );
4455
+ }
4456
+
4457
+ /** 主面板页:点侧边栏图标后,右侧显示的内容(设置 + 诊断) */
4458
+ function BotPanelPage() {
4459
+ try {
4460
+ const load = React.useCallback(async () => {
4461
+ const r = await fetch('/_dsh-bot/settings', { headers: { accept: 'application/json' } });
4462
+ const j = await r.json();
4463
+ if (!j?.ok) throw new Error(j?.message || '读取失败');
4464
+ return j.value.effective;
4465
+ }, []);
4466
+ const save = React.useCallback(async (next) => {
4467
+ try {
4468
+ await fetch('/_dsh-bot/settings', {
4469
+ method: 'POST',
4470
+ headers: { 'content-type': 'application/json' },
4471
+ body: JSON.stringify({ settings: next }),
4472
+ });
4473
+ } catch {
4474
+ /* 下次保存再试 */
4475
+ }
4476
+ }, []);
4477
+ const clearRuns = React.useCallback(async () => {
4478
+ try {
4479
+ const r = await fetch('/_dsh-bot/overview', { headers: { accept: 'application/json' } });
4480
+ const j = await r.json();
4481
+ const first = j?.value?.bots?.[0];
4482
+ if (!first) return;
4483
+ await fetch('/_dsh-bot/runs/clear', {
4484
+ method: 'POST',
4485
+ headers: { 'content-type': 'application/json' },
4486
+ body: JSON.stringify({ botId: first.id, confirm: true }),
4487
+ });
4488
+ } catch {
4489
+ /* 忽略 */
4490
+ }
4491
+ }, []);
4492
+
4493
+ return h(
4494
+ 'div',
4495
+ { style: { height: '100%', overflowY: 'auto', padding: '20px 24px 40px', fontFamily: FONT, color: LABEL_1 } },
4496
+ h(
4497
+ 'div',
4498
+ { style: { maxWidth: 720, margin: '0 auto' } },
4499
+ h('div', { style: { fontSize: 18, fontWeight: 600, marginBottom: 2 } }, 'dsh-bot'),
4500
+ h('div', { style: { fontSize: 11, color: LABEL_3, marginBottom: 14 } }, '常驻 AI 队友 · 设置与诊断'),
4501
+ h(DoctorPanel, null),
4502
+ h('div', { style: { height: 14 } }),
4503
+ h(SettingsView, {
4504
+ busy: false,
4505
+ onClose: () => {},
4506
+ onLoad: load,
4507
+ onSave: save,
4508
+ onClearRuns: clearRuns,
4509
+ hideClose: true,
4510
+ }),
4511
+ ),
4512
+ );
4513
+ } catch (e) {
4514
+ report('main-panel-render-error', String(e?.message ?? e));
4515
+ return null;
4516
+ }
4517
+ }
4518
+
4519
+ /** 首次运行询问:是否在侧边栏显示入口(只问一次) */
4520
+ function SidebarEntryPrompt() {
4521
+ const [show, setShow] = React.useState(() => {
4522
+ try {
4523
+ return !localStorage.getItem('dsh-bot:sidebarPrompted');
4524
+ } catch {
4525
+ return false;
4526
+ }
4527
+ });
4528
+ if (!show) return null;
4529
+ const choose = (enabled) => {
4530
+ try {
4531
+ localStorage.setItem('dsh-bot:sidebarPrompted', '1');
4532
+ } catch {
4533
+ /* 忽略 */
4534
+ }
4535
+ setShow(false);
4536
+ try {
4537
+ sidebarController.apply(enabled);
4538
+ } catch {
4539
+ /* 注册失败不影响保存 */
4540
+ }
4541
+ try {
4542
+ void fetch('/_dsh-bot/settings', {
4543
+ method: 'POST',
4544
+ headers: { 'content-type': 'application/json' },
4545
+ body: JSON.stringify({ settings: { sidebarEntry: enabled } }),
4546
+ }).catch(() => {});
4547
+ } catch {
4548
+ /* 忽略 */
4549
+ }
4550
+ };
4551
+ return h(
4552
+ 'div',
4553
+ {
4554
+ style: {
4555
+ position: 'fixed',
4556
+ inset: 0,
4557
+ zIndex: 9999,
4558
+ background: 'rgba(0, 0, 0, 0.45)',
4559
+ display: 'flex',
4560
+ alignItems: 'center',
4561
+ justifyContent: 'center',
4562
+ fontFamily: FONT,
4563
+ },
4564
+ },
4565
+ h(
4566
+ 'div',
4567
+ {
4568
+ style: {
4569
+ width: 380,
4570
+ background: BG_L2,
4571
+ border: `1px solid ${BORDER_L1}`,
4572
+ borderRadius: R_LG,
4573
+ padding: '16px 18px',
4574
+ color: LABEL_1,
4575
+ boxShadow: 'var(--dsw-shadow-lv3)',
4576
+ },
4577
+ },
4578
+ h('div', { style: { fontSize: 13, fontWeight: 600, marginBottom: 6 } }, '在侧边栏显示 Bot 入口?'),
4579
+ h(
4580
+ 'div',
4581
+ { style: { fontSize: 11, color: LABEL_3, lineHeight: 1.7, marginBottom: 12 } },
4582
+ '开启后左侧边栏会出现 dsh-bot 图标,点一下就在右侧打开 Bot 设置页。之后可在「设置 → Bot → 界面」里随时关闭。',
4583
+ ),
4584
+ h(
4585
+ 'div',
4586
+ { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
4587
+ h(Btn, { onClick: () => choose(false) }, '先不显示'),
4588
+ h(Btn, { kind: 'primary', onClick: () => choose(true) }, '显示(推荐)'),
4589
+ ),
4590
+ ),
4591
+ );
4592
+ }
4593
+
4064
4594
  function BotSettingsSection() {
4065
4595
  try {
4066
4596
  const save = React.useCallback(async (next) => {
@@ -4182,6 +4712,60 @@ window.__ModuleLoader__.load({
4182
4712
  report('settings-section-error', String(e?.message ?? e));
4183
4713
  }
4184
4714
 
4715
+ // ---------- 主面板 + 侧边栏入口(v0.3.7) ----------
4716
+ // 侧边栏入口可开关:注册/注销都走 slots 的 disposer,切换立即生效。
4717
+ let sidebarDisposer = null;
4718
+ const applySidebarEntry = (enabled) => {
4719
+ try {
4720
+ if (enabled && !sidebarDisposer && ctx?.slots?.inject) {
4721
+ sidebarDisposer = ctx.slots.inject('sidebar.panellist', () =>
4722
+ ctx.slots.register(
4723
+ {
4724
+ name: 'sidebar.panellist',
4725
+ id: 'dsh-bot',
4726
+ order: 40,
4727
+ label: () => 'dsh-bot',
4728
+ },
4729
+ BotSidebarIcon,
4730
+ ),
4731
+ );
4732
+ report('ok', 'sidebar.panellist registered');
4733
+ } else if (!enabled && sidebarDisposer) {
4734
+ sidebarDisposer();
4735
+ sidebarDisposer = null;
4736
+ report('ok', 'sidebar.panellist removed');
4737
+ }
4738
+ } catch (e) {
4739
+ report('sidebar-entry-error', String(e?.message ?? e));
4740
+ }
4741
+ };
4742
+ sidebarController.apply = applySidebarEntry;
4743
+
4744
+ // 主面板:点侧边栏图标后右侧渲染的页面
4745
+ try {
4746
+ if (ctx?.slots?.inject) {
4747
+ ctx.slots.inject('main', () =>
4748
+ ctx.slots.register({ name: 'main', key: 'dsh-bot' }, BotPanelPage),
4749
+ );
4750
+ report('ok', 'main panel registered');
4751
+ }
4752
+ } catch (e) {
4753
+ report('main-panel-error', String(e?.message ?? e));
4754
+ }
4755
+
4756
+ // 先按默认显示,再按已保存的设置纠正
4757
+ applySidebarEntry(true);
4758
+ (async () => {
4759
+ try {
4760
+ const r = await fetch('/_dsh-bot/settings', { headers: { accept: 'application/json' } });
4761
+ const j = await r.json();
4762
+ const v = j?.value?.effective;
4763
+ if (v && v.sidebarEntry === false) applySidebarEntry(false);
4764
+ } catch {
4765
+ /* 读不到就用默认 */
4766
+ }
4767
+ })();
4768
+
4185
4769
  // ---------- 运行完成通知(全局轮询器) ----------
4186
4770
  //
4187
4771
  // 为什么是轮询而不是推送:宿主没有给插件暴露「向会话投递消息」
@@ -4255,15 +4839,29 @@ window.__ModuleLoader__.load({
4255
4839
  };
4256
4840
 
4257
4841
  let notifying = false;
4842
+
4843
+ /** 取某个 Bot 的生效设置;失败时回退全局。 */
4844
+ const policyOf = async (botId) => {
4845
+ try {
4846
+ const r = await fetch(
4847
+ `/_dsh-bot/settings?botId=${encodeURIComponent(botId)}`,
4848
+ { headers: { accept: 'application/json' } },
4849
+ );
4850
+ const j = await r.json();
4851
+ if (j?.ok && j.value?.effective) return j.value.effective;
4852
+ } catch {
4853
+ /* 回退全局 */
4854
+ }
4855
+ return null;
4856
+ };
4857
+
4258
4858
  const notifyTick = async () => {
4259
4859
  if (notifying) return;
4260
4860
  notifying = true;
4261
4861
  try {
4262
4862
  const sRes = await fetch('/_dsh-bot/settings', { headers: { accept: 'application/json' } });
4263
4863
  const sJson = await sRes.json();
4264
- const settings = sJson?.ok ? sJson.value?.effective : null;
4265
- if (!settings?.notifySystem) return;
4266
- if (inQuietHours(settings.quietHours)) return;
4864
+ const globalSettings = sJson?.ok ? sJson.value?.effective : null;
4267
4865
 
4268
4866
  const oRes = await fetch('/_dsh-bot/overview', { headers: { accept: 'application/json' } });
4269
4867
  const oJson = await oRes.json();
@@ -4275,6 +4873,11 @@ window.__ModuleLoader__.load({
4275
4873
  let newest = lastSeen;
4276
4874
  // 每个新完成运行都要看;为控制请求量只拉每 Bot 最近 5 条
4277
4875
  for (const b of bots) {
4876
+ // ⭐ 单 Bot 设置要覆盖全局:0.3.5 及之前这里只看全局 settings,
4877
+ // 导致「某个 Bot 关闭仅异常打扰」永远不生效(0.3.6 修复)。
4878
+ const settings = (await policyOf(b.id)) ?? globalSettings;
4879
+ if (!settings?.notifySystem) continue;
4880
+ if (inQuietHours(settings.quietHours)) continue;
4278
4881
  const rRes = await fetch(`/_dsh-bot/runs/list?botId=${encodeURIComponent(b.id)}&limit=5`, {
4279
4882
  headers: { accept: 'application/json' },
4280
4883
  });
@@ -4329,6 +4932,19 @@ window.__ModuleLoader__.load({
4329
4932
  setInterval(() => void notifyTick(), NOTIFY_POLL_MS);
4330
4933
  }, 15_000);
4331
4934
  report('ok', 'notify poller armed');
4935
+ // 通知能力自证:没有它,「收不到通知」只能靠猜
4936
+ try {
4937
+ if (typeof Notification === 'undefined') {
4938
+ report('notify-unavailable', 'Notification API 不存在');
4939
+ } else {
4940
+ report('notify-capability', `permission=${Notification.permission}`);
4941
+ if (Notification.permission === 'default') {
4942
+ try { void Notification.requestPermission?.(); } catch {}
4943
+ }
4944
+ }
4945
+ } catch {
4946
+ /* 能力探测失败不影响轮询 */
4947
+ }
4332
4948
  } catch (e) {
4333
4949
  report('notify-poller-error', String(e?.message ?? e));
4334
4950
  }
package/lib/index.js CHANGED
@@ -2586,7 +2586,8 @@ const DEFAULT_SETTINGS = {
2586
2586
  defaultCadence: "",
2587
2587
  costSensitiveScheduling: true,
2588
2588
  snapshotKeepRecent: 10,
2589
- snapshotEnabled: true
2589
+ snapshotEnabled: true,
2590
+ sidebarEntry: true
2590
2591
  };
2591
2592
  function readJsonSync(file) {
2592
2593
  try {
@@ -2628,6 +2629,7 @@ function sanitizeSettings(raw) {
2628
2629
  bool("autoPropose", raw.autoPropose);
2629
2630
  bool("costSensitiveScheduling", raw.costSensitiveScheduling);
2630
2631
  bool("snapshotEnabled", raw.snapshotEnabled);
2632
+ bool("sidebarEntry", raw.sidebarEntry);
2631
2633
  if ([
2632
2634
  "low",
2633
2635
  "high",
@@ -5759,6 +5761,52 @@ function writeError(res, e) {
5759
5761
  writeJson(res, statusForCode(payload.code), payload);
5760
5762
  }
5761
5763
  /**
5764
+ * cron → 人话短语(只覆盖本面板生成的三类;自定义返回 null)
5765
+ * 用于在改执行周期时,同步目标描述里的「每 12 小时 / 每天 09:00」等措辞。
5766
+ */
5767
+ function cadencePhrase(cron) {
5768
+ const raw = String(cron || "").trim();
5769
+ if (!raw) return null;
5770
+ const parts = raw.split(/\s+/);
5771
+ if (parts.length !== 5) return null;
5772
+ const [mi, ho, dom, mon, dow] = parts;
5773
+ const num = (s) => /^\d+$/.test(s);
5774
+ const hm = (h, m) => `${h.padStart(2, "0")}:${m.padStart(2, "0")}`;
5775
+ const WEEK = [
5776
+ "日",
5777
+ "一",
5778
+ "二",
5779
+ "三",
5780
+ "四",
5781
+ "五",
5782
+ "六"
5783
+ ];
5784
+ if (mi === "0" && /^\*\/\d+$/.test(ho) && dom === "*" && mon === "*" && dow === "*") {
5785
+ const n = Number(ho.slice(2));
5786
+ return n >= 24 ? "每天 00:00" : `每 ${n} 小时`;
5787
+ }
5788
+ if (num(mi) && num(ho) && dom === "*" && mon === "*" && dow === "*") return `每天 ${hm(ho, mi)}`;
5789
+ if (num(mi) && num(ho) && dom === "*" && mon === "*" && /^[0-6](,[0-6])*$/.test(dow)) return `每${dow.split(",").map(Number).map((d) => `周${WEEK[d]}`).join("、")} ${hm(ho, mi)}`;
5790
+ return null;
5791
+ }
5792
+ /**
5793
+ * 把目标描述里的旧节奏措辞替换成新 cron 对应的人话短语。
5794
+ * 只替换「节奏片段」,其余用户文案原样保留;匹配不到就不动(不硬塞)。
5795
+ */
5796
+ function syncCadenceInDescription(desc, cron) {
5797
+ const text = String(desc || "");
5798
+ const phrase = cadencePhrase(cron);
5799
+ if (!phrase) return text;
5800
+ const withSpace = () => /\d$/.test(phrase) ? phrase + " " : phrase;
5801
+ const rules = [
5802
+ [/每过?\s*\d+\s*小时\s*/, withSpace()],
5803
+ [/每天\s*\d{1,2}:\d{2}\s*/, withSpace()],
5804
+ [/每周[^,。;\s]{0,12}\s*/, withSpace()]
5805
+ ];
5806
+ for (const [re, repl] of rules) if (re.test(text)) return text.replace(re, repl);
5807
+ return text;
5808
+ }
5809
+ /**
5762
5810
  * 构造全部路由。
5763
5811
  *
5764
5812
  * @param service BotService 实例
@@ -5813,6 +5861,58 @@ function makeBotApiRoutes(service, runAction) {
5813
5861
  }
5814
5862
  }
5815
5863
  },
5864
+ {
5865
+ kind: "exact",
5866
+ path: `${API_PREFIX}/bot/update`,
5867
+ handler: async (req, res) => {
5868
+ if (req.method !== "POST") {
5869
+ writeJson(res, 405, {
5870
+ ok: false,
5871
+ code: "METHOD_NOT_ALLOWED"
5872
+ });
5873
+ return;
5874
+ }
5875
+ try {
5876
+ const body = await readJsonBody(req);
5877
+ const botId = String(body?.botId ?? "").trim();
5878
+ if (!botId) throw new BotError("INVALID_ARGS", "缺少 botId");
5879
+ const patch = {};
5880
+ if (typeof body?.name === "string") {
5881
+ const name$1 = body.name.trim();
5882
+ if (!name$1) throw new BotError("INVALID_ARGS", "名称不能为空");
5883
+ patch.name = name$1.slice(0, 40);
5884
+ }
5885
+ if (typeof body?.role === "string") {
5886
+ const role = body.role.trim();
5887
+ if (!role) throw new BotError("INVALID_ARGS", "职责不能为空");
5888
+ patch.role = role.slice(0, 400);
5889
+ }
5890
+ if (typeof body?.systemPromptExtra === "string") patch.systemPromptExtra = body.systemPromptExtra.slice(0, 4e3);
5891
+ let cadencePatch;
5892
+ if (typeof body?.cadence === "string") {
5893
+ cadencePatch = body.cadence.trim();
5894
+ if (cadencePatch && !isValidCron(cadencePatch)) throw new BotError("INVALID_ARGS", "执行周期必须是合法的 5 段 cron,例如 0 0,12 * * *(留空表示不自动跑)");
5895
+ }
5896
+ if (Object.keys(patch).length === 0 && cadencePatch === void 0) throw new BotError("INVALID_ARGS", "没有可更新的字段");
5897
+ const next = await service.update(botId, patch);
5898
+ if (cadencePatch !== void 0) {
5899
+ const goal = await service.getGoal(botId);
5900
+ if (goal) await service.saveGoal(botId, {
5901
+ ...goal,
5902
+ description: cadencePatch ? syncCadenceInDescription(goal.description, cadencePatch) : goal.description,
5903
+ cadence: cadencePatch || void 0,
5904
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5905
+ });
5906
+ }
5907
+ writeJson(res, 200, {
5908
+ ok: true,
5909
+ value: next
5910
+ });
5911
+ } catch (e) {
5912
+ writeError(res, e);
5913
+ }
5914
+ }
5915
+ },
5816
5916
  {
5817
5917
  kind: "exact",
5818
5918
  path: `${API_PREFIX}/bot`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zifeng1023/dsh-bot",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "常驻 AI 队友:记得住、守得住、收得回。默认 dry-run 演习、执行前自动快照、可一键回滚,并支持错峰调度省钱。",
5
5
  "repository": {
6
6
  "type": "git",