dsh-harness-kit 0.0.0-stage → 0.1.0

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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
package/client.js ADDED
@@ -0,0 +1,1272 @@
1
+ // Harness Kit — Client panel v2(M4b 作战室)。
2
+ // 顶栏(工作区切换/同步健康/⚙🕘+⟳)→「需要你」注意力条 → 泳道三列(规划中/实施中/待归档)
3
+ // → 底部折叠历史板;独立视图:配置(⚙)与团队动态(🕘);立项走居中模态。
4
+ // 数据:Host webServer 端点(state 3s 轮询;config/activity 进视图时拉取;sync 立即同步)。
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-harness-kit',
7
+ factory(require) {
8
+ const React = require('react');
9
+ const h = React.createElement;
10
+ const { useState, useEffect, useCallback, useRef } = React;
11
+
12
+ // 注入圆点动画 + 表单可读性样式(每次装载都重写,保证 HMR 后样式同步)
13
+ {
14
+ let style = document.getElementById('hk-style');
15
+ if (!style) {
16
+ style = document.createElement('style');
17
+ style.id = 'hk-style';
18
+ document.head.appendChild(style);
19
+ }
20
+ style.textContent =
21
+ '@keyframes hk-breathe{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.45;transform:scale(.82)}}' +
22
+ '@keyframes hk-pulse{0%,100%{opacity:1}50%{opacity:.35}}' +
23
+ '.hk-dot-current{animation:hk-breathe 1.6s ease-in-out infinite}' +
24
+ '.hk-sync-checking{animation:hk-pulse 1.2s ease-in-out infinite}' +
25
+ // 占位符:UA 默认灰不随主题,暗色下几乎不可读 → 显式跟随主题次级文字色
26
+ '.hk-root input::placeholder,.hk-root textarea::placeholder{color:var(--dsw-alias-label-secondary);opacity:.65}' +
27
+ '.hk-root input:focus,.hk-root select:focus,.hk-root textarea:focus{outline:none;border-color:var(--dsw-alias-brand-primary)}' +
28
+ '.hk-browse-row:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 9%, transparent)}';
29
+ }
30
+
31
+ const V = {
32
+ bg: 'var(--dsw-alias-bg-layer-1)',
33
+ bg2: 'var(--dsw-alias-bg-layer-2)',
34
+ overlay: 'var(--dsw-alias-bg-overlay)',
35
+ border: 'var(--dsw-alias-border-l1)',
36
+ border2: 'var(--dsw-alias-border-l2)',
37
+ brand: 'var(--dsw-alias-brand-primary)',
38
+ // 品牌色按钮上的文字色:亮主题白字深底、暗主题深字白底(主题按系统反转)
39
+ brandInvert: 'var(--dsw-alias-label-primary-inverted, #fff)',
40
+ text: 'var(--dsw-alias-label-primary)',
41
+ sub: 'var(--dsw-alias-label-secondary)',
42
+ err: 'var(--dsw-alias-state-error-primary)',
43
+ ok: 'var(--dsw-alias-state-success-primary)',
44
+ warn: 'var(--dsw-alias-state-warn-primary)',
45
+ idle: 'var(--dsw-alias-state-idle-primary)',
46
+ };
47
+ // 主题自适应浅面:bg-layer-2 在浅色主题下与底色同为纯白、在暗色下区分度也低,
48
+ // 改用「主文字色低透明度」混合,明暗两态都保证结构可见。
49
+ const tint = (pct) => `color-mix(in srgb, var(--dsw-alias-label-primary) ${pct}%, transparent)`;
50
+ V.surface = tint(4); // 泳道/区块底
51
+ V.fieldBg = tint(3); // 输入框底
52
+ V.modalShadow = '0 10px 36px rgba(0, 0, 0, 0.35)';
53
+
54
+ const S = {
55
+ wrap: { display: 'flex', flexDirection: 'column', height: '100%', fontSize: 13, lineHeight: 1.5, color: V.text, overflow: 'hidden' },
56
+ body: { flex: 1, overflowY: 'auto', padding: '0 16px 24px' },
57
+ header: { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', borderBottom: `1px solid ${V.border}`, flexWrap: 'wrap' },
58
+ hTitle: { fontWeight: 600, fontSize: 14 },
59
+ // 模型下拉建议(provider 切换/取消映射时过滤)——宿主端用,保持同源
60
+ modelSuggest: (models, provider) => (models ?? []).filter((mo) => !provider || mo.provider === provider).flatMap((mo) => mo.models ?? []).map((m) => m.id),
61
+ select: { padding: '3px 8px', borderRadius: 8, border: `1px solid ${V.border2}`, background: V.bg, color: V.text, fontSize: 12, maxWidth: 220 },
62
+ iconBtn: { width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 8, border: `1px solid ${V.border}`, background: 'transparent', color: V.text, cursor: 'pointer', fontSize: 14 },
63
+ btn: (disabled, primary) => ({
64
+ padding: '4px 12px', borderRadius: 8, fontSize: 12, cursor: disabled ? 'not-allowed' : 'pointer',
65
+ border: primary ? 'none' : `1px solid ${V.border2}`,
66
+ background: primary ? V.brand : 'transparent',
67
+ color: primary ? V.brandInvert : V.text, opacity: disabled ? 0.45 : 1,
68
+ }),
69
+ attn: (level) => ({
70
+ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px', marginBottom: 6, borderRadius: 8, fontSize: 12,
71
+ background: `color-mix(in srgb, ${level === 'block' ? V.err : V.warn} 12%, transparent)`,
72
+ borderLeft: `3px solid ${level === 'block' ? V.err : V.warn}`,
73
+ }),
74
+ lanes: { display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 12 },
75
+ lane: { flex: '1 1 220px', minWidth: 220, background: V.surface, borderRadius: 8, padding: 8, display: 'flex', flexDirection: 'column', gap: 8 },
76
+ laneHead: { display: 'flex', justifyContent: 'space-between', fontSize: 12, color: V.sub, padding: '2px 4px', fontWeight: 600 },
77
+ card: { background: V.bg, border: `1px solid ${V.border2}`, borderRadius: 8, padding: '10px 12px', cursor: 'pointer' },
78
+ cardTitle: { fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
79
+ capsule: { fontSize: 10, padding: '1px 6px', borderRadius: 8, border: `1px solid ${V.border2}`, color: V.sub },
80
+ avatar: { width: 16, height: 16, borderRadius: '50%', background: V.brand, color: V.brandInvert, fontSize: 10, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
81
+ statusLine: { fontSize: 12, color: V.sub, marginTop: 3 },
82
+ dots: { display: 'flex', gap: 5, alignItems: 'center', marginTop: 8 },
83
+ actions: { display: 'flex', gap: 6, marginTop: 10, alignItems: 'center' },
84
+ detail: { marginTop: 8, paddingTop: 8, borderTop: `1px solid ${V.border}`, fontSize: 12, color: V.sub },
85
+ history: { marginTop: 16, border: `1px solid ${V.border2}`, borderRadius: 8 },
86
+ histHead: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', cursor: 'pointer', fontSize: 12, color: V.sub, fontWeight: 600 },
87
+ table: { borderCollapse: 'collapse', width: '100%', fontSize: 12 },
88
+ th: { textAlign: 'left', padding: '4px 10px', borderBottom: `1px solid ${V.border2}`, color: V.sub, whiteSpace: 'nowrap' },
89
+ td: { padding: '4px 10px', borderBottom: `1px solid ${V.border}`, verticalAlign: 'top' },
90
+ input: { padding: '4px 10px', borderRadius: 8, border: `1px solid ${V.border2}`, background: V.fieldBg, color: V.text, fontSize: 12, width: '100%', boxSizing: 'border-box' },
91
+ overlayBox: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 },
92
+ modal: { background: V.bg, borderRadius: 10, border: `1px solid ${V.border2}`, boxShadow: V.modalShadow, padding: 20, width: 380, maxWidth: '90vw' },
93
+ field: { marginBottom: 12 },
94
+ label: { fontSize: 12, color: V.sub, marginBottom: 4, display: 'block' },
95
+ toast: (okv) => ({ padding: '8px 12px', borderRadius: 8, fontSize: 12, background: V.bg, border: `1px solid ${okv ? V.ok : V.err}`, boxShadow: V.modalShadow, color: V.text, marginBottom: 6, maxWidth: 420, whiteSpace: 'pre-wrap', cursor: okv ? 'default' : 'pointer' }),
96
+ toastWrap: { position: 'fixed', bottom: 16, right: 16, zIndex: 200 },
97
+ empty: { textAlign: 'center', padding: '40px 0', color: V.sub },
98
+ section: { background: V.surface, borderRadius: 8, padding: 14, marginBottom: 12 },
99
+ secTitle: { fontWeight: 600, fontSize: 13, marginBottom: 8 },
100
+ kv: { display: 'flex', gap: 8, fontSize: 12, marginBottom: 4 },
101
+ day: { fontSize: 11, color: V.sub, fontWeight: 600, margin: '12px 0 6px', borderBottom: `1px solid ${V.border}`, paddingBottom: 4 },
102
+ actRow: { display: 'flex', gap: 8, alignItems: 'flex-start', padding: '5px 0', fontSize: 12 },
103
+ syncDot: (color, checking) => ({ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0 }),
104
+ obCard: { flex: '1 1 240px', minWidth: 240, background: V.surface, border: `1px solid ${V.border2}`, borderRadius: 10, padding: 16, cursor: 'pointer' },
105
+ pre: { background: V.bg, border: `1px solid ${V.border}`, borderRadius: 8, padding: 10, fontSize: 11, whiteSpace: 'pre-wrap', maxHeight: 260, overflowY: 'auto', fontFamily: 'monospace', marginTop: 8 },
106
+ };
107
+
108
+ const LANES = [
109
+ { id: 'plan', name: '规划中' },
110
+ { id: 'build', name: '实施中' },
111
+ { id: 'archive', name: '待归档' },
112
+ ];
113
+
114
+ const SYNC_META = {
115
+ clean: { color: 'var(--dsw-alias-state-success-primary)', label: '已同步' },
116
+ ahead: { color: 'var(--dsw-alias-state-success-primary)', label: '本地领先' },
117
+ behind: { color: 'var(--dsw-alias-state-warn-primary)', label: '落后远端' },
118
+ diverged: { color: 'var(--dsw-alias-state-warn-primary)', label: '已分叉' },
119
+ blocked: { color: 'var(--dsw-alias-state-error-primary)', label: '同步冲突' },
120
+ offline: { color: 'var(--dsw-alias-state-error-primary)', label: '远端不可达' },
121
+ unknown: { color: 'var(--dsw-alias-state-error-primary)', label: '状态未知' },
122
+ checking: { color: 'var(--dsw-alias-state-idle-primary)', label: '检查中' },
123
+ local: { color: 'var(--dsw-alias-state-idle-primary)', label: '本地模式' },
124
+ 'no-remote': { color: 'var(--dsw-alias-state-idle-primary)', label: '未配远端' },
125
+ embedded: { color: 'var(--dsw-alias-state-success-primary)', label: '随工作区仓' },
126
+ };
127
+
128
+ // .harness 无独立 git、被工作区根仓库跟踪时(layout==='embedded'),同步状态随根仓库
129
+ // 计算,标签统一加后缀说明归属,避免与「独立资产仓库」语义混淆。
130
+ const withLayout = (meta, sync) =>
131
+ sync?.layout === 'embedded' && sync?.state !== 'embedded' ? { ...meta, label: `${meta.label}·随工作区仓` } : meta;
132
+
133
+ function relDay(dateStr) {
134
+ if (!dateStr || dateStr === '—') return '';
135
+ const d = new Date(dateStr);
136
+ if (Number.isNaN(d.getTime())) return dateStr;
137
+ const days = Math.floor((Date.now() - d.getTime()) / 86400000);
138
+ if (days <= 0) return '今天';
139
+ if (days === 1) return '昨天';
140
+ return `${days} 天前`;
141
+ }
142
+
143
+ function Icon(props) {
144
+ const size = (props && props.size) || 20;
145
+ return h('svg', { viewBox: '0 0 24 24', width: size, height: size, 'aria-hidden': true, style: { display: 'block' } },
146
+ h('path', { d: 'M4 5h16M4 12h16M4 19h10', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', fill: 'none' }),
147
+ h('circle', { cx: 19, cy: 19, r: 2.4, fill: 'currentColor' }));
148
+ }
149
+
150
+ // 看板链词表 → 中文显示名(证据推导路径的阶段名本身即中文,原样通过)
151
+ const STAGE_LABEL = {
152
+ propose: '需求方案', Dev: '开发', CR: '代码审查', TE: '测试', 验证: '验证',
153
+ 审批1: '审批 1', 审批2: '审批 2', 质量门: '质量门', 影响面: '影响面分析',
154
+ };
155
+ const stageLabel = (name) => STAGE_LABEL[name] || name;
156
+
157
+ // 阶段圆点(审批为菱形;跳过为空心;阻塞为红色)
158
+ function Dots({ stages }) {
159
+ return h('div', { style: S.dots },
160
+ stages.map((s, i) => {
161
+ const isApproval = s.kind === 'approval';
162
+ const base = {
163
+ width: 8, height: 8, display: 'inline-block', flexShrink: 0,
164
+ borderRadius: isApproval ? 2 : '50%', transform: isApproval ? 'rotate(45deg)' : 'none',
165
+ background: s.done ? V.ok : s.blocked ? V.err : s.skipped ? 'transparent' : 'var(--dsw-alias-border-l2)',
166
+ border: s.skipped ? '1px solid var(--dsw-alias-border-l2)' : 'none',
167
+ };
168
+ const state = s.done ? ' · 已完成' : s.blocked ? ' · 阻塞' : s.skipped ? ' · 已跳过' : s.current ? ' · 当前阶段' : ' · 待进行';
169
+ return h('span', {
170
+ key: i, title: `${stageLabel(s.name)}${state}${isApproval ? ' · 审批点' : ''}`,
171
+ className: s.current ? 'hk-dot-current' : undefined,
172
+ style: s.current ? { ...base, background: V.brand } : base,
173
+ });
174
+ }));
175
+ }
176
+
177
+ function Panel({ uiWorkspace }) {
178
+ const [data, setData] = useState(null);
179
+ // 工作区选择记忆:打开插件时恢复上次选择的工作区(而非列表第一个)
180
+ const [lastWsId, setLastWsId] = useState(() => {
181
+ try { return localStorage.getItem('harness-kit.lastWorkspaceId'); } catch { return null; }
182
+ });
183
+ const [wsId, setWsId] = useState(null);
184
+ const [view, setView] = useState('main'); // main|config|activity
185
+ const [config, setConfig] = useState(null);
186
+ const [activity, setActivity] = useState(null);
187
+ const [toasts, setToasts] = useState([]);
188
+ const [expanded, setExpanded] = useState(() => new Set());
189
+ const [histOpen, setHistOpen] = useState(false);
190
+ const [histQuery, setHistQuery] = useState('');
191
+ const [modal, setModal] = useState(null); // {name, desc, file}
192
+ const [browse, setBrowse] = useState(null); // 需求文件浏览:{dir, parent, entries, loading, error}
193
+ const [busy, setBusy] = useState(false);
194
+ // 工作区开通引导:null 不显示;'choice'|'new'|'open'。无工作区时自动进入 choice。
195
+ const [obMode, setObMode] = useState(null);
196
+ const [obPath, setObPath] = useState(''); // 「打开」被拒后转「新建」时预填的目录
197
+ const tick = useRef(0);
198
+
199
+ const toast = useCallback((text, okv = true) => {
200
+ const id = ++tick.current;
201
+ setToasts((ts) => [...ts, { id, text: String(text).slice(0, 500), ok: okv }]);
202
+ // 成功 3s、失败 6s 自动消失;点击立即关闭
203
+ setTimeout(() => setToasts((ts) => ts.filter((x) => x.id !== id)), okv ? 3000 : 6000);
204
+ }, []);
205
+
206
+ const fetchState = useCallback(() => {
207
+ fetch('/harness-kit/state', { cache: 'no-store' })
208
+ .then((r) => r.json())
209
+ .then((j) => { if (j.ok) setData(j); })
210
+ .catch(() => {});
211
+ }, []);
212
+ useEffect(() => {
213
+ fetchState();
214
+ const t = setInterval(fetchState, 3000);
215
+ return () => clearInterval(t);
216
+ }, [fetchState]);
217
+
218
+ const workspaces = data?.workspaces ?? [];
219
+ // 解析顺序:显式选择 > 记忆的上次工作区 > 列表第一个(记忆值已从列表移除时自然回落)
220
+ const ws = workspaces.find((w) => w.id === wsId)
221
+ ?? workspaces.find((w) => w.id === lastWsId)
222
+ ?? workspaces[0] ?? null;
223
+ const selectWs = useCallback((id) => {
224
+ setWsId(id);
225
+ setLastWsId(id);
226
+ try { localStorage.setItem('harness-kit.lastWorkspaceId', id); } catch { /* 无痕模式等场景静默 */ }
227
+ }, []);
228
+
229
+ // 无活动会话时的兜底:优先唤醒最近会话,无会话则开空白会话(保留草稿)
230
+ const openFallbackSession = useCallback(async () => {
231
+ if (!uiWorkspace || !ws) return false;
232
+ const sessions = ws.sessions ?? [];
233
+ const last = sessions[sessions.length - 1];
234
+ try {
235
+ if (last) { uiWorkspace.openSession(last.id); return true; }
236
+ if (uiWorkspace.openWorkspace) { await uiWorkspace.openWorkspace(ws.id); return true; }
237
+ } catch { /* 忽略,走提示 */ }
238
+ return false;
239
+ }, [ws, uiWorkspace]);
240
+
241
+ const run = useCallback((line, retried = false) => {
242
+ if (!ws) return;
243
+ setBusy(true);
244
+ fetch('/harness-kit/command', {
245
+ method: 'POST', headers: { 'content-type': 'application/json' },
246
+ body: JSON.stringify({ workspace: ws.id, line }),
247
+ }).then((r) => r.json()).then(async (j) => {
248
+ if (!j.ok && !retried && /没有活动会话/.test(j.error || '')) {
249
+ toast('该工作区暂无活动会话,正在打开并重试…');
250
+ setBusy(false);
251
+ if (await openFallbackSession()) {
252
+ setTimeout(() => run(line, true), 2500);
253
+ } else {
254
+ toast('请先在该工作区打开一个会话再操作', false);
255
+ }
256
+ return;
257
+ }
258
+ if (j.ok && j.sessionId && uiWorkspace?.openSession) {
259
+ // 命令在某个会话里注入执行:直接切过去,让用户看到执行现场。
260
+ // 走 unarchiveThenOpen:目标会话若被归档,直接 openSession 会被导航效应
261
+ // 立刻清回空白「新会话」视图(归档会话在侧栏隐藏)。
262
+ try {
263
+ await unarchiveThenOpen(j.sessionId);
264
+ dbgClient({ step: 'legacy-jump', ok: true, target: j.sessionId });
265
+ } catch (e) {
266
+ dbgClient({ step: 'legacy-jump', ok: false, target: j.sessionId, err: String(e?.message || e) });
267
+ }
268
+ }
269
+ toast(j.ok ? `已发送到会话执行:${line}` : j.error || '失败', j.ok);
270
+ setTimeout(fetchState, 600);
271
+ }).catch((e) => toast(e.message, false)).finally(() => setBusy(false));
272
+ }, [ws, toast, fetchState, openFallbackSession]);
273
+
274
+ // 立项/fix 直通:为任务开专属新会话(openWorkspace 在当前窗口直达新会话,
275
+ // beforeOpen 同步拿到 sessionId),再把命令定向注入该会话——host 端轮询等
276
+ // agent 就绪(≤15s),用户全程看到执行现场,侧栏也有新会话记录。
277
+ // 打开失败/被取代则回落旧路径(注入最近活动会话)。
278
+ const runFresh = useCallback(async (line) => {
279
+ if (!ws) return;
280
+ if (!uiWorkspace?.openWorkspace) { run(line); return; }
281
+ setBusy(true);
282
+ let sid = null;
283
+ try { await uiWorkspace.openWorkspace(ws.id, (id) => { sid = id; }); } catch { /* 回落旧路径 */ }
284
+ if (!sid) { run(line); return; }
285
+ try {
286
+ const j = await fetch('/harness-kit/command', {
287
+ method: 'POST', headers: { 'content-type': 'application/json' },
288
+ body: JSON.stringify({ workspace: ws.id, line, sessionId: sid }),
289
+ }).then((r) => r.json());
290
+ toast(j.ok ? `已发送到会话执行:${line}` : j.error || '失败', j.ok);
291
+ } catch (e) { toast(e.message, false); }
292
+ setBusy(false);
293
+ setTimeout(fetchState, 600);
294
+ }, [ws, uiWorkspace, run, toast, fetchState]);
295
+
296
+ const syncNow = useCallback(() => {
297
+ if (!ws) return;
298
+ // embedded 兜底:不 POST(host 会回"不适用"),直接指路
299
+ if (ws.sync?.layout === 'embedded') {
300
+ toast('资产随工作区根仓库管理:在根仓库 git pull/push 即共享,面板同步不适用', false);
301
+ return;
302
+ }
303
+ setBusy(true);
304
+ toast('同步中…(git fetch/rebase/push)');
305
+ fetch('/harness-kit/sync', {
306
+ method: 'POST', headers: { 'content-type': 'application/json' },
307
+ body: JSON.stringify({ workspace: ws.id }),
308
+ }).then((r) => r.json()).then((j) => {
309
+ toast(j.text || (j.ok ? '同步完成' : '同步失败'), j.ok);
310
+ setTimeout(fetchState, 800);
311
+ }).catch((e) => toast(e.message, false)).finally(() => setBusy(false));
312
+ }, [ws, toast, fetchState]);
313
+
314
+ // 需求文件浏览:打开/进入目录(宿主无文件选择器,走 /harness-kit/browse 列举)
315
+ const browseInto = useCallback(async (dir) => {
316
+ if (!ws) return;
317
+ setBrowse((b) => ({ ...(b ?? {}), dir, loading: true, error: null }));
318
+ try {
319
+ const r = await fetch(`/harness-kit/browse?workspace=${encodeURIComponent(ws.id)}&dir=${encodeURIComponent(dir)}`, { cache: 'no-store' });
320
+ const j = await r.json();
321
+ if (!j.ok) setBrowse((b) => ({ ...(b ?? {}), dir, loading: false, error: j.error || '列举失败' }));
322
+ else setBrowse({ dir: j.dir, parent: j.parent, entries: j.entries, loading: false, error: null });
323
+ } catch (e) {
324
+ setBrowse((b) => ({ ...(b ?? {}), dir, loading: false, error: e.message }));
325
+ }
326
+ }, [ws]);
327
+
328
+ // 目录选择:Desktop 快速路径优先,退回 uiWorkspace 服务,均不可用时由用户手填
329
+ const pickDirectory = useCallback(async () => {
330
+ try {
331
+ const picker = globalThis.__DSH_DIRECTORY_PICKER__;
332
+ if (picker?.pick) return await picker.pick();
333
+ if (uiWorkspace?.pickDirectory) return await uiWorkspace.pickDirectory();
334
+ } catch { /* 用户取消或宿主不支持 */ }
335
+ return null;
336
+ }, [uiWorkspace]);
337
+
338
+ // 面板化初始化入口(配置视图:重跑初始化 / 添加子工程)
339
+ const runInitPanel = useCallback((payload, okMsg) => {
340
+ if (!ws) return;
341
+ setBusy(true);
342
+ fetch('/harness-kit/workspace/init', {
343
+ method: 'POST', headers: { 'content-type': 'application/json' },
344
+ body: JSON.stringify({ workspace: ws.id, ...payload }),
345
+ }).then((r) => r.json()).then((j) => {
346
+ toast(j.ok ? (okMsg ?? '初始化完成') : j.error || '操作失败', j.ok);
347
+ if (j.ok) {
348
+ fetch(`/harness-kit/config?workspace=${encodeURIComponent(ws.id)}`, { cache: 'no-store' })
349
+ .then((r) => r.json()).then((c) => setConfig(c.ok ? c : null)).catch(() => {});
350
+ setTimeout(fetchState, 800);
351
+ }
352
+ }).catch((e) => toast(e.message, false)).finally(() => setBusy(false));
353
+ }, [ws, toast, fetchState]);
354
+
355
+ // 任务级跳转(2026-11-12 人裁决第三版):仅当任务有 session 绑定记录、
356
+ // 且该会话仍在本机工作区列表中,才允许「继续会话」——点击 openSession 直达窗口。
357
+ // 其余情况(无记录 / 会话不在本机)一律不提供入口:不支持接管别人的任务。
358
+ const hasLiveSession = (t) => !!t?.sessionId && (ws?.sessions ?? []).some((s) => s.id === t.sessionId);
359
+ // 临时排障(2026-11-13):把跳转链路关键步骤回报到 host,落盘 /tmp/hk-command-debug.log
360
+ const dbgClient = (obj) => {
361
+ try {
362
+ fetch('/harness-kit/debug-log', {
363
+ method: 'POST', headers: { 'content-type': 'application/json' },
364
+ body: JSON.stringify(obj),
365
+ }).catch(() => { });
366
+ } catch { /* 排障回报失败不阻断 */ }
367
+ };
368
+ // 跳转到绑定会话前的统一准备:归档会话被选中会被导航效应立刻清回空白「新会话」视图
369
+ // 且从侧栏隐藏(2026-11-13 定位的「跳转后只见空白新对话窗」根因),故先幂等取消归档,
370
+ // 稍等列表快照刷新再跳转。对未归档会话是无害空操作。
371
+ const unarchiveThenOpen = async (sessionId) => {
372
+ if (!uiWorkspace?.openSession || !sessionId) return;
373
+ await uiWorkspace.unarchiveSession?.(sessionId)?.catch?.(() => { });
374
+ await new Promise((r) => setTimeout(r, 200));
375
+ uiWorkspace.openSession(sessionId);
376
+ };
377
+
378
+ const jumpTask = useCallback((t) => {
379
+ if (!uiWorkspace) return toast('界面未提供工作区操作能力', false);
380
+ if (!hasLiveSession(t)) return toast('该任务在本机没有可继续的会话', false);
381
+ unarchiveThenOpen(t.sessionId)
382
+ .then(() => toast(`已打开「${t.task}」的会话`))
383
+ .catch((e) => toast(`打开会话失败:${e?.message || e}`, false));
384
+ }, [ws, uiWorkspace, toast]);
385
+
386
+ // 任务动作(继续推进/归档)定向执行:有本机存活绑定会话时,命令定向注入绑定会话、
387
+ // 跳转也直达绑定会话——命令目标=跳转目标=绑定会话,避免旧路径「最近活动会话」启发式
388
+ // 把命令打进别的会话、再跳到用户意料之外的窗口。无存活绑定时回落旧 run()。
389
+ const runTask = useCallback((t) => {
390
+ const line = t?.action?.line;
391
+ if (!ws || !line) return;
392
+ const directed = hasLiveSession(t);
393
+ dbgClient({ step: 'runTask', task: t?.task, directed, bound: t?.sessionId ?? null,
394
+ wsSessions: (ws.sessions ?? []).map((s) => s.id) });
395
+ if (!directed) { run(line); return; }
396
+ setBusy(true);
397
+ fetch('/harness-kit/command', {
398
+ method: 'POST', headers: { 'content-type': 'application/json' },
399
+ body: JSON.stringify({ workspace: ws.id, line, sessionId: t.sessionId }),
400
+ }).then((r) => r.json()).then(async (j) => {
401
+ dbgClient({ step: 'resp', ok: !!j.ok, sid: j.sessionId ?? null, err: j.error ?? null });
402
+ if (j.ok && uiWorkspace?.openSession) {
403
+ try {
404
+ await unarchiveThenOpen(t.sessionId);
405
+ dbgClient({ step: 'jump', ok: true, target: t.sessionId });
406
+ } catch (e) {
407
+ dbgClient({ step: 'jump', ok: false, target: t.sessionId, err: String(e?.message || e) });
408
+ }
409
+ }
410
+ toast(j.ok ? `已发送到会话执行:${line}` : j.error || '失败', j.ok);
411
+ setTimeout(fetchState, 600);
412
+ }).catch((e) => toast(e.message, false)).finally(() => setBusy(false));
413
+ }, [ws, uiWorkspace, run, toast, fetchState]);
414
+
415
+ // 进入配置/动态视图时拉数据
416
+ useEffect(() => {
417
+ if (!ws) return;
418
+ if (view === 'config') {
419
+ fetch(`/harness-kit/config?workspace=${encodeURIComponent(ws.id)}`, { cache: 'no-store' })
420
+ .then((r) => r.json()).then((j) => setConfig(j.ok ? j : null)).catch(() => setConfig(null));
421
+ } else if (view === 'activity') {
422
+ fetch(`/harness-kit/activity?workspace=${encodeURIComponent(ws.id)}`, { cache: 'no-store' })
423
+ .then((r) => r.json()).then((j) => setActivity(j.ok ? j.entries : [])).catch(() => setActivity([]));
424
+ }
425
+ }, [view, ws?.id]);
426
+
427
+ const liveSession = (ws?.sessions ?? []).some((s) => s.live);
428
+
429
+ // ---------- 顶栏 ----------
430
+ const syncMeta = withLayout(SYNC_META[ws?.sync?.state] ?? SYNC_META.checking, ws?.sync);
431
+ const header = h('div', { style: S.header },
432
+ h('span', { style: S.hTitle }, 'Harness'),
433
+ workspaces.length > 1 && h('select', {
434
+ style: S.select, value: ws?.id ?? '', onChange: (e) => selectWs(e.target.value),
435
+ }, workspaces.map((w) => h('option', { key: w.id, value: w.id }, w.title || w.id))),
436
+ ws && h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: V.sub }, title: ws.sync?.checkedAt ? `检查于 ${new Date(ws.sync.checkedAt).toLocaleTimeString()}` : '' },
437
+ h('span', { style: S.syncDot(syncMeta.color), className: ws.sync?.state === 'checking' ? 'hk-sync-checking' : undefined }),
438
+ syncMeta.label,
439
+ ws.sync?.state === 'behind' && ` ${ws.sync.behind}↓`,
440
+ ws.sync?.state === 'diverged' && ` ${ws.sync.behind}↓${ws.sync.ahead}↑`),
441
+ // embedded(.harness 随工作区根仓库管理):同步对象是根仓库,面板不能替用户动代码仓库,
442
+ // 不提供「立即同步」(旧版点了只会得到"/hk-sync 不适用"报错);提示由注意力项给出。
443
+ ws && ws.sync?.layout !== 'embedded' && h('button', { style: S.btn(busy), disabled: busy, onClick: syncNow }, '立即同步'),
444
+ h('span', { style: { flex: 1 } }),
445
+ h('button', { style: { ...S.btn(false), fontSize: 12 }, title: '新建 / 打开工作区', onClick: () => setObMode('choice') }, '+ 工作区'),
446
+ ws && h('button', { style: S.iconBtn, title: '新建任务', onClick: () => setModal({ name: '', desc: '', file: '' }) }, '+'),
447
+ ws && h('button', { style: S.iconBtn, title: '团队动态', onClick: () => setView(view === 'activity' ? 'main' : 'activity') }, '🕘'),
448
+ ws && h('button', { style: S.iconBtn, title: '配置', onClick: () => setView(view === 'config' ? 'main' : 'config') }, '⚙'),
449
+ h('button', { style: S.iconBtn, title: '刷新', onClick: fetchState }, '⟳'),
450
+ );
451
+
452
+ if (!data) return h('div', { style: S.wrap, className: 'hk-root' }, header, h('div', { style: S.body }, h('div', { style: S.empty }, '加载中…')));
453
+
454
+ // ---------- 工作区开通引导(无工作区自动进入;顶栏「+ 工作区」随时可开) ----------
455
+ const obActive = obMode ?? (workspaces.length === 0 ? 'choice' : null);
456
+ if (obActive) {
457
+ return h('div', { style: S.wrap, className: 'hk-root' }, header, h('div', { style: S.body },
458
+ h(OnboardView, {
459
+ mode: obActive,
460
+ setMode: setObMode,
461
+ canClose: workspaces.length > 0,
462
+ onClose: () => setObMode(null),
463
+ uiWorkspace, toast, busy, setBusy, pickDirectory,
464
+ initialPath: obPath,
465
+ onDone: (id) => { if (id) selectWs(id); fetchState(); },
466
+ onSwitchToNew: (p) => { setObPath(p); setObMode('new'); },
467
+ })),
468
+ h('div', { style: S.toastWrap },
469
+ toasts.map((tst) => h('div', {
470
+ key: tst.id, style: S.toast(tst.ok),
471
+ onClick: () => !tst.ok && setToasts((ts) => ts.filter((x) => x.id !== tst.id)),
472
+ }, tst.text))));
473
+ }
474
+
475
+ // ---------- 配置视图 ----------
476
+ const saveConfig = (patch, okMsg) => {
477
+ setBusy(true);
478
+ fetch('/harness-kit/config', {
479
+ method: 'POST', headers: { 'content-type': 'application/json' },
480
+ body: JSON.stringify({ workspace: ws.id, patch }),
481
+ }).then((r) => r.json()).then((j) => {
482
+ toast(j.ok ? okMsg : j.error || '保存失败', j.ok);
483
+ if (j.ok) {
484
+ fetch(`/harness-kit/config?workspace=${encodeURIComponent(ws.id)}`, { cache: 'no-store' })
485
+ .then((r) => r.json()).then((c) => setConfig(c.ok ? c : null)).catch(() => {});
486
+ }
487
+ }).catch((e) => toast(e.message, false)).finally(() => setBusy(false));
488
+ };
489
+
490
+ if (view === 'config') {
491
+ return h('div', { style: S.wrap, className: 'hk-root' }, header, h('div', { style: S.body },
492
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, margin: '12px 0' } },
493
+ h('button', { style: S.iconBtn, onClick: () => setView('main') }, '←'),
494
+ h('span', { style: S.hTitle }, `配置 · ${ws.title || ws.id}`)),
495
+ !config ? h('div', { style: S.empty }, '加载中…') : h(ConfigView, { config, syncMeta, ws, busy, saveConfig, runInit: runInitPanel, onOrchestrate: () => run('/hk-init'), catalog: config.catalog ?? [], toast }),
496
+ ), h('div', { style: S.toastWrap }, toasts.map((tst) => h('div', { key: tst.id, style: S.toast(tst.ok), onClick: () => !tst.ok && setToasts((ts) => ts.filter((x) => x.id !== tst.id)) }, tst.text))));
497
+ }
498
+
499
+ // ---------- 团队动态视图 ----------
500
+ if (view === 'activity') {
501
+ const groups = {};
502
+ for (const e of activity ?? []) {
503
+ const day = (e.at || '').split(' ')[0] || '未知日期';
504
+ (groups[day] = groups[day] ?? []).push(e);
505
+ }
506
+ let content;
507
+ if (activity === null) content = h('div', { style: S.empty }, '加载中…');
508
+ else if (activity.length === 0) content = h('div', { style: S.empty }, '资产仓库暂无提交记录(本地模式或无 git)');
509
+ else {
510
+ content = Object.keys(groups).sort().reverse().map((day) => {
511
+ const rows = groups[day].map((e, i) => h('div', { key: i, style: S.actRow },
512
+ h('span', { style: S.avatar }, (e.author || '?').slice(0, 1).toUpperCase()),
513
+ h('div', null,
514
+ h('div', null, h('b', null, e.author), ' · ', e.subject),
515
+ h('div', { style: { fontSize: 11, color: V.sub } }, (e.at || '').split(' ')[1] ?? '', ' · ', e.hash))));
516
+ return h('div', { key: day }, h('div', { style: S.day }, day), rows);
517
+ });
518
+ }
519
+ return h('div', { style: S.wrap, className: 'hk-root' }, header, h('div', { style: S.body },
520
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, margin: '12px 0' } },
521
+ h('button', { style: S.iconBtn, onClick: () => setView('main') }, '←'),
522
+ h('span', { style: S.hTitle }, `团队动态 · ${ws.title || ws.id}`)),
523
+ content));
524
+ }
525
+
526
+ // ---------- 主视图 ----------
527
+ const active = ws.tasks.filter((t) => t.lane !== 'done');
528
+ // 历史任务板:按「上次活动」时间倒序(最新完成在前)
529
+ const done = ws.tasks.filter((t) => t.lane === 'done')
530
+ .sort((a, b) => String(b.updated || '').localeCompare(String(a.updated || '')));
531
+ const histRows = done.filter((t) => !histQuery || t.task.toLowerCase().includes(histQuery.toLowerCase()));
532
+
533
+ const primaryOf = (t) => {
534
+ const a = t.action;
535
+ // 用户裁决(2026-11-12 第三版):「继续会话」仅对本机存在绑定会话的任务出现;
536
+ // 无会话的任务不显示跳转按钮(不支持接管他人任务),归档/继续推进不受影响。
537
+ const sessionBtn = { label: '继续会话', onClick: () => jumpTask(t), primary: true };
538
+ if (a.kind === 'wait') return hasLiveSession(t) ? sessionBtn : null;
539
+ if (a.kind === 'archive') return { label: '归档', onClick: () => runTask(t), primary: true };
540
+ if (a.kind === 'apply') return hasLiveSession(t) ? sessionBtn : null;
541
+ // 用户裁决(2026-11-12):历史任务不需要重开按钮
542
+ if (a.kind === 'reopen') return null;
543
+ return { label: '继续推进', onClick: () => runTask(t), primary: true };
544
+ };
545
+
546
+ const card = (t) => {
547
+ const cur = t.progress.current >= 0 ? t.progress.stages[t.progress.current] : null;
548
+ const open = expanded.has(t.task);
549
+ const primary = primaryOf(t);
550
+ return h('div', { key: t.task, style: S.card, onClick: () => setExpanded((s) => { const n = new Set(s); n.has(t.task) ? n.delete(t.task) : n.add(t.task); return n; }) },
551
+ h('div', { style: S.cardTitle },
552
+ t.task,
553
+ t.profile && t.profile !== '—' && h('span', { style: S.capsule }, t.profile),
554
+ t.claimer && h('span', { style: S.avatar, title: `认领人:${t.claimer}` }, t.claimer.slice(0, 1).toUpperCase())),
555
+ h('div', { style: S.statusLine },
556
+ t.status === 'AWAITING_ARCHIVE' ? '已完成' : cur ? `${cur.kind === 'approval' ? '⛔ ' : ''}${stageLabel(cur.name)}` : '—',
557
+ ' · ', relDay(t.updated),
558
+ t.claimer ? ` · ${t.claimer}` : '',
559
+ // M2:slot 开发的任务打槽位标记(主树任务不打,保持默认形态干净)
560
+ (() => {
561
+ const w = t.workspace && Object.values(t.workspace).find((x) => x.placement !== 'main');
562
+ return w ? ` · 🗂 ${w.placement}` : '';
563
+ })(),
564
+ // TE 环境持有者标记(串行租约)
565
+ t.teHolder ? ' · 🧪TE环境' : ''),
566
+ h(Dots, { stages: t.progress.stages.map((s, i) => ({ ...s, current: i === t.progress.current })) }),
567
+ // 圆点与看板 Apply 链同源:链原文贴出便于对照(绿✅ 蓝▶当前 灰…待做 红⛔阻塞 空心—跳过)
568
+ t.apply && t.apply !== '—' && t.apply !== '已归档'
569
+ && h('div', { style: { fontSize: 11, color: V.sub, marginTop: 3 } }, t.apply),
570
+ h('div', { style: { ...S.actions, position: 'relative' }, onClick: (e) => e.stopPropagation() },
571
+ primary && h('button', { style: S.btn(primary.disabled || busy, primary.primary), disabled: primary.disabled || busy, onClick: primary.onClick }, primary.label),
572
+ ),
573
+ open && h('div', { style: S.detail, onClick: (e) => e.stopPropagation() },
574
+ h('div', null, h('b', null, '状态:'), t.status, ' ', h('b', null, '分支:'), t.branch),
575
+ // M2 工作区分配(本机):主工作树 or 池化 slot
576
+ t.workspace && h('div', null, h('b', null, '工作区:'),
577
+ Object.entries(t.workspace).map(([repo, w], i) => h('span', { key: repo, title: w.branch ? `${w.branch} ← ${w.base}` : '' },
578
+ i > 0 && ';',
579
+ `${repo} → ${w.placement === 'main' ? '主工作树' : w.placement}`,
580
+ w.branch ? `(${w.branch})` : ''))),
581
+ t.apply && t.apply !== '—' && h('div', null, h('b', null, 'Apply:'), t.apply),
582
+ t.progress.deliverables.length > 0 && h('div', null, h('b', null, '产物:'), t.progress.deliverables.join('、')),
583
+ t.hint && t.hint !== '—' && h('div', null, h('b', null, '续接:'), t.hint),
584
+ t.progress.pendingApproval && h('div', { style: { color: V.warn } }, `⛔ ${t.progress.pendingApproval} 等待人工审批(在会话中答复,并写入通过标记)`)),
585
+ );
586
+ };
587
+
588
+ return h('div', { style: S.wrap, className: 'hk-root' }, header,
589
+ h('div', { style: S.body },
590
+ // 初始化进行中横幅(2026-11-17):页面中途关掉/重开后依旧可见,防止无感知重复初始化
591
+ ws?.init && !ws.init.done && h('div', { style: { ...S.attn('warn'), marginTop: 12 } },
592
+ h('span', null, '🔧'),
593
+ h('span', { style: { flex: 1 } },
594
+ `工作区初始化进行中:${ws.init.stage}${ws.init.detail ? ` — ${ws.init.detail}` : ''}` +
595
+ `(已耗时 ${Math.max(0, Math.round((Date.now() - (ws.init.startedAt || Date.now())) / 1000))}s;刷新页面不影响,完成后自动消失)`)),
596
+ // 「需要你」注意力条
597
+ ws.attention.length > 0 && h('div', { style: { marginTop: 12 } },
598
+ ws.attention.map((a, i) => h('div', { key: i, style: S.attn(a.level) },
599
+ h('span', null, a.level === 'block' ? '🔴' : '🟠'),
600
+ h('span', { style: { flex: 1 } }, a.text),
601
+ a.jump && (() => { const t = a.task && active.concat(done).find((x) => x.task === a.task); return t && hasLiveSession(t)
602
+ ? h('button', { style: S.btn(busy, true), disabled: busy, onClick: () => jumpTask(t) }, '继续会话')
603
+ : null; })(),
604
+ // 结构化决策点选项(外来分支占用等):可点按钮直接重跑对应命令
605
+ (a.options ?? []).map((o) => h('button', {
606
+ key: o.label, style: S.btn(busy, !o.primary), disabled: busy,
607
+ title: o.line, onClick: () => run(o.line),
608
+ }, o.label)),
609
+ a.line && h('button', { style: S.btn(busy, true), disabled: busy, onClick: () => run(a.line) }, '处理'),
610
+ a.init && h('button', { style: S.btn(busy, true), disabled: busy, onClick: () => run('/hk-init') }, '运行初始化编排'),
611
+ a.sync && h('button', { style: S.btn(busy, true), disabled: busy, onClick: syncNow }, a.kind === 'sync-blocked' ? '查看' : '立即同步'),
612
+ ))),
613
+ // 泳道
614
+ active.length === 0
615
+ ? h('div', { style: S.empty },
616
+ h('div', { style: { fontSize: 28, marginBottom: 8 } }, '🛠'),
617
+ h('div', null, '还没有进行中的任务'),
618
+ h('button', { style: { ...S.btn(false, true), marginTop: 10 }, onClick: () => setModal({ name: '', desc: '', file: '' }) }, '立一个新项'))
619
+ : h('div', { style: S.lanes },
620
+ LANES.map((lane) => {
621
+ const ts = active.filter((t) => t.lane === lane.id);
622
+ return h('div', { key: lane.id, style: S.lane },
623
+ h('div', { style: S.laneHead }, h('span', null, lane.name), h('span', null, ts.length)),
624
+ ts.length === 0 ? h('div', { style: { fontSize: 11, color: V.idle, textAlign: 'center', padding: '12px 0' } }, '—')
625
+ : ts.map(card));
626
+ })),
627
+ // 历史任务板(折叠)
628
+ done.length > 0 && h('div', { style: S.history },
629
+ h('div', { style: S.histHead, onClick: () => setHistOpen(!histOpen) },
630
+ h('span', null, histOpen ? '▾' : '▸'), `历史任务板(${done.length})`),
631
+ histOpen && h('div', { style: { padding: '0 12px 12px' } },
632
+ h('input', { style: { ...S.input, width: 220, marginBottom: 8 }, placeholder: '搜索任务名…', value: histQuery, onChange: (e) => setHistQuery(e.target.value) }),
633
+ h('table', { style: S.table },
634
+ h('thead', null, h('tr', null, ['任务', 'Profile', '完成时间'].map((x) => h('th', { key: x, style: S.th }, x)))),
635
+ h('tbody', null, histRows.map((t) => h('tr', { key: t.task },
636
+ h('td', { style: S.td }, t.task),
637
+ h('td', { style: S.td }, t.profile),
638
+ h('td', { style: S.td }, relDay(t.updated)))))))),
639
+ ),
640
+ // 立项模态(需求 / fix 直通 两种模式;任务名可选,留空由 AI 按描述生成)
641
+ modal && h('div', { style: S.overlayBox, onClick: () => { setModal(null); setBrowse(null); } },
642
+ h('div', { style: S.modal, onClick: (e) => e.stopPropagation() },
643
+ h('div', { style: { ...S.hTitle, marginBottom: 10 } }, '新建任务'),
644
+ h('div', { style: { display: 'flex', gap: 6, marginBottom: 14 } },
645
+ [['new', '需求'], ['fix', 'fix 直通']].map(([m, label]) =>
646
+ h('button', {
647
+ key: m,
648
+ style: { ...S.btn(false), padding: '4px 12px', fontSize: 12, borderRadius: 14,
649
+ background: (modal.mode ?? 'new') === m ? V.brand : 'transparent',
650
+ color: (modal.mode ?? 'new') === m ? V.brandInvert : V.text },
651
+ onClick: () => setModal({ ...modal, mode: m }),
652
+ }, label))),
653
+ h('div', { style: { fontSize: 11, color: V.sub, margin: '-8px 0 12px' } },
654
+ (modal.mode ?? 'new') === 'fix'
655
+ ? '简单 bug 修复:跳过文档审批,PM 评估质量门后交你裁决(轻量=只开发+验证)'
656
+ : '完整流程:提案澄清 → Profile 判定 → 人工审批 → 开发实施'),
657
+ h('div', { style: S.field }, h('label', { style: S.label }, '任务名(可选,留空自动按描述生成英文短名)'),
658
+ h('input', { style: S.input, value: modal.name, autoFocus: true, placeholder: '留空自动起名;仅限英文/数字/-_', onChange: (e) => setModal({ ...modal, name: e.target.value }) })),
659
+ h('div', { style: S.field }, h('label', { style: S.label }, '一句话需求描述'),
660
+ h('input', { style: S.input, value: modal.desc, onChange: (e) => setModal({ ...modal, desc: e.target.value }) })),
661
+ (modal.mode ?? 'new') === 'new' && h('div', { style: S.field }, h('label', { style: S.label }, '需求文件路径(可选)'),
662
+ h('div', { style: { display: 'flex', gap: 6 } },
663
+ h('input', { style: { ...S.input, flex: 1 }, value: modal.file, placeholder: 'docs/xxx.md', onChange: (e) => setModal({ ...modal, file: e.target.value }) }),
664
+ h('button', {
665
+ style: S.btn(false),
666
+ onClick: () => {
667
+ if (browse) { setBrowse(null); return; }
668
+ const cur = modal.file.trim();
669
+ browseInto(cur.includes('/') ? cur.slice(0, cur.lastIndexOf('/')) : '');
670
+ },
671
+ }, browse ? '收起' : '浏览…')),
672
+ // 工作区内文件浏览(默认落在工作区根目录;📁 进入,📄 选中回填)
673
+ browse && h('div', { style: { marginTop: 6, border: `1px solid ${V.border2}`, borderRadius: 6, padding: '6px 8px', fontSize: 12, maxHeight: 180, overflowY: 'auto', background: V.fieldBg } },
674
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, color: V.sub } },
675
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
676
+ browse.dir ? `工作区根目录/${browse.dir}` : '工作区根目录'),
677
+ browse.dir ? h('button', {
678
+ style: { ...S.btn(false), padding: '1px 8px', fontSize: 11 },
679
+ onClick: () => browseInto(browse.parent ?? ''),
680
+ }, '‹ 上级') : null),
681
+ browse.loading && h('div', { style: { color: V.sub, padding: '4px 2px' } }, '加载中…'),
682
+ browse.error && h('div', { style: { color: V.err, padding: '4px 2px' } }, browse.error),
683
+ !browse.loading && !browse.error && (browse.entries?.length
684
+ ? browse.entries.map((e) => h('div', {
685
+ key: e.kind + '/' + e.name,
686
+ className: 'hk-browse-row',
687
+ style: { padding: '3px 6px', borderRadius: 4, cursor: 'pointer', color: e.kind === 'dir' ? V.brand : V.text },
688
+ onClick: () => {
689
+ const p = browse.dir ? `${browse.dir}/${e.name}` : e.name;
690
+ if (e.kind === 'dir') browseInto(p);
691
+ else { setModal({ ...modal, file: p }); setBrowse(null); }
692
+ },
693
+ }, `${e.kind === 'dir' ? '📁' : '📄'} ${e.name}`))
694
+ : h('div', { style: { color: V.sub, padding: '4px 2px' } }, '(空目录)')))),
695
+ // 分析基点(可选):各仓分支选择 → /hk-new --base,BA/SA/RR 基于所选分支读码
696
+ Object.keys(ws?.gitBranches ?? {}).length > 0 && h('div', { style: S.field },
697
+ h('label', { style: S.label }, '分析基点(可选,留空 = 共享基线镜像)'),
698
+ Object.entries(ws.gitBranches).map(([repo, branches]) => h('div', { key: repo, style: { display: 'flex', gap: 6, alignItems: 'center', marginBottom: 4 } },
699
+ h('span', { style: { minWidth: 90, fontSize: 12, color: V.sub } }, repo),
700
+ h(Combobox, {
701
+ style: { flex: 1 },
702
+ value: (modal.base ?? {})[repo] ?? '',
703
+ placeholder: '默认(基线镜像)',
704
+ options: branches ?? [],
705
+ onChange: (v) => setModal({ ...modal, base: { ...(modal.base ?? {}), [repo]: v } }),
706
+ })))),
707
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
708
+ h('button', { style: S.btn(false), onClick: () => { setModal(null); setBrowse(null); } }, '取消'),
709
+ h('button', {
710
+ style: S.btn(!modal.desc.trim() || (modal.name.trim() && !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(modal.name.trim())) || busy, true),
711
+ disabled: !modal.desc.trim() || (modal.name.trim() && !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(modal.name.trim())) || busy,
712
+ onClick: () => {
713
+ const mode = modal.mode ?? 'new';
714
+ const name = modal.name.trim() || '--auto';
715
+ const file = mode === 'new' && modal.file.trim() ? ` --file ${modal.file.trim()}` : '';
716
+ const basePairs = Object.entries(modal.base ?? {}).filter(([, b]) => (b ?? '').trim()).map(([r, b]) => `${r}:${b.trim()}`);
717
+ const base = basePairs.length > 0 ? ` --base ${basePairs.join(',')}` : '';
718
+ runFresh(mode === 'fix' ? `/hk-fix ${name} ${modal.desc.trim()}${base}` : `/hk-new ${name} ${modal.desc.trim()}${file}${base}`);
719
+ setModal(null);
720
+ setBrowse(null);
721
+ },
722
+ }, '立项')))),
723
+ // Toast
724
+ h('div', { style: S.toastWrap },
725
+ toasts.map((tst) => h('div', {
726
+ key: tst.id, style: S.toast(tst.ok),
727
+ onClick: () => !tst.ok && setToasts((ts) => ts.filter((x) => x.id !== tst.id)),
728
+ }, tst.text))),
729
+ );
730
+ }
731
+
732
+ // ---------- 配置视图组件 ----------
733
+ function ConfigView({ config, syncMeta, ws, busy, saveConfig, runInit, onOrchestrate, catalog, toast }) {
734
+ const k = config.kit;
735
+ const initGap = (ws?.attention ?? []).find((a) => a.kind === 'init-incomplete') ?? null;
736
+ const [branches, setBranches] = useState(() => Object.fromEntries((k.sources ?? []).map((s) => [s.name, s.branch ?? ''])));
737
+ const [autoSync, setAutoSync] = useState(k.assets?.autoSync === true);
738
+ const [models, setModels] = useState(() => Object.entries(k.models ?? {}).map(([name, m]) => ({ name, provider: m.provider ?? '', model: m.model ?? '' })));
739
+ useEffect(() => {
740
+ setBranches(Object.fromEntries((k.sources ?? []).map((s) => [s.name, s.branch ?? ''])));
741
+ setAutoSync(k.assets?.autoSync === true);
742
+ setModels(Object.entries(k.models ?? {}).map(([name, m]) => ({ name, provider: m.provider ?? '', model: m.model ?? '' })));
743
+ }, [ws.id]);
744
+ const kv = (label, value) => h('div', { style: S.kv }, h('span', { style: { color: V.sub, minWidth: 96 } }, label), h('span', null, value ?? '—'));
745
+
746
+ return h('div', null,
747
+ // ① 只读信息
748
+ h('div', { style: S.section },
749
+ h('div', { style: S.secTitle }, '资产仓库'),
750
+ kv('地址', k.assets?.url),
751
+ kv('分支', k.assets?.branch),
752
+ kv('模式', ws?.sync?.layout === 'embedded' ? `${k.assets?.mode ?? 'local'}(随工作区仓管理)` : k.assets?.mode),
753
+ kv('同步健康', syncMeta.label),
754
+ kv('上次检查', config.sync?.checkedAt ? new Date(config.sync.checkedAt).toLocaleString() : '—'),
755
+ kv('内容包', k.pack),
756
+ kv('宿主', (k.hosts ?? []).join('、'))),
757
+ // M2:池化工作区概览(本机台账)
758
+ ws?.slots && Object.keys(ws.slots).length > 0 && h('div', { style: S.section },
759
+ h('div', { style: S.secTitle }, '工作区池(本机)'),
760
+ Object.entries(ws.slots).map(([repo, arr]) => h('div', { key: repo, style: { fontSize: 12, marginBottom: 6 } },
761
+ h('div', { style: { fontWeight: 600, marginBottom: 2 } }, repo),
762
+ arr.length === 0 && h('div', { style: { color: V.sub } }, '无 slot(并发任务出现时自动创建)'),
763
+ arr.map((s) => h('div', { key: s.slot, style: { marginBottom: 3 } },
764
+ h('div', { style: { color: s.state === 'stale-unmerged' ? V.warn : V.sub } },
765
+ `${s.slot}:${s.state === 'stale-unmerged' ? '⚠ 保留未释放' : `任务 ${s.task}`} · ${s.branch}`),
766
+ // 完整路径(点击复制,方便直接 cd/在文件管理器打开)
767
+ h('div', {
768
+ style: { fontFamily: 'monospace', fontSize: 11, color: V.sub, wordBreak: 'break-all', cursor: 'copy' },
769
+ title: '点击复制完整路径',
770
+ onClick: () => { try { navigator.clipboard?.writeText(`${ws.path}/.worktrees/${repo}/${s.slot}`); toast('路径已复制'); } catch { /* 剪贴板不可用时无操作 */ } },
771
+ }, `${ws.path}/.worktrees/${repo}/${s.slot}`)))))),
772
+ // ② 可配项
773
+ (k.sources ?? []).length > 0 && h('div', { style: S.section },
774
+ h('div', { style: S.secTitle }, '子工程基线分支'),
775
+ k.sources.map((s) => h('div', { key: s.name, style: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 } },
776
+ h('span', { style: { minWidth: 120, fontSize: 12 } }, `${s.name}(${s.role})`),
777
+ h('input', { style: { ...S.input, width: 140 }, value: branches[s.name] ?? '', onChange: (e) => setBranches({ ...branches, [s.name]: e.target.value }) }))),
778
+ h('button', {
779
+ style: S.btn(busy, true), disabled: busy,
780
+ onClick: () => saveConfig({ sources: k.sources.map((s) => ({ name: s.name, branch: branches[s.name] ?? s.branch })) }, '基线分支已保存'),
781
+ }, '保存分支')),
782
+ h('div', { style: S.section },
783
+ h('div', { style: S.secTitle }, '自动同步'),
784
+ h('label', { style: { display: 'flex', gap: 8, alignItems: 'center', fontSize: 12, marginBottom: 8, cursor: 'pointer' } },
785
+ h('input', { type: 'checkbox', checked: autoSync, onChange: (e) => setAutoSync(e.target.checked) }),
786
+ '归档后自动执行资产同步(/hk-sync)'),
787
+ h('button', { style: S.btn(busy, true), disabled: busy, onClick: () => saveConfig({ autoSync }, autoSync ? '已开启自动同步' : '已关闭自动同步') }, '保存')),
788
+ h('div', { style: S.section },
789
+ h('div', { style: S.secTitle }, 'Worker 模型映射'),
790
+ h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } },
791
+ '键支持两级:角色名(business-analyst / solution-architect / developer / code-reviewer / test-engineer 等流程角色,优先)或逻辑模型名(fast / coding / reasoning)。命中即按映射派发 Worker;都未命中走会话默认。已映射且 provider/model 成对的路由会自动授权为该工作区会话的子智能体可用模型(跨 provider 派发不再降级)。'),
792
+ models.length === 0 && h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } }, '尚未配置,全部角色走默认模型'),
793
+ models.map((m, i) => h('div', { key: i, style: { display: 'flex', gap: 6, marginBottom: 6, alignItems: 'center' } },
794
+ // 角色名下拉:流程角色(BA/SA/Dev/CR/TE 等,宿主扫 agents/ 目录)+ 已映射的逻辑模型名 + 自由输入
795
+ h(Combobox, {
796
+ style: { width: 130 },
797
+ value: m.name, placeholder: '角色名',
798
+ options: [...new Set([
799
+ ...(config.roles ?? []).map((r) => r.role),
800
+ ...(config.presetModels ?? []).map((x) => x.name),
801
+ ])],
802
+ onChange: (v) => setModels(models.map((x, j) => j === i ? { ...x, name: v } : x)),
803
+ }),
804
+ // provider 下拉:宿主已注册的全部 LLM provider;切换时清空 model(避免脏组合);已配置但不可用的值保留显示并标灰
805
+ h('select', {
806
+ style: { ...S.select, width: 110 },
807
+ value: m.provider ?? '',
808
+ onChange: (e) => setModels(models.map((x, j) => j === i ? { ...x, provider: e.target.value, model: '' } : x)),
809
+ }, [
810
+ h('option', { key: '', value: '' }, '(会话默认)'),
811
+ ...(m.provider && !(catalog ?? []).some((c) => c.provider === m.provider)
812
+ ? [h('option', { key: '__missing', value: m.provider }, `⚠ ${m.provider}(不可用)`)] : []),
813
+ ...(catalog ?? []).map((c) => h('option', { key: c.provider, value: c.provider }, c.provider)),
814
+ ]),
815
+ // model 下拉:所选 provider 的模型清单 + 自由输入
816
+ h(Combobox, {
817
+ style: { flex: 1 },
818
+ value: m.model, placeholder: 'model',
819
+ options: (catalog ?? []).find((c) => c.provider === (m.provider || ''))?.models?.map((mo) => mo.id) ?? [],
820
+ onChange: (v) => setModels(models.map((x, j) => j === i ? { ...x, model: v } : x)),
821
+ }),
822
+ h('button', { style: S.iconBtn, title: '删除', onClick: () => setModels(models.filter((_, j) => j !== i)) }, '×'))),
823
+ (catalog ?? []).length === 0 && h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } }, '未发现可用模型清单(宿主未注册 LLM 或接口不可用),仍可手动输入'),
824
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
825
+ h('button', { style: S.btn(false), onClick: () => setModels([...models, { name: '', provider: '', model: '' }]) }, '+ 添加映射'),
826
+ h('button', {
827
+ style: S.btn(busy || models.some((m) => !m.name.trim() || !m.model.trim()), true),
828
+ disabled: busy || models.some((m) => !m.name.trim() || !m.model.trim()),
829
+ onClick: () => saveConfig({ models: Object.fromEntries(models.map((m) => [m.name.trim(), { ...(m.provider.trim() ? { provider: m.provider.trim() } : {}), model: m.model.trim() }])) }, '模型映射已保存'),
830
+ }, '保存'))),
831
+ // ③ 初始化与子工程(面板化的 /hk-init、/hk-setup --add)
832
+ h('div', { style: S.section },
833
+ h('div', { style: S.secTitle }, '初始化与子工程'),
834
+ h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } },
835
+ '重跑初始化是幂等的:补齐骨架 / 模板 / 脚本并重新扫描子工程,不覆盖已有内容。资产换绑、解绑、删除子工程仍请在会话中执行 /hk-init、/hk-setup。'),
836
+ initGap && h('div', { style: { ...S.attn('warn'), marginBottom: 8 } },
837
+ h('span', null, '🟠'),
838
+ h('span', { style: { flex: 1 } }, initGap.text),
839
+ h('button', { style: S.btn(busy, true), disabled: busy, onClick: onOrchestrate }, '启动初始化编排')),
840
+ ws?.init && !ws.init.done && h('div', { style: { ...S.attn('warn'), marginBottom: 8 } },
841
+ h('span', null, '🔧'),
842
+ h('span', { style: { flex: 1 } }, `初始化进行中:${ws.init.stage}${ws.init.detail ? ` — ${ws.init.detail}` : ''}(刷新不影响,完成后再重跑以免重复克隆)`)),
843
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
844
+ h('button', { style: S.btn(busy || (ws?.init && !ws.init.done), true), disabled: busy || !!(ws?.init && !ws.init.done), title: ws?.init && !ws.init.done ? '初始化进行中,请等待完成' : undefined, onClick: () => runInit({}, '骨架/脚本已幂等补齐(子工程文档由初始化编排生成)') }, '重跑初始化'),
845
+ h(AddSourceForm, { busy, onSubmit: (spec) => runInit({ sources: [spec] }, `子工程 ${spec.name || spec.url} 已登记`) }))),
846
+ );
847
+ }
848
+
849
+ // ---------- Combobox:可输入 + 可下拉选择(解决原生 datalist 点击无反应问题) ----------
850
+ function Combobox({ value, onChange, options = [], placeholder = '', style: extraStyle, suggest }) {
851
+ const wrapRef = useRef(null);
852
+ const [open, setOpen] = useState(false);
853
+ const filtered = (suggest ?? options).filter((o) => !value || o.toLowerCase().includes(value.toLowerCase()));
854
+ useEffect(() => {
855
+ if (!open) return undefined;
856
+ const close = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
857
+ document.addEventListener('mousedown', close);
858
+ return () => document.removeEventListener('mousedown', close);
859
+ }, [open]);
860
+ return h('div', { ref: wrapRef, style: { position: 'relative', ...extraStyle } },
861
+ h('input', {
862
+ style: { ...S.input, width: '100%' }, value, placeholder,
863
+ onChange: (e) => { onChange(e.target.value); setOpen(true); },
864
+ onFocus: () => setOpen(true),
865
+ }),
866
+ h('button', {
867
+ type: 'button', title: '选择',
868
+ style: { position: 'absolute', right: 3, top: '50%', transform: 'translateY(-50%)', width: 22, height: 22, border: 'none', background: 'transparent', color: V.sub, cursor: 'pointer', fontSize: 10, padding: 0 },
869
+ onClick: (e) => { e.preventDefault(); setOpen(!open); },
870
+ }, open ? '▴' : '▾'),
871
+ open && h('div', {
872
+ style: { position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 40, maxHeight: 200, overflowY: 'auto', background: V.bg, border: `1px solid ${V.border2}`, borderRadius: 8, boxShadow: V.modalShadow, marginTop: 2 },
873
+ }, filtered.length === 0
874
+ ? h('div', { style: { padding: '6px 8px', fontSize: 12, color: V.sub } }, '无匹配项')
875
+ : filtered.map((o) => h('div', {
876
+ key: o, onClick: () => { onChange(o); setOpen(false); },
877
+ style: { padding: '4px 8px', fontSize: 12, cursor: 'pointer', color: V.text, fontFamily: 'monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
878
+ onMouseEnter: (e) => { e.currentTarget.style.background = V.brand; e.currentTarget.style.color = V.brandInvert; },
879
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = V.text; },
880
+ }, o))));
881
+ }
882
+
883
+ // ---------- 工作区开通引导(新建 / 打开已有) ----------
884
+ const ROLE_OPTIONS = ['backend', 'frontend', 'app'];
885
+ const EMPTY_SOURCE = { url: '', name: '', path: '', role: '', branch: '' };
886
+ // path 派生预览(后端 addSource 同款规则):显式 role 在批次内唯一 → services/<role>;否则 services/<仓名>
887
+ const repoBaseName = (url) => (url.trim().split('/').pop() || '').replace(/\.git$/, '');
888
+ const derivePathHint = (s, siblings = []) => {
889
+ const role = (s.role ?? '').trim();
890
+ if (role && !siblings.some((o) => o !== s && (o.role ?? '').trim() === role)) return `services/${role}`;
891
+ return `services/${repoBaseName(s.url || '') || '<仓名>'}`;
892
+ };
893
+
894
+ // 目录预检结果行(新建向导用)
895
+ function InspectLine({ info, registered }) {
896
+ if (!info || !info.path) return null;
897
+ if (!info.exists) return h('div', { style: { fontSize: 12, color: V.err, marginTop: 6 } }, '目录不存在,请先在本地创建');
898
+ if (!info.isDir) return h('div', { style: { fontSize: 12, color: V.err, marginTop: 6 } }, '该路径不是目录');
899
+ const bits = [];
900
+ if (info.hasKit) bits.push(['✓ 已初始化(.harness/kit.json)', V.ok]);
901
+ else if (info.hasHarness) bits.push(['⚠ 已有 .harness 但缺 kit.json(提交时自动补齐)', V.warn]);
902
+ else bits.push(['未初始化', V.sub]);
903
+ if (registered) bits.push([`已注册:${registered.title || registered.id}`, V.brand]);
904
+ return h('div', { style: { fontSize: 12, color: V.sub, marginTop: 6 } },
905
+ bits.map(([t, c], i) => h('span', { key: i, style: { color: c, marginRight: 10 } }, t)));
906
+ }
907
+
908
+ function OnboardView({ mode, setMode, canClose, onClose, uiWorkspace, toast, busy, setBusy, pickDirectory, initialPath, onDone, onSwitchToNew }) {
909
+ const head = h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, margin: '12px 0' } },
910
+ (mode !== 'choice' || canClose) && h('button', { style: S.iconBtn, onClick: () => (mode === 'choice' ? onClose() : setMode('choice')) }, '←'),
911
+ h('span', { style: S.hTitle }, mode === 'new' ? '新建 Harness 工作区' : mode === 'open' ? '打开已有工作区' : '开始使用 Harness'));
912
+ if (mode === 'new') {
913
+ return h('div', null, head,
914
+ h(NewWorkspaceForm, { uiWorkspace, toast, busy, setBusy, pickDirectory, initialPath, onDone, onFinish: onClose, onBack: () => setMode('choice') }));
915
+ }
916
+ if (mode === 'open') {
917
+ return h('div', null, head,
918
+ h(OpenWorkspaceForm, { toast, busy, setBusy, pickDirectory, onDone, onFinish: onClose, onBack: () => setMode('choice'), onSwitchToNew }));
919
+ }
920
+ return h('div', null, head,
921
+ h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 12 } },
922
+ '把任意本地目录开通为 Harness 作战室:登记到 DSH、物化 .harness 资产、登记子工程,全程在面板完成。'),
923
+ h('div', { style: { display: 'flex', gap: 12, flexWrap: 'wrap' } },
924
+ h('div', { style: S.obCard, onClick: () => setMode('new') },
925
+ h('div', { style: { fontSize: 22 } }, '🆕'),
926
+ h('div', { style: { ...S.secTitle, margin: '6px 0 4px' } }, '新建工作区'),
927
+ h('div', { style: { fontSize: 12, color: V.sub } },
928
+ '选择一个本地目录(可以是空目录),通过向导表单完成初始化:资产仓库绑定 + 子工程登记(等价 /hk-init 与 /hk-setup)。')),
929
+ h('div', { style: S.obCard, onClick: () => setMode('open') },
930
+ h('div', { style: { fontSize: 22 } }, '📂'),
931
+ h('div', { style: { ...S.secTitle, margin: '6px 0 4px' } }, '打开已有工作区'),
932
+ h('div', { style: { fontSize: 12, color: V.sub } },
933
+ '选择已初始化的 Harness 工作区目录(须包含 .harness/kit.json),直接接入作战室面板。'))));
934
+ }
935
+
936
+ // 新建向导:目录 → 资产仓库 → 子工程 → 提交(create + init),成功后出报告与后续动作
937
+ function NewWorkspaceForm({ uiWorkspace, toast, busy, setBusy, pickDirectory, initialPath, onDone, onFinish, onBack }) {
938
+ const [wsPath, setWsPath] = useState(initialPath ?? '');
939
+ const [info, setInfo] = useState(null); // {inspect, registered}
940
+ const [mode, setMode] = useState('local');
941
+ const [assetUrl, setAssetUrl] = useState('');
942
+ const [assetBranch, setAssetBranch] = useState('');
943
+ const [sources, setSources] = useState(() => [{ ...EMPTY_SOURCE }]);
944
+ const [err, setErr] = useState(null);
945
+ const [result, setResult] = useState(null); // {report, wsId, sources, sourceErrors}
946
+ const [progress, setProgress] = useState(null); // 初始化进度 {stage, detail, startedAt, done}
947
+ const pollRef = useRef(null);
948
+ // 环境预检:提交前暴露 git / Python 3 缺失项,并给出对应平台的安装命令。
949
+ const [env, setEnv] = useState(null);
950
+ const [envBusy, setEnvBusy] = useState(false);
951
+ const checkEnv = useCallback(async () => {
952
+ setEnvBusy(true);
953
+ try {
954
+ const j = await fetch('/harness-kit/env').then((r) => r.json());
955
+ setEnv(j.ok ? j : { error: j.error || '检查失败' });
956
+ } catch (e) {
957
+ setEnv({ error: String(e?.message || e) });
958
+ } finally {
959
+ setEnvBusy(false);
960
+ }
961
+ }, []);
962
+ useEffect(() => { void checkEnv(); }, [checkEnv]);
963
+
964
+ const doInspect = useCallback((p) => {
965
+ if (!p || !p.trim()) { setInfo(null); return; }
966
+ fetch('/harness-kit/workspace/inspect', {
967
+ method: 'POST', headers: { 'content-type': 'application/json' },
968
+ body: JSON.stringify({ path: p.trim() }),
969
+ }).then((r) => r.json()).then((j) => { if (j.ok) setInfo(j); }).catch(() => {});
970
+ }, []);
971
+ useEffect(() => { if (initialPath) doInspect(initialPath); }, []); // 来自「打开」转「新建」的预填目录
972
+
973
+ const pick = async () => {
974
+ const p = await pickDirectory();
975
+ if (p) { setWsPath(p); doInspect(p); }
976
+ else if (!globalThis.__DSH_DIRECTORY_PICKER__?.pick && !uiWorkspace?.pickDirectory) {
977
+ toast('当前宿主不支持目录选择器,请手工输入绝对路径', false);
978
+ }
979
+ };
980
+
981
+ const setSrc = (i, patch) => setSources((ss) => ss.map((x, j) => (j === i ? { ...x, ...patch } : x)));
982
+ // url 失焦时只补名称(从 url 取仓名)。
983
+ // 路径不预填实值——留空的 path 由后端按「role → services/<role>」派生,placeholder 实时预览;
984
+ // 角色不自动猜——角色必选,由人显式确认(2026-11-17 定:猜测会把 path 实值写死成仓名,选角色后不生效)
985
+ const derive = (i) => setSources((ss) => ss.map((x, j) => {
986
+ if (j !== i) return x;
987
+ const name = x.name.trim() || (x.url.trim() ? x.url.trim().split('/').pop().replace(/\.git$/, '') : '');
988
+ const next = { ...x };
989
+ if (!next.name.trim() && name) next.name = name;
990
+ return next;
991
+ }));
992
+
993
+ const submit = async () => {
994
+ setErr(null); setBusy(true); setProgress(null);
995
+ try {
996
+ const post = (url, body) => fetch(url, {
997
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
998
+ }).then((r) => r.json());
999
+ // ① 预检:目录必须已存在
1000
+ const ij = await post('/harness-kit/workspace/inspect', { path: wsPath.trim() });
1001
+ if (!ij.ok || !ij.inspect.isDir) throw new Error(ij.inspect?.exists ? '该路径不是目录' : '目录不存在,请先在本地创建');
1002
+ // ② 注册(幂等:已注册直接复用)
1003
+ let reg = ij.registered;
1004
+ if (!reg) {
1005
+ const cj = await post('/harness-kit/workspace/create', { path: wsPath.trim() });
1006
+ if (!cj.ok) throw new Error(cj.error || '注册工作区失败');
1007
+ reg = cj.workspace;
1008
+ }
1009
+ // ③ 初始化:宿主异步任务化——POST 立即返回,后台执行 + 进度轮询。
1010
+ // 这样大仓克隆(十几分钟)期间刷新/重载页面都不会中断任务(旧实现挂在单请求上,
1011
+ // 一刷新就报 "Failed to fetch",2026-11-17 事故)。
1012
+ const j = await post('/harness-kit/workspace/init', {
1013
+ workspace: reg.id,
1014
+ assets: {
1015
+ mode,
1016
+ ...(mode === 'url' ? { url: assetUrl.trim() } : {}),
1017
+ ...(assetBranch.trim() ? { branch: assetBranch.trim() } : {}),
1018
+ },
1019
+ sources: sources.filter((s) => s.url.trim()).map((s) => {
1020
+ const spec = { url: s.url.trim() };
1021
+ for (const k of ['name', 'path', 'role', 'branch']) if (s[k].trim()) spec[k] = s[k].trim();
1022
+ return spec;
1023
+ }),
1024
+ });
1025
+ if (!j.ok) throw new Error(j.error || '初始化失败');
1026
+ const final = await new Promise((resolve, reject) => {
1027
+ let settled = false;
1028
+ const timer = setInterval(async () => {
1029
+ try {
1030
+ const p = await fetch(`/harness-kit/workspace/init-progress?workspace=${encodeURIComponent(reg.id)}`, { cache: 'no-store' }).then((r) => r.json());
1031
+ if (!p.ok || !p.progress) return;
1032
+ setProgress(p.progress);
1033
+ if (p.progress.done && !settled) {
1034
+ settled = true;
1035
+ clearInterval(timer);
1036
+ if (p.progress.error) reject(new Error(p.progress.error));
1037
+ else resolve(p.progress.result ?? null);
1038
+ }
1039
+ } catch { /* 单次轮询失败继续(任务在宿主侧照常执行) */ }
1040
+ }, 800);
1041
+ pollRef.current = timer;
1042
+ });
1043
+ if (!final) throw new Error('初始化状态丢失,请到「配置」页重跑初始化查看结果');
1044
+ setResult({ report: final.report, wsId: reg.id, sources: final.sources ?? [], sourceErrors: final.sourceErrors ?? [] });
1045
+ onDone(reg.id);
1046
+ toast('初始化完成');
1047
+ } catch (e) { setErr(String(e?.message || e)); }
1048
+ finally {
1049
+ if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
1050
+ setBusy(false);
1051
+ }
1052
+ };
1053
+
1054
+ // 初始化编排(steer)需要活会话:打开工作区会话后转发 /hk-init
1055
+ const steer = () => {
1056
+ const wsId = result.wsId;
1057
+ onFinish();
1058
+ if (uiWorkspace?.openWorkspace) { try { uiWorkspace.openWorkspace(wsId); } catch { /* 忽略 */ } }
1059
+ toast('正在打开会话并提交初始化编排…');
1060
+ setTimeout(() => {
1061
+ fetch('/harness-kit/command', {
1062
+ method: 'POST', headers: { 'content-type': 'application/json' },
1063
+ body: JSON.stringify({ workspace: wsId, line: '/hk-init' }),
1064
+ }).then((r) => r.json()).then((j) => {
1065
+ if (j.ok && j.sessionId) { try { uiWorkspace?.openSession?.(j.sessionId); } catch { /* 忽略 */ } }
1066
+ toast(j.ok ? '初始化编排已提交 PM(探测子工程 → 生成文档 / 索引)' : (j.error || '提交失败'), j.ok);
1067
+ }).catch((e) => toast(e.message, false));
1068
+ }, 2500);
1069
+ };
1070
+
1071
+ if (result) {
1072
+ return h('div', null,
1073
+ h('div', { style: { fontSize: 16, marginBottom: 4 } }, '✅ 工作区已就绪'),
1074
+ h('div', { style: S.pre }, result.report),
1075
+ result.sourceErrors.length > 0 && h('div', { style: { fontSize: 12, color: V.warn, marginTop: 6 } },
1076
+ `部分子工程登记失败:${result.sourceErrors.join(';')}`),
1077
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 12 } },
1078
+ result.sources.length > 0 && h('button', { style: S.btn(false, true), onClick: steer },
1079
+ '启动初始化编排(文档生成 + 编译启动验证)'),
1080
+ h('button', { style: S.btn(false), onClick: onFinish }, '进入作战室')));
1081
+ }
1082
+
1083
+ const submitDisabled = busy || !wsPath.trim()
1084
+ || (mode === 'url' && !assetUrl.trim())
1085
+ || !!(info && info.inspect && info.inspect.path && !info.inspect.isDir)
1086
+ // 角色强制确认(2026-11-17 定):登记的每个仓库必须显式选角色,不再静默自动推断
1087
+ || sources.some((s) => s.url.trim() && !s.role.trim());
1088
+
1089
+ // 环境检查卡片:缺失项直接给安装命令,安装后点「重新检查」
1090
+ const envCard = h('div', { style: S.section },
1091
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 } },
1092
+ h('div', { style: { ...S.secTitle, marginBottom: 0 } }, '环境检查'),
1093
+ h('span', { style: { flex: 1 } }),
1094
+ h('button', { style: S.btn(envBusy), disabled: envBusy, onClick: checkEnv }, envBusy ? '检查中…' : '重新检查')),
1095
+ !env && h('div', { style: { fontSize: 12, color: V.sub } }, '正在检查 git / Python 3…'),
1096
+ env?.error && h('div', { style: { fontSize: 12, color: V.err, whiteSpace: 'pre-wrap' } }, `检查失败:${env.error}`),
1097
+ env?.tools && env.tools.map((t) => h('div', { key: t.id, style: { padding: '4px 0', fontSize: 12 } },
1098
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'baseline' } },
1099
+ h('span', { style: { color: t.ok ? V.ok : V.warn, fontWeight: 600 } }, `${t.ok ? '✓' : '✗'} ${t.name}`),
1100
+ h('span', { style: { color: V.sub } }, t.ok ? (t.version || '可用') : t.purpose)),
1101
+ !t.ok && h('div', { style: { marginTop: 3, paddingLeft: 18, color: V.sub } },
1102
+ h('div', null, '安装:',
1103
+ h('code', { style: { fontSize: 11, padding: '1px 6px', borderRadius: 4, background: V.fieldBg } }, t.install.command)),
1104
+ h('a', { href: t.install.url, target: '_blank', rel: 'noreferrer', style: { color: V.brand, fontSize: 11 } }, '查看安装说明')))),
1105
+ env?.tools && !env.allOk && h('div', { style: { fontSize: 11, color: V.warn, marginTop: 4 } },
1106
+ '缺失项不会阻止创建,但用到对应功能时会失败;安装后点「重新检查」。'));
1107
+
1108
+ return h('div', null,
1109
+ envCard,
1110
+ // ① 目录
1111
+ h('div', { style: S.section },
1112
+ h('div', { style: S.secTitle }, '① 工作区目录'),
1113
+ h('div', { style: { display: 'flex', gap: 8 } },
1114
+ h('input', {
1115
+ style: { ...S.input, flex: 1 }, value: wsPath,
1116
+ placeholder: '本地目录绝对路径(须已存在)',
1117
+ onChange: (e) => setWsPath(e.target.value),
1118
+ onBlur: () => doInspect(wsPath),
1119
+ }),
1120
+ h('button', { style: S.btn(busy), disabled: busy, onClick: pick }, '浏览…')),
1121
+ h(InspectLine, { info: info?.inspect, registered: info?.registered }),
1122
+ info?.inspect?.hasKit && h('div', { style: { fontSize: 12, color: V.sub, marginTop: 4 } },
1123
+ '该目录已初始化,提交将按幂等重跑补齐(不会覆盖已有内容)。')),
1124
+ // ② 资产仓库
1125
+ h('div', { style: S.section },
1126
+ h('div', { style: S.secTitle }, '② 资产仓库(.harness)'),
1127
+ [['local', '本地模式', '不绑 git;需要团队共享时可稍后在会话中绑定'],
1128
+ ['init', '新建 git 仓库', '在 .harness 内 git init 并完成首次提交'],
1129
+ ['url', '绑定团队资产仓库', '克隆已有仓库;本地已有资产时可自动接管空远端']].map(([m, name, hint]) =>
1130
+ h('label', { key: m, style: { display: 'flex', gap: 8, alignItems: 'flex-start', marginBottom: 6, cursor: 'pointer', fontSize: 12 } },
1131
+ h('input', { type: 'radio', name: 'hk-assets', checked: mode === m, onChange: () => setMode(m), style: { marginTop: 2 } }),
1132
+ h('span', null, h('b', null, name), h('span', { style: { color: V.sub } }, ` — ${hint}`)))),
1133
+ mode === 'url' && h('div', { style: { display: 'flex', gap: 8, marginTop: 4 } },
1134
+ h('input', { style: { ...S.input, flex: 2 }, value: assetUrl, placeholder: 'git 仓库地址(https / ssh)', onChange: (e) => setAssetUrl(e.target.value) }),
1135
+ h('input', { style: { ...S.input, flex: 1 }, value: assetBranch, placeholder: '分支(默认远端主分支)', onChange: (e) => setAssetBranch(e.target.value) }))),
1136
+ // ③ 子工程
1137
+ h('div', { style: S.section },
1138
+ h('div', { style: S.secTitle }, '③ 代码仓库(子工程,可稍后添加)'),
1139
+ sources.length === 0 && h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } },
1140
+ '暂不登记:初始化完成后可在「配置」页或会话 /hk-setup 中添加。'),
1141
+ sources.length > 0 && h('div', { style: { fontSize: 12, color: V.sub, marginBottom: 8 } },
1142
+ '名称默认取 git 仓名(身份键,任务跑起来后不可改,保持唯一可追溯);角色是流程语义标签(模板选择/展示),每个仓库必选一个。'),
1143
+ sources.map((s, i) => h('div', { key: i, style: { borderTop: i ? `1px solid ${V.border}` : 'none', paddingTop: i ? 8 : 0, marginBottom: 8 } },
1144
+ h('div', { style: { display: 'flex', gap: 8, marginBottom: 6 } },
1145
+ h('input', {
1146
+ style: { ...S.input, flex: 1 }, value: s.url, placeholder: 'git 仓库地址',
1147
+ onChange: (e) => setSrc(i, { url: e.target.value }), onBlur: () => derive(i),
1148
+ }),
1149
+ h('button', { style: S.iconBtn, title: '移除', onClick: () => setSources((ss) => ss.filter((_, j) => j !== i)) }, '×')),
1150
+ h('div', { style: { display: 'flex', gap: 6 } },
1151
+ h('input', { style: { ...S.input, width: 110 }, value: s.name, placeholder: '名称', onChange: (e) => setSrc(i, { name: e.target.value }) }),
1152
+ h('input', { style: { ...S.input, flex: 1 }, value: s.path, placeholder: `路径(留空 = ${derivePathHint(s, sources)})`, onChange: (e) => setSrc(i, { path: e.target.value }) }),
1153
+ h('select', { style: { ...S.select, borderColor: s.role.trim() ? undefined : V.warn }, value: s.role, onChange: (e) => setSrc(i, { role: e.target.value }) },
1154
+ h('option', { value: '' }, '请选择角色…'),
1155
+ ROLE_OPTIONS.map((r) => h('option', { key: r, value: r }, r))),
1156
+ h('input', { style: { ...S.input, width: 90 }, value: s.branch, placeholder: '分支', onChange: (e) => setSrc(i, { branch: e.target.value }) })))),
1157
+ h('button', { style: S.btn(false), onClick: () => setSources((ss) => [...ss, { ...EMPTY_SOURCE }]) }, '+ 添加仓库')),
1158
+ // 提交区
1159
+ err && h('div', { style: { fontSize: 12, color: V.err, marginBottom: 10, whiteSpace: 'pre-wrap' } }, err),
1160
+ h('div', { style: { display: 'flex', gap: 8 } },
1161
+ h('button', { style: S.btn(false), onClick: onBack }, '返回'),
1162
+ h('button', { style: S.btn(submitDisabled, true), disabled: submitDisabled, onClick: submit },
1163
+ busy ? '执行中…' : '创建并初始化')),
1164
+ busy && h('div', { style: { fontSize: 11, color: V.sub, marginTop: 6 } },
1165
+ progress
1166
+ ? `正在执行:${progress.stage}${progress.detail ? ` — ${progress.detail}` : ''}` +
1167
+ `(已耗时 ${Math.max(0, Math.round((Date.now() - (progress.startedAt || Date.now())) / 1000))}s${progress.stage === '克隆子工程' ? ',大仓库可能数分钟' : ''};刷新页面不会中断,任务在后台继续)`
1168
+ : '正在执行(克隆大型仓库可能需要数分钟,请耐心等待,勿重复提交)…'));
1169
+ }
1170
+
1171
+ // 打开已有工作区:必须含 .harness/kit.json,否则引导改走新建向导
1172
+ function OpenWorkspaceForm({ toast, busy, setBusy, pickDirectory, onDone, onFinish, onBack, onSwitchToNew }) {
1173
+ const [wsPath, setWsPath] = useState('');
1174
+ const [err, setErr] = useState(null);
1175
+ const [notHarness, setNotHarness] = useState(false);
1176
+
1177
+ const pick = async () => {
1178
+ const p = await pickDirectory();
1179
+ if (p) { setWsPath(p); setErr(null); setNotHarness(false); }
1180
+ };
1181
+ const submit = async () => {
1182
+ setErr(null); setNotHarness(false); setBusy(true);
1183
+ try {
1184
+ const j = await fetch('/harness-kit/workspace/open', {
1185
+ method: 'POST', headers: { 'content-type': 'application/json' },
1186
+ body: JSON.stringify({ path: wsPath.trim() }),
1187
+ }).then((r) => r.json());
1188
+ if (!j.ok) {
1189
+ setErr(j.error || '打开失败');
1190
+ if (j.code === 'not-harness') setNotHarness(true);
1191
+ return;
1192
+ }
1193
+ toast(`已打开工作区:${j.workspace.title || j.workspace.id}`);
1194
+ onDone(j.workspace.id);
1195
+ onFinish();
1196
+ } catch (e) { setErr(String(e?.message || e)); }
1197
+ finally {
1198
+ if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
1199
+ setBusy(false);
1200
+ }
1201
+ };
1202
+
1203
+ return h('div', null,
1204
+ h('div', { style: S.section },
1205
+ h('div', { style: S.secTitle }, '工作区目录'),
1206
+ h('div', { style: { display: 'flex', gap: 8 } },
1207
+ h('input', {
1208
+ style: { ...S.input, flex: 1 }, value: wsPath,
1209
+ placeholder: '已初始化的 Harness 工作区目录',
1210
+ onChange: (e) => { setWsPath(e.target.value); setErr(null); setNotHarness(false); },
1211
+ }),
1212
+ h('button', { style: S.btn(busy), disabled: busy, onClick: pick }, '浏览…')),
1213
+ h('div', { style: { fontSize: 12, color: V.sub, marginTop: 6 } },
1214
+ '该目录必须包含 .harness/kit.json(由新建向导或 /hk-init 生成)。')),
1215
+ err && h('div', { style: { fontSize: 12, color: V.err, marginBottom: 10, whiteSpace: 'pre-wrap' } }, err),
1216
+ h('div', { style: { display: 'flex', gap: 8 } },
1217
+ h('button', { style: S.btn(false), onClick: onBack }, '返回'),
1218
+ notHarness && h('button', { style: S.btn(busy, true), disabled: busy, onClick: () => onSwitchToNew(wsPath.trim()) },
1219
+ '改为在此目录初始化 →'),
1220
+ h('button', { style: S.btn(busy || !wsPath.trim(), true), disabled: busy || !wsPath.trim(), onClick: submit },
1221
+ '打开工作区')));
1222
+ }
1223
+
1224
+ // 配置视图内联:添加子工程(等价 /hk-setup --add)
1225
+ function AddSourceForm({ busy, onSubmit }) {
1226
+ const [open, setOpen] = useState(false);
1227
+ const [s, setS] = useState({ ...EMPTY_SOURCE });
1228
+ if (!open) return h('button', { style: S.btn(false), onClick: () => setOpen(true) }, '+ 添加子工程');
1229
+ const set = (k) => (e) => setS({ ...s, [k]: e.target.value });
1230
+ return h('div', { style: { flex: '1 1 100%', marginTop: 8 } },
1231
+ h('div', { style: { display: 'flex', gap: 6, marginBottom: 6 } },
1232
+ h('input', { style: { ...S.input, flex: 1 }, value: s.url, placeholder: 'git 仓库地址', onChange: set('url') })),
1233
+ h('div', { style: { display: 'flex', gap: 6, marginBottom: 6 } },
1234
+ h('input', { style: { ...S.input, width: 100 }, value: s.name, placeholder: '名称', onChange: set('name') }),
1235
+ h('input', { style: { ...S.input, flex: 1 }, value: s.path, placeholder: `路径(留空 = ${derivePathHint(s)})`, onChange: set('path') }),
1236
+ h('select', { style: { ...S.select, borderColor: s.role.trim() ? undefined : V.warn }, value: s.role, onChange: set('role') },
1237
+ h('option', { value: '' }, '角色(必选)'),
1238
+ ROLE_OPTIONS.map((r) => h('option', { key: r, value: r }, r))),
1239
+ h('input', { style: { ...S.input, width: 80 }, value: s.branch, placeholder: '分支', onChange: set('branch') })),
1240
+ h('div', { style: { fontSize: 11, color: V.sub, marginBottom: 6 } },
1241
+ '名称默认取 git 仓名(任务跑起来后不可改);角色是流程语义标签,必选。'),
1242
+ h('div', { style: { display: 'flex', gap: 8 } },
1243
+ h('button', { style: S.btn(false), onClick: () => setOpen(false) }, '收起'),
1244
+ h('button', {
1245
+ style: S.btn(busy || !s.url.trim() || !s.role.trim(), true), disabled: busy || !s.url.trim() || !s.role.trim(),
1246
+ title: !s.role.trim() ? '请先选择角色' : undefined,
1247
+ onClick: () => {
1248
+ const spec = { url: s.url.trim() };
1249
+ for (const k of ['name', 'path', 'role', 'branch']) if (s[k].trim()) spec[k] = s[k].trim();
1250
+ onSubmit(spec);
1251
+ setS({ ...EMPTY_SOURCE });
1252
+ setOpen(false);
1253
+ },
1254
+ }, busy ? '登记中…' : '登记并克隆')));
1255
+ }
1256
+
1257
+ return {
1258
+ inject: ['slots'],
1259
+ apply(ctx) {
1260
+ // uiWorkspace 是界面服务,可能在插件 apply 时尚未就绪(冷启动/重载竞态):
1261
+ // 必须在渲染时惰性解析,不能在这里一次性捕获——否则拿到 undefined 后
1262
+ // 「继续会话」等所有跳转会永久降级为「界面未提供工作区操作能力」报错(2026-11-17 事故)。
1263
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1264
+ name: 'sidebar.panellist', id: 'harness-kit', order: 20,
1265
+ }, Icon));
1266
+ ctx.slots.inject('main', () => ctx.slots.register({
1267
+ name: 'main', key: 'harness-kit', id: 'harness-kit',
1268
+ }, (props) => h(Panel, { ...props, uiWorkspace: ctx.get('uiWorkspace') })));
1269
+ },
1270
+ };
1271
+ },
1272
+ });