@twinsearth/dsh-fang 3.1.0 → 3.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.
Files changed (38) hide show
  1. package/client.js +1511 -1
  2. package/cordis.patch.yml +9 -0
  3. package/package.json +6 -2
  4. package/src/compose.mjs +4 -1
  5. package/src/kernel/paths.mjs +9 -1
  6. package/src/kernel/role.mjs +1 -0
  7. package/src/kernel/types.mjs +5 -1
  8. package/src/lib/ai-secret-store.mjs +202 -0
  9. package/src/lib/boot-guard.mjs +182 -0
  10. package/src/lib/business-producers.mjs +109 -0
  11. package/src/lib/compat.mjs +1 -1
  12. package/src/lib/composer-journal.mjs +8 -0
  13. package/src/lib/decision-events.mjs +129 -0
  14. package/src/lib/decision-ingest-client.mjs +41 -0
  15. package/src/lib/decision-outbox.mjs +129 -0
  16. package/src/lib/desktop-launch.mjs +138 -0
  17. package/src/lib/fork-supervision-settings.mjs +58 -0
  18. package/src/lib/mirror-official-source.mjs +93 -0
  19. package/src/lib/mirror.mjs +10 -3
  20. package/src/lib/producer-contract.mjs +162 -0
  21. package/src/lib/restart-contract.mjs +650 -0
  22. package/src/lib/rule-registry.mjs +69 -0
  23. package/src/lib/ssrf-guard.mjs +170 -0
  24. package/src/lib/umbrella.mjs +143 -18
  25. package/src/plugins/adapter.mjs +31 -2
  26. package/src/plugins/approver.mjs +423 -40
  27. package/src/plugins/decision-center.mjs +2255 -0
  28. package/src/plugins/forker.mjs +20 -1
  29. package/src/plugins/healer.mjs +53 -20
  30. package/src/plugins/imports.mjs +48 -0
  31. package/src/plugins/orchestrator.mjs +814 -42
  32. package/src/plugins/restart-guard.mjs +645 -52
  33. package/src/plugins/scorer.mjs +227 -15
  34. package/src/plugins/umbrella.mjs +18 -14
  35. package/tools/boot-guard.mjs +95 -0
  36. package/tools/decision-ingest.mjs +53 -0
  37. package/tools/desktop-launch.mjs +71 -0
  38. package/tools/fangctl.mjs +229 -1
package/client.js CHANGED
@@ -118,6 +118,10 @@ window.__ModuleLoader__.load({
118
118
  'stop-failed': '分身进程未停止,归档没有生效;任务仍保留。',
119
119
  'derived-session-missing': '会话已不在目录中(可能刚被归档),请刷新。',
120
120
  'capture-failed': '从母体生成元主失败:母体 profile 不可读或补丁解析失败(详情见下方)。',
121
+ 'not-pending': '该票已被处理(可能刚被其他人/另一个标签页处理),请刷新后再看。',
122
+ 'explicit-choice-required': '红色/阻塞票需要逐条显式处理,不能被批量代选。',
123
+ 'session-daily-quota-exceeded': '该会话今日创建决策票已达上限;请先处理已有票,或换会话。',
124
+ 'ai-schema-invalid': 'AI 返回结构不符合 schema,已拒绝写入这张票的建议;可重试。',
121
125
  }
122
126
 
123
127
  // ── 通用工具 ──────────────────────────────────────────────────────────
@@ -558,6 +562,7 @@ window.__ModuleLoader__.load({
558
562
  disc: (size = 14) => glyph(['M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18', 'M12 9.6a2.4 2.4 0 1 0 0 4.8a2.4 2.4 0 0 0 0-4.8', 'M12 3v6.6', 'M12 14.4V21'], size),
559
563
  arrowUp: (size = 14) => glyph(['M12 19V5', 'M6 11l6-6 6 6'], size),
560
564
  play: (size = 13) => glyph(['M8 5l11 7-11 7z'], size),
565
+ inbox: (size = 14) => glyph(['M4 5h16v14H4z', 'M4 13h4l2 3h4l2-3h4'], size),
561
566
  spinner: (size = 14) => {
562
567
  const node = svg('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', class: 'fang-icon fang-spin', 'aria-hidden': 'true', focusable: 'false' })
563
568
  node.appendChild(svg('circle', { cx: 12, cy: 12, r: 8.5, stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-dasharray': '38 12' }))
@@ -949,6 +954,125 @@ window.__ModuleLoader__.load({
949
954
  @media (prefers-reduced-motion:reduce){
950
955
  .fang-console *,.fang-console *::before,.fang-console *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
951
956
  }
957
+
958
+ /* ── 决策收件箱(独立侧边栏入口 + 右侧抽屉 / 独立 Slot)────────────────── */
959
+ .fang-inbox{
960
+ --f-inbox-border:rgba(16,17,20,.1);--f-inbox-text:#1D1D1F;--f-inbox-text2:#5F6368;--f-inbox-surface:#fff;--f-inbox-surface2:#FAFAFC;
961
+ position:relative;display:flex;flex-direction:column;min-height:0;height:100%;background:var(--f-inbox-surface);color:var(--f-inbox-text);
962
+ font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI",sans-serif;font-size:13px;line-height:1.45;
963
+ }
964
+ .fang-inbox *{box-sizing:border-box}
965
+ .fang-inbox button,.fang-inbox input,.fang-inbox select{font-family:inherit}
966
+ .fang-inbox-head{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--f-inbox-border);flex:0 0 auto}
967
+ .fang-inbox-title{font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;min-width:0}
968
+ .fang-inbox-unread{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:#C8102E;color:#fff;font-size:11px;font-weight:600}
969
+ .fang-inbox-actions{margin-left:auto;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
970
+ .fang-inbox-btn{height:26px;padding:0 8px;border-radius:8px;border:1px solid rgba(16,17,20,.14);background:#fff;color:inherit;font:inherit;font-size:12px;cursor:pointer}
971
+ .fang-inbox-btn:hover{background:#F2F2F5}
972
+ .fang-inbox-btn:disabled{opacity:.5;cursor:default}
973
+ .fang-inbox-btn--primary{background:#0A6BE0;border-color:#0A6BE0;color:#fff}
974
+ .fang-inbox-btn--primary:hover{background:#0857B8}
975
+ .fang-inbox-btn--danger{color:#C8102E;border-color:rgba(200,16,46,.3)}
976
+ .fang-inbox-ai{padding:8px 12px;border-bottom:1px solid var(--f-inbox-border);font-size:12px;color:var(--f-inbox-text2);flex:0 0 auto}
977
+ .fang-inbox-ai summary{cursor:pointer;color:var(--f-inbox-text2)}
978
+ .fang-inbox-ai-row{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px;align-items:center}
979
+ .fang-inbox-ai input,.fang-inbox-ai select{height:26px;padding:0 6px;border-radius:7px;border:1px solid rgba(16,17,20,.14);font:inherit;font-size:12px;background:#fff;color:#1D1D1F}
980
+ .fang-inbox-ai-status{font-size:11px;color:#6E6E73;margin-top:2px}
981
+ .fang-inbox-ai-test{font-size:11.5px;margin-top:6px;padding:5px 8px;border-radius:7px;background:#F2F2F5;color:#5F6368}
982
+ .fang-inbox-ai-test--ok{background:rgba(23,128,61,.08);color:#17803D}
983
+ .fang-inbox-ai-test--err{background:rgba(200,16,46,.07);color:#C8102E}
984
+ .fang-inbox-ai-test--testing{background:rgba(10,107,224,.07);color:#0857B8}
985
+ .fang-inbox-ai-risks{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
986
+ .fang-inbox-ai-tag{font-size:10px;font-weight:700;color:#8A5A00;background:rgba(180,83,9,.1);border-radius:4px;padding:0 4px;margin-right:5px}
987
+ .fang-inbox-ai-stream{font-size:11px;color:#0857B8;background:rgba(10,107,224,.05);border-radius:6px;padding:4px 6px;margin-top:4px;white-space:pre-wrap;max-height:120px;overflow:auto}.fang-inbox-risk{font-size:10.5px;padding:1px 5px;border-radius:5px;background:#F2F2F5;color:#5F6368}
988
+ .fang-inbox-risk--low{background:rgba(23,128,61,.1);color:#17803D}
989
+ .fang-inbox-risk--medium{background:rgba(180,83,9,.1);color:#9A4A06}
990
+ .fang-inbox-risk--high{background:rgba(200,16,46,.09);color:#C8102E}
991
+ .fang-inbox-ai-missing{font-size:10.5px;color:#8A5A00;margin-top:3px}
992
+ .fang-inbox-exec{font-size:10.5px;margin-top:3px;color:#5F6368}
993
+ .fang-inbox-exec--done{color:#17803D}
994
+ .fang-inbox-exec--failed{color:#C8102E}
995
+ .fang-inbox-exec--running{color:#0857B8}
996
+ .fang-inbox-toolbar{display:flex;align-items:center;gap:6px;padding:8px 12px;border-bottom:1px solid var(--f-inbox-border);flex-wrap:wrap;flex:0 0 auto}
997
+ .fang-inbox-hint{font-size:11.5px;color:#86868B}
998
+ .fang-inbox-body{flex:1 1 auto;min-height:0;overflow:auto;padding:8px 10px 16px;display:flex;flex-direction:column;gap:8px}
999
+ .fang-inbox-group{border:1px solid var(--f-inbox-border);border-radius:12px;overflow:hidden;background:#fff}
1000
+ .fang-inbox-group-head{display:flex;align-items:center;gap:8px;width:100%;padding:8px 10px;border:0;background:var(--f-inbox-surface2);cursor:pointer;font:inherit;text-align:left;color:inherit}
1001
+ .fang-inbox-group-toggle{display:flex;align-items:center;gap:8px;flex:1;min-width:0;border:0;background:transparent;color:inherit;font:inherit;text-align:left;padding:0;cursor:pointer}
1002
+ .fang-inbox-group-check{flex:none;margin:0;accent-color:#0A6BE0;cursor:pointer}
1003
+ .fang-inbox-group-head b{font-size:12.5px}
1004
+ .fang-inbox-group-head .n{margin-left:auto;font-size:11.5px;color:#6E6E73}
1005
+ .fang-inbox-group[data-level="red"] .fang-inbox-group-head{background:rgba(200,16,46,.06);color:#C8102E}
1006
+ .fang-inbox-group[data-level="yellow"] .fang-inbox-group-head{background:rgba(180,83,9,.07);color:#9A4A06}
1007
+ .fang-inbox-group[data-level="blue"] .fang-inbox-group-head{background:rgba(10,107,224,.06);color:#0857B8}
1008
+ .fang-inbox-group[data-level="green"] .fang-inbox-group-head{background:rgba(23,128,61,.06);color:#17803D}
1009
+ .fang-inbox-group[data-level="gray"] .fang-inbox-group-head{color:#6E6E73}
1010
+ .fang-inbox-item{display:flex;gap:8px;padding:8px 10px;border-top:1px solid rgba(16,17,20,.06);align-items:flex-start}
1011
+ .fang-inbox-item[data-level="red"]{border-left:3px solid #C8102E}
1012
+ .fang-inbox-item[data-level="yellow"]{border-left:3px solid #B45309}
1013
+ .fang-inbox-item[data-level="blue"]{border-left:3px solid #0A6BE0}
1014
+ .fang-inbox-item[data-level="green"]{border-left:3px solid #17803D}
1015
+ .fang-inbox-item[data-level="gray"]{border-left:3px solid #C7C7CC;opacity:.72}
1016
+ .fang-inbox-item.is-active{background:#F2F6FF;outline:2px solid rgba(10,107,224,.35);outline-offset:-2px}
1017
+ .fang-inbox-check{margin-top:2px;flex:0 0 auto}
1018
+ .fang-inbox-main{min-width:0;flex:1 1 auto}
1019
+ .fang-inbox-item-title{font-size:12.5px;font-weight:600;line-height:1.35;overflow-wrap:anywhere}
1020
+ .fang-inbox-item-context{font-size:12px;color:#5F6368;margin-top:2px;white-space:pre-wrap;max-height:72px;overflow:hidden}
1021
+ .fang-inbox-meta{font-size:11px;color:#86868B;margin-top:3px}
1022
+ .fang-inbox-item-actions{display:flex;flex-wrap:wrap;gap:4px;margin-top:5px}
1023
+ .fang-inbox-item-actions .fang-inbox-btn{height:24px;padding:0 7px;font-size:11.5px}
1024
+ .fang-inbox-ai-advice{font-size:11.5px;color:#0857B8;background:rgba(10,107,224,.06);border-radius:6px;padding:4px 6px;margin-top:4px;white-space:pre-wrap}
1025
+ .fang-inbox-empty{padding:28px 16px;text-align:center;color:#86868B;font-size:12px}
1026
+ .fang-inbox-err{margin:8px 10px;padding:8px 10px;border-radius:8px;background:rgba(200,16,46,.07);color:#C8102E;font-size:12px}
1027
+ .fang-inbox-seat{display:inline-flex;align-items:center;justify-content:center;position:relative;width:28px;height:28px;border:0;border-radius:8px;background:transparent;color:inherit;cursor:pointer}
1028
+ .fang-inbox-seat:hover{background:rgba(127,127,127,.1)}
1029
+ .fang-inbox-seat .fang-inbox-badge{position:absolute;top:-3px;right:-4px;min-width:15px;height:15px;padding:0 3px;border-radius:999px;background:#C8102E;color:#fff;font-size:9.5px;line-height:15px;text-align:center;font-weight:600}
1030
+ .fang-decision-mini{margin:0 0 12px;border:1px solid var(--f-border,rgba(16,17,20,.1));border-radius:14px;background:var(--f-surface,#fff);overflow:hidden;box-shadow:0 2px 8px rgba(16,17,20,.05)}
1031
+ .fang-decision-mini-head{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--f-border,rgba(16,17,20,.1))}
1032
+ .fang-decision-mini-head b{font-size:13px}
1033
+ .fang-decision-mini-count{font-size:11px;color:var(--f-text-3,#8A8A8E)}
1034
+ .fang-decision-mini-spacer{flex:1}
1035
+ .fang-decision-mini-refresh{height:24px;padding:0 8px;border-radius:7px;border:1px solid var(--f-border,rgba(16,17,20,.14));background:transparent;color:inherit;font-size:11px;cursor:pointer}
1036
+ .fang-decision-mini-body{padding:6px 10px 10px;display:flex;flex-direction:column;gap:6px;max-height:340px;overflow:auto}
1037
+ .fang-decision-mini-group{border-radius:9px;background:rgba(127,127,127,.04)}
1038
+ .fang-decision-mini-group[data-level="red"]{background:rgba(200,16,46,.05)}
1039
+ .fang-decision-mini-group-head{display:flex;align-items:center;gap:8px;width:100%;padding:6px 8px;border:0;background:transparent;color:inherit;font-size:12px;cursor:pointer;text-align:left}
1040
+ .fang-decision-mini-group-head span{margin-left:auto;font-size:10.5px;color:var(--f-text-3,#8A8A8E)}
1041
+ .fang-decision-mini-list{display:flex;flex-direction:column;gap:6px;padding:0 8px 8px}
1042
+ .fang-decision-mini-item{border-left:3px solid rgba(16,17,20,.18);padding:4px 0 4px 8px}
1043
+ .fang-decision-mini-item[data-level="red"],.fang-decision-mini-group[data-level="red"] .fang-decision-mini-item{border-left-color:#C8102E}
1044
+ .fang-decision-mini-item[data-level="yellow"]{border-left-color:#B45309}
1045
+ .fang-decision-mini-item[data-level="blue"]{border-left-color:#0A6BE0}
1046
+ .fang-decision-mini-title{font-size:12.5px;font-weight:600;overflow-wrap:anywhere}
1047
+ .fang-decision-mini-meta{font-size:10.5px;color:var(--f-text-3,#8A8A8E);margin-top:1px;overflow-wrap:anywhere}
1048
+ .fang-decision-mini-context{font-size:11px;color:var(--f-text-2,#5F6368);margin-top:2px;overflow-wrap:anywhere}
1049
+ .fang-decision-mini-actions{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
1050
+ .fang-decision-mini-actions .fang-inbox-btn{height:22px;font-size:11px;padding:0 7px}
1051
+ .fang-inbox-drawer{position:fixed;top:0;right:0;bottom:0;width:min(420px,92vw);z-index:2147483001;background:#fff;border-left:1px solid rgba(16,17,20,.12);box-shadow:-18px 0 48px rgba(0,0,0,.18);transform:translateX(100%);transition:transform .18s ease;display:flex;flex-direction:column}
1052
+ .fang-inbox-drawer.is-open{transform:none}
1053
+ .fang-inbox-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.26);z-index:2147483000;animation:fang-fade .15s ease}
1054
+ .fang-inbox-stream{font-size:11px;color:#17803D;white-space:nowrap}
1055
+ .fang-inbox-seat.has-red .fang-inbox-badge{animation:fang-inbox-pulse 1.2s ease-in-out infinite}
1056
+ @keyframes fang-inbox-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.18)}}
1057
+ .fang-red-alert-stack{position:fixed;top:14px;left:50%;transform:translateX(-50%);z-index:2147483002;display:flex;flex-direction:column;gap:8px;width:min(560px,92vw)}
1058
+ .fang-inbox-red-alert{background:#fff;border:1px solid rgba(200,16,46,.4);border-left:5px solid #C8102E;border-radius:12px;box-shadow:0 16px 40px rgba(200,16,46,.22);padding:10px 12px;animation:fang-rise .18s ease}
1059
+ .fang-inbox-red-alert-title{display:flex;align-items:center;gap:6px;color:#C8102E;font-weight:700;font-size:13px}
1060
+ .fang-inbox-red-alert-body{font-size:13px;font-weight:600;margin-top:2px;color:#1D1D1F}
1061
+ .fang-inbox-red-alert-context{font-size:11.5px;color:#6E6E73;margin-top:2px}
1062
+ .fang-inbox-red-alert-actions{display:flex;gap:6px;margin-top:7px}
1063
+ .fang-inbox-batch-fail{margin:0 0 8px;padding:8px 10px;border:1px solid rgba(180,83,9,.35);background:rgba(180,83,9,.06);border-radius:10px;font-size:12px}
1064
+ .fang-inbox-batch-fail-title{font-weight:700;color:#9A4A06;margin-bottom:4px}
1065
+ .fang-inbox-batch-fail-row{display:flex;gap:8px;justify-content:space-between;padding:3px 0;border-top:1px dashed rgba(180,83,9,.2)}
1066
+ .fang-inbox-batch-fail-row b{font-weight:600;overflow-wrap:anywhere}
1067
+ .fang-inbox-batch-fail-row span{color:#6E6E73;white-space:nowrap}
1068
+ .fang-inbox-batch-fail-actions{display:flex;gap:6px;margin-top:6px}
1069
+ .fang-inbox-confirm{position:absolute;inset:0;z-index:5;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center;padding:16px}
1070
+ .fang-inbox-confirm-card{width:min(420px,100%);background:#fff;border-radius:14px;box-shadow:0 18px 48px rgba(0,0,0,.24);padding:14px 16px}
1071
+ .fang-inbox-confirm-title{font-size:14px;font-weight:700;color:#1D1D1F}
1072
+ .fang-inbox-confirm-msg{font-size:12.5px;color:#5F6368;margin-top:6px;line-height:1.5}
1073
+ .fang-inbox-confirm-detail{font-size:11.5px;color:#6E6E73;background:#FAFAFC;border-radius:8px;padding:6px 8px;margin-top:6px;white-space:pre-wrap;max-height:120px;overflow:auto}
1074
+ .fang-inbox-confirm-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}
1075
+ @media (prefers-reduced-motion:reduce){.fang-inbox-drawer{transition:none}.fang-inbox-seat.has-red .fang-inbox-badge{animation:none}}
952
1076
  `
953
1077
  target.head.appendChild(style)
954
1078
  }
@@ -1124,6 +1248,11 @@ window.__ModuleLoader__.load({
1124
1248
  aliases: loadAliases(),
1125
1249
  mirror: { state: 'idle', data: null, error: '', busy: '', etag: '' },
1126
1250
  link: { state: 'idle', data: null, error: '', probe: null, target: resolveMotherOrigin(), busy: false },
1251
+ approvals: { state: 'idle', items: [], failed: [], degraded: false, error: '', at: 0 },
1252
+ forkSupervision: { state: 'idle', data: null, error: '', at: 0 },
1253
+ decisions: { state: 'idle', items: [], counts: {}, rev: 0, error: '', at: 0 },
1254
+ decisionAi: { state: 'idle', configured: false, provider: null, model: null, providers: [], error: '' },
1255
+ decisionOpen: { green: false, gray: false },
1127
1256
  lastRefreshAt: 0,
1128
1257
  }
1129
1258
 
@@ -1269,13 +1398,40 @@ window.__ModuleLoader__.load({
1269
1398
  const seq = ++refreshSeq
1270
1399
  if (options.manual) { S.refreshing = true; schedule() }
1271
1400
  try {
1272
- const [statusRes, tasksRes, sessionsRes, essenceRes] = await Promise.all([
1401
+ const [statusRes, tasksRes, sessionsRes, essenceRes, approvalsRes, supervisionRes] = await Promise.all([
1273
1402
  api('/fang/api/status').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1274
1403
  api('/fang/api/tasks').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1275
1404
  api(`/fang/api/sessions?limit=${S.sessionWindow === 'all' ? 1000 : S.sessionWindow}`).catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1276
1405
  api('/fang/api/essence/list').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1406
+ api('/fang/api/approvals').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1407
+ api('/fang/api/forks/supervision').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1277
1408
  ])
1278
1409
  if (!alive || seq !== refreshSeq) return
1410
+ if (supervisionRes.status === 200 && supervisionRes.body?.ok) {
1411
+ S.forkSupervision = { state: 'ready', data: supervisionRes.body, error: '', at: Date.now() }
1412
+ } else {
1413
+ S.forkSupervision = {
1414
+ ...S.forkSupervision, state: 'error',
1415
+ error: supervisionRes.body?.error || (supervisionRes.status ? 'http-' + supervisionRes.status : 'network'),
1416
+ at: Date.now(),
1417
+ }
1418
+ }
1419
+ if (approvalsRes.status === 200 && approvalsRes.body && approvalsRes.body.ok !== false) {
1420
+ S.approvals = {
1421
+ state: 'ready',
1422
+ items: Array.isArray(approvalsRes.body.items) ? approvalsRes.body.items : [],
1423
+ failed: Array.isArray(approvalsRes.body.failed) ? approvalsRes.body.failed : [],
1424
+ degraded: approvalsRes.body.degraded === true,
1425
+ error: '', at: Date.now(),
1426
+ }
1427
+ } else {
1428
+ S.approvals = {
1429
+ ...S.approvals,
1430
+ state: 'error',
1431
+ error: approvalsRes.body?.error || (approvalsRes.status ? 'http-' + approvalsRes.status : 'network'),
1432
+ at: Date.now(),
1433
+ }
1434
+ }
1279
1435
 
1280
1436
  if (essenceRes.status === 200 && essenceRes.body && Array.isArray(essenceRes.body.essences)) {
1281
1437
  S.essenceList = { data: essenceRes.body, error: '', at: Date.now() }
@@ -2224,10 +2380,140 @@ window.__ModuleLoader__.load({
2224
2380
 
2225
2381
  const unsubscribe = deriveStore.subscribe((value) => { S.derive = value; schedule() })
2226
2382
 
2383
+ async function decideApproval(item, outcome) {
2384
+ if (isBusy()) return
2385
+ const key = `${item?.source ?? ''}:${item?.taskId ?? ''}:${item?.approvalId ?? ''}`
2386
+ S.busy = 'approval:' + key
2387
+ schedule(true)
2388
+ const result = await api('/fang/api/approvals/decide', {
2389
+ method: 'POST',
2390
+ body: JSON.stringify({
2391
+ source: item?.source,
2392
+ taskId: item?.taskId ?? null,
2393
+ approvalId: item?.approvalId,
2394
+ outcome,
2395
+ by: 'fang-ui',
2396
+ }),
2397
+ })
2398
+ S.busy = ''
2399
+ if (result.status === 200 && result.body?.ok !== false) {
2400
+ setNotice({
2401
+ tone: 'ok',
2402
+ title: outcome === 'approved' ? '已批准' : '已拒绝',
2403
+ message: `${item?.source === 'mother' ? '母体' : '分身'} · ${item?.title || item?.approvalId || ''}`,
2404
+ })
2405
+ } else if (result.status === 409) {
2406
+ setNotice({ tone: 'warn', title: '已被处理', message: '该审批项已结算或不存在,列表将刷新。' })
2407
+ } else {
2408
+ setNotice({
2409
+ tone: 'bad',
2410
+ title: '审批操作失败',
2411
+ message: failureHint(result.body?.error || (result.status ? 'http-' + result.status : 'network')),
2412
+ detail: diagnosticText(result.diagnostic),
2413
+ })
2414
+ }
2415
+ await refresh({ manual: true })
2416
+ }
2417
+
2418
+ async function decisionAction(ticket, action, option) {
2419
+ if (isBusy()) return
2420
+ const key = `decision:${ticket?.id ?? ''}`
2421
+ S.busy = key
2422
+ schedule(true)
2423
+ const path = action === 'abandon' ? '/fang/api/decisions/abandon' : '/fang/api/decisions/resolve'
2424
+ const result = await api(path, {
2425
+ method: 'POST',
2426
+ body: JSON.stringify({ id: ticket?.id, option, by: 'fang-ui' }),
2427
+ })
2428
+ S.busy = ''
2429
+ if (result.status === 200 && result.body?.ok !== false) {
2430
+ setNotice({ tone: 'ok', title: action === 'abandon' ? '已放弃' : '已处理', message: ticket?.title || ticket?.id || '' })
2431
+ } else if (result.status === 409) {
2432
+ setNotice({ tone: 'warn', title: '已被处理', message: '该决策已结算或过期,列表将刷新。' })
2433
+ } else {
2434
+ setNotice({ tone: 'bad', title: '决策操作失败', message: failureHint(result.body?.error || (result.status ? 'http-' + result.status : 'network')) })
2435
+ }
2436
+ await refresh({ manual: true })
2437
+ }
2438
+
2439
+ async function decisionBatch(level) {
2440
+ if (isBusy()) return
2441
+ const items = (S.decisions?.items ?? []).filter((item) => item.status === 'pending' && item.level === level)
2442
+ if (!items.length) return
2443
+ S.busy = `decision-batch:${level}`
2444
+ schedule(true)
2445
+ const result = await api('/fang/api/decisions/resolve', {
2446
+ method: 'POST',
2447
+ body: JSON.stringify({ ids: items.map((item) => item.id), by: 'fang-ui' }),
2448
+ })
2449
+ S.busy = ''
2450
+ if (result.status === 200 && result.body?.ok !== false) {
2451
+ setNotice({ tone: 'ok', title: '已批量处理', message: `${level} · ${items.length} 项` })
2452
+ } else {
2453
+ setNotice({ tone: 'bad', title: '批量处理失败', message: failureHint(result.body?.error || 'http-' + result.status) })
2454
+ }
2455
+ await refresh({ manual: true })
2456
+ }
2457
+
2458
+ async function saveDecisionAi() {
2459
+ const read = (name) => String(view.querySelector(`[data-ai-field="${name}"]`)?.value ?? '').trim()
2460
+ const provider = read('provider') || 'deepseek'
2461
+ const apiKey = read('apiKey')
2462
+ const model = read('model')
2463
+ const baseUrl = read('baseUrl')
2464
+ if (!apiKey) { setNotice({ tone: 'warn', title: '需要 API Key', message: '请填入你自己的模型 API Key;只保存在宿主内存,不写入仓库。' }); return }
2465
+ const result = await api('/fang/api/decisions/ai/config', {
2466
+ method: 'POST',
2467
+ body: JSON.stringify({ provider, apiKey, model: model || undefined, baseUrl: baseUrl || undefined }),
2468
+ })
2469
+ if (result.status === 200 && result.body?.ok !== false) {
2470
+ setNotice({ tone: 'ok', title: 'AI 已启用', message: `${result.body.provider || provider} · ${result.body.model || model}` })
2471
+ } else {
2472
+ setNotice({ tone: 'bad', title: 'AI 配置失败', message: failureHint(result.body?.error || result.body?.reason || 'http-' + result.status) })
2473
+ }
2474
+ await refresh({ manual: true })
2475
+ }
2476
+
2477
+ async function adviseDecision(ticket) {
2478
+ if (isBusy()) return
2479
+ S.busy = `decision-ai:${ticket?.id ?? ''}`
2480
+ schedule(true)
2481
+ const result = await api('/fang/api/decisions/ai/advise', { method: 'POST', body: JSON.stringify({ id: ticket?.id }) })
2482
+ S.busy = ''
2483
+ if (result.status === 200 && result.body?.ok !== false) {
2484
+ setNotice({ tone: 'ok', title: 'AI 建议已生成', message: result.body.advice?.summary || ticket?.title || '' })
2485
+ } else {
2486
+ setNotice({ tone: 'bad', title: 'AI 建议失败', message: failureHint(result.body?.error || result.body?.reason || 'http-' + result.status) })
2487
+ }
2488
+ await refresh({ manual: true })
2489
+ }
2490
+
2491
+ async function setForkSupervision(patch = {}) {
2492
+ const res = await api('/fang/api/forks/supervision', { method: 'POST', body: JSON.stringify(patch) })
2493
+ if (res.status === 200 && res.body?.ok) {
2494
+ S.forkSupervision = { state: 'ready', data: res.body, error: '', at: Date.now() }
2495
+ setNotice({ tone: 'ok', title: '分身看护已更新', message: `自动启动 ${res.body.effective?.autostartForks ? '开' : '关'} · 崩溃重启 ${res.body.effective?.supervise ? '开' : '关'}` })
2496
+ } else {
2497
+ S.forkSupervision = {
2498
+ ...S.forkSupervision, state: 'error',
2499
+ error: res.body?.error || (res.status ? 'http-' + res.status : 'network'), at: Date.now(),
2500
+ }
2501
+ setNotice({ tone: 'bad', title: '分身看护更新失败', message: failureHint(S.forkSupervision.error) })
2502
+ }
2503
+ schedule(true)
2504
+ return res
2505
+ }
2506
+
2227
2507
  const app = {
2228
2508
  state: S, view, render, schedule, refresh, deriveTask, openMother, closeModal,
2229
2509
  archiveTask, restoreTask, deleteArchive, promoteTask, openTask, copyText, captureEssence,
2230
2510
  cloneMotherProfile, syncEssence, syncEssences, setSessionWindow, essenceRuntime,
2511
+ decideApproval,
2512
+ setForkSupervision,
2513
+ decisionAction,
2514
+ decisionBatch,
2515
+ saveDecisionAi,
2516
+ adviseDecision,
2231
2517
  openEssence, copyEssence, archiveEssence, deleteEssence, downloadEssence, essenceImport,
2232
2518
  essenceBackup, essenceRestore, openEssenceDetail, unfreezeEssence, stopEssenceRuntime,
2233
2519
  openBranches, forkBranch, activateBranch, deriveFromEssence,
@@ -2404,6 +2690,7 @@ window.__ModuleLoader__.load({
2404
2690
 
2405
2691
  function renderStats(S) {
2406
2692
  const data = S.status.data
2693
+ const restart = data?.restart
2407
2694
  const ready = Number(data?.tasks?.ready ?? 0) || 0
2408
2695
  const running = Number(data?.tasks?.running ?? 0) || 0
2409
2696
  const max = data?.tasks?.max ?? '—'
@@ -2427,6 +2714,15 @@ window.__ModuleLoader__.load({
2427
2714
  item(ready > 0 ? 'ok' : 'neutral', '就绪', data ? `${ready}/${max}` : '—', `适配器已握手的分身 ${ready} 个 / 上限 ${max} 个。`),
2428
2715
  h('span', { class: 'stat-sep', 'aria-hidden': 'true' }),
2429
2716
  item(running > 0 ? 'bad' : 'neutral', '未握手', data ? String(running) : '—', `进程在跑但适配器未握手的分身 ${running} 个;大于 0 时按三色模型标红。`),
2717
+ ...(restart?.available ? [
2718
+ h('span', { class: 'stat-sep', 'aria-hidden': 'true' }),
2719
+ item(
2720
+ restart.redLineAutoAllowed ? 'bad' : (restart.state && restart.state !== 'idle' ? 'warn' : 'neutral'),
2721
+ '重启守卫',
2722
+ restart.mode ? String(restart.mode) : '—',
2723
+ `重启守卫:state=${restart.state ?? '—'} · mode=${restart.mode ?? '—'} · authMode=${restart.authMode ?? '—'} · strictRedLine=${restart.strictRedLine === false ? 'false(红灯可自动放行)' : 'true'} · 决策层不执行`,
2724
+ ),
2725
+ ] : []),
2430
2726
  total > 0 ? h('span', { class: 'stat-sep', 'aria-hidden': 'true' }) : null,
2431
2727
  total > 0 ? item('neutral', '项目', String(total), `当前分身项目总数 ${total}(含临时与存档)。`) : null)
2432
2728
  }
@@ -2485,6 +2781,7 @@ window.__ModuleLoader__.load({
2485
2781
 
2486
2782
  function renderHeader(S, app) {
2487
2783
  const data = S.status.data
2784
+ const restart = data?.restart
2488
2785
  const cap = projectCapacity(data, S.tasks.items)
2489
2786
  const quotaFull = !cap.deriveEnabled || cap.headroom <= 0
2490
2787
  const reasonId = 'fang-quota-reason'
@@ -2499,6 +2796,13 @@ window.__ModuleLoader__.load({
2499
2796
  h('span', { class: 'fh-sub' }, '母体 × 分身 · 三区控制台'))),
2500
2797
  renderStats(S),
2501
2798
  h('div', { class: 'fh-actions' },
2799
+ restart?.available && restart.redLineAutoAllowed
2800
+ ? chip('warn', '红灯自动放行', {
2801
+ title: 'strictRedLine=false:auto 授权模式下红灯可被策略自动放行。这只到决策层;execution.executed 恒为 false,真正重启仍由外部 supervisor 的 armed 清单决定。',
2802
+ state: 'red-line-auto-allowed',
2803
+ danger: true,
2804
+ })
2805
+ : null,
2502
2806
  quotaFull ? h('span', { class: 'quota-reason', id: reasonId, tabindex: -1, 'data-reason': 'M-05', 'data-reason-code': 'quota-exceeded' }, `配额已满(${cap.used}/${cap.limit}):先归档旧分身。`) : null,
2503
2807
  button(`${S.view === 'archive' ? '返回面板' : `读档 (${archivedCount})`}`, {
2504
2808
  variant: S.view === 'archive' ? 'ghost' : 'quiet', size: 'sm', dataBtnId: 'M-01',
@@ -2511,6 +2815,11 @@ window.__ModuleLoader__.load({
2511
2815
  title: '临时 = 快速派生的空白分身与空会话;偏好会记住(localStorage)',
2512
2816
  onClick: () => app.toggleTemporary(), fk: 'temp-toggle', dataBtnId: 'M-02',
2513
2817
  }),
2818
+ button('收件箱', {
2819
+ variant: 'ghost', size: 'sm', icon: icon('inbox', 14),
2820
+ title: '决策收件箱:独立抽屉;红/黄/蓝/绿/灰分组、未读计数、键盘导航与批量处理',
2821
+ onClick: () => openInboxExternally?.(), fk: 'inbox', dataBtnId: 'M-06',
2822
+ }),
2514
2823
  button('刷新', {
2515
2824
  variant: 'ghost', size: 'sm', icon: icon('refresh', 14), busy: S.refreshing,
2516
2825
  title: '重新读取母体状态、分身任务与母体会话', onClick: () => void app.refresh({ manual: true }), fk: 'refresh', dataBtnId: 'M-03',
@@ -2551,6 +2860,63 @@ window.__ModuleLoader__.load({
2551
2860
  }
2552
2861
 
2553
2862
  // ── 全局提示(派生结果 / 动作结果 / 接口错误)───────────────────────────
2863
+ // 待批区:只读母体聚合接口;不直接跨 fork adapter
2864
+ // 瓮城·决策中心:注意力分级面板。红色置顶;绿/灰默认折叠;所有操作等接口返回。
2865
+ function renderApprovals(S, app) {
2866
+ const state = S.approvals || { state: 'idle', items: [], failed: [], degraded: false, error: '' }
2867
+ if (state.state === 'error' && state.items.length === 0) {
2868
+ return [h('div', { class: 'notice notice--warn', role: 'status' },
2869
+ h('div', { class: 'notice-main' },
2870
+ h('div', { class: 'notice-title' }, icon('alert', 14), '待批信息不可用'),
2871
+ h('div', { class: 'notice-text' }, failureHint(state.error || 'network'))))]
2872
+ }
2873
+ if (state.items.length === 0 && state.failed.length === 0) return []
2874
+ const toneOf = (risk) => risk === 'red' ? 'bad' : risk === 'yellow' ? 'warn' : risk === 'blue' ? 'info' : 'ok'
2875
+ const ttlText = (deadlineAt) => {
2876
+ const at = Number(deadlineAt)
2877
+ if (!Number.isFinite(at) || at <= 0) return '无期限'
2878
+ const left = at - Date.now()
2879
+ if (left <= 0) return '已到期'
2880
+ const seconds = Math.ceil(left / 1000)
2881
+ return seconds < 60 ? `${seconds}s` : `${Math.ceil(seconds / 60)}m`
2882
+ }
2883
+ const rows = state.items.map((item) => {
2884
+ const key = `${item.source}:${item.taskId ?? ''}:${item.approvalId}`
2885
+ const busy = S.busy === 'approval:' + key
2886
+ const orphaned = item.state === 'orphaned'
2887
+ return h('div', {
2888
+ class: 'notice', role: 'listitem', 'data-approval-key': key, 'data-approval-state': item.state,
2889
+ style: { display: 'flex', alignItems: 'center', gap: 8, padding: '7px 9px', marginTop: 4 },
2890
+ },
2891
+ chip(toneOf(item.risk), item.source === 'mother' ? '母体' : '分身'),
2892
+ h('div', { class: 'notice-main', style: { minWidth: 0, flex: 1 } },
2893
+ h('div', { class: 'notice-title', style: { fontSize: 13 } }, clampText(item.title) || item.approvalId || '未命名审批'),
2894
+ h('div', { class: 'notice-text', style: { fontSize: 12 } },
2895
+ `${item.kind || 'approval'} · ${orphaned ? '已中断(重启前)' : '剩余 ' + ttlText(item.deadlineAt)}${item.taskId ? ' · ' + short(item.taskId, 10) : ''}`)),
2896
+ orphaned ? null : button('批准', {
2897
+ size: 'sm', variant: 'primary', busy,
2898
+ disabled: busy,
2899
+ onClick: () => void app.decideApproval(item, 'approved'),
2900
+ }),
2901
+ orphaned ? null : button('拒绝', {
2902
+ size: 'sm', variant: 'ghost', busy,
2903
+ disabled: busy,
2904
+ onClick: () => void app.decideApproval(item, 'denied'),
2905
+ }))
2906
+ })
2907
+ return [h('div', {
2908
+ class: 'notice notice--info', role: 'region', 'aria-label': '待批事项',
2909
+ 'data-zone': 'approvals', style: { padding: '8px 10px' },
2910
+ },
2911
+ h('div', { class: 'notice-main' },
2912
+ h('div', { class: 'notice-title' }, icon('alert', 14), `待批 ${state.items.length}`,
2913
+ state.failed.length > 0 ? h('span', { class: 'chip', title: '部分来源不可用;不显示假 pending' }, '部分不可用') : null),
2914
+ state.failed.length > 0
2915
+ ? h('div', { class: 'notice-text' }, `前端不可用:${state.failed.map((entry) => entry.taskId || '母体').join('、')}`)
2916
+ : null,
2917
+ h('div', { role: 'list', style: { marginTop: 4 } }, ...rows)))]
2918
+ }
2919
+
2554
2920
  function renderNotices(S, app) {
2555
2921
  const nodes = []
2556
2922
  const derive = S.derive
@@ -2959,6 +3325,134 @@ window.__ModuleLoader__.load({
2959
3325
  }
2960
3326
 
2961
3327
  // ── 右栏:分身区 ─────────────────────────────────────────────────────
3328
+ /**
3329
+ * 右侧工作区内的「决策中心」区域:红置顶、黄/蓝分组、绿/灰默认折叠;
3330
+ * 操作后重新拉取(不乐观删除);409 显示「已被处理」。
3331
+ */
3332
+ function renderDecisionMini() {
3333
+ const section = h('div', { class: 'fang-decision-mini', 'data-zone': 'decision-mini' })
3334
+ const state = {
3335
+ loading: true, items: [], error: '', notice: '', busy: false,
3336
+ collapsed: new Set(['green', 'gray']),
3337
+ }
3338
+ const LEVELS_MINI = [
3339
+ { level: 'red', label: '红色 · 阻塞', tone: 'red' },
3340
+ { level: 'yellow', label: '黄色', tone: 'yellow' },
3341
+ { level: 'blue', label: '蓝色', tone: 'blue' },
3342
+ { level: 'green', label: '绿色', tone: 'green' },
3343
+ { level: 'gray', label: '灰色归档', tone: 'gray' },
3344
+ ]
3345
+ const remaining = (expiresAt) => {
3346
+ if (!expiresAt) return '无期限'
3347
+ const diff = Number(expiresAt) - Date.now()
3348
+ if (diff <= 0) return '已过期'
3349
+ const minutes = Math.max(1, Math.round(diff / 60000))
3350
+ if (minutes < 60) return `剩余 ${minutes} 分钟`
3351
+ return `剩余 ${Math.floor(minutes / 60)} 小时`
3352
+ }
3353
+ const sourceLabel = (item) => {
3354
+ const source = item?.source ?? {}
3355
+ return String(source.rawSource || source.agentRole || 'unknown')
3356
+ + (source.taskName ? ` · ${source.taskName}` : '')
3357
+ + (source.sessionId && source.sessionId !== 'unknown' ? ` · ${source.sessionId}` : '')
3358
+ }
3359
+ const itemsFor = (level) => level === 'gray'
3360
+ ? state.items.filter((item) => item.status !== 'pending')
3361
+ : state.items.filter((item) => item.status === 'pending' && item.level === level)
3362
+
3363
+ const load = async () => {
3364
+ const result = await api('/fang/api/decisions?includeArchived=1')
3365
+ if (result.status === 200 && result.body?.ok !== false) {
3366
+ state.items = Array.isArray(result.body.items) ? result.body.items : []
3367
+ state.error = ''
3368
+ } else {
3369
+ state.error = result.body?.error || (result.status ? 'http-' + result.status : 'network')
3370
+ }
3371
+ state.loading = false
3372
+ render()
3373
+ }
3374
+ const act = async (item, option) => {
3375
+ if (state.busy) return
3376
+ state.busy = true
3377
+ state.notice = ''
3378
+ render()
3379
+ const result = option === null
3380
+ ? await api('/fang/api/decisions/abandon', { method: 'POST', body: JSON.stringify({ id: item.id, by: 'fang-panel' }) })
3381
+ : await api('/fang/api/decisions/resolve', { method: 'POST', body: JSON.stringify({ id: item.id, option, by: 'fang-panel' }) })
3382
+ if (result.status === 409) state.notice = '该票已被处理(可能刚被其他人/另一标签页处理),已刷新'
3383
+ else if (result.status !== 200 || result.body?.ok === false) state.notice = '操作失败:' + failureHint(result.body?.reason || result.body?.error || ('http-' + result.status))
3384
+ state.busy = false
3385
+ await load() // 不做乐观删除:无论成功失败都重新拉取
3386
+ }
3387
+
3388
+ function render() {
3389
+ const pending = state.items.filter((item) => item.status === 'pending')
3390
+ const head = h('div', { class: 'fang-decision-mini-head' },
3391
+ h('b', null, '决策中心'),
3392
+ h('span', { class: 'fang-decision-mini-count' }, pending.length ? `${pending.length} 待处理` : '暂无待处理'),
3393
+ h('span', { class: 'fang-decision-mini-spacer' }),
3394
+ h('button', { type: 'button', class: 'fang-decision-mini-refresh', title: '重新拉取', onClick: () => { if (!state.busy) void load() } }, '刷新'))
3395
+ const body = h('div', { class: 'fang-decision-mini-body' })
3396
+ if (state.notice) body.append(h('div', { class: 'notice notice--warn', role: 'status' }, state.notice))
3397
+ if (state.loading) body.append(h('div', { class: 'loading-line' }, icon('spinner', 13), '正在读取决策…'))
3398
+ else if (state.error) body.append(h('div', { class: 'notice notice--bad', role: 'alert' }, '决策中心不可用:' + failureHint(state.error)))
3399
+ else {
3400
+ for (const meta of LEVELS_MINI) {
3401
+ const items = itemsFor(meta.level)
3402
+ if (!items.length) continue
3403
+ const collapsed = state.collapsed.has(meta.level)
3404
+ const group = h('div', { class: 'fang-decision-mini-group', 'data-level': meta.level },
3405
+ h('button', {
3406
+ type: 'button', class: 'fang-decision-mini-group-head',
3407
+ 'aria-expanded': collapsed ? 'false' : 'true',
3408
+ onClick: () => {
3409
+ if (collapsed) state.collapsed.delete(meta.level)
3410
+ else state.collapsed.add(meta.level)
3411
+ render()
3412
+ },
3413
+ }, h('b', null, meta.label), h('span', null, `${items.length} 项 · ${collapsed ? '展开' : '收起'}`)))
3414
+ if (!collapsed) {
3415
+ const list = h('div', { class: 'fang-decision-mini-list' })
3416
+ for (const item of items.slice(0, 30)) {
3417
+ const actions = h('div', { class: 'fang-decision-mini-actions' })
3418
+ for (const option of (item.options || []).slice(0, 4)) {
3419
+ actions.append(h('button', {
3420
+ type: 'button', class: 'fang-inbox-btn' + (option.isRecommended ? ' fang-inbox-btn--primary' : ''),
3421
+ disabled: state.busy || item.status !== 'pending',
3422
+ onClick: () => void act(item, option.value),
3423
+ }, option.label || option.value))
3424
+ }
3425
+ if (item.status === 'pending') {
3426
+ actions.append(h('button', {
3427
+ type: 'button', class: 'fang-inbox-btn fang-inbox-btn--danger', disabled: state.busy,
3428
+ onClick: () => void act(item, null),
3429
+ }, '放弃/忽略'))
3430
+ }
3431
+ list.append(h('div', { class: 'fang-decision-mini-item', 'data-inbox-id': item.id, 'data-level': item.level },
3432
+ h('div', { class: 'fang-decision-mini-title' }, inboxText(item.title) || item.id),
3433
+ h('div', { class: 'fang-decision-mini-meta' }, `${sourceLabel(item)} · ${remaining(item.expiresAt)}`),
3434
+ item.context ? h('div', { class: 'fang-decision-mini-context' }, inboxText(item.context, 240)) : null,
3435
+ actions))
3436
+ }
3437
+ group.append(list)
3438
+ }
3439
+ body.append(group)
3440
+ }
3441
+ if (!pending.length && !itemsFor('gray').length) body.append(h('div', { class: 'loading-line' }, '没有待处理决策。'))
3442
+ }
3443
+ section.replaceChildren(head, body)
3444
+ }
3445
+
3446
+ render()
3447
+ void load()
3448
+ const timer = setInterval(() => {
3449
+ if (!section.isConnected) { clearInterval(timer); return }
3450
+ if (!state.busy) void load()
3451
+ }, 5000)
3452
+ timer.unref?.()
3453
+ return section
3454
+ }
3455
+
2962
3456
  function renderForkPanel(S, app) {
2963
3457
  const freshness = freshnessOf(S)
2964
3458
  const all = S.tasks.items
@@ -2992,6 +3486,7 @@ window.__ModuleLoader__.load({
2992
3486
  renderCapacityStrip(cap))
2993
3487
 
2994
3488
  const scroll = h('div', { class: 'panel-scroll', 'data-sk': 'right' })
3489
+ scroll.append(renderDecisionMini())
2995
3490
 
2996
3491
  if (S.tasks.state === 'loading' && all.length === 0) {
2997
3492
  scroll.append(h('div', { class: 'loading-line' }, icon('spinner', 14), '正在读取分身任务…'))
@@ -3735,10 +4230,44 @@ window.__ModuleLoader__.load({
3735
4230
  h('a', { class: 'fang-portal-link', href: '/fang/panel', target: '_blank', rel: 'noopener' }, '独立门户', icon('external', 11))))
3736
4231
  }
3737
4232
 
4233
+ function renderForkSupervision(S, app) {
4234
+ const sv = S.forkSupervision || { state: 'idle' }
4235
+ if (sv.state === 'idle') return null
4236
+ if (sv.state === 'error') {
4237
+ return h('div', { class: 'notice notice--warn', role: 'status', 'data-zone': 'fork-supervision' },
4238
+ h('div', { class: 'notice-main' },
4239
+ h('div', { class: 'notice-title' }, '分身看护不可用'),
4240
+ h('div', { class: 'notice-text' }, failureHint(sv.error || 'network'))),
4241
+ button('重试', { size: 'sm', variant: 'ghost', onClick: () => void app.refresh({ manual: true }) }))
4242
+ }
4243
+ const data = sv.data || {}
4244
+ const eff = data.effective || {}
4245
+ const persisted = data.persisted || {}
4246
+ const toggle = (key, label, checked, title) => h('label', {
4247
+ class: 'supervision-toggle', title, style: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, cursor: 'pointer' },
4248
+ },
4249
+ h('input', {
4250
+ type: 'checkbox', checked: checked === true, 'data-supervision': key,
4251
+ onChange: () => void app.setForkSupervision({ [key]: !checked }),
4252
+ }), label)
4253
+ return h('div', { class: 'notice notice--info', role: 'status', 'data-zone': 'fork-supervision', style: { padding: '8px 10px' } },
4254
+ h('div', { class: 'notice-main', style: { width: '100%' } },
4255
+ h('div', { class: 'notice-title' }, '分身看护'),
4256
+ h('div', { class: 'notice-text', style: { display: 'flex', flexWrap: 'wrap', gap: 14, alignItems: 'center', marginTop: 4 } },
4257
+ toggle('autostartForks', '自动启动分身(watchdog 下次启动生效)', eff.autostartForks === true),
4258
+ toggle('supervise', '崩溃自动重启(立即生效)', eff.supervise === true),
4259
+ h('span', { style: { color: 'var(--f-text-3)' } },
4260
+ `持久化:${persisted.exists ? '已保存' : '默认值'}${data.forker?.enabled === true ? ' · forker 看护中' : ''}`))))
4261
+ }
4262
+
3738
4263
  function renderApp(S, app) {
3739
4264
  const frag = document.createDocumentFragment()
3740
4265
  frag.append(renderHeader(S, app))
3741
4266
  for (const node of renderNotices(S, app)) frag.append(node)
4267
+ for (const node of renderApprovals(S, app)) frag.append(node)
4268
+ const forkSupervisionNode = renderForkSupervision(S, app)
4269
+ if (forkSupervisionNode) frag.append(forkSupervisionNode)
4270
+ // 决策中心已移出主面板:独立「收件箱」侧栏入口 + 右侧抽屉 / sidebar.right.pane.tab。
3742
4271
 
3743
4272
  if (S.role.value === 'mother') {
3744
4273
  const body = h('div', { class: 'fang-body', 'aria-busy': S.refreshing ? 'true' : undefined })
@@ -4122,6 +4651,911 @@ window.__ModuleLoader__.load({
4122
4651
  return () => { trigger.remove(); popup.remove() }
4123
4652
  }
4124
4653
 
4654
+ // ── 决策收件箱(独立侧栏入口 + 右侧抽屉 / 独立 Slot)────────────────────
4655
+ // 数据与渲染都不依赖「瓮城」主面板:右侧 slot / 抽屉挂载时自轮询 /fang/api/decisions。
4656
+ const DECISION_INBOX = Object.freeze({ id: 'fang-decision-inbox', kind: 'fangDecisionInbox', label: '收件箱' })
4657
+ /** 插件 apply 时注入;主面板 Header 用它兜底打开收件箱(侧栏 Slot 不可用时)。 */
4658
+ let openInboxExternally = null
4659
+ const INBOX_LEVELS = Object.freeze([
4660
+ { level: 'red', label: '紧急决策', hint: '会阻塞 Agent' },
4661
+ { level: 'yellow', label: '建议决策', hint: '影响方向/进度' },
4662
+ { level: 'blue', label: '日常建议', hint: '可按推荐处理' },
4663
+ { level: 'green', label: '通知与汇报', hint: '默认折叠' },
4664
+ { level: 'gray', label: '已归档 / 过期', hint: '只读' },
4665
+ ])
4666
+ const INBOX_POLL_MS = 5000
4667
+ const inboxText = (value, max = 420) => {
4668
+ const text = String(value ?? '').trim()
4669
+ return text.length > max ? text.slice(0, max - 1) + '…' : text
4670
+ }
4671
+ function inboxButton(label, onClick, options = {}) {
4672
+ const node = h('button', {
4673
+ type: 'button',
4674
+ class: 'fang-inbox-btn' + (options.primary ? ' fang-inbox-btn--primary' : '') + (options.danger ? ' fang-inbox-btn--danger' : ''),
4675
+ disabled: options.disabled === true,
4676
+ title: options.title,
4677
+ 'aria-label': options.ariaLabel,
4678
+ }, label)
4679
+ if (typeof onClick === 'function') node.addEventListener('click', (event) => { event.preventDefault(); onClick(event) })
4680
+ return node
4681
+ }
4682
+
4683
+ const INBOX_SEEN_KEY = 'fang.inbox.seenRev'
4684
+ function readInboxSeenRev() {
4685
+ try {
4686
+ const value = Number(window?.localStorage?.getItem(INBOX_SEEN_KEY))
4687
+ return Number.isFinite(value) && value > 0 ? value : 0
4688
+ } catch { return 0 }
4689
+ }
4690
+ function writeInboxSeenRev(rev) {
4691
+ try { window?.localStorage?.setItem(INBOX_SEEN_KEY, String(rev)) } catch { /* local only */ }
4692
+ }
4693
+
4694
+ /** 红色强提醒:页面内红色横幅 + 标题闪烁 +(已授权时)系统通知;同一 ticket 只提醒一次。 */
4695
+ function showRedDecisionAlert(ticket, store) {
4696
+ const doc = typeof document !== 'undefined' ? document : null
4697
+ if (!doc || !ticket?.id) return
4698
+ let stack = doc.querySelector('[data-fang-red-alerts]')
4699
+ if (!stack) {
4700
+ stack = h('div', { class: 'fang-red-alert-stack', 'data-fang-red-alerts': '1' })
4701
+ doc.body.append(stack)
4702
+ }
4703
+ if (stack.querySelector(`[data-red-ticket="${ticket.id}"]`)) return
4704
+ const remove = () => { node.remove(); if (!stack.childElementCount) stack.remove() }
4705
+ const node = h('div', {
4706
+ class: 'fang-inbox-red-alert', role: 'alert', 'data-red-ticket': ticket.id,
4707
+ },
4708
+ h('div', { class: 'fang-inbox-red-alert-title' }, icon('alert', 15), '红色决策待处理'),
4709
+ h('div', { class: 'fang-inbox-red-alert-body' }, inboxText(ticket.title, 120)),
4710
+ ticket.context ? h('div', { class: 'fang-inbox-red-alert-context' }, inboxText(ticket.context, 160)) : null,
4711
+ h('div', { class: 'fang-inbox-red-alert-actions' },
4712
+ inboxButton('打开收件箱', () => { remove(); store.openHandler?.() }, { primary: true }),
4713
+ inboxButton('关闭', remove)))
4714
+ stack.append(node)
4715
+ // 标题闪烁(不改回原值前先记下),10s 后恢复。
4716
+ try {
4717
+ const base = String(doc.title || '').replace(/^● 红色决策 · /, '')
4718
+ doc.title = '● 红色决策 · ' + base
4719
+ clearTimeout(showRedDecisionAlert._titleTimer)
4720
+ showRedDecisionAlert._titleTimer = setTimeout(() => {
4721
+ const current = String(doc.title || '')
4722
+ if (current.startsWith('● 红色决策 · ')) doc.title = current.replace('● 红色决策 · ', '')
4723
+ }, 10000)
4724
+ } catch { /* ignore */ }
4725
+ // 系统通知只在用户已授权时发;不在这里自动申请权限(避免打扰)。
4726
+ try {
4727
+ if (typeof window !== 'undefined' && window.Notification?.permission === 'granted') {
4728
+ const notice = new window.Notification('红色决策待处理', { body: inboxText(ticket.title, 120), tag: ticket.id, renotify: false })
4729
+ notice.onclick = () => { try { window.focus() } catch { /* ignore */ } remove() }
4730
+ }
4731
+ } catch { /* notification optional */ }
4732
+ }
4733
+
4734
+ /** 收件箱唯一数据源:侧栏未读徽标 / 右侧 tab / 抽屉 共用。 */
4735
+ function createDecisionInboxStore() {
4736
+ const S = {
4737
+ state: 'idle', items: [], rev: 0, error: '', at: 0,
4738
+ streamState: 'idle', seenRev: readInboxSeenRev(), redPending: 0,
4739
+ selected: new Set(), collapsed: new Set(['green', 'gray']),
4740
+ batchFailures: [], batchFailuresKind: null,
4741
+ busy: '', notice: '',
4742
+ ai: { state: 'idle', configured: false, provider: null, model: null, providers: [], error: '' },
4743
+ aiTest: { state: 'idle', ok: null, message: '', latencyMs: 0 },
4744
+ aiStream: { id: '', text: '', state: '' },
4745
+ }
4746
+ const listeners = new Set()
4747
+ let timer = null
4748
+ let inflight = null
4749
+ let streamAbort = null
4750
+ let reconnectTimer = null
4751
+ let disposed = false
4752
+ let openHandler = null
4753
+ const emit = () => { for (const fn of [...listeners]) { try { fn(S) } catch { /* listener must not break */ } } }
4754
+ const pending = () => S.items.filter(item => item.status === 'pending')
4755
+ const ticketRev = (item) => Number(item?.rev) || 0
4756
+ // 未读计数 = pending 数:侧栏 badge、tab 标题、收件箱标题三处共用同一口径。
4757
+ // seenRev 仍保留用于“新 ticket 提醒”去重,但不参与 badge 计数。
4758
+ const unread = () => pending().length
4759
+ const syncBadges = () => {
4760
+ S.redPending = pending().filter(item => item.level === 'red').length
4761
+ }
4762
+ const snapshot = () => S
4763
+ const inboxOnScreen = () => {
4764
+ try {
4765
+ const doc = typeof document !== 'undefined' ? document : null
4766
+ if (!doc) return false
4767
+ if (doc.visibilityState === 'hidden') return false
4768
+ const node = doc.querySelector('[data-zone="decision-inbox"]')
4769
+ if (!node) return false
4770
+ return node.getClientRects?.().length > 0
4771
+ } catch { return false }
4772
+ }
4773
+ const markSeen = () => {
4774
+ const maxRev = S.items.reduce((max, item) => Math.max(max, ticketRev(item)), S.seenRev)
4775
+ if (maxRev <= S.seenRev) return
4776
+ S.seenRev = maxRev
4777
+ writeInboxSeenRev(maxRev)
4778
+ syncBadges()
4779
+ emit()
4780
+ }
4781
+ const mergeTickets = (incoming) => {
4782
+ const byId = new Map(S.items.map(item => [item.id, item]))
4783
+ const freshRed = []
4784
+ for (const item of incoming) {
4785
+ if (!item || !item.id) continue
4786
+ if (!byId.has(item.id) && item.status === 'pending' && item.level === 'red') freshRed.push(item)
4787
+ byId.set(item.id, item)
4788
+ }
4789
+ S.items = [...byId.values()]
4790
+ S.rev = S.items.reduce((max, item) => Math.max(max, ticketRev(item)), S.rev)
4791
+ syncBadges()
4792
+ return freshRed
4793
+ }
4794
+ const alertTarget = { get openHandler() { return openHandler } }
4795
+ const alertFresh = (freshRed) => {
4796
+ if (!freshRed.length) return
4797
+ if (inboxOnScreen()) { markSeen(); return }
4798
+ for (const ticket of freshRed) showRedDecisionAlert(ticket, alertTarget)
4799
+ }
4800
+
4801
+ async function refresh() {
4802
+ if (inflight) return inflight
4803
+ inflight = (async () => {
4804
+ const query = '/fang/api/decisions?includeArchived=1' + (S.rev > 0 ? '&since=' + encodeURIComponent(String(S.rev)) : '')
4805
+ const [decisions, ai] = await Promise.all([
4806
+ api(query).catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
4807
+ api('/fang/api/decisions/ai').catch(() => ({ status: 0, body: null })),
4808
+ ])
4809
+ if (decisions.status === 200 && decisions.body?.ok !== false) {
4810
+ const incoming = Array.isArray(decisions.body.items) ? decisions.body.items : []
4811
+ const freshRed = mergeTickets(incoming)
4812
+ S.rev = Math.max(S.rev, Number(decisions.body.rev) || 0)
4813
+ S.state = 'ready'; S.error = ''
4814
+ alertFresh(freshRed)
4815
+ } else {
4816
+ S.state = S.items.length ? 'stale' : 'error'
4817
+ S.error = decisions.body?.error || (decisions.status ? 'http-' + decisions.status : 'network')
4818
+ }
4819
+ if (ai.status === 200 && ai.body?.ok !== false) S.ai = { ...S.ai, ...ai.body, state: 'ready', error: '' }
4820
+ else S.ai = { ...S.ai, state: 'error', error: ai.body?.error || 'ai-unavailable' }
4821
+ const alive = new Set(pending().map(item => item.id))
4822
+ for (const id of [...S.selected]) if (!alive.has(id)) S.selected.delete(id)
4823
+ S.at = Date.now()
4824
+ emit()
4825
+ })()
4826
+ try { return await inflight } finally { inflight = null }
4827
+ }
4828
+
4829
+ /** SSE:bus 事件 → 立即合并;断线 2.5s 重连;轮询仅作降级。 */
4830
+ async function connectStream() {
4831
+ if (disposed || streamAbort) return
4832
+ const controller = new AbortController()
4833
+ streamAbort = controller
4834
+ try {
4835
+ const token = await ensureFangAuthToken()
4836
+ const response = await fetch('/fang/api/decisions/events', {
4837
+ headers: { accept: 'text/event-stream', 'x-fang-auth': token },
4838
+ cache: 'no-store',
4839
+ signal: controller.signal,
4840
+ })
4841
+ if (!response.ok || !response.body?.getReader) throw new Error('stream-unavailable')
4842
+ S.streamState = 'open'
4843
+ emit()
4844
+ const reader = response.body.getReader()
4845
+ const decoder = new TextDecoder()
4846
+ let buffer = ''
4847
+ for (;;) {
4848
+ const { done, value } = await reader.read()
4849
+ if (done) break
4850
+ buffer += decoder.decode(value, { stream: true })
4851
+ let index = buffer.indexOf('\n\n')
4852
+ while (index >= 0) {
4853
+ handleStreamFrame(buffer.slice(0, index))
4854
+ buffer = buffer.slice(index + 2)
4855
+ index = buffer.indexOf('\n\n')
4856
+ }
4857
+ }
4858
+ throw new Error('stream-closed')
4859
+ } catch (error) {
4860
+ if (controller.signal.aborted || disposed) return
4861
+ streamAbort = null
4862
+ S.streamState = 'retry'
4863
+ emit()
4864
+ clearTimeout(reconnectTimer)
4865
+ reconnectTimer = setTimeout(() => { if (!disposed && !streamAbort) void connectStream() }, 2500)
4866
+ }
4867
+ }
4868
+
4869
+ function handleStreamFrame(raw) {
4870
+ let event = 'message'
4871
+ const dataLines = []
4872
+ for (const line of String(raw ?? '').split('\n')) {
4873
+ if (line.startsWith('event:')) event = line.slice(6).trim()
4874
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).trimStart())
4875
+ }
4876
+ if (!dataLines.length) return
4877
+ let payload = null
4878
+ try { payload = JSON.parse(dataLines.join('\n')) } catch { return }
4879
+ if (event === 'ready') {
4880
+ S.streamState = 'open'
4881
+ S.rev = Math.max(S.rev, Number(payload?.rev) || 0)
4882
+ S.at = Date.now()
4883
+ emit()
4884
+ return
4885
+ }
4886
+ if (event === 'ticket' && payload?.ticket?.id) {
4887
+ const freshRed = mergeTickets([payload.ticket])
4888
+ S.state = 'ready'; S.error = ''
4889
+ S.at = Date.now()
4890
+ alertFresh(freshRed)
4891
+ emit()
4892
+ }
4893
+ }
4894
+
4895
+ function start() {
4896
+ if (timer) return
4897
+ syncBadges()
4898
+ void refresh()
4899
+ void connectStream()
4900
+ // 降级轮询:SSE 正常时也低频兜底(SSE 掉线时由重连补齐,最多 30s 的空窗)。
4901
+ timer = setInterval(() => {
4902
+ try { if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return } catch { /* ignore */ }
4903
+ if (S.streamState === 'open') return
4904
+ void refresh()
4905
+ }, INBOX_POLL_MS)
4906
+ }
4907
+ function stop() {
4908
+ disposed = true
4909
+ if (timer) clearInterval(timer)
4910
+ timer = null
4911
+ clearTimeout(reconnectTimer)
4912
+ reconnectTimer = null
4913
+ try { streamAbort?.abort() } catch { /* ignore */ }
4914
+ streamAbort = null
4915
+ }
4916
+ function subscribe(fn) { listeners.add(fn); try { fn(S) } catch { /* ignore */ } return () => listeners.delete(fn) }
4917
+ async function act(label, run) {
4918
+ if (S.busy) return null
4919
+ S.busy = label; S.notice = ''; emit()
4920
+ try {
4921
+ const result = await run()
4922
+ if (result?.status === 200 && result.body?.ok !== false) {
4923
+ S.notice = result.body?.ok === false ? '' : 'ok'
4924
+ } else {
4925
+ S.notice = 'err:' + (result?.body?.error || result?.body?.reason || (result?.status ? 'http-' + result.status : 'network'))
4926
+ }
4927
+ return result
4928
+ } finally {
4929
+ S.busy = ''
4930
+ await refresh().catch(() => {})
4931
+ }
4932
+ }
4933
+ async function runBatch(label, request) {
4934
+ if (S.busy) return null
4935
+ const ids = [...S.selected].filter(id => pending().some(item => item.id === id))
4936
+ if (!ids.length) { S.notice = 'err:no-selected'; emit(); return null }
4937
+ S.busy = label; S.notice = ''; S.batchFailures = []
4938
+ S.batchFailuresKind = label === 'batch-archive' ? 'archive' : 'resolve'
4939
+ emit()
4940
+ try {
4941
+ const result = await request(ids)
4942
+ const rows = Array.isArray(result?.body?.results) ? result.body.results : []
4943
+ S.batchFailures = rows
4944
+ .filter(row => row.ok === false)
4945
+ .map(row => ({
4946
+ id: String(row.id ?? ''),
4947
+ reason: String(row.reason ?? 'failed'),
4948
+ title: String(S.items.find(item => item.id === row.id)?.title ?? row.id ?? ''),
4949
+ }))
4950
+ if (result?.status === 200) S.notice = S.batchFailures.length ? '' : 'ok'
4951
+ else S.notice = 'err:' + (result?.body?.error || (result?.status ? 'http-' + result.status : 'network'))
4952
+ return result
4953
+ } finally {
4954
+ S.busy = ''
4955
+ await refresh().catch(() => {})
4956
+ }
4957
+ }
4958
+ async function runAiTest(input) {
4959
+ S.aiTest = { state: 'testing', ok: null, message: '正在测试连接…', latencyMs: 0 }
4960
+ S.busy = 'ai-test'; emit()
4961
+ try {
4962
+ const result = await api('/fang/api/decisions/ai/test', { method: 'POST', body: JSON.stringify(input ?? {}) })
4963
+ const body = result?.body ?? {}
4964
+ if (result?.status === 200 && body.ok !== false) {
4965
+ S.aiTest = {
4966
+ state: 'ok', ok: true,
4967
+ message: `连接成功 · ${body.provider || input?.provider || 'AI'} / ${body.model || '—'} · ${Number(body.latencyMs) || 0}ms`,
4968
+ latencyMs: Number(body.latencyMs) || 0,
4969
+ }
4970
+ } else {
4971
+ S.aiTest = {
4972
+ state: 'err', ok: false,
4973
+ message: failureHint(body.reason || body.error || (result?.status ? 'http-' + result.status : 'network')),
4974
+ latencyMs: 0,
4975
+ }
4976
+ }
4977
+ return result
4978
+ } catch (error) {
4979
+ S.aiTest = { state: 'err', ok: false, message: String(error?.message ?? error), latencyMs: 0 }
4980
+ return null
4981
+ } finally {
4982
+ S.busy = ''
4983
+ emit()
4984
+ }
4985
+ }
4986
+ async function saveAiWithTest(input) {
4987
+ // 保存前先真实调用一次;测试失败绝不启用(避免“保存即启用”的假成功)。
4988
+ const tested = await runAiTest(input)
4989
+ if (!(tested?.status === 200 && tested.body?.ok !== false)) {
4990
+ S.notice = 'err:ai-test-failed'; emit(); return null
4991
+ }
4992
+ return act('ai-config', () => api('/fang/api/decisions/ai/config', {
4993
+ method: 'POST', body: JSON.stringify(input ?? {}),
4994
+ }))
4995
+ }
4996
+ async function runAdviseStream(id) {
4997
+ if (S.busy) return null
4998
+ S.busy = 'ai-advise-stream'
4999
+ S.aiStream = { id: String(id), text: '', state: 'running' }
5000
+ emit()
5001
+ try {
5002
+ const token = await ensureFangAuthToken()
5003
+ const response = await fetch('/fang/api/decisions/ai/advise/stream', {
5004
+ method: 'POST',
5005
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream', 'x-fang-auth': token },
5006
+ body: JSON.stringify({ id }),
5007
+ })
5008
+ if (!response.ok || !response.body?.getReader) {
5009
+ S.aiStream = { id: '', text: '', state: '' }
5010
+ S.busy = ''
5011
+ emit()
5012
+ return act('ai-advise', () => api('/fang/api/decisions/ai/advise', { method: 'POST', body: JSON.stringify({ id }) }))
5013
+ }
5014
+ const reader = response.body.getReader()
5015
+ const decoder = new TextDecoder()
5016
+ let buffer = ''
5017
+ for (;;) {
5018
+ const { done, value } = await reader.read()
5019
+ if (done) break
5020
+ buffer += decoder.decode(value, { stream: true })
5021
+ let index = buffer.indexOf('\n\n')
5022
+ while (index >= 0) {
5023
+ const raw = buffer.slice(0, index)
5024
+ buffer = buffer.slice(index + 2)
5025
+ index = buffer.indexOf('\n\n')
5026
+ let event = 'message'
5027
+ const dataLines = []
5028
+ for (const line of raw.split('\n')) {
5029
+ if (line.startsWith('event:')) event = line.slice(6).trim()
5030
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).trimStart())
5031
+ }
5032
+ if (!dataLines.length) continue
5033
+ let payload = null
5034
+ try { payload = JSON.parse(dataLines.join('\n')) } catch { continue }
5035
+ if (event === 'delta' && typeof payload?.text === 'string') {
5036
+ S.aiStream = { ...S.aiStream, text: payload.text.slice(0, 4000), state: 'running' }
5037
+ emit()
5038
+ } else if (event === 'error') {
5039
+ S.notice = 'err:' + (payload?.reason || payload?.error || 'ai-failed')
5040
+ }
5041
+ }
5042
+ }
5043
+ S.aiStream = { id: S.aiStream.id, text: S.aiStream.text, state: 'done' }
5044
+ return true
5045
+ } catch (error) {
5046
+ S.notice = 'err:' + String(error?.message ?? error)
5047
+ return null
5048
+ } finally {
5049
+ S.busy = ''
5050
+ emit()
5051
+ await refresh().catch(() => {})
5052
+ }
5053
+ }
5054
+ return {
5055
+ id: DECISION_INBOX.id,
5056
+ kind: DECISION_INBOX.kind,
5057
+ state: S,
5058
+ pending, unread, snapshot, start, stop, subscribe, refresh,
5059
+ markSeen,
5060
+ streamState: () => S.streamState,
5061
+ setOpenHandler(fn) { openHandler = typeof fn === 'function' ? fn : null },
5062
+ get openHandler() { return openHandler },
5063
+ toggleSelected(id) { if (S.selected.has(id)) S.selected.delete(id); else S.selected.add(id); emit() },
5064
+ setNotice(text) { S.notice = String(text ?? ''); emit() },
5065
+ clearSelected() { S.selected.clear(); emit() },
5066
+ toggleCollapsed(level) { if (S.collapsed.has(level)) S.collapsed.delete(level); else S.collapsed.add(level); emit() },
5067
+ collapseAll(all) { S.collapsed = new Set(all ? INBOX_LEVELS.map(item => item.level) : []); emit() },
5068
+ /** 分组头三态全选:未选 → 全选;部分/全选 → 全选;全选再点 → 清空本组。 */
5069
+ toggleGroupSelected(level) {
5070
+ const items = pending().filter(item => item.level === level)
5071
+ if (!items.length) return
5072
+ const all = items.every(item => S.selected.has(item.id))
5073
+ for (const item of items) {
5074
+ if (all) S.selected.delete(item.id)
5075
+ else S.selected.add(item.id)
5076
+ }
5077
+ emit()
5078
+ },
5079
+ selectRecommended() {
5080
+ for (const item of pending()) {
5081
+ if (item.level === 'green' || item.options?.some(option => option.isRecommended)) S.selected.add(item.id)
5082
+ }
5083
+ emit()
5084
+ },
5085
+ selectAllPending() {
5086
+ for (const item of pending()) S.selected.add(item.id)
5087
+ emit()
5088
+ },
5089
+ clearBatchFailures() { S.batchFailures = []; emit() },
5090
+ resolve(id, option) {
5091
+ return act('resolve', () => api('/fang/api/decisions/resolve', {
5092
+ method: 'POST', body: JSON.stringify({ id, option, by: 'fang-inbox' }),
5093
+ }))
5094
+ },
5095
+ abandon(id) {
5096
+ return act('abandon', () => api('/fang/api/decisions/abandon', {
5097
+ method: 'POST', body: JSON.stringify({ id, by: 'fang-inbox' }),
5098
+ }))
5099
+ },
5100
+ resolveSelected() {
5101
+ return runBatch('batch-resolve', (ids) => api('/fang/api/decisions/resolve', {
5102
+ method: 'POST', body: JSON.stringify({ ids, by: 'fang-inbox' }),
5103
+ }))
5104
+ },
5105
+ archiveSelected() {
5106
+ return runBatch('batch-archive', (ids) => api('/fang/api/decisions/abandon', {
5107
+ method: 'POST', body: JSON.stringify({ ids, by: 'fang-inbox' }),
5108
+ }))
5109
+ },
5110
+ retryFailures() {
5111
+ const ids = [...new Set(S.batchFailures.map(failure => failure.id))]
5112
+ .filter(id => pending().some(item => item.id === id))
5113
+ const kind = S.batchFailuresKind === 'archive' ? 'archive' : 'resolve'
5114
+ S.batchFailures = []
5115
+ S.selected = new Set(ids)
5116
+ emit()
5117
+ if (!ids.length) return Promise.resolve(null)
5118
+ const path = kind === 'archive' ? '/fang/api/decisions/abandon' : '/fang/api/decisions/resolve'
5119
+ return runBatch(kind === 'archive' ? 'batch-archive' : 'batch-resolve', (nextIds) => api(path, {
5120
+ method: 'POST', body: JSON.stringify({ ids: nextIds, by: 'fang-inbox' }),
5121
+ }))
5122
+ },
5123
+ configureAi(input) {
5124
+ return act('ai-config', () => api('/fang/api/decisions/ai/config', {
5125
+ method: 'POST', body: JSON.stringify(input),
5126
+ }))
5127
+ },
5128
+ testAi(input) { return runAiTest(input) },
5129
+ saveAiWithTest(input) { return saveAiWithTest(input) },
5130
+ adviseStream(id) { return runAdviseStream(id) },
5131
+ advise(id) {
5132
+ return act('ai-advise', () => api('/fang/api/decisions/ai/advise', {
5133
+ method: 'POST', body: JSON.stringify({ id }),
5134
+ }))
5135
+ },
5136
+ }
5137
+ }
5138
+
5139
+ function mountInboxTitle(host, store) {
5140
+ const doc = host.ownerDocument
5141
+ injectStyle(doc)
5142
+ const render = () => {
5143
+ const n = store.unread()
5144
+ host.replaceChildren(h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600 } },
5145
+ '收件箱',
5146
+ n > 0 ? h('span', { class: 'fang-inbox-unread' }, n > 99 ? '99+' : String(n)) : null))
5147
+ }
5148
+ const unsubscribe = store.subscribe(render)
5149
+ render()
5150
+ return () => { unsubscribe(); host.replaceChildren() }
5151
+ }
5152
+
5153
+ /** 左侧栏独立入口:图标 + 未读红点;点击打开右侧收件箱。 */
5154
+ function mountInboxSeat(host, store, open) {
5155
+ const doc = host.ownerDocument
5156
+ injectStyle(doc)
5157
+ const badge = h('span', { class: 'fang-inbox-badge', 'aria-hidden': 'true' })
5158
+ const button = h('button', {
5159
+ type: 'button', class: 'fang-inbox-seat',
5160
+ 'data-fang-entry': 'decision-inbox',
5161
+ title: '决策收件箱', 'aria-label': '决策收件箱',
5162
+ onClick: (event) => { event.preventDefault(); event.stopPropagation(); open() },
5163
+ }, icon('inbox', 17), badge)
5164
+ host.replaceChildren(button)
5165
+ const render = () => {
5166
+ const n = store.unread()
5167
+ badge.textContent = n > 99 ? '99+' : String(n)
5168
+ badge.style.display = n > 0 ? 'block' : 'none'
5169
+ button.classList.toggle('has-red', store.state.redPending > 0)
5170
+ button.title = store.state.redPending > 0
5171
+ ? `决策收件箱:${n} 条待处理,其中 ${store.state.redPending} 条红色待处理`
5172
+ : (n > 0 ? `决策收件箱:${n} 条待处理` : '决策收件箱:暂无待处理')
5173
+ }
5174
+ const unsubscribe = store.subscribe(render)
5175
+ render()
5176
+ return () => { unsubscribe(); host.replaceChildren() }
5177
+ }
5178
+
5179
+ function openInboxDrawer(store) {
5180
+ const doc = typeof document !== 'undefined' ? document : null
5181
+ if (!doc) return
5182
+ const existing = doc.querySelector('[data-fang-inbox-drawer]')
5183
+ if (existing) { existing.classList.add('is-open'); existing.querySelector('button')?.focus?.(); return }
5184
+ const backdrop = h('div', { class: 'fang-inbox-backdrop', 'data-fang-inbox-backdrop': '1' })
5185
+ const panel = h('aside', { class: 'fang-inbox-drawer', 'data-fang-inbox-drawer': '1', role: 'dialog', 'aria-modal': 'true', 'aria-label': '决策收件箱' })
5186
+ let teardown = null
5187
+ const close = () => {
5188
+ try { teardown?.() } catch { /* ignore */ }
5189
+ backdrop.remove(); panel.remove()
5190
+ doc.removeEventListener('keydown', onKey, true)
5191
+ try { window.removeEventListener('resize', onResize) } catch { /* ignore */ }
5192
+ }
5193
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); close() } }
5194
+ const onResize = () => { if (!doc.body.contains(panel)) close() }
5195
+ backdrop.addEventListener('click', close)
5196
+ doc.body.append(backdrop, panel)
5197
+ teardown = mountDecisionInbox(panel, store, { drawer: true, onClose: close })
5198
+ doc.addEventListener('keydown', onKey, true)
5199
+ try { window.addEventListener('resize', onResize) } catch { /* ignore */ }
5200
+ try {
5201
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => panel.classList.add('is-open'))
5202
+ else panel.classList.add('is-open')
5203
+ } catch { panel.classList.add('is-open') }
5204
+ try {
5205
+ const active = doc.activeElement
5206
+ if (active && typeof active.blur === 'function') active.blur()
5207
+ } catch { /* ignore */ }
5208
+ }
5209
+
5210
+ /** 收件箱主体:可折叠分组 + 未读计数 + 键盘导航 + 批量操作。 */
5211
+ function mountDecisionInbox(host, store, options = {}) {
5212
+ const doc = host.ownerDocument
5213
+ injectStyle(doc)
5214
+ const state = store.state
5215
+ let activeId = ''
5216
+ let disposed = false
5217
+ let aiOpen = false
5218
+ const root = h('div', {
5219
+ class: 'fang-inbox', tabindex: 0, role: 'region', 'aria-label': '决策收件箱',
5220
+ 'data-zone': 'decision-inbox', 'data-drawer': options.drawer ? '1' : '0',
5221
+ })
5222
+ host.replaceChildren(root)
5223
+ try { host.style.height = host.style.height || '100%' } catch { /* ignore */ }
5224
+ try { host.style.minHeight = '0' } catch { /* ignore */ }
5225
+
5226
+ const focusRoot = () => { try { root.focus({ preventScroll: true }) } catch { root.focus?.() } }
5227
+ const pickOption = (item) => {
5228
+ const recommended = item.options?.find(option => option.isRecommended)
5229
+ if (recommended) return recommended.value
5230
+ if (item.options?.length) return item.options[0].value
5231
+ return '__ACK__'
5232
+ }
5233
+ const sourceText = (item) => {
5234
+ const source = item?.source || {}
5235
+ const role = source.agentRole || 'worker'
5236
+ const trusted = source.roleTrusted === true || String(source.roleSource || '').startsWith('host:')
5237
+ const name = source.taskName || (source.sessionId && source.sessionId !== 'unknown' ? short(source.sessionId, 10) : '')
5238
+ return `${role}${trusted ? '' : '(自报)'}${name ? ' · ' + name : ''}`
5239
+ }
5240
+ const visiblePending = () => {
5241
+ const list = []
5242
+ for (const level of INBOX_LEVELS) {
5243
+ if (level.level === 'gray' || state.collapsed.has(level.level)) continue
5244
+ for (const item of state.items) {
5245
+ if (item.status === 'pending' && item.level === level.level) list.push(item)
5246
+ }
5247
+ }
5248
+ return list
5249
+ }
5250
+
5251
+ function itemNode(item, archived = false) {
5252
+ const selected = state.selected.has(item.id)
5253
+ const busy = state.busy === 'resolve' || state.busy === 'abandon' || state.busy === 'batch'
5254
+ const node = h('div', {
5255
+ class: 'fang-inbox-item' + (activeId === item.id ? ' is-active' : ''),
5256
+ 'data-level': item.level, 'data-inbox-id': item.id, role: 'listitem',
5257
+ onClick: () => { activeId = item.id; render() },
5258
+ },
5259
+ archived ? null : h('input', {
5260
+ type: 'checkbox', class: 'fang-inbox-check', checked: selected,
5261
+ 'aria-label': `选择:${item.title || item.id}`,
5262
+ onClick: (event) => event.stopPropagation(),
5263
+ onChange: () => { store.toggleSelected(item.id); focusRoot() },
5264
+ }),
5265
+ h('div', { class: 'fang-inbox-main' },
5266
+ h('div', { class: 'fang-inbox-item-title' }, inboxText(item.title) || item.id,
5267
+ item.budgetDemoted ? h('span', { class: 'chip', style: { marginLeft: 6, fontSize: 10 }, title: '全库 pending red 超限,已降级为黄色' }, '预算降级') : null,
5268
+ item.attentionDemoted
5269
+ ? h('span', {
5270
+ class: 'chip', style: { marginLeft: 6, fontSize: 10 },
5271
+ title: `注意力配额不足(${item.attentionQuota?.scope === 'source' ? '来源' : '全库'} ${item.attentionQuota?.used ?? '?'}/${item.attentionQuota?.limit ?? '?'}),已降一级`,
5272
+ }, '注意力降级')
5273
+ : null),
5274
+ item.context ? h('div', { class: 'fang-inbox-item-context' }, inboxText(item.context)) : null,
5275
+ h('div', { class: 'fang-inbox-meta' }, `${sourceText(item)} · ${fmtRelative(item.createdAt)}${item.expiresAt ? ' · 到期 ' + fmtRelative(item.expiresAt) : ''}`),
5276
+ item.ai ? h('div', { class: 'fang-inbox-ai-advice' }, h('span', { class: 'fang-inbox-ai-tag' }, 'AI · 未核实'),
5277
+ `${item.ai.summary || ''}${item.ai.recommendation ? ' · 推荐:' + item.ai.recommendation : ''}`,
5278
+ Array.isArray(item.ai.optionRisks) && item.ai.optionRisks.length
5279
+ ? h('div', { class: 'fang-inbox-ai-risks' },
5280
+ ...item.ai.optionRisks.map(risk => h('span', {
5281
+ class: 'fang-inbox-risk fang-inbox-risk--' + String(risk.risk || 'unknown'),
5282
+ title: risk.reason || '',
5283
+ }, `${risk.value}: ${({ low: '低', medium: '中', high: '高' })[risk.risk] || risk.risk}`)))
5284
+ : null,
5285
+ Array.isArray(item.ai.missingInfo) && item.ai.missingInfo.length
5286
+ ? h('div', { class: 'fang-inbox-ai-missing' }, '缺失信息:' + item.ai.missingInfo.join('、'))
5287
+ : null) : null,
5288
+ item.execution
5289
+ ? h('div', {
5290
+ class: 'fang-inbox-exec fang-inbox-exec--' + String(item.execution.status || 'unknown'),
5291
+ title: item.execution.error || '',
5292
+ }, `动作 ${item.execution.actionId || '?'}:${({ running: '执行中…', done: '已执行', failed: '执行失败' })[item.execution.status] || item.execution.status}`)
5293
+ : null,
5294
+ state.aiStream?.id === item.id && state.aiStream.text
5295
+ ? h('div', { class: 'fang-inbox-ai-stream' }, state.aiStream.text)
5296
+ : null,
5297
+ archived ? null : h('div', { class: 'fang-inbox-item-actions' },
5298
+ ...(item.options?.length
5299
+ ? item.options.slice(0, 5).map(option => inboxButton(option.label || option.value, () => void store.resolve(item.id, option.value), {
5300
+ primary: option.isRecommended === true, disabled: busy,
5301
+ }))
5302
+ : [inboxButton('知道了', () => void store.resolve(item.id, '__ACK__'), { primary: true, disabled: busy })]),
5303
+ inboxButton('AI 建议', () => void store.adviseStream(item.id), { title: 'AI 建议(流式,失败自动回落一次性)', disabled: busy || state.ai.configured !== true }),
5304
+ inboxButton('忽略', () => void store.abandon(item.id), { danger: true, disabled: busy }))))
5305
+ return node
5306
+ }
5307
+
5308
+ function aiPanel() {
5309
+ const ai = state.ai || {}
5310
+ const configured = ai.configured === true
5311
+ const persistence = ai.persistence || {}
5312
+ const quota = ai.quota || {}
5313
+ const circuit = ai.circuit || {}
5314
+ const testState = state.aiTest || { state: 'idle', message: '' }
5315
+ const readFields = () => ({
5316
+ provider: String(root.querySelector('[data-inbox-ai="provider"]')?.value || 'deepseek'),
5317
+ apiKey: String(root.querySelector('[data-inbox-ai="apiKey"]')?.value || '').trim(),
5318
+ model: String(root.querySelector('[data-inbox-ai="model"]')?.value || '').trim() || undefined,
5319
+ baseUrl: String(root.querySelector('[data-inbox-ai="baseUrl"]')?.value || '').trim() || undefined,
5320
+ })
5321
+ const persistenceText = persistence.enabled === false
5322
+ ? 'Key 持久化:关闭(仅内存)'
5323
+ : (persistence.available
5324
+ ? `Key 持久化:${persistence.backend}${persistence.saved ? ' · 已保存' : ''}`
5325
+ : `Key 持久化:不可用(${persistence.reason || 'backend-unavailable'})→ 仅内存`)
5326
+ const hostText = ai.endpointHost ? ` · 发往 ${ai.endpointHost}` : ''
5327
+ const quotaText = `今日 AI:${quota.used ?? 0}/${quota.limit ? quota.limit : '∞'}`
5328
+ const usage = ai.usage || {}
5329
+ const tokenText = (usage.promptTokens || usage.completionTokens)
5330
+ ? `tokens ${Number(usage.promptTokens || 0) + Number(usage.completionTokens || 0)}${usage.costMicros !== null && usage.costMicros !== undefined ? ` · $${(Number(usage.costMicros) / 1e6).toFixed(4)}` : ''}`
5331
+ : ''
5332
+ const circuitText = circuit.state === 'open'
5333
+ ? `熔断:开(${Math.ceil((circuit.retryAfterMs || 0) / 1000)}s)`
5334
+ : '熔断:关'
5335
+ return h('details', { class: 'fang-inbox-ai', open: aiOpen, onToggle: (event) => { aiOpen = event.target.open } },
5336
+ h('summary', null, configured ? `AI:${ai.provider || 'custom'} / ${ai.model || '—'}` : 'AI 智能建议(需配置自有 API Key)'),
5337
+ h('div', { class: 'fang-inbox-ai-status' }, `${persistenceText}${hostText} · ${quotaText}${tokenText ? ' · ' + tokenText : ''} · ${circuitText}`),
5338
+ h('div', { class: 'fang-inbox-ai-row' },
5339
+ h('select', { 'data-inbox-ai': 'provider', 'aria-label': '模型提供商' },
5340
+ ...((Array.isArray(ai.providers) && ai.providers.length ? ai.providers : [{ id: 'deepseek', label: 'DeepSeek' }]).map(provider =>
5341
+ h('option', { value: provider.id }, provider.label || provider.id)))),
5342
+ h('input', {
5343
+ 'data-inbox-ai': 'apiKey', type: 'password', autocomplete: 'off',
5344
+ placeholder: configured ? '新 API Key(更换时填写)' : 'API Key', 'aria-label': '模型 API Key',
5345
+ }),
5346
+ h('input', { 'data-inbox-ai': 'model', type: 'text', placeholder: '模型(可留空)', autocomplete: 'off', 'aria-label': '模型名' }),
5347
+ h('input', { 'data-inbox-ai': 'baseUrl', type: 'url', placeholder: 'Base URL(可留空)', autocomplete: 'off', 'aria-label': '模型 Base URL' }),
5348
+ inboxButton('测试连接', () => {
5349
+ const fields = readFields()
5350
+ if (!fields.apiKey) { store.setNotice('err:api-key-required'); return }
5351
+ void store.testAi(fields)
5352
+ }),
5353
+ inboxButton(configured ? '测试并更换' : '测试并保存启用', () => {
5354
+ const fields = readFields()
5355
+ if (!fields.apiKey) { store.setNotice('err:api-key-required'); return }
5356
+ void store.saveAiWithTest(fields)
5357
+ }, { primary: true })),
5358
+ testState.message
5359
+ ? h('div', { class: 'fang-inbox-ai-test fang-inbox-ai-test--' + String(testState.state || 'idle') }, testState.message)
5360
+ : null)
5361
+ }
5362
+
5363
+ function groupNode(levelMeta) {
5364
+ const level = levelMeta.level
5365
+ const archived = level === 'gray'
5366
+ const items = state.items.filter(item => archived ? item.status !== 'pending' : (item.status === 'pending' && item.level === level))
5367
+ if (!items.length) return null
5368
+ const collapsed = state.collapsed.has(level)
5369
+ const unread = archived ? 0 : items.length
5370
+ const allSelected = !archived && items.every(item => state.selected.has(item.id))
5371
+ const someSelected = !archived && !allSelected && items.some(item => state.selected.has(item.id))
5372
+ let check = null
5373
+ if (!archived) {
5374
+ check = h('input', {
5375
+ type: 'checkbox', class: 'fang-inbox-group-check', 'data-group-select': level,
5376
+ checked: allSelected || undefined,
5377
+ title: allSelected ? `取消全选「${levelMeta.label}」` : `全选「${levelMeta.label}」(${items.length} 项)`,
5378
+ 'aria-label': `全选${levelMeta.label}分组`,
5379
+ onClick: (event) => event.stopPropagation(),
5380
+ onChange: () => { store.toggleGroupSelected(level); focusRoot() },
5381
+ })
5382
+ check.indeterminate = someSelected
5383
+ }
5384
+ return h('div', { class: 'fang-inbox-group', 'data-level': level },
5385
+ h('div', {
5386
+ class: 'fang-inbox-group-head',
5387
+ onClick: (event) => {
5388
+ if (event.target?.closest?.('input')) return
5389
+ store.toggleCollapsed(level); focusRoot()
5390
+ },
5391
+ },
5392
+ check,
5393
+ h('button', {
5394
+ type: 'button', class: 'fang-inbox-group-toggle',
5395
+ 'aria-expanded': collapsed ? 'false' : 'true',
5396
+ },
5397
+ h('b', null, levelMeta.label),
5398
+ h('span', { style: { fontSize: 11, color: 'inherit', opacity: .8 } }, levelMeta.hint),
5399
+ h('span', { class: 'n' }, `${unread} 项 · ${collapsed ? '展开' : '收起'}`))),
5400
+ collapsed ? null : h('div', { role: 'list' }, ...items.slice(0, archived ? 80 : 200).map(item => itemNode(item, archived))))
5401
+ }
5402
+
5403
+ /** 批量确认弹窗:返回 Promise<boolean>;Esc/取消/点遮罩 = false。 */
5404
+ function confirmBatchDialog({ title, message, detail, confirmLabel = '确认', danger = false }) {
5405
+ return new Promise((resolve) => {
5406
+ const overlay = h('div', { class: 'fang-inbox-confirm', role: 'presentation' })
5407
+ const finish = (value) => {
5408
+ try { overlay.remove() } catch { /* ignore */ }
5409
+ try { root.removeEventListener('keydown', onConfirmKey, true) } catch { /* ignore */ }
5410
+ resolve(value)
5411
+ }
5412
+ const onConfirmKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); finish(false) } }
5413
+ const card = h('div', { class: 'fang-inbox-confirm-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': title },
5414
+ h('div', { class: 'fang-inbox-confirm-title' }, title),
5415
+ h('div', { class: 'fang-inbox-confirm-msg' }, message),
5416
+ detail ? h('div', { class: 'fang-inbox-confirm-detail' }, detail) : null,
5417
+ h('div', { class: 'fang-inbox-confirm-actions' },
5418
+ inboxButton('取消', () => finish(false)),
5419
+ inboxButton(confirmLabel, () => finish(true), { primary: !danger, danger })))
5420
+ overlay.append(card)
5421
+ overlay.addEventListener('click', (event) => { if (event.target === overlay) finish(false) })
5422
+ root.append(overlay)
5423
+ root.addEventListener('keydown', onConfirmKey, true)
5424
+ try { card.querySelector('button')?.focus?.() } catch { /* ignore */ }
5425
+ })
5426
+ }
5427
+
5428
+ async function runBatchWithConfirm(kind) {
5429
+ const ids = [...state.selected]
5430
+ if (!ids.length) { store.setNotice('err:no-selected'); return }
5431
+ const selectedItems = state.items.filter((item) => ids.includes(item.id))
5432
+ const redCount = selectedItems.filter((item) => item.level === 'red' || item.isBlocking === true).length
5433
+ const ok = await confirmBatchDialog({
5434
+ title: kind === 'archive' ? '批量归档选中项?' : '批量按推荐处理选中项?',
5435
+ message: `将处理 ${ids.length} 项${redCount > 0 ? `,其中 ${redCount} 项是红色/阻塞项(服务端会拒绝,需逐条处理)` : ''}。`,
5436
+ detail: selectedItems.slice(0, 3).map((item) => `· ${item.title || item.id}`).join('\n') + (ids.length > 3 ? `\n… 另有 ${ids.length - 3} 项` : ''),
5437
+ confirmLabel: kind === 'archive' ? '归档' : '处理',
5438
+ danger: kind === 'archive',
5439
+ })
5440
+ if (!ok) return
5441
+ if (kind === 'archive') void store.archiveSelected()
5442
+ else void store.resolveSelected()
5443
+ }
5444
+
5445
+ function render() {
5446
+ if (disposed) return
5447
+ const pending = store.pending()
5448
+ const selectedCount = state.selected.size
5449
+ const unread = pending.length
5450
+ const head = h('div', { class: 'fang-inbox-head' },
5451
+ h('div', { class: 'fang-inbox-title' }, icon('inbox', 16), '收件箱',
5452
+ unread > 0 ? h('span', { class: 'fang-inbox-unread' }, unread > 99 ? '99+' : String(unread)) : null),
5453
+ h('div', { class: 'fang-inbox-actions' },
5454
+ inboxButton('刷新', () => void store.refresh(), { disabled: state.busy !== '' }),
5455
+ inboxButton(state.collapsed.size ? '展开全部' : '收起全部', () => { store.collapseAll(state.collapsed.size === 0); focusRoot() }),
5456
+ options.drawer ? inboxButton('关闭', () => options.onClose?.()) : null))
5457
+ const toolbar = h('div', { class: 'fang-inbox-toolbar' },
5458
+ h('span', { class: 'fang-inbox-hint' }, `待处理 ${unread} · 已选 ${selectedCount}`),
5459
+ h('span', { class: 'fang-inbox-stream', title: state.streamState === 'open' ? 'SSE 实时推送已连接' : 'SSE 未连接,使用低频轮询兜底' },
5460
+ state.streamState === 'open' ? '● 实时' : '○ 轮询'),
5461
+ inboxButton('处理选中', () => void runBatchWithConfirm('resolve'), { primary: true, disabled: selectedCount === 0 || state.busy !== '' }),
5462
+ inboxButton('归档选中', () => void runBatchWithConfirm('archive'), { danger: true, disabled: selectedCount === 0 || state.busy !== '' }),
5463
+ inboxButton('全选', () => { store.selectAllPending(); focusRoot() }, { disabled: pending.length === 0, title: '全选所有待处理 ticket' }),
5464
+ inboxButton('全选可推荐', () => { store.selectRecommended(); focusRoot() }, { disabled: pending.length === 0 }),
5465
+ inboxButton('清空选择', () => { store.clearSelected(); focusRoot() }, { disabled: selectedCount === 0 }),
5466
+ h('span', { class: 'fang-inbox-hint', style: { marginLeft: 'auto' } }, '↑↓ 选择 · Enter 处理 · X 勾选 · Shift+A 全选 · Esc 关闭'))
5467
+ const body = h('div', { class: 'fang-inbox-body', role: 'list' })
5468
+ // 批量失败逐条 UI:服务端返回 results[],逐条展示 id/标题/原因,可重试。
5469
+ if (state.batchFailures.length) {
5470
+ body.prepend(h('div', { class: 'fang-inbox-batch-fail', role: 'alert' },
5471
+ h('div', { class: 'fang-inbox-batch-fail-title' }, `批量操作有 ${state.batchFailures.length} 项失败(其余已处理)`),
5472
+ ...state.batchFailures.map((failure) => h('div', { class: 'fang-inbox-batch-fail-row', 'data-fail-id': failure.id },
5473
+ h('b', null, failure.title || failure.id),
5474
+ h('span', null, failureHint(failure.reason)))),
5475
+ h('div', { class: 'fang-inbox-batch-fail-actions' },
5476
+ inboxButton('重试失败项', () => void store.retryFailures(), { primary: true }),
5477
+ inboxButton('关闭', () => { store.clearBatchFailures(); focusRoot() }))))
5478
+ }
5479
+ if (state.state === 'loading' && !state.items.length) body.append(h('div', { class: 'fang-inbox-empty' }, icon('spinner', 16), ' 正在读取收件箱…'))
5480
+ else if (state.state === 'error' && !state.items.length) {
5481
+ body.append(h('div', { class: 'fang-inbox-err', role: 'alert' }, `收件箱不可用:${failureHint(state.error || 'network')}`))
5482
+ } else if (!state.items.length) {
5483
+ body.append(h('div', { class: 'fang-inbox-empty' },
5484
+ '收件箱是空的。', h('br'), '决策中心创建的红/黄/蓝/绿 ticket 会出现在这里。'))
5485
+ } else {
5486
+ for (const meta of INBOX_LEVELS) {
5487
+ const node = groupNode(meta)
5488
+ if (node) body.append(node)
5489
+ }
5490
+ }
5491
+ if (state.error && state.items.length) body.prepend(h('div', { class: 'fang-inbox-err', role: 'status' }, `刷新失败:${failureHint(state.error)}(显示上次结果)`))
5492
+ if (state.notice && String(state.notice).startsWith('err:')) {
5493
+ body.prepend(h('div', { class: 'fang-inbox-err', role: 'status' }, failureHint(String(state.notice).slice(4))))
5494
+ }
5495
+ // 确认弹窗不能被一次 store 刷新(SSE/轮询)从 DOM 里替换掉。
5496
+ const openConfirm = root.querySelector(':scope > .fang-inbox-confirm')
5497
+ root.replaceChildren(head, aiPanel(), toolbar, body)
5498
+ if (openConfirm) root.append(openConfirm)
5499
+ }
5500
+
5501
+ const onKeyDown = (event) => {
5502
+ const tag = String(event.target?.tagName || '').toUpperCase()
5503
+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return
5504
+ const list = visiblePending()
5505
+ const currentIndex = list.findIndex(item => item.id === activeId)
5506
+ if (event.key === 'ArrowDown' || event.key === 'j') {
5507
+ event.preventDefault()
5508
+ const next = list[Math.min(list.length - 1, currentIndex + 1)] || list[0]
5509
+ if (next) { activeId = next.id; render(); root.querySelector(`[data-inbox-id="${activeId}"]`)?.scrollIntoView?.({ block: 'nearest' }) }
5510
+ return
5511
+ }
5512
+ if (event.key === 'ArrowUp' || event.key === 'k') {
5513
+ event.preventDefault()
5514
+ const prev = list[Math.max(0, currentIndex - 1)] || list[list.length - 1]
5515
+ if (prev) { activeId = prev.id; render(); root.querySelector(`[data-inbox-id="${activeId}"]`)?.scrollIntoView?.({ block: 'nearest' }) }
5516
+ return
5517
+ }
5518
+ if (event.key === 'Enter') {
5519
+ const item = list.find(entry => entry.id === activeId)
5520
+ if (!item) return
5521
+ event.preventDefault()
5522
+ void store.resolve(item.id, pickOption(item))
5523
+ return
5524
+ }
5525
+ if (event.key === 'x' || event.key === 'X') {
5526
+ const item = list.find(entry => entry.id === activeId)
5527
+ if (item) { event.preventDefault(); store.toggleSelected(item.id) }
5528
+ return
5529
+ }
5530
+ if (event.key === 'a' || event.key === 'A') {
5531
+ event.preventDefault()
5532
+ if (event.shiftKey) store.selectAllPending()
5533
+ else store.selectRecommended()
5534
+ return
5535
+ }
5536
+ if (event.key === 'r' || event.key === 'R') { event.preventDefault(); void store.refresh(); return }
5537
+ if (event.key === 'Escape') {
5538
+ event.preventDefault()
5539
+ if (state.selected.size) store.clearSelected()
5540
+ else if (options.drawer) options.onClose?.()
5541
+ }
5542
+ }
5543
+ root.addEventListener('keydown', onKeyDown)
5544
+ root.addEventListener('click', () => { focusRoot(); store.markSeen() })
5545
+ root.addEventListener('focus', () => store.markSeen())
5546
+ const unsubscribe = store.subscribe(render)
5547
+ render()
5548
+ // 收件箱在屏幕上 = 已读:未读红点只在「没看」时亮。
5549
+ try { store.markSeen() } catch { /* ignore */ }
5550
+ try { root.focus({ preventScroll: true }) } catch { /* ignore */ }
5551
+ return () => {
5552
+ disposed = true
5553
+ try { unsubscribe() } catch { /* ignore */ }
5554
+ try { root.removeEventListener('keydown', onKeyDown) } catch { /* ignore */ }
5555
+ host.replaceChildren()
5556
+ }
5557
+ }
5558
+
4125
5559
  function mountPanel(host) {
4126
5560
  // Electron: remember the real upstream origin so "打开母体 Web" does not
4127
5561
  // open the loopback proxy (which intentionally serves only /fang/api/*).
@@ -4553,6 +5987,7 @@ window.__ModuleLoader__.load({
4553
5987
  // ── 插件入口 ──────────────────────────────────────────────────────────
4554
5988
  return {
4555
5989
  mountPanel,
5990
+ ...(typeof window !== 'undefined' && window.__FANG_TEST_HOOK__ ? { __renderDecisionMini: renderDecisionMini } : {}),
4556
5991
  inject: ['slots'],
4557
5992
  apply(ctx) {
4558
5993
  const disposers = []
@@ -4604,6 +6039,81 @@ window.__ModuleLoader__.load({
4604
6039
  mount: (host) => mountBadge(host, props?.ctx ?? ctx),
4605
6040
  style: { display: 'inline-flex', alignItems: 'center' },
4606
6041
  }))))
6042
+ // ── 决策收件箱:独立侧栏入口 + 右侧抽屉 / 独立 Slot ─────────────────
6043
+ const inbox = createDecisionInboxStore()
6044
+ inbox.start()
6045
+ disposers.push(() => { try { inbox.stop() } catch { /* ignore */ } })
6046
+ openInboxExternally = () => openInbox()
6047
+ const tryService = (name) => {
6048
+ try { if (ctx && typeof ctx === 'object' && ctx[name]) return ctx[name] } catch { /* ignore */ }
6049
+ try { if (typeof ctx?.get === 'function') return ctx.get(name) } catch { /* ignore */ }
6050
+ return null
6051
+ }
6052
+ let sidebarRight = tryService('sidebarRight')
6053
+ let sidebarRightTabs = tryService('sidebarRightTabs')
6054
+ if ((!sidebarRight || !sidebarRightTabs) && typeof ctx?.inject === 'function') {
6055
+ try {
6056
+ ctx.inject(['sidebarRight'], (scope) => {
6057
+ sidebarRight = sidebarRight || scope?.sidebarRight || (typeof scope?.get === 'function' ? scope.get('sidebarRight') : null)
6058
+ })
6059
+ } catch { /* old host: drawer fallback below */ }
6060
+ try {
6061
+ ctx.inject(['sidebarRightTabs'], (scope) => {
6062
+ sidebarRightTabs = sidebarRightTabs || scope?.sidebarRightTabs || (typeof scope?.get === 'function' ? scope.get('sidebarRightTabs') : null)
6063
+ })
6064
+ } catch { /* old host */ }
6065
+ }
6066
+ const openInbox = () => {
6067
+ // 用户手势里申请通知权限(不能在自动提醒里弹权限框)。
6068
+ try {
6069
+ if (typeof window !== 'undefined' && window.Notification && window.Notification.permission === 'default') {
6070
+ void window.Notification.requestPermission()
6071
+ }
6072
+ } catch { /* notification optional */ }
6073
+ try {
6074
+ if (sidebarRight && typeof sidebarRight.openTab === 'function') {
6075
+ sidebarRight.openTab(DECISION_INBOX.kind, { params: {} })
6076
+ return
6077
+ }
6078
+ } catch { /* fall through to local drawer */ }
6079
+ openInboxDrawer(inbox)
6080
+ }
6081
+ inbox.setOpenHandler(openInbox)
6082
+ openInboxExternally = () => openInbox()
6083
+ if (sidebarRightTabs && typeof sidebarRightTabs.register === 'function') {
6084
+ try {
6085
+ const disposeTabType = sidebarRightTabs.register({
6086
+ id: DECISION_INBOX.id,
6087
+ kind: DECISION_INBOX.kind,
6088
+ priority: 'builtin',
6089
+ title: () => '收件箱',
6090
+ })
6091
+ disposers.push(() => { try { disposeTabType?.() } catch { /* ignore */ } })
6092
+ } catch { /* old host */ }
6093
+ }
6094
+ disposers.push(ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
6095
+ name: 'sidebar.right.pane.tab',
6096
+ key: DECISION_INBOX.id,
6097
+ }, () => React.createElement(DomMount, {
6098
+ mount: (host) => mountDecisionInbox(host, inbox),
6099
+ style: { display: 'block', height: '100%', minHeight: 0 },
6100
+ }))))
6101
+ disposers.push(ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
6102
+ name: 'sidebar.right.pane.tab.title',
6103
+ key: DECISION_INBOX.id,
6104
+ }, () => React.createElement(DomMount, {
6105
+ mount: (host) => mountInboxTitle(host, inbox),
6106
+ style: { display: 'inline-flex', alignItems: 'center' },
6107
+ }))))
6108
+ disposers.push(ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
6109
+ name: 'sidebar.footer.action',
6110
+ id: 'fang-inbox',
6111
+ order: 80,
6112
+ label: '收件箱',
6113
+ }, () => React.createElement(DomMount, {
6114
+ mount: (host) => mountInboxSeat(host, inbox, openInbox),
6115
+ style: { display: 'inline-flex', alignItems: 'center' },
6116
+ }))))
4607
6117
  return () => {
4608
6118
  for (const dispose of disposers) { try { if (typeof dispose === 'function') dispose() } catch { /* ignore */ } }
4609
6119
  }