@xi4z/dsh-utils 0.0.0-stage → 0.5.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +576 -2
  3. package/client.js +2330 -0
  4. package/cordis.patch.yml +101 -0
  5. package/icon.svg +21 -0
  6. package/lib/index.d.ts +69 -0
  7. package/lib/index.js +865 -0
  8. package/lib/index.js.map +1 -0
  9. package/lib/ui-host.d.ts +96 -0
  10. package/lib/ui-host.js +970 -0
  11. package/lib/ui-host.js.map +1 -0
  12. package/locale/en.json +6 -0
  13. package/locale/zh.json +6 -0
  14. package/package.json +124 -3
  15. package/packages/approval-policy/lib/index.d.ts +297 -0
  16. package/packages/approval-policy/lib/index.js +425 -0
  17. package/packages/approval-policy/lib/index.js.map +1 -0
  18. package/packages/approval-policy/locale/en.json +6 -0
  19. package/packages/approval-policy/locale/zh.json +6 -0
  20. package/packages/notify/lib/index.d.ts +290 -0
  21. package/packages/notify/lib/index.js +915 -0
  22. package/packages/notify/lib/index.js.map +1 -0
  23. package/packages/notify/locale/en.json +6 -0
  24. package/packages/notify/locale/zh.json +6 -0
  25. package/packages/skill-panel/lib/index.d.ts +49 -0
  26. package/packages/skill-panel/lib/index.js +420 -0
  27. package/packages/skill-panel/lib/index.js.map +1 -0
  28. package/packages/skill-panel/locale/en.json +6 -0
  29. package/packages/skill-panel/locale/zh.json +6 -0
  30. package/packages/utils-agents/lib/git.d.ts +87 -0
  31. package/packages/utils-agents/lib/git.js +403 -0
  32. package/packages/utils-agents/lib/git.js.map +1 -0
  33. package/packages/utils-agents/lib/global-repo.d.ts +57 -0
  34. package/packages/utils-agents/lib/global-repo.js +301 -0
  35. package/packages/utils-agents/lib/global-repo.js.map +1 -0
  36. package/packages/utils-agents/lib/index.d.ts +80 -0
  37. package/packages/utils-agents/lib/index.js +435 -0
  38. package/packages/utils-agents/lib/index.js.map +1 -0
  39. package/packages/utils-agents/lib/legacy.d.ts +30 -0
  40. package/packages/utils-agents/lib/legacy.js +141 -0
  41. package/packages/utils-agents/lib/legacy.js.map +1 -0
  42. package/packages/utils-agents/lib/native.d.ts +74 -0
  43. package/packages/utils-agents/lib/native.js +232 -0
  44. package/packages/utils-agents/lib/native.js.map +1 -0
  45. package/packages/utils-agents/lib/presets.d.ts +34 -0
  46. package/packages/utils-agents/lib/presets.js +312 -0
  47. package/packages/utils-agents/lib/presets.js.map +1 -0
  48. package/packages/utils-agents/lib/shared.d.ts +105 -0
  49. package/packages/utils-agents/lib/shared.js +507 -0
  50. package/packages/utils-agents/lib/shared.js.map +1 -0
  51. package/packages/utils-agents/lib/update.d.ts +129 -0
  52. package/packages/utils-agents/lib/update.js +507 -0
  53. package/packages/utils-agents/lib/update.js.map +1 -0
  54. package/packages/utils-agents/lib/util.d.ts +215 -0
  55. package/packages/utils-agents/lib/util.js +475 -0
  56. package/packages/utils-agents/lib/util.js.map +1 -0
  57. package/packages/utils-agents/locale/en.json +6 -0
  58. package/packages/utils-agents/locale/zh.json +6 -0
  59. package/skills/dsh-approval-policy-config/SKILL.md +96 -0
  60. package/src/index.ts +933 -0
  61. package/src/ui-host.ts +1073 -0
package/client.js ADDED
@@ -0,0 +1,2330 @@
1
+ /**
2
+ * Browser half of `@xi4z/dsh-utils`, served from the root package: the
3
+ * `utils-main` row is a package-root row and the package declares `dsh.client`,
4
+ * so DSH's client-module scanner resolves this file from that row.
5
+ *
6
+ * Registers one configuration page per row and the sidebar skill /
7
+ * skill-repository panels. Host routes come from `src/ui-host.ts`.
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: '@xi4z/dsh-utils',
11
+ factory(require) {
12
+ const React = require('react')
13
+ const h = React.createElement
14
+
15
+ // Settings namespaces are the row ids the bundle's patch mounts; the bundle
16
+ // page's configuration cell and each row's own page are keyed by the bundle
17
+ // package name and by `${bundle}#${rowId}`.
18
+ const BUNDLE = '@xi4z/dsh-utils'
19
+ const SKILL_NS = 'utils-main'
20
+ const APPROVAL_NS = 'dsh-approval-policy'
21
+ const NOTIFY_NS = 'dsh-notify'
22
+ const SKILL_PANEL_NS = 'dsh-skill-panel'
23
+ const AGENTS_NS = 'utils-agents'
24
+ const WB_TAB = 'utils-agents'
25
+ const ORIGINS = [
26
+ ['subagent', '子智能体'],
27
+ ['scheduled', '定时任务'],
28
+ ['cron', 'cron 任务'],
29
+ ['all', '全部审批'],
30
+ ]
31
+
32
+ const SKILL_FIELDS = [
33
+ { key: 'minDepth', label: '最小深度', kind: 'number', min: 1, hint: '允许出现技能的第一个目录层级(相对技能根)。' },
34
+ { key: 'maxDepth', label: '最大深度', kind: 'number', min: 1, hint: '最深扫描层级,不得小于最小深度。' },
35
+ { key: 'watch', label: '监听变化', kind: 'boolean', hint: '技能文件变化后刷新技能目录。' },
36
+ { key: 'debounceMs', label: '防抖(毫秒)', kind: 'number', min: 0, hint: '监听失效的合并间隔。' },
37
+ { key: 'pollIntervalMs', label: '轮询间隔(毫秒)', kind: 'number', min: 250, hint: '不支持递归监听时的兜底间隔。' },
38
+ { key: 'includeProjectRoots', label: '扫描项目根', kind: 'boolean', hint: '项目的 .dsh/skills 与 .agents/skills。' },
39
+ { key: 'includeUserRoots', label: '扫描用户根', kind: 'boolean', hint: '用户级技能根。' },
40
+ { key: 'followSymlinks', label: '跟随符号链接', kind: 'boolean', hint: '跟随符号链接目录,带环路保护。' },
41
+ { key: 'extraRoots', label: '追加技能根', kind: 'lines', hint: '每行一个绝对路径。' },
42
+ { key: 'ignoreDirs', label: '忽略的目录名', kind: 'lines', hint: '每行一个目录名,永不进入。' },
43
+ ]
44
+
45
+ const APPROVAL_FIELDS = [
46
+ { key: 'origins', label: '门控来源', kind: 'origins', hint: '判定为无人值守的来源;“全部审批”是显式全门控。' },
47
+ { key: 'sessions', label: '点名会话', kind: 'lines', hint: '按 agent id 的 glob 点名,命中即门控该会话所有轮次;每行一个。' },
48
+ { key: 'windowSeconds', label: '应答窗口(秒)', kind: 'number', min: 0, max: 86400, hint: '0 = 立即拒绝且不询问下游。' },
49
+ { key: 'defaultOutcome', label: '超时落定值', kind: 'select', options: [['rejected', '拒绝(rejected)'], ['unavailable', '下游不可用(unavailable)']], hint: '没有“本次放行”这一档:无人值守的默认裁决必须 fail-closed。' },
50
+ { key: 'defaultPermissionPreset', label: '新会话权限档', kind: 'text', hint: '留空跟随部署默认;auto = 实验性自动审批(需对应 bundle)。' },
51
+ { key: 'autoReviewContent', label: '回传复核内容', kind: 'boolean', hint: '窗口拒绝的是自动审批发起的请求时,把复核内容附进模型读到的工具结果。' },
52
+ ]
53
+
54
+ const REASONS = [
55
+ ['completed', '完成'],
56
+ ['error', '出错'],
57
+ ['aborted', '被中止'],
58
+ ['blocked', '被阻塞'],
59
+ ]
60
+
61
+ const NOTIFY_FIELDS = [
62
+ { key: 'enabled', label: '启用', kind: 'boolean', hint: '总开关;关掉后本设备不发任何通知。' },
63
+ { key: 'dryRun', label: '只记日志', kind: 'boolean', hint: '开启时只写日志不发消息,确认配置无误后再关闭。' },
64
+ {
65
+ key: 'transport', label: '出口', kind: 'select',
66
+ options: [['gotify', 'Gotify 网关'], ['onebot', 'OneBot 直连(已废弃)']],
67
+ hint: '默认走公网 Gotify 网关:任何能上网的设备都能发,不依赖本机 NapCat。',
68
+ },
69
+ { key: 'gotifyUrl', label: '网关地址', kind: 'text', hint: '如 https://notify.example.com;配了 targets 后忽略这一项。' },
70
+ { key: 'gotifyToken', label: '网关 token', kind: 'text', hint: '该系列的 Gotify application token;敏感值建议走环境变量。' },
71
+ { key: 'gotifyPriority', label: '默认优先级', kind: 'number', min: 0, hint: 'targets 没单独指定优先级时使用。' },
72
+ { key: 'gotifyHeaders', label: '附加请求头', kind: 'json', empty: {}, hint: 'JSON 对象,用于反代 Basic Auth 等;X-Gotify-Key 始终以目标 token 为准。' },
73
+ {
74
+ key: 'targets', label: '多目标', kind: 'json', empty: [],
75
+ hint: 'JSON 数组:[{"name":"qq-home","url":"https://…","token":"…","priority":3,"devices":["办公本"]}];非空时忽略上面的单目标字段。',
76
+ },
77
+ { key: 'deviceName', label: '设备名', kind: 'text', hint: '留空取主机名;多设备区分的基础。' },
78
+ { key: 'deviceLabel', label: '设备显示名', kind: 'text', hint: '渲染到 {device} 占位符;留空同设备名。' },
79
+ { key: 'deviceInTitle', label: '标题带设备名', kind: 'boolean', hint: 'true 时 Gotify 标题加 [设备名] 前缀。' },
80
+ { key: 'notifyOnReasons', label: '通知的结束原因', kind: 'checks', options: REASONS, hint: '至少选一个;全不选会回落默认的完成、出错、中止。' },
81
+ { key: 'notifyOnApproval', label: '等待授权时通知', kind: 'boolean', hint: '审批请求挂起时推送;被自动裁决的不会打扰。' },
82
+ { key: 'notifyOnQuestion', label: '等待回答时通知', kind: 'boolean', hint: 'ask_user_question / 计划确认挂起时推送。' },
83
+ { key: 'questionDelayMs', label: '提问去抖(毫秒)', kind: 'number', min: 0, hint: '窗口内已在界面答复就取消推送。' },
84
+ { key: 'approvalDelayMs', label: '审批去抖(毫秒)', kind: 'number', min: 0, hint: '窗口内已自动裁决就取消推送。' },
85
+ { key: 'includeSubagents', label: '包含子会话', kind: 'boolean', hint: '默认只通知根会话,避免主会话 + N 个子会话连发。' },
86
+ { key: 'summaryChars', label: '回复摘要长度', kind: 'number', min: 1, hint: '{reply} 纯文本化后的截断长度。' },
87
+ { key: 'timeoutMs', label: '请求超时(毫秒)', kind: 'number', min: 100, hint: '单次 HTTP 超时;失败自动重试一次。' },
88
+ { key: 'traceFile', label: '诊断轨迹文件', kind: 'text', hint: '可选 JSONL 路径,排障用;留空不记录。' },
89
+ { key: 'template', label: '会话结束模板', kind: 'textarea', hint: '占位符:{status} {kind} {sessionId} {cwd} {reply} {error} {device} {host} {date} {time};空行删整行,留空用内置默认。' },
90
+ { key: 'questionTemplate', label: '提问模板', kind: 'textarea', hint: '额外可用 {question} {detail} {options}。' },
91
+ { key: 'approvalTemplate', label: '授权模板', kind: 'textarea', hint: '额外可用 {tool} {reason}。' },
92
+ ]
93
+
94
+ const AGENTS_FIELDS = [
95
+ { key: 'maxBytes', label: '单文件大小上限(字节)', kind: 'number', min: 1024, hint: '读取和写入都受这个上限约束;超过时面板会提示。' },
96
+ { key: 'presetDirs', label: '额外预设目录', kind: 'lines', hint: '每行一个绝对路径;目录下每个子目录视为一个预设。' },
97
+ { key: 'presetSourceDirs', label: '额外共享预设来源', kind: 'lines', hint: '每行一个技能仓库绝对路径;读取其 .dsh 下的预设供同步。' },
98
+ { key: 'builtinPresets', label: '保留原生的预设 id', kind: 'lines', hint: '每行一个 id;其余原生声明可通过“预设同步”导入为目录预设。' },
99
+ { key: 'extraAgentsFiles', label: '额外 AGENTS 文件', kind: 'lines', hint: '全局视图额外列出的绝对路径;每行一个。' },
100
+ { key: 'scanNestedAgents', label: '递归寻找嵌套 AGENTS.md', kind: 'boolean', hint: '在项目当前目录下继续向下寻找 AGENTS.md / CLAUDE.md。' },
101
+ { key: 'nestedDepth', label: '嵌套扫描深度', kind: 'number', min: 1, hint: '递归寻找嵌套文件的目录深度。' },
102
+ { key: 'defaultRepoUrl', label: '默认技能仓库', kind: 'text', hint: '新预设的仓库地址默认值。' },
103
+ { key: 'defaultBranch', label: '默认仓库分支', kind: 'text', hint: '新预设的仓库分支默认值。' },
104
+ { key: 'updateCheck', label: '定时检查发布版本', kind: 'boolean', hint: '按下面的间隔查询 npm registry 上 @xi4z/dsh-utils 的 latest,并在面板里提示。' },
105
+ { key: 'updateCheckIntervalHours', label: '版本检查间隔(小时)', kind: 'number', min: 1, max: 168, hint: '1–168 小时;面板的「检查更新」按钮不受它限制。' },
106
+ { key: 'updateRegistry', label: 'npm registry', kind: 'text', hint: '默认 https://registry.npmjs.org;可换成镜像,例如 https://registry.npmmirror.com。' },
107
+ { key: 'updateAutoInstall', label: '自动安装新版本', kind: 'boolean', hint: '查到新版本后在后台执行 pnpm add,装完需要重启 dsh web 才生效;link:/file: 安装会跳过。' },
108
+ ]
109
+ const STYLE = `
110
+ .dsu-root { display: grid; gap: 18px; padding: 4px 0; color: var(--dsw-alias-label-primary); font-size: 13px; }
111
+ .dsu-section { display: grid; gap: 12px; }
112
+ .dsu-section + .dsu-section { padding-top: 16px; border-top: 1px solid var(--dsw-alias-border-l1); }
113
+ .dsu-sectionHead { display: grid; gap: 4px; }
114
+ .dsu-title { margin: 0; font-size: 14px; font-weight: 600; }
115
+ .dsu-hint { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 1.5; }
116
+ .dsu-row { display: grid; gap: 6px; }
117
+ .dsu-check { grid-auto-flow: column; justify-content: start; align-items: center; gap: 8px; }
118
+ .dsu-label { color: var(--dsw-alias-label-secondary); }
119
+ .dsu-input { width: 100%; box-sizing: border-box; padding: 6px 8px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; font: inherit; }
120
+ .dsu-input:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
121
+ .dsu-input:disabled { opacity: 0.6; }
122
+ .dsu-textarea { resize: vertical; min-height: 68px; }
123
+ .dsu-choices { display: flex; flex-wrap: wrap; gap: 12px; }
124
+ .dsu-actions { display: flex; align-items: center; gap: 10px; }
125
+ .dsu-save { padding: 6px 14px; border: 1px solid var(--dsw-alias-brand-primary); border-radius: 6px; background: transparent; color: var(--dsw-alias-brand-primary); font: inherit; cursor: pointer; }
126
+ .dsu-save:disabled { opacity: 0.6; cursor: default; }
127
+ .dsu-status { color: var(--dsw-alias-label-secondary); }
128
+ .dsu-note { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 13px; }
129
+ .dsu-error { margin: 0; color: var(--dsw-alias-label-error, #d9534f); font-size: 12px; }
130
+ `
131
+
132
+ function splitLines(text) {
133
+ return String(text).split('\n').map((line) => line.trim()).filter(Boolean)
134
+ }
135
+
136
+ function isList(value) {
137
+ return Array.isArray(value)
138
+ }
139
+
140
+ /** Render an unknown error for a status line. */
141
+ function messageOf(error) {
142
+ return error instanceof Error ? error.message : String(error)
143
+ }
144
+
145
+ /** Key-order-independent JSON text, for change detection on `json` fields. */
146
+ function stable(value) {
147
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`
148
+ if (value !== null && typeof value === 'object') {
149
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`
150
+ }
151
+ return JSON.stringify(value)
152
+ }
153
+
154
+ /** Turn one component's stored value into editable draft text/booleans. */
155
+ function toDraft(fields, value) {
156
+ const draft = {}
157
+ for (const field of fields) {
158
+ const current = value?.[field.key]
159
+ if (field.kind === 'number') draft[field.key] = current === undefined ? '' : String(current)
160
+ else if (field.kind === 'boolean') draft[field.key] = current === true
161
+ else if (field.kind === 'origins' || field.kind === 'checks') draft[field.key] = new Set(isList(current) ? current : [])
162
+ else if (field.kind === 'lines') draft[field.key] = isList(current) ? current.join('\n') : ''
163
+ else if (field.kind === 'json') {
164
+ draft[field.key] = JSON.stringify(current === undefined ? (field.empty ?? {}) : current, null, 2)
165
+ } else if (field.kind === 'textarea') draft[field.key] = current === undefined ? '' : String(current)
166
+ else draft[field.key] = current === undefined ? '' : String(current)
167
+ }
168
+ return draft
169
+ }
170
+
171
+ /** Validate one draft into the value the Host schema accepts. */
172
+ function parseDraft(fields, draft) {
173
+ const next = {}
174
+ for (const field of fields) {
175
+ if (field.kind === 'number') {
176
+ const raw = String(draft[field.key]).trim()
177
+ if (raw === '') throw new Error(`“${field.label}”不能为空。`)
178
+ const number = Number(raw)
179
+ if (!Number.isInteger(number)) throw new Error(`“${field.label}”必须是整数。`)
180
+ if (field.min !== undefined && number < field.min) throw new Error(`“${field.label}”不得小于 ${field.min}。`)
181
+ if (field.max !== undefined && number > field.max) throw new Error(`“${field.label}”不得大于 ${field.max}。`)
182
+ next[field.key] = number
183
+ } else if (field.kind === 'boolean') {
184
+ next[field.key] = draft[field.key] === true
185
+ } else if (field.kind === 'origins') {
186
+ const chosen = [...(draft[field.key] ?? [])]
187
+ next[field.key] = ORIGINS.map(([id]) => id).filter((id) => chosen.includes(id))
188
+ } else if (field.kind === 'checks') {
189
+ const chosen = new Set(draft[field.key] ?? [])
190
+ next[field.key] = field.options.map(([id]) => id).filter((id) => chosen.has(id))
191
+ } else if (field.kind === 'lines') {
192
+ next[field.key] = splitLines(draft[field.key])
193
+ } else if (field.kind === 'json') {
194
+ const raw = String(draft[field.key] ?? '').trim()
195
+ if (raw === '') next[field.key] = field.empty ?? {}
196
+ else {
197
+ try {
198
+ next[field.key] = JSON.parse(raw)
199
+ } catch {
200
+ throw new Error(`“${field.label}”不是合法 JSON。`)
201
+ }
202
+ }
203
+ } else if (field.kind === 'textarea') {
204
+ next[field.key] = String(draft[field.key] ?? '')
205
+ } else if (field.kind === 'select') {
206
+ const allowed = field.options.map(([id]) => id)
207
+ const value = String(draft[field.key])
208
+ if (!allowed.includes(value)) throw new Error(`“${field.label}”取值无效。`)
209
+ next[field.key] = value
210
+ } else {
211
+ next[field.key] = String(draft[field.key]).trim()
212
+ }
213
+ }
214
+ const minDepth = next.minDepth
215
+ const maxDepth = next.maxDepth
216
+ if (typeof minDepth === 'number' && typeof maxDepth === 'number' && maxDepth < minDepth) {
217
+ throw new Error('“最大深度”不得小于“最小深度”。')
218
+ }
219
+ return next
220
+ }
221
+
222
+ /** Field-level operations for the entries whose values actually changed. */
223
+ function changesOf(fields, next, current) {
224
+ const ops = []
225
+ for (const field of fields) {
226
+ const before = current?.[field.key]
227
+ const after = next[field.key]
228
+ const changed = field.kind === 'json'
229
+ ? stable(after) !== stable(before === undefined ? (field.empty ?? {}) : before)
230
+ : field.kind === 'origins' || field.kind === 'checks' || field.kind === 'lines'
231
+ ? JSON.stringify(after) !== JSON.stringify(Array.isArray(before) ? before : [])
232
+ : after !== before
233
+ if (changed) ops.push({ op: 'set', path: [field.key], value: after })
234
+ }
235
+ return ops
236
+ }
237
+
238
+ /** One component's configuration section: fields, validation, save. */
239
+ function Section({ form, fields, title, intro }) {
240
+ const state = form.getSnapshot()
241
+ const [draft, setDraft] = React.useState(() => toDraft(fields, state.value))
242
+ const [status, setStatus] = React.useState('')
243
+
244
+ React.useEffect(() => {
245
+ setDraft(toDraft(fields, state.value))
246
+ }, [state.value])
247
+
248
+ if (state.status === 'loading') return h('p', { className: 'dsu-note' }, '正在读取配置…')
249
+ if (state.status === 'unavailable') return h('p', { className: 'dsu-note' }, '当前 dsh 版本没有向浏览器暴露这项配置。')
250
+
251
+ const readOnly = state.writable !== true
252
+ const update = (key, value) => {
253
+ setStatus('')
254
+ setDraft((current) => ({ ...current, [key]: value }))
255
+ }
256
+ const toggleOption = (key, id, checked) => {
257
+ setStatus('')
258
+ setDraft((current) => {
259
+ const chosen = new Set(current[key])
260
+ if (checked) chosen.add(id)
261
+ else chosen.delete(id)
262
+ return { ...current, [key]: chosen }
263
+ })
264
+ }
265
+ const save = async () => {
266
+ setStatus('保存中…')
267
+ try {
268
+ const ops = changesOf(fields, parseDraft(fields, draft), state.value ?? {})
269
+ if (ops.length === 0) {
270
+ setStatus('已保存')
271
+ return
272
+ }
273
+ const accepted = await form.mutate(ops, state.revision)
274
+ setStatus(accepted ? '已保存' : '宿主拒绝了这次修改。')
275
+ } catch (error) {
276
+ setStatus(error instanceof Error ? error.message : String(error))
277
+ }
278
+ }
279
+
280
+ return h('section', { className: 'dsu-section' }, [
281
+ h('div', { className: 'dsu-sectionHead', key: 'head' }, [
282
+ h('h4', { className: 'dsu-title', key: 'title' }, title),
283
+ intro === undefined ? null : h('p', { className: 'dsu-hint', key: 'intro' }, intro),
284
+ ]),
285
+ ...fields.map((field) => renderField(field, draft, readOnly, update, toggleOption)),
286
+ h('div', { className: 'dsu-actions', key: 'actions' }, [
287
+ h('button', {
288
+ className: 'dsu-save', key: 'save', type: 'button',
289
+ disabled: readOnly || status === '保存中…', onClick: save,
290
+ }, '保存'),
291
+ status === '' ? null : h('span', { className: 'dsu-status', key: 'status', role: 'status' }, status),
292
+ ]),
293
+ ])
294
+ }
295
+
296
+ /** Render one field according to its kind. */
297
+ function renderField(field, draft, readOnly, update, toggleOption) {
298
+ const hint = field.hint === undefined ? null : h('span', { className: 'dsu-hint', key: 'hint' }, field.hint)
299
+ if (field.kind === 'boolean') {
300
+ return h('label', { className: 'dsu-row dsu-check', key: field.key }, [
301
+ h('input', {
302
+ key: 'input', type: 'checkbox', checked: draft[field.key] === true, disabled: readOnly,
303
+ onChange: (event) => update(field.key, event.target.checked),
304
+ }),
305
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
306
+ hint,
307
+ ])
308
+ }
309
+ if (field.kind === 'origins') {
310
+ const chosen = draft[field.key] ?? new Set()
311
+ return h('div', { className: 'dsu-row', key: field.key }, [
312
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
313
+ h('div', { className: 'dsu-choices', key: 'choices' }, ORIGINS.map(([id, label]) => h('label', { className: 'dsu-check', key: id }, [
314
+ h('input', {
315
+ key: 'input', type: 'checkbox', checked: chosen.has(id), disabled: readOnly,
316
+ onChange: (event) => toggleOption(field.key, id, event.target.checked),
317
+ }),
318
+ h('span', { className: 'dsu-label', key: 'label' }, label),
319
+ ]))),
320
+ hint,
321
+ ])
322
+ }
323
+ if (field.kind === 'checks') {
324
+ const chosen = draft[field.key] ?? new Set()
325
+ return h('div', { className: 'dsu-row', key: field.key }, [
326
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
327
+ h('div', { className: 'dsu-choices', key: 'choices' }, field.options.map(([id, label]) => h('label', { className: 'dsu-check', key: id }, [
328
+ h('input', {
329
+ key: 'input', type: 'checkbox', checked: chosen.has(id), disabled: readOnly,
330
+ onChange: (event) => toggleOption(field.key, id, event.target.checked),
331
+ }),
332
+ h('span', { className: 'dsu-label', key: 'label' }, label),
333
+ ]))),
334
+ hint,
335
+ ])
336
+ }
337
+ if (field.kind === 'select') {
338
+ return h('label', { className: 'dsu-row', key: field.key }, [
339
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
340
+ h('select', {
341
+ className: 'dsu-input', key: 'input', value: draft[field.key] ?? '', disabled: readOnly,
342
+ onChange: (event) => update(field.key, event.target.value),
343
+ }, field.options.map(([id, label]) => h('option', { key: id, value: id }, label))),
344
+ hint,
345
+ ])
346
+ }
347
+ if (field.kind === 'lines') {
348
+ return h('label', { className: 'dsu-row', key: field.key }, [
349
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
350
+ h('textarea', {
351
+ className: 'dsu-input dsu-textarea', key: 'input', rows: 3, value: draft[field.key] ?? '', disabled: readOnly,
352
+ onChange: (event) => update(field.key, event.target.value),
353
+ }),
354
+ hint,
355
+ ])
356
+ }
357
+ if (field.kind === 'textarea' || field.kind === 'json') {
358
+ return h('label', { className: 'dsu-row', key: field.key }, [
359
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
360
+ h('textarea', {
361
+ className: 'dsu-input dsu-textarea', key: 'input',
362
+ rows: field.kind === 'json' ? 5 : 4,
363
+ value: draft[field.key] ?? '', disabled: readOnly,
364
+ onChange: (event) => update(field.key, event.target.value),
365
+ }),
366
+ hint,
367
+ ])
368
+ }
369
+ return h('label', { className: 'dsu-row', key: field.key }, [
370
+ h('span', { className: 'dsu-label', key: 'label' }, field.label),
371
+ h('input', {
372
+ className: 'dsu-input', key: 'input',
373
+ type: field.kind === 'number' ? 'number' : 'text',
374
+ ...(field.kind === 'number' ? { min: field.min, max: field.max, step: 1 } : {}),
375
+ value: draft[field.key] ?? '', disabled: readOnly,
376
+ onChange: (event) => update(field.key, event.target.value),
377
+ }),
378
+ hint,
379
+ ])
380
+ }
381
+
382
+ // -------------------------------------------------------- skills panel --
383
+ //
384
+ // The panel lists the Skill catalog the Host resolves for one Session (or
385
+ // the default workspace when the row page opens it without a Session) and
386
+ // turns each model-invocable row into one switch over the `dsh-skill-panel`
387
+ // config namespace. A switch hides the Skill from the model catalog only;
388
+ // /name still loads it manually, which is why the rest render as "仅手动".
389
+
390
+ const PANEL_STYLE = `
391
+ .dsp-root { display: grid; align-content: start; gap: 12px; box-sizing: border-box; height: 100%; padding: 12px; overflow: auto; color: var(--dsw-alias-label-primary); font-size: 13px; }
392
+ .dsp-head { display: flex; align-items: center; gap: 8px; }
393
+ .dsp-title { margin: 0; font-size: 14px; font-weight: 600; }
394
+ .dsp-count { color: var(--dsw-alias-label-secondary); font-size: 12px; }
395
+ .dsp-refresh { padding: 4px 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; cursor: pointer; }
396
+ .dsp-refresh:hover { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }
397
+ .dsp-refresh:disabled { opacity: 0.6; cursor: default; }
398
+ .dsp-note { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 1.5; }
399
+ .dsp-list { display: grid; gap: 8px; }
400
+ .dsp-item { display: grid; gap: 4px; padding: 8px 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-base); }
401
+ .dsp-itemHead { display: flex; align-items: center; gap: 8px; }
402
+ .dsp-name { font-weight: 600; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
403
+ .dsp-tag { padding: 0 6px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 999px; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 18px; }
404
+ .dsp-switch { margin-left: auto; width: 14px; height: 14px; accent-color: var(--dsw-alias-brand-primary); cursor: pointer; }
405
+ .dsp-switch:disabled { cursor: default; opacity: 0.6; }
406
+ .dsp-desc { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 1.45; }
407
+ .dsp-meta { color: var(--dsw-alias-label-secondary); font-size: 11px; word-break: break-all; }
408
+ .dsp-state { margin: 0; color: var(--dsw-alias-label-secondary); }
409
+ .dsp-error { margin: 0; color: var(--dsw-alias-label-error, #d9534f); font-size: 12px; }
410
+ .dsp-empty { display: grid; gap: 8px; justify-items: start; }
411
+ .dsp-host { display: grid; height: 100%; min-height: 0; }
412
+ `
413
+
414
+ /** Normalize the Host's rows into something the list can trust, sorted by name. */
415
+ function normalizeSkills(body) {
416
+ const rows = body !== null && typeof body === 'object' && Array.isArray(body.skills) ? body.skills : []
417
+ return rows
418
+ .filter((row) => row !== null && typeof row === 'object' && typeof row.name === 'string' && row.name !== '')
419
+ .map((row) => ({
420
+ name: row.name,
421
+ description: typeof row.description === 'string' ? row.description : '',
422
+ source: typeof row.source === 'string' ? row.source : '',
423
+ provider: typeof row.provider === 'string' ? row.provider : '',
424
+ path: typeof row.path === 'string' ? row.path : '',
425
+ modelInvocable: row.modelInvocable === true,
426
+ }))
427
+ .sort((left, right) => left.name.localeCompare(right.name))
428
+ }
429
+
430
+ /** The disabled list this form currently holds, or null when it cannot say. */
431
+ function formDisabled(form) {
432
+ if (!form || typeof form.getSnapshot !== 'function') return null
433
+ let snapshot
434
+ try {
435
+ snapshot = form.getSnapshot()
436
+ } catch {
437
+ return null
438
+ }
439
+ const value = snapshot?.value
440
+ if (value === null || typeof value !== 'object' || !Array.isArray(value.disabledSkills)) return null
441
+ return value.disabledSkills.filter((name) => typeof name === 'string')
442
+ }
443
+
444
+ /** The next disabled array for one row switch, in canonical (sorted) order. */
445
+ function nextDisabled(current, name, enabled) {
446
+ const chosen = new Set(Array.isArray(current) ? current : [])
447
+ if (enabled) chosen.delete(name)
448
+ else chosen.add(name)
449
+ return [...chosen].sort()
450
+ }
451
+
452
+ /** The Host's list URL; document.baseURI keeps a sub-path deployment working. */
453
+ function skillPanelUrl(sessionId) {
454
+ const base = typeof document !== 'undefined' && typeof document.baseURI === 'string' && document.baseURI !== ''
455
+ ? document.baseURI
456
+ : 'http://localhost/'
457
+ const url = new URL('api/dsh-utils/skill-panel/list', base)
458
+ if (typeof sessionId === 'string' && sessionId !== '') {
459
+ url.searchParams.set('sessionId', sessionId)
460
+ }
461
+ return url
462
+ }
463
+
464
+ /** GET one Session's skill catalog, mapping transport and HTTP failures to prose. */
465
+ async function fetchSkillPanel(sessionId) {
466
+ if (typeof fetch !== 'function') throw new Error('当前环境不支持网络请求。')
467
+ let response
468
+ try {
469
+ response = await fetch(skillPanelUrl(sessionId), {
470
+ method: 'GET', headers: { accept: 'application/json' },
471
+ })
472
+ } catch {
473
+ throw new Error('无法连接宿主服务,请检查页面连接后重试。')
474
+ }
475
+ if (response.status === 401) throw new Error('登录状态已过期,请刷新页面后重试。')
476
+ if (response.status === 404) {
477
+ throw new Error('宿主还没有加载技能面板组件(HTTP 404)。请重启 dsh web;如果已重启,请在插件页确认 dsh-skill-panel 行已启用。')
478
+ }
479
+ if (!response.ok) {
480
+ let detail = ''
481
+ try {
482
+ const body = await response.json()
483
+ if (body !== null && typeof body === 'object' && typeof body.error === 'string') detail = body.error
484
+ } catch {
485
+ detail = ''
486
+ }
487
+ throw new Error('技能目录读取失败(HTTP ' + response.status + ')' + (detail === '' ? '' : ':' + detail))
488
+ }
489
+ let body
490
+ try {
491
+ body = await response.json()
492
+ } catch {
493
+ throw new Error('技能目录返回了无法解析的数据。')
494
+ }
495
+ if (body === null || typeof body !== 'object') throw new Error('技能目录返回了无法识别的数据。')
496
+ return { skills: normalizeSkills(body), body }
497
+ }
498
+
499
+ /** The Skill catalog panel shared by the right sidebar and the plugin row page. */
500
+ function SkillPanel({ form, sessionId }) {
501
+ // Every hook runs before the first early return: the panel renders a
502
+ // loading, error, empty or populated branch on the same hook layout.
503
+ const [status, setStatus] = React.useState('loading')
504
+ const [skills, setSkills] = React.useState([])
505
+ const [meta, setMeta] = React.useState({})
506
+ const [error, setError] = React.useState('')
507
+ const [reloadKey, setReloadKey] = React.useState(0)
508
+ const [disabled, setDisabled] = React.useState(() => formDisabled(form) ?? [])
509
+ const [writing, setWriting] = React.useState('')
510
+ const [saveError, setSaveError] = React.useState('')
511
+
512
+ // The form's snapshot is the source of truth for the switches: it changes
513
+ // when the Host folds a write back, including the rollback after a refusal.
514
+ React.useEffect(() => {
515
+ if (!form || typeof form.subscribe !== 'function') return undefined
516
+ setDisabled(formDisabled(form) ?? [])
517
+ return form.subscribe(() => setDisabled(formDisabled(form) ?? []))
518
+ }, [])
519
+
520
+ React.useEffect(() => {
521
+ let cancelled = false
522
+ setStatus('loading')
523
+ setError('')
524
+ fetchSkillPanel(sessionId).then((result) => {
525
+ if (cancelled) return
526
+ setSkills(result.skills)
527
+ setMeta(result.body)
528
+ // The Host's answer is only a fallback: while the config namespace is
529
+ // served the form already carries the authoritative disabled list.
530
+ if (formDisabled(form) === null) {
531
+ const reported = Array.isArray(result.body.disabledSkills) ? result.body.disabledSkills : []
532
+ setDisabled(reported.filter((name) => typeof name === 'string'))
533
+ }
534
+ setStatus('ready')
535
+ }).catch((failure) => {
536
+ if (cancelled) return
537
+ setSkills([])
538
+ setMeta({})
539
+ setError(failure instanceof Error ? failure.message : String(failure))
540
+ setStatus('error')
541
+ })
542
+ return () => {
543
+ cancelled = true
544
+ }
545
+ }, [sessionId, reloadKey, form])
546
+
547
+ const snapshot = form && typeof form.getSnapshot === 'function' ? form.getSnapshot() : null
548
+ const readOnly = snapshot === null || snapshot.writable !== true
549
+ const unavailable = form === null || (snapshot !== null && snapshot.status === 'unavailable')
550
+ const disabledSet = new Set(disabled)
551
+ const reload = () => setReloadKey((key) => key + 1)
552
+
553
+ const toggle = async (skill, enabled) => {
554
+ if (!skill.modelInvocable || writing !== '') return
555
+ if (!form || typeof form.set !== 'function') {
556
+ setSaveError('当前 dsh 版本没有向浏览器暴露技能开关配置。')
557
+ return
558
+ }
559
+ if (readOnly) {
560
+ setSaveError('当前配置只读,无法修改开关。')
561
+ return
562
+ }
563
+ const before = disabled
564
+ const next = nextDisabled(before, skill.name, enabled)
565
+ setSaveError('')
566
+ setDisabled(next)
567
+ setWriting(skill.name)
568
+ try {
569
+ const accepted = await form.set('disabledSkills', next)
570
+ if (accepted === false) {
571
+ setDisabled(before)
572
+ setSaveError('宿主拒绝了这次修改,开关已还原。')
573
+ }
574
+ } catch (failure) {
575
+ setDisabled(before)
576
+ setSaveError(failure instanceof Error ? failure.message : String(failure))
577
+ } finally {
578
+ setWriting('')
579
+ }
580
+ }
581
+
582
+ const visible = skills.filter((skill) => skill.modelInvocable && !disabledSet.has(skill.name)).length
583
+ const children = [
584
+ h('div', { className: 'dsp-head', key: 'head' }, [
585
+ h('h3', { className: 'dsp-title', key: 'title' }, '技能'),
586
+ status === 'ready' ? h('span', { className: 'dsp-count', key: 'count' }, '共 ' + skills.length + ' 个 · 模型可见 ' + visible) : null,
587
+ h('button', {
588
+ className: 'dsp-refresh', key: 'refresh', type: 'button',
589
+ disabled: status === 'loading', onClick: reload,
590
+ }, status === 'loading' ? '读取中…' : '刷新'),
591
+ ]),
592
+ ]
593
+
594
+ if (typeof meta.cwd === 'string' && meta.cwd !== '') {
595
+ children.push(h('p', { className: 'dsp-note', key: 'cwd' }, '工作目录:' + meta.cwd))
596
+ } else if (typeof sessionId !== 'string' || sessionId === '') {
597
+ children.push(h('p', { className: 'dsp-note', key: 'scope' }, '未绑定会话,显示默认工作目录的技能。'))
598
+ }
599
+ if (unavailable) {
600
+ children.push(h('p', { className: 'dsp-note', key: 'config' }, '当前 dsh 版本没有向浏览器暴露技能开关配置,列表仍可查看。'))
601
+ } else if (readOnly) {
602
+ children.push(h('p', { className: 'dsp-note', key: 'config' }, '配置只读:开关改动不会写入。'))
603
+ }
604
+
605
+ if (status === 'loading') {
606
+ children.push(h('p', { className: 'dsp-state', key: 'state' }, '正在读取技能目录…'))
607
+ } else if (status === 'error') {
608
+ children.push(h('div', { className: 'dsp-empty', key: 'state' }, [
609
+ h('p', { className: 'dsp-error', key: 'error', role: 'alert' }, error),
610
+ h('button', { className: 'dsp-refresh', key: 'retry', type: 'button', onClick: reload }, '重试'),
611
+ ]))
612
+ } else if (skills.length === 0) {
613
+ children.push(h('div', { className: 'dsp-empty', key: 'state' }, [
614
+ h('p', { className: 'dsp-note', key: 'empty' }, '当前没有可读取的技能。'),
615
+ h('p', { className: 'dsp-note', key: 'hint' }, '技能从用户级与项目级技能根发现;添加 SKILL.md 后点“刷新”。'),
616
+ ]))
617
+ } else {
618
+ children.push(h('div', { className: 'dsp-list', key: 'list' }, skills.map((skill) => {
619
+ const enabled = !disabledSet.has(skill.name)
620
+ const metaText = [skill.source, skill.provider].filter((part) => part !== '').join(' · ')
621
+ return h('div', { className: 'dsp-item', key: skill.name, 'data-skill': skill.name }, [
622
+ h('div', { className: 'dsp-itemHead', key: 'head' }, [
623
+ h('span', { className: 'dsp-name', key: 'name' }, skill.name),
624
+ skill.modelInvocable ? null : h('span', { className: 'dsp-tag', key: 'tag' }, '仅手动'),
625
+ h('input', {
626
+ className: 'dsp-switch', key: 'switch', type: 'checkbox',
627
+ 'data-skill': skill.name,
628
+ checked: skill.modelInvocable ? enabled : false,
629
+ disabled: !skill.modelInvocable || readOnly || writing !== '',
630
+ 'aria-label': skill.modelInvocable ? '模型可见:' + skill.name : skill.name + ' 仅手动可调用',
631
+ onChange: (event) => {
632
+ toggle(skill, event.target.checked)
633
+ },
634
+ }),
635
+ ]),
636
+ skill.description === '' ? null : h('p', { className: 'dsp-desc', key: 'desc' }, skill.description),
637
+ metaText === '' ? null : h('span', { className: 'dsp-meta', key: 'meta' }, metaText),
638
+ skill.path === '' ? null : h('span', { className: 'dsp-meta', key: 'path', title: skill.path }, skill.path),
639
+ ])
640
+ })))
641
+ }
642
+
643
+ if (saveError !== '') {
644
+ children.push(h('p', { className: 'dsp-error', key: 'saveError', role: 'status' }, saveError))
645
+ }
646
+ children.push(h('p', { className: 'dsp-note', key: 'foot' }, '关闭后该技能不再出现在模型技能目录中,仍可用“/名称”手动加载。'))
647
+ return h('div', { className: 'dsp-root' }, children)
648
+ }
649
+
650
+ // ---------------------------------------------------- utils-agents ----
651
+ //
652
+ // One sidebar tab replaces the former 技能 / 技能仓库 / Markdown cards.
653
+ // A preset is one directory under ~/.dsh/.agent-presets; the utils-agents panel
654
+ // lists that preset's skills, edits its Markdown, and syncs a Git skill
655
+ // repository into its skills/ directory. The special global target edits
656
+ // the user/project AGENTS.md chain.
657
+
658
+ const GLOBAL_PRESET = '__global__'
659
+ const WB_STYLE = [
660
+ '.dswb-root { display: flex; flex-direction: column; gap: 8px; box-sizing: border-box; height: 100%; min-height: 0; padding: 10px; overflow: hidden; color: var(--dsw-alias-label-primary); font-size: 13px; }',
661
+ '.dswb-host { display: grid; height: 100%; min-height: 0; }',
662
+ '.dswb-head { display: flex; align-items: center; gap: 8px; }',
663
+ '.dswb-title { margin: 0; font-size: 14px; font-weight: 600; }',
664
+ '.dswb-count { color: var(--dsw-alias-label-secondary); font-size: 11px; }',
665
+ '.dswb-update { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 11px; }',
666
+ '.dswb-refresh { margin-left: auto; padding: 4px 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; cursor: pointer; }',
667
+ '.dswb-refresh:hover { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }',
668
+ '.dswb-refresh:disabled { opacity: 0.6; cursor: default; }',
669
+ '.dswb-presetBar { display: flex; align-items: center; gap: 6px; min-width: 0; }',
670
+ '.dswb-select { flex: 1; min-width: 0; padding: 5px 7px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; font: inherit; font-size: 12px; }',
671
+ '.dswb-paths { display: grid; gap: 2px; }',
672
+ '.dswb-note { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.5; word-break: break-all; }',
673
+ '.dswb-error { margin: 0; color: var(--dsw-alias-label-error, #d9534f); font-size: 11px; white-space: pre-wrap; }',
674
+ '.dswb-ok { margin: 0; color: var(--dsw-alias-label-success, #2e7d32); font-size: 11px; }',
675
+ '.dswb-tabs { display: flex; gap: 2px; padding: 2px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 7px; }',
676
+ '.dswb-tab { flex: 1; padding: 4px 6px; border: 0; border-radius: 5px; background: transparent; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 12px; cursor: pointer; }',
677
+ '.dswb-tab:hover { color: var(--dsw-alias-label-primary); }',
678
+ '.dswb-tabActive { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); font-weight: 600; }',
679
+ '.dswb-body { display: flex; flex: 1 1 auto; flex-direction: column; gap: 8px; min-height: 0; overflow: auto; }',
680
+ '.dswb-skill { display: grid; gap: 3px; padding: 6px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; }',
681
+ '.dswb-skillHead { display: flex; align-items: center; gap: 6px; min-width: 0; }',
682
+ '.dswb-skillName { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }',
683
+ '.dswb-badge { padding: 0 5px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 999px; color: var(--dsw-alias-label-secondary); font-size: 10px; line-height: 16px; white-space: nowrap; }',
684
+ '.dswb-badgeOn { color: var(--dsw-alias-label-success, #2e7d32); border-color: currentColor; }',
685
+ '.dswb-badgeOff { color: var(--dsw-alias-label-tertiary, #888); }',
686
+ '.dswb-skillPath { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-secondary); font: 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }',
687
+ '.dswb-skillActions { display: flex; flex-wrap: wrap; gap: 6px; }',
688
+ '.dswb-linkBtn { padding: 2px 6px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 5px; background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 11px; cursor: pointer; }',
689
+ '.dswb-linkBtn:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }',
690
+ '.dswb-linkBtn:disabled { opacity: 0.5; cursor: default; }',
691
+ '.dswb-field { display: grid; gap: 4px; }',
692
+ '.dswb-label { color: var(--dsw-alias-label-secondary); font-size: 11px; }',
693
+ '.dswb-input { width: 100%; box-sizing: border-box; padding: 5px 7px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; font: inherit; font-size: 12px; }',
694
+ '.dswb-input:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }',
695
+ '.dswb-textarea { width: 100%; box-sizing: border-box; min-height: 56px; resize: vertical; padding: 6px 7px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }',
696
+ '.dswb-check { display: flex; align-items: center; gap: 6px; color: var(--dsw-alias-label-secondary); font-size: 11px; }',
697
+ '.dswb-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }',
698
+ '.dswb-btn { padding: 5px 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; cursor: pointer; }',
699
+ '.dswb-btn:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }',
700
+ '.dswb-btn:disabled { opacity: 0.55; cursor: default; }',
701
+ '.dswb-primary { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }',
702
+ '.dswb-fileBar { display: flex; align-items: center; gap: 6px; min-width: 0; }',
703
+ '.dswb-filePath { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-secondary); font: 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }',
704
+ '.dswb-editor { flex: 1 1 auto; min-height: 150px; width: 100%; box-sizing: border-box; resize: none; padding: 7px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; tab-size: 2; }',
705
+ '.dswb-editor:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }',
706
+ '.dswb-editor:disabled { opacity: 0.6; }',
707
+ '.dswb-status { color: var(--dsw-alias-label-secondary); font-size: 10px; }',
708
+ '.dswb-kv { display: grid; gap: 2px; padding: 6px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; }',
709
+ '.dswb-empty { display: grid; gap: 6px; justify-items: start; }',
710
+ ].join('\n')
711
+
712
+ /** One string or ''. */
713
+ function wbText(value) {
714
+ return typeof value === 'string' ? value : ''
715
+ }
716
+
717
+ /** Normalize one file row. */
718
+ function wbFile(row, fallback) {
719
+ const value = row !== null && typeof row === 'object' ? row : {}
720
+ const base = fallback !== null && typeof fallback === 'object' ? fallback : {}
721
+ const pick = function (key, type) {
722
+ if (typeof value[key] === type) return value[key]
723
+ if (typeof base[key] === type) return base[key]
724
+ return type === 'number' ? 0 : ''
725
+ }
726
+ return {
727
+ id: wbText(value.id) || wbText(base.id),
728
+ label: pick('label', 'string'),
729
+ path: pick('path', 'string'),
730
+ presetId: pick('presetId', 'string'),
731
+ kind: wbText(value.kind) || wbText(base.kind) || 'reference',
732
+ scope: pick('scope', 'string'),
733
+ exists: value.exists === true,
734
+ editable: value.editable === true,
735
+ size: pick('size', 'number'),
736
+ mtimeMs: typeof value.mtimeMs === 'number' ? value.mtimeMs : null,
737
+ }
738
+ }
739
+
740
+ /** Normalize a files payload. */
741
+ function wbFiles(body) {
742
+ const rows = body !== null && typeof body === 'object' && Array.isArray(body.files) ? body.files : []
743
+ return rows
744
+ .filter(function (row) { return row !== null && typeof row === 'object' && typeof row.id === 'string' && row.id !== '' })
745
+ .map(function (row) { return wbFile(row, null) })
746
+ }
747
+
748
+ /** Normalize one skill row. */
749
+ function wbSkill(row) {
750
+ const value = row !== null && typeof row === 'object' ? row : {}
751
+ return {
752
+ name: wbText(value.name),
753
+ description: wbText(value.description),
754
+ path: wbText(value.path),
755
+ enabled: value.enabled === true,
756
+ size: typeof value.size === 'number' ? value.size : 0,
757
+ mtimeMs: typeof value.mtimeMs === 'number' ? value.mtimeMs : null,
758
+ }
759
+ }
760
+
761
+ /** Normalize the list payload. */
762
+ function wbPresets(body) {
763
+ const rows = body !== null && typeof body === 'object' && Array.isArray(body.presets) ? body.presets : []
764
+ return rows
765
+ .filter(function (row) { return row !== null && typeof row === 'object' && typeof row.id === 'string' && row.id !== '' })
766
+ .map(function (row) {
767
+ return {
768
+ id: row.id,
769
+ name: wbText(row.name) || row.id,
770
+ description: wbText(row.description),
771
+ path: wbText(row.path),
772
+ skills: Array.isArray(row.skills) ? row.skills.map(wbSkill) : [],
773
+ agents: wbFile(row.agents, null),
774
+ registered: row.registered === true,
775
+ broken: wbText(row.broken),
776
+ }
777
+ })
778
+ }
779
+
780
+ /** Normalize the repository view. */
781
+ function wbRepo(body) {
782
+ const value = body !== null && typeof body === 'object' ? body : {}
783
+ const state = value.state !== null && typeof value.state === 'object' ? value.state : {}
784
+ const status = value.status !== null && typeof value.status === 'object' ? value.status : {}
785
+ const key = value.key !== null && typeof value.key === 'object' ? value.key : {}
786
+ return {
787
+ state: {
788
+ repoUrl: wbText(state.repoUrl),
789
+ branch: wbText(state.branch),
790
+ targetSubdir: wbText(state.targetSubdir),
791
+ keyPath: wbText(state.keyPath),
792
+ recurseSubmodules: state.recurseSubmodules !== false,
793
+ lastSync: state.lastSync !== null && typeof state.lastSync === 'object' ? state.lastSync : null,
794
+ },
795
+ target: wbText(value.target),
796
+ status: {
797
+ exists: status.exists === true,
798
+ isRepo: status.isRepo === true,
799
+ branch: wbText(status.branch),
800
+ commit: wbText(status.commit),
801
+ dirty: status.dirty === true,
802
+ skills: typeof status.skills === 'number' ? status.skills : 0,
803
+ },
804
+ key: {
805
+ source: wbText(key.source) || 'none',
806
+ hasStoredKey: key.hasStoredKey === true,
807
+ },
808
+ }
809
+ }
810
+
811
+ /** Normalize one SSH key status. */
812
+ function wbKeyStatus(value) {
813
+ const key = value !== null && typeof value === 'object' ? value : {}
814
+ return {
815
+ source: wbText(key.source) || 'none',
816
+ hasStoredKey: key.hasStoredKey === true,
817
+ }
818
+ }
819
+
820
+ /** Human-readable SSH identity source. */
821
+ function wbKeyText(key) {
822
+ if (key === null || typeof key !== 'object') return '无'
823
+ if (key.source === 'path') return '密钥路径'
824
+ if (key.source === 'stored') return '已保存的 Deploy Key'
825
+ if (key.source === 'global') return '通用 Deploy Key'
826
+ return '无'
827
+ }
828
+
829
+ /** Normalize the automatic-install state. */
830
+ function wbInstall(value) {
831
+ const install = value !== null && typeof value === 'object' ? value : {}
832
+ const phase = install.phase
833
+ return {
834
+ phase: phase === 'installing' || phase === 'installed' || phase === 'failed' ? phase : 'idle',
835
+ version: wbText(install.version) !== '' ? wbText(install.version) : null,
836
+ message: wbText(install.message) !== '' ? wbText(install.message) : null,
837
+ }
838
+ }
839
+
840
+ /** Normalize the published-version answer. */
841
+ function wbUpdate(value) {
842
+ const update = value !== null && typeof value === 'object' ? value : {}
843
+ return {
844
+ current: wbText(update.current),
845
+ latest: wbText(update.latest) !== '' ? wbText(update.latest) : null,
846
+ updateAvailable: update.updateAvailable === true,
847
+ source: wbText(update.source) || 'npm',
848
+ origin: wbText(update.origin),
849
+ install: wbInstall(update.install),
850
+ checkedAt: wbText(update.checkedAt) !== '' ? wbText(update.checkedAt) : null,
851
+ attemptedAt: wbText(update.attemptedAt) !== '' ? wbText(update.attemptedAt) : null,
852
+ error: wbText(update.error) !== '' ? wbText(update.error) : null,
853
+ }
854
+ }
855
+
856
+ /** How long ago one ISO timestamp was, in the panel's short wording. */
857
+ function wbAgo(iso) {
858
+ if (iso === null) return ''
859
+ const time = Date.parse(iso)
860
+ if (!Number.isFinite(time)) return ''
861
+ const minutes = Math.max(0, Math.round((Date.now() - time) / 60000))
862
+ if (minutes < 1) return '刚刚'
863
+ if (minutes < 60) return minutes + ' 分钟前'
864
+ const hours = Math.round(minutes / 60)
865
+ if (hours < 48) return hours + ' 小时前'
866
+ return new Date(time).toLocaleDateString()
867
+ }
868
+
869
+ /** The short label for where the newest version was read from. */
870
+ function wbSourceLabel(update) {
871
+ if (update === null) return ''
872
+ if (update.source === 'git') return 'GitHub'
873
+ if (update.source === 'local') return '本地'
874
+ return 'npm'
875
+ }
876
+
877
+ /** The sentence describing one published-version answer. */
878
+ function wbUpdateText(update) {
879
+ if (update === null) return '尚未检查'
880
+ if (update.install.phase === 'installing') return '正在自动更新到 ' + update.install.version + '…'
881
+ if (update.install.phase === 'installed') return '已自动更新到 ' + update.install.version + '(重启 dsh web 生效)'
882
+ if (update.install.phase === 'failed') return '自动更新失败:' + (update.install.message || '未知错误')
883
+ if (update.error !== null) {
884
+ return update.latest === null ? '检查失败:' + update.error : '检查失败(上次看到 ' + update.latest + '):' + update.error
885
+ }
886
+ if (update.updateAvailable) return '可更新到 ' + update.latest
887
+ if (update.checkedAt !== null) return '已是最新(' + wbAgo(update.checkedAt) + '检查)'
888
+ return '尚未检查'
889
+ }
890
+
891
+ /** Editable repository draft. */
892
+ function wbRepoDraft(repo) {
893
+ if (repo === null || typeof repo !== 'object') return null
894
+ return {
895
+ repoUrl: repo.state.repoUrl,
896
+ branch: repo.state.branch,
897
+ targetSubdir: repo.state.targetSubdir,
898
+ keyPath: repo.state.keyPath,
899
+ recurseSubmodules: repo.state.recurseSubmodules,
900
+ }
901
+ }
902
+
903
+ /** Normalize the shared skill repository view. */
904
+ function wbSharedRepo(body) {
905
+ const value = body !== null && typeof body === 'object' ? body : {}
906
+ const state = value.state !== null && typeof value.state === 'object' ? value.state : {}
907
+ const target = value.target !== null && typeof value.target === 'object' ? value.target : {}
908
+ const key = value.key !== null && typeof value.key === 'object' ? value.key : {}
909
+ return {
910
+ state: {
911
+ repoUrl: wbText(state.repoUrl),
912
+ branch: wbText(state.branch),
913
+ targetDir: wbText(state.targetDir),
914
+ keyPath: wbText(state.keyPath),
915
+ recurseSubmodules: state.recurseSubmodules !== false,
916
+ lastSync: state.lastSync !== null && typeof state.lastSync === 'object' ? state.lastSync : null,
917
+ },
918
+ target: {
919
+ exists: target.exists === true,
920
+ isRepo: target.isRepo === true,
921
+ branch: wbText(target.branch),
922
+ commit: wbText(target.commit),
923
+ dirty: target.dirty === true,
924
+ skills: typeof target.skills === 'number' ? target.skills : 0,
925
+ },
926
+ key: {
927
+ source: wbText(key.source) || 'none',
928
+ hasStoredKey: key.hasStoredKey === true,
929
+ },
930
+ }
931
+ }
932
+
933
+ /** Editable shared repository draft. */
934
+ function wbSharedRepoDraft(view) {
935
+ if (view === null || typeof view !== 'object') return null
936
+ return {
937
+ repoUrl: view.state.repoUrl,
938
+ branch: view.state.branch,
939
+ targetDir: view.state.targetDir,
940
+ keyPath: view.state.keyPath,
941
+ recurseSubmodules: view.state.recurseSubmodules,
942
+ }
943
+ }
944
+
945
+ /** Normalize the native-preset takeover view. */
946
+ function wbNative(body) {
947
+ const value = body !== null && typeof body === 'object' ? body : {}
948
+ const rows = Array.isArray(value.presets) ? value.presets : []
949
+ return {
950
+ builtin: Array.isArray(value.builtin) ? value.builtin.filter(function (id) { return typeof id === 'string' }) : [],
951
+ localRoot: wbText(value.localRoot),
952
+ presets: rows
953
+ .filter(function (row) { return row !== null && typeof row === 'object' && typeof row.id === 'string' && row.id !== '' })
954
+ .map(function (row) {
955
+ return {
956
+ id: row.id,
957
+ name: wbText(row.name) || row.id,
958
+ description: wbText(row.description),
959
+ builtin: row.builtin === true,
960
+ directory: row.directory === true,
961
+ importable: row.importable === true,
962
+ }
963
+ }),
964
+ }
965
+ }
966
+
967
+ /** Normalize the shared-preset status. */
968
+ function wbSharedStatus(value) {
969
+ return value === 'new' || value === 'update' || value === 'same' || value === 'invalid' ? value : 'invalid'
970
+ }
971
+
972
+ /** Normalize one shared preset row. */
973
+ function wbSharedPreset(row) {
974
+ const value = row !== null && typeof row === 'object' ? row : {}
975
+ return {
976
+ id: wbText(value.id),
977
+ name: wbText(value.name) || wbText(value.id),
978
+ description: wbText(value.description),
979
+ status: wbSharedStatus(value.status),
980
+ sourceKind: wbText(value.sourceKind) || 'extra',
981
+ sourceRoot: wbText(value.sourceRoot),
982
+ sourcePath: wbText(value.sourcePath),
983
+ targetPath: wbText(value.targetPath),
984
+ skills: typeof value.skills === 'number' ? value.skills : 0,
985
+ files: typeof value.files === 'number' ? value.files : 0,
986
+ managed: value.managed === true,
987
+ lastSyncAt: wbText(value.lastSyncAt),
988
+ reason: wbText(value.reason),
989
+ }
990
+ }
991
+
992
+ /** Normalize the shared-preset view. */
993
+ function wbShared(body) {
994
+ const value = body !== null && typeof body === 'object' ? body : {}
995
+ const rows = Array.isArray(value.sources) ? value.sources : []
996
+ return {
997
+ localRoot: wbText(value.localRoot),
998
+ sources: rows
999
+ .filter(function (row) { return row !== null && typeof row === 'object' })
1000
+ .map(function (row) {
1001
+ return {
1002
+ path: wbText(row.path),
1003
+ kind: wbText(row.kind) || 'extra',
1004
+ exists: row.exists === true,
1005
+ presets: (Array.isArray(row.presets) ? row.presets : [])
1006
+ .map(wbSharedPreset)
1007
+ .filter(function (preset) { return preset.id !== '' }),
1008
+ }
1009
+ }),
1010
+ }
1011
+ }
1012
+
1013
+ /** Human-readable shared preset status. */
1014
+ function wbSharedStatusText(status) {
1015
+ if (status === 'new') return '本地未安装'
1016
+ if (status === 'update') return '有更新'
1017
+ if (status === 'same') return '已同步'
1018
+ return '无法同步'
1019
+ }
1020
+
1021
+ /** Human-readable shared source kind. */
1022
+ function wbSharedKindText(kind) {
1023
+ if (kind === 'preset-repo') return '预设技能仓库'
1024
+ if (kind === 'global-repo') return '共享技能仓库'
1025
+ if (kind === 'skills-home') return '$DSH_HOME/skills'
1026
+ return '额外来源'
1027
+ }
1028
+
1029
+ /** Host URL for one utils-agents action. */
1030
+ function wbUrl(action, params) {
1031
+ const base = typeof document !== 'undefined' && typeof document.baseURI === 'string' && document.baseURI !== ''
1032
+ ? document.baseURI
1033
+ : 'http://localhost/'
1034
+ const url = new URL('api/dsh-utils/utils-agents/' + action, base)
1035
+ const values = params !== null && typeof params === 'object' ? params : {}
1036
+ Object.keys(values).forEach(function (key) {
1037
+ const value = values[key]
1038
+ if (typeof value === 'string' && value !== '') url.searchParams.set(key, value)
1039
+ })
1040
+ return url
1041
+ }
1042
+
1043
+ /** One Host request with prose errors. */
1044
+ async function wbRequest(action, options) {
1045
+ if (typeof fetch !== 'function') throw new Error('当前环境不支持网络请求。')
1046
+ const request = options !== null && typeof options === 'object' ? options : {}
1047
+ const url = wbUrl(action, request.params)
1048
+ const init = { headers: { accept: 'application/json' } }
1049
+ if (request.body !== undefined) {
1050
+ init.method = 'POST'
1051
+ init.headers['content-type'] = 'application/json'
1052
+ init.body = JSON.stringify(request.body)
1053
+ }
1054
+ let response
1055
+ try {
1056
+ response = await fetch(url.toString(), init)
1057
+ } catch (error) {
1058
+ throw new Error('无法连接宿主服务,请检查页面连接后重试。')
1059
+ }
1060
+ if (response.status === 401) throw new Error('登录状态已过期,请刷新页面后重试。')
1061
+ if (response.status === 404) {
1062
+ throw new Error('宿主还没有加载 utils-agents 组件(HTTP 404)。请重启 dsh web;如果已重启,请在插件页确认 utils-agents 行已启用。')
1063
+ }
1064
+ let body = null
1065
+ try {
1066
+ body = await response.json()
1067
+ } catch (error) {
1068
+ body = null
1069
+ }
1070
+ if (!response.ok) {
1071
+ const detail = body !== null && typeof body === 'object' && typeof body.error === 'string' ? body.error : ''
1072
+ const failure = new Error('utils-agents 请求失败(HTTP ' + response.status + ')' + (detail === '' ? '' : ':' + detail))
1073
+ failure.status = response.status
1074
+ throw failure
1075
+ }
1076
+ if (body === null || typeof body !== 'object') throw new Error('utils-agents 返回了无法解析的数据。')
1077
+ return body
1078
+ }
1079
+
1080
+ /** Whether one file has an unsaved draft. */
1081
+ function wbDirty(drafts, baseline, id) {
1082
+ if (!Object.prototype.hasOwnProperty.call(drafts, id)) return false
1083
+ if (!Object.prototype.hasOwnProperty.call(baseline, id)) return false
1084
+ return drafts[id] !== baseline[id]
1085
+ }
1086
+
1087
+ /** Human-readable last sync. */
1088
+ function wbSyncText(record) {
1089
+ if (record === null || typeof record !== 'object') return '尚未同步'
1090
+ const commit = wbText(record.commit)
1091
+ const parts = [
1092
+ wbText(record.at) || '未知时间',
1093
+ record.ok === true ? '成功' : '失败',
1094
+ 'commit ' + (commit === '' ? '-' : commit.slice(0, 7)),
1095
+ '技能 ' + (typeof record.skills === 'number' ? record.skills : 0),
1096
+ ]
1097
+ if (wbText(record.message) !== '') parts.push(wbText(record.message))
1098
+ return parts.join(' · ')
1099
+ }
1100
+
1101
+ /** The unified utils-agents panel. */
1102
+ function AgentsPanel({ sessionId }) {
1103
+ const [status, setStatus] = React.useState('loading')
1104
+ const [data, setData] = React.useState(null)
1105
+ const [selectedId, setSelectedId] = React.useState('')
1106
+ const [view, setView] = React.useState('skills')
1107
+ const [files, setFiles] = React.useState([])
1108
+ const [filesState, setFilesState] = React.useState('idle')
1109
+ const [selectedFileId, setSelectedFileId] = React.useState('')
1110
+ const [drafts, setDrafts] = React.useState({})
1111
+ const [baseline, setBaseline] = React.useState({})
1112
+ const [readState, setReadState] = React.useState('idle')
1113
+ const [saving, setSaving] = React.useState(false)
1114
+ const [repo, setRepo] = React.useState(null)
1115
+ const [repoState, setRepoState] = React.useState('idle')
1116
+ const [repoDraft, setRepoDraft] = React.useState(null)
1117
+ const [shared, setShared] = React.useState(null)
1118
+ const [sharedState, setSharedState] = React.useState('idle')
1119
+ const [sharedKey, setSharedKey] = React.useState(0)
1120
+ const [pruneShared, setPruneShared] = React.useState(false)
1121
+ const [sharedRepo, setSharedRepo] = React.useState(null)
1122
+ const [sharedRepoState, setSharedRepoState] = React.useState('idle')
1123
+ const [sharedRepoDraft, setSharedRepoDraft] = React.useState(null)
1124
+ const [sharedRepoKeyDraft, setSharedRepoKeyDraft] = React.useState('')
1125
+ const [nativeView, setNativeView] = React.useState(null)
1126
+ const [publishMessage, setPublishMessage] = React.useState('presets: sync from dsh-utils')
1127
+ const [publishPush, setPublishPush] = React.useState(true)
1128
+ const [keyDraft, setKeyDraft] = React.useState('')
1129
+ const [deployKey, setDeployKey] = React.useState(null)
1130
+ const [deployKeyState, setDeployKeyState] = React.useState('loading')
1131
+ const [deployKeyDraft, setDeployKeyDraft] = React.useState('')
1132
+ const [update, setUpdate] = React.useState(null)
1133
+ const [updateState, setUpdateState] = React.useState('loading')
1134
+ const [busy, setBusy] = React.useState('')
1135
+ const [error, setError] = React.useState('')
1136
+ const [notice, setNotice] = React.useState('')
1137
+ const [reloadKey, setReloadKey] = React.useState(0)
1138
+ const [filesKey, setFilesKey] = React.useState(0)
1139
+
1140
+ React.useEffect(function () {
1141
+ let cancelled = false
1142
+ setStatus('loading')
1143
+ setError('')
1144
+ wbRequest('list', { params: { sessionId: sessionId } }).then(function (body) {
1145
+ if (cancelled) return
1146
+ const presets = wbPresets(body)
1147
+ setData({
1148
+ presets: presets,
1149
+ global: body.global !== null && typeof body.global === 'object' ? body.global : null,
1150
+ cwd: wbText(body.cwd),
1151
+ sessionPreset: wbText(body.sessionPreset),
1152
+ defaultPresetId: wbText(body.defaultPresetId),
1153
+ })
1154
+ setStatus('ready')
1155
+ setSelectedId(function (current) {
1156
+ if (current === GLOBAL_PRESET || presets.some(function (preset) { return preset.id === current })) return current
1157
+ const preferred = wbText(body.defaultPresetId)
1158
+ if (preferred === GLOBAL_PRESET || presets.some(function (preset) { return preset.id === preferred })) return preferred
1159
+ return presets[0] !== undefined ? presets[0].id : GLOBAL_PRESET
1160
+ })
1161
+ }).catch(function (failure) {
1162
+ if (cancelled) return
1163
+ setStatus('error')
1164
+ setData(null)
1165
+ setError(messageOf(failure))
1166
+ })
1167
+ return function () { cancelled = true }
1168
+ }, [sessionId, reloadKey])
1169
+
1170
+ React.useEffect(function () {
1171
+ if (selectedId === '') return undefined
1172
+ let cancelled = false
1173
+ setFiles([])
1174
+ setSelectedFileId('')
1175
+ setFilesState('loading')
1176
+ wbRequest('files', { params: { presetId: selectedId, sessionId: sessionId } }).then(function (body) {
1177
+ if (cancelled) return
1178
+ const rows = wbFiles(body)
1179
+ setFiles(rows)
1180
+ setFilesState('ready')
1181
+ setSelectedFileId(function (current) {
1182
+ if (current !== '' && rows.some(function (file) { return file.id === current })) return current
1183
+ return rows[0] !== undefined ? rows[0].id : ''
1184
+ })
1185
+ }).catch(function (failure) {
1186
+ if (cancelled) return
1187
+ setFiles([])
1188
+ setFilesState('error')
1189
+ setError(messageOf(failure))
1190
+ })
1191
+ return function () { cancelled = true }
1192
+ }, [selectedId, sessionId, filesKey, reloadKey])
1193
+
1194
+ React.useEffect(function () {
1195
+ if (selectedId === '' || selectedId === GLOBAL_PRESET) {
1196
+ setRepo(null)
1197
+ setRepoDraft(null)
1198
+ setRepoState('idle')
1199
+ return undefined
1200
+ }
1201
+ let cancelled = false
1202
+ setRepoState('loading')
1203
+ wbRequest('repo', { params: { presetId: selectedId } }).then(function (body) {
1204
+ if (cancelled) return
1205
+ const normalized = wbRepo(body)
1206
+ setRepo(normalized)
1207
+ setRepoDraft(wbRepoDraft(normalized))
1208
+ setRepoState('ready')
1209
+ }).catch(function (failure) {
1210
+ if (cancelled) return
1211
+ setRepoState('error')
1212
+ setRepo(null)
1213
+ setRepoDraft(null)
1214
+ setError(messageOf(failure))
1215
+ })
1216
+ return function () { cancelled = true }
1217
+ }, [selectedId, reloadKey])
1218
+
1219
+ React.useEffect(function () {
1220
+ if (selectedId === '' || selectedId === GLOBAL_PRESET) {
1221
+ setShared(null)
1222
+ setSharedState('idle')
1223
+ return undefined
1224
+ }
1225
+ let cancelled = false
1226
+ setSharedState('loading')
1227
+ wbRequest('shared', { params: { presetId: selectedId } }).then(function (body) {
1228
+ if (cancelled) return
1229
+ setShared(wbShared(body))
1230
+ setSharedState('ready')
1231
+ }).catch(function (failure) {
1232
+ if (cancelled) return
1233
+ setShared(null)
1234
+ setSharedState('error')
1235
+ setError(messageOf(failure))
1236
+ })
1237
+ return function () { cancelled = true }
1238
+ }, [selectedId, sharedKey, reloadKey])
1239
+
1240
+ React.useEffect(function () {
1241
+ if (selectedId === '' || selectedId === GLOBAL_PRESET) {
1242
+ setSharedRepo(null)
1243
+ setSharedRepoDraft(null)
1244
+ setSharedRepoState('idle')
1245
+ return undefined
1246
+ }
1247
+ let cancelled = false
1248
+ setSharedRepoState('loading')
1249
+ wbRequest('shared-repo', {}).then(function (body) {
1250
+ if (cancelled) return
1251
+ const view = wbSharedRepo(body)
1252
+ setSharedRepo(view)
1253
+ setSharedRepoDraft(wbSharedRepoDraft(view))
1254
+ setSharedRepoState('ready')
1255
+ }).catch(function (failure) {
1256
+ if (cancelled) return
1257
+ setSharedRepo(null)
1258
+ setSharedRepoDraft(null)
1259
+ setSharedRepoState('error')
1260
+ setError(messageOf(failure))
1261
+ })
1262
+ return function () { cancelled = true }
1263
+ }, [selectedId, sharedKey, reloadKey])
1264
+
1265
+ React.useEffect(function () {
1266
+ if (selectedId === '' || selectedId === GLOBAL_PRESET) {
1267
+ setNativeView(null)
1268
+ return undefined
1269
+ }
1270
+ let cancelled = false
1271
+ wbRequest('native-presets', {}).then(function (body) {
1272
+ if (!cancelled) setNativeView(wbNative(body))
1273
+ }).catch(function () {
1274
+ if (!cancelled) setNativeView(null)
1275
+ })
1276
+ return function () { cancelled = true }
1277
+ }, [selectedId, sharedKey, reloadKey])
1278
+
1279
+ React.useEffect(function () {
1280
+ let cancelled = false
1281
+ setDeployKeyState('loading')
1282
+ wbRequest('deploy-key', {}).then(function (body) {
1283
+ if (cancelled) return
1284
+ setDeployKey(wbKeyStatus(body.key))
1285
+ setDeployKeyState('ready')
1286
+ }).catch(function () {
1287
+ if (cancelled) return
1288
+ setDeployKey(null)
1289
+ setDeployKeyState('unsupported')
1290
+ })
1291
+ return function () { cancelled = true }
1292
+ }, [reloadKey])
1293
+
1294
+ React.useEffect(function () {
1295
+ let cancelled = false
1296
+ setUpdateState('loading')
1297
+ wbRequest('update', {}).then(function (body) {
1298
+ if (cancelled) return
1299
+ setUpdate(wbUpdate(body.update))
1300
+ setUpdateState('ready')
1301
+ }).catch(function () {
1302
+ if (cancelled) return
1303
+ setUpdate(null)
1304
+ setUpdateState('unsupported')
1305
+ })
1306
+ return function () { cancelled = true }
1307
+ }, [reloadKey])
1308
+
1309
+ // While a background install runs, refresh the answer a few times so the
1310
+ // panel can report "installed, restart to apply" without a manual reload.
1311
+ React.useEffect(function () {
1312
+ if (update === null || update.install.phase !== 'installing') return undefined
1313
+ let cancelled = false
1314
+ let timer = null
1315
+ let attempts = 0
1316
+ const poll = async function () {
1317
+ if (cancelled || attempts >= 40) return
1318
+ attempts += 1
1319
+ try {
1320
+ const body = await wbRequest('update', {})
1321
+ if (cancelled) return
1322
+ const next = wbUpdate(body.update)
1323
+ setUpdate(next)
1324
+ if (next.install.phase !== 'installing') return
1325
+ } catch {
1326
+ // Keep the current sentence; the next attempt may still answer.
1327
+ }
1328
+ if (!cancelled) timer = setTimeout(poll, 3000)
1329
+ }
1330
+ timer = setTimeout(poll, 3000)
1331
+ return function () {
1332
+ cancelled = true
1333
+ if (timer !== null) clearTimeout(timer)
1334
+ }
1335
+ }, [update === null ? 'none' : update.install.phase])
1336
+
1337
+ React.useEffect(function () {
1338
+ if (selectedFileId === '') {
1339
+ setReadState('idle')
1340
+ return undefined
1341
+ }
1342
+ let cancelled = false
1343
+ setReadState('reading')
1344
+ wbRequest('file', { params: { id: selectedFileId, sessionId: sessionId } }).then(function (body) {
1345
+ if (cancelled) return
1346
+ const content = typeof body.content === 'string' ? body.content : ''
1347
+ setBaseline(function (previous) {
1348
+ const next = Object.assign({}, previous)
1349
+ next[selectedFileId] = content
1350
+ return next
1351
+ })
1352
+ setDrafts(function (previous) {
1353
+ if (Object.prototype.hasOwnProperty.call(previous, selectedFileId)) return previous
1354
+ const next = Object.assign({}, previous)
1355
+ next[selectedFileId] = content
1356
+ return next
1357
+ })
1358
+ const nextFile = wbFile(body.file, null)
1359
+ if (nextFile.id !== '') {
1360
+ setFiles(function (previous) {
1361
+ return previous.map(function (file) { return file.id === selectedFileId ? nextFile : file })
1362
+ })
1363
+ }
1364
+ setReadState('ready')
1365
+ }).catch(function (failure) {
1366
+ if (cancelled) return
1367
+ setReadState('error')
1368
+ setError(messageOf(failure))
1369
+ })
1370
+ return function () { cancelled = true }
1371
+ }, [selectedFileId, sessionId, reloadKey])
1372
+
1373
+ const presets = data !== null && Array.isArray(data.presets) ? data.presets : []
1374
+ const isGlobal = selectedId === GLOBAL_PRESET
1375
+ const preset = isGlobal ? null : presets.find(function (item) { return item.id === selectedId }) || null
1376
+ const currentFile = files.find(function (file) { return file.id === selectedFileId }) || null
1377
+ const baselineText = Object.prototype.hasOwnProperty.call(baseline, selectedFileId) ? baseline[selectedFileId] : ''
1378
+ const draftText = Object.prototype.hasOwnProperty.call(drafts, selectedFileId) ? drafts[selectedFileId] : baselineText
1379
+ const dirty = readState === 'ready' && draftText !== baselineText
1380
+ const editable = currentFile !== null && currentFile.editable && readState === 'ready'
1381
+ const targetName = isGlobal ? '全局 / 项目' : preset !== null ? preset.name : selectedId
1382
+ const presetStatus = isGlobal || preset === null
1383
+ ? ''
1384
+ : preset.broken !== '' ? ' · 加载失败'
1385
+ : preset.registered ? ' · 已注册到 DSH'
1386
+ : ' · 未注册到 DSH'
1387
+ const sessionPreset = data !== null ? wbText(data.sessionPreset) : ''
1388
+ const sessionNote = sessionPreset === ''
1389
+ ? ''
1390
+ : sessionPreset === selectedId
1391
+ ? ' · 当前会话预设'
1392
+ : presets.some(function (item) { return item.id === sessionPreset }) ? '' : ' · 当前会话预设 ' + sessionPreset + ' 不是目录式预设'
1393
+ const skills = preset !== null ? preset.skills : []
1394
+ const enabledSkills = skills.filter(function (skill) { return skill.enabled }).length
1395
+
1396
+ const refresh = function () {
1397
+ setError('')
1398
+ setNotice('')
1399
+ setReloadKey(function (key) { return key + 1 })
1400
+ }
1401
+
1402
+ const selectPreset = function (id) {
1403
+ setSelectedId(id)
1404
+ setView(id === GLOBAL_PRESET ? 'markdown' : 'skills')
1405
+ setKeyDraft('')
1406
+ setError('')
1407
+ setNotice('')
1408
+ }
1409
+
1410
+ const openFile = function (id) {
1411
+ setView('markdown')
1412
+ setSelectedFileId(id)
1413
+ setError('')
1414
+ setNotice('')
1415
+ }
1416
+
1417
+ const updateDraft = function (value) {
1418
+ setDrafts(function (previous) {
1419
+ const next = Object.assign({}, previous)
1420
+ next[selectedFileId] = value
1421
+ return next
1422
+ })
1423
+ setNotice('')
1424
+ }
1425
+
1426
+ const save = async function () {
1427
+ if (currentFile === null || saving || readState !== 'ready' || !currentFile.editable) return
1428
+ setSaving(true)
1429
+ setError('')
1430
+ setNotice('')
1431
+ try {
1432
+ const result = await wbRequest('file', {
1433
+ body: {
1434
+ sessionId: sessionId,
1435
+ id: selectedFileId,
1436
+ content: draftText,
1437
+ baseMtimeMs: currentFile.exists ? currentFile.mtimeMs : null,
1438
+ },
1439
+ })
1440
+ const nextContent = draftText
1441
+ setBaseline(function (previous) {
1442
+ const next = Object.assign({}, previous)
1443
+ next[selectedFileId] = nextContent
1444
+ return next
1445
+ })
1446
+ const nextFile = wbFile(result.file, currentFile)
1447
+ if (nextFile.id !== '') {
1448
+ setFiles(function (previous) {
1449
+ return previous.map(function (file) { return file.id === selectedFileId ? nextFile : file })
1450
+ })
1451
+ }
1452
+ setNotice('已保存 · ' + new Date().toLocaleTimeString())
1453
+ } catch (failure) {
1454
+ setError(messageOf(failure))
1455
+ } finally {
1456
+ setSaving(false)
1457
+ }
1458
+ }
1459
+
1460
+ const reset = function () {
1461
+ if (!dirty) return
1462
+ setDrafts(function (previous) {
1463
+ const next = Object.assign({}, previous)
1464
+ next[selectedFileId] = baselineText
1465
+ return next
1466
+ })
1467
+ setNotice('')
1468
+ }
1469
+
1470
+ const toggleSkill = async function (skill) {
1471
+ if (busy !== '' || preset === null) return
1472
+ setBusy('skill:' + skill.path)
1473
+ setError('')
1474
+ setNotice('')
1475
+ try {
1476
+ const result = await wbRequest('skill', {
1477
+ body: { presetId: preset.id, path: skill.path, enabled: !skill.enabled },
1478
+ })
1479
+ const updated = wbSkill(result.skill)
1480
+ setData(function (previous) {
1481
+ if (previous === null) return previous
1482
+ return {
1483
+ ...previous,
1484
+ presets: previous.presets.map(function (item) {
1485
+ if (item.id !== preset.id) return item
1486
+ return {
1487
+ ...item,
1488
+ skills: item.skills.map(function (candidate) {
1489
+ return candidate.path === skill.path ? updated : candidate
1490
+ }),
1491
+ }
1492
+ }),
1493
+ }
1494
+ })
1495
+ setNotice(updated.enabled ? '已启用 ' + updated.name : '已关闭 ' + updated.name)
1496
+ setFilesKey(function (key) { return key + 1 })
1497
+ } catch (failure) {
1498
+ setError(messageOf(failure))
1499
+ } finally {
1500
+ setBusy('')
1501
+ }
1502
+ }
1503
+
1504
+ const openSkill = function (skill) {
1505
+ const found = files.find(function (file) { return file.label === skill.path })
1506
+ if (found !== undefined) {
1507
+ openFile(found.id)
1508
+ return
1509
+ }
1510
+ setView('markdown')
1511
+ setNotice('文件列表还没有这个技能,点“刷新”后再试。')
1512
+ }
1513
+
1514
+ const setRepoField = function (key, value) {
1515
+ setRepoDraft(function (previous) {
1516
+ if (previous === null) return previous
1517
+ const next = Object.assign({}, previous)
1518
+ next[key] = value
1519
+ return next
1520
+ })
1521
+ }
1522
+
1523
+ const saveRepo = async function () {
1524
+ if (preset === null || repoDraft === null || busy !== '') return
1525
+ setBusy('repo')
1526
+ setError('')
1527
+ setNotice('')
1528
+ try {
1529
+ const result = await wbRequest('repo', {
1530
+ body: {
1531
+ presetId: preset.id,
1532
+ repoUrl: repoDraft.repoUrl,
1533
+ branch: repoDraft.branch,
1534
+ targetSubdir: repoDraft.targetSubdir,
1535
+ keyPath: repoDraft.keyPath,
1536
+ recurseSubmodules: repoDraft.recurseSubmodules,
1537
+ },
1538
+ })
1539
+ const normalized = wbRepo(result)
1540
+ setRepo(normalized)
1541
+ setRepoDraft(wbRepoDraft(normalized))
1542
+ setNotice('仓库设置已保存')
1543
+ } catch (failure) {
1544
+ setError(messageOf(failure))
1545
+ } finally {
1546
+ setBusy('')
1547
+ }
1548
+ }
1549
+
1550
+ const saveKey = async function (clear) {
1551
+ if (preset === null || busy !== '') return
1552
+ setBusy('key')
1553
+ setError('')
1554
+ setNotice('')
1555
+ try {
1556
+ const result = await wbRequest('key', {
1557
+ body: { presetId: preset.id, key: clear ? '' : keyDraft },
1558
+ })
1559
+ setKeyDraft('')
1560
+ setRepo(function (previous) {
1561
+ return previous === null ? previous : { ...previous, key: result.key }
1562
+ })
1563
+ setNotice(clear || result.key.source !== 'stored' ? 'Deploy Key 已清除' : 'Deploy Key 已保存')
1564
+ } catch (failure) {
1565
+ setError(messageOf(failure))
1566
+ } finally {
1567
+ setBusy('')
1568
+ }
1569
+ }
1570
+
1571
+ const saveDeployKey = async function (clear) {
1572
+ if (busy !== '') return
1573
+ setBusy('deploy-key')
1574
+ setError('')
1575
+ setNotice('')
1576
+ try {
1577
+ const result = await wbRequest('deploy-key', { body: { key: clear ? '' : deployKeyDraft } })
1578
+ setDeployKey(wbKeyStatus(result.key))
1579
+ setDeployKeyDraft('')
1580
+ setNotice(clear ? '已清除通用 Deploy Key。' : '已保存通用 Deploy Key。')
1581
+ } catch (failure) {
1582
+ setError(messageOf(failure))
1583
+ } finally {
1584
+ setBusy('')
1585
+ }
1586
+ }
1587
+
1588
+ const checkUpdate = async function () {
1589
+ if (busy !== '') return
1590
+ setBusy('update')
1591
+ setError('')
1592
+ try {
1593
+ const body = await wbRequest('update', { body: {} })
1594
+ setUpdate(wbUpdate(body.update))
1595
+ setUpdateState('ready')
1596
+ } catch (failure) {
1597
+ setError(messageOf(failure))
1598
+ } finally {
1599
+ setBusy('')
1600
+ }
1601
+ }
1602
+
1603
+ const syncNow = async function () {
1604
+ if (preset === null || busy !== '') return
1605
+ setBusy('sync')
1606
+ setError('')
1607
+ setNotice('')
1608
+ try {
1609
+ const result = await wbRequest('sync', { body: { presetId: preset.id } })
1610
+ const normalized = wbRepo(result)
1611
+ setRepo(normalized)
1612
+ setRepoDraft(wbRepoDraft(normalized))
1613
+ setNotice('同步完成:' + wbSyncText(normalized.state.lastSync))
1614
+ setReloadKey(function (key) { return key + 1 })
1615
+ } catch (failure) {
1616
+ setError(messageOf(failure))
1617
+ } finally {
1618
+ setBusy('')
1619
+ }
1620
+ }
1621
+
1622
+ const syncShared = async function (ids) {
1623
+ if (preset === null || busy !== '') return
1624
+ setBusy('shared')
1625
+ setError('')
1626
+ setNotice('')
1627
+ try {
1628
+ const result = await wbRequest('shared-sync', {
1629
+ body: { presetId: preset.id, ids: ids === null ? [] : ids, prune: pruneShared },
1630
+ })
1631
+ setShared(wbShared(result.view))
1632
+ const rows = Array.isArray(result.results) ? result.results : []
1633
+ let written = 0
1634
+ let removed = 0
1635
+ const failed = []
1636
+ rows.forEach(function (row) {
1637
+ const value = row !== null && typeof row === 'object' ? row : {}
1638
+ written += typeof value.written === 'number' ? value.written : 0
1639
+ removed += typeof value.removed === 'number' ? value.removed : 0
1640
+ if (typeof value.error === 'string' && value.error !== '') failed.push(wbText(value.id) + ':' + value.error)
1641
+ })
1642
+ if (failed.length > 0) setError('部分预设同步失败:' + failed.join(';'))
1643
+ else setNotice('预设同步完成:写入 ' + written + ' 个文件' + (removed > 0 ? ',删除 ' + removed + ' 个' : ''))
1644
+ setReloadKey(function (key) { return key + 1 })
1645
+ setSharedKey(function (key) { return key + 1 })
1646
+ } catch (failure) {
1647
+ setError(messageOf(failure))
1648
+ } finally {
1649
+ setBusy('')
1650
+ }
1651
+ }
1652
+
1653
+ const setSharedRepoField = function (key, value) {
1654
+ setSharedRepoDraft(function (previous) {
1655
+ if (previous === null) return previous
1656
+ const next = Object.assign({}, previous)
1657
+ next[key] = value
1658
+ return next
1659
+ })
1660
+ }
1661
+
1662
+ const applySharedRepo = function (body) {
1663
+ const view = wbSharedRepo(body)
1664
+ setSharedRepo(view)
1665
+ setSharedRepoDraft(wbSharedRepoDraft(view))
1666
+ return view
1667
+ }
1668
+
1669
+ const saveSharedRepo = async function () {
1670
+ if (sharedRepoDraft === null || busy !== '') return
1671
+ setBusy('shared-repo')
1672
+ setError('')
1673
+ setNotice('')
1674
+ try {
1675
+ const result = await wbRequest('shared-repo', {
1676
+ body: {
1677
+ repoUrl: sharedRepoDraft.repoUrl,
1678
+ branch: sharedRepoDraft.branch,
1679
+ targetDir: sharedRepoDraft.targetDir,
1680
+ keyPath: sharedRepoDraft.keyPath,
1681
+ recurseSubmodules: sharedRepoDraft.recurseSubmodules,
1682
+ },
1683
+ })
1684
+ applySharedRepo(result)
1685
+ setNotice('共享技能仓库设置已保存')
1686
+ } catch (failure) {
1687
+ setError(messageOf(failure))
1688
+ } finally {
1689
+ setBusy('')
1690
+ }
1691
+ }
1692
+
1693
+ const saveSharedRepoKey = async function (clear) {
1694
+ if (busy !== '') return
1695
+ setBusy('shared-key')
1696
+ setError('')
1697
+ setNotice('')
1698
+ try {
1699
+ const result = await wbRequest('shared-key', { body: { key: clear ? '' : sharedRepoKeyDraft } })
1700
+ setSharedRepoKeyDraft('')
1701
+ const view = applySharedRepo(result)
1702
+ setNotice(clear || view.key.source !== 'stored' ? '共享仓库 Deploy Key 已清除' : '共享仓库 Deploy Key 已保存')
1703
+ } catch (failure) {
1704
+ setError(messageOf(failure))
1705
+ } finally {
1706
+ setBusy('')
1707
+ }
1708
+ }
1709
+
1710
+ const pullSharedRepo = async function () {
1711
+ if (busy !== '') return
1712
+ setBusy('shared-pull')
1713
+ setError('')
1714
+ setNotice('')
1715
+ try {
1716
+ const view = applySharedRepo(await wbRequest('shared-pull', { body: {} }))
1717
+ setNotice('共享技能仓库拉取完成:' + wbSyncText(view.state.lastSync))
1718
+ setReloadKey(function (key) { return key + 1 })
1719
+ setSharedKey(function (key) { return key + 1 })
1720
+ } catch (failure) {
1721
+ setError(messageOf(failure))
1722
+ } finally {
1723
+ setBusy('')
1724
+ }
1725
+ }
1726
+
1727
+ const importNative = async function (ids) {
1728
+ if (busy !== '') return
1729
+ setBusy('native')
1730
+ setError('')
1731
+ setNotice('')
1732
+ try {
1733
+ const result = await wbRequest('native-presets-import', { body: { ids: ids === null ? [] : ids } })
1734
+ setNativeView(wbNative(result.view))
1735
+ const rows = Array.isArray(result.results) ? result.results : []
1736
+ const imported = rows.filter(function (row) { return row.status === 'imported' }).length
1737
+ const existed = rows.filter(function (row) { return row.status === 'exists' }).length
1738
+ const failed = rows.filter(function (row) { return row.status === 'error' })
1739
+ if (failed.length > 0) setError('部分预设导入失败:' + failed.map(function (row) { return row.id + ':' + row.error }).join(';'))
1740
+ else setNotice('导入完成:新导入 ' + imported + ' 个' + (existed > 0 ? ',已存在 ' + existed + ' 个' : ''))
1741
+ setReloadKey(function (key) { return key + 1 })
1742
+ setSharedKey(function (key) { return key + 1 })
1743
+ } catch (failure) {
1744
+ setError(messageOf(failure))
1745
+ } finally {
1746
+ setBusy('')
1747
+ }
1748
+ }
1749
+
1750
+ const publishPresets = async function () {
1751
+ if (busy !== '') return
1752
+ setBusy('publish')
1753
+ setError('')
1754
+ setNotice('')
1755
+ try {
1756
+ const result = await wbRequest('presets-publish', { body: { message: publishMessage, push: publishPush } })
1757
+ const ids = Array.isArray(result.results) ? result.results.map(function (row) { return row.id }) : []
1758
+ const commit = wbText(result.commit)
1759
+ setNotice('发布完成:' + ids.length + ' 个预设' + (commit === '' ? ',没有变更' : ',commit ' + commit.slice(0, 7)) + (result.pushed === true ? ',已推送' : ''))
1760
+ setSharedKey(function (key) { return key + 1 })
1761
+ } catch (failure) {
1762
+ setError(messageOf(failure))
1763
+ } finally {
1764
+ setBusy('')
1765
+ }
1766
+ }
1767
+
1768
+ const children = [
1769
+ h('div', { className: 'dswb-head', key: 'head' }, [
1770
+ h('h3', { className: 'dswb-title', key: 'title' }, 'utils-agents'),
1771
+ data !== null ? h('span', { className: 'dswb-count', key: 'count' }, presets.length + ' 个预设') : null,
1772
+ h('button', {
1773
+ className: 'dswb-refresh', key: 'refresh', type: 'button',
1774
+ disabled: status === 'loading', onClick: refresh,
1775
+ }, status === 'loading' ? '读取中…' : '刷新'),
1776
+ ]),
1777
+ ]
1778
+
1779
+ if (updateState !== 'unsupported') {
1780
+ const updateLabel = updateState === 'loading' ? '读取中…' : wbUpdateText(update)
1781
+ children.push(h('div', { className: 'dswb-update', key: 'update' }, [
1782
+ update === null ? null : h('span', { className: 'dswb-badge', key: 'current' }, 'v' + update.current),
1783
+ update === null ? null : h('span', { className: 'dswb-badge', key: 'source' }, wbSourceLabel(update)),
1784
+ update !== null && update.updateAvailable
1785
+ ? h('span', { className: 'dswb-badge dswb-badgeOn', key: 'latest' }, '有新版本 ' + update.latest)
1786
+ : null,
1787
+ h('button', {
1788
+ className: 'dswb-linkBtn', key: 'check', type: 'button',
1789
+ disabled: busy !== '' || updateState === 'loading' || (update !== null && update.install.phase === 'installing'), onClick: checkUpdate,
1790
+ }, busy === 'update' ? '检查中…' : '检查更新'),
1791
+ h('span', {
1792
+ className: 'dswb-status', key: 'state',
1793
+ title: update === null ? undefined : update.error !== null ? update.error : '来源:' + (update.origin || '未知'),
1794
+ }, updateLabel),
1795
+ ]))
1796
+ }
1797
+
1798
+ if (status === 'loading') {
1799
+ children.push(h('p', { className: 'dswb-note', key: 'loading' }, '正在读取预设…'))
1800
+ } else if (status === 'error') {
1801
+ children.push(h('div', { className: 'dswb-empty', key: 'listError' }, [
1802
+ h('p', { className: 'dswb-error', key: 'error', role: 'alert' }, error),
1803
+ h('button', { className: 'dswb-refresh', key: 'retry', type: 'button', onClick: refresh }, '重试'),
1804
+ ]))
1805
+ } else if (data !== null) {
1806
+ const options = presets.map(function (item) {
1807
+ return h('option', { key: item.id, value: item.id }, item.name + '(' + item.id + ')')
1808
+ })
1809
+ options.push(h('option', { key: GLOBAL_PRESET, value: GLOBAL_PRESET }, '全局 / 项目 AGENTS.md'))
1810
+ children.push(h('div', { className: 'dswb-presetBar', key: 'presetBar' }, [
1811
+ h('select', {
1812
+ className: 'dswb-select', key: 'select', value: selectedId,
1813
+ 'aria-label': '选择预设', onChange: function (event) { selectPreset(event.target.value) },
1814
+ }, options),
1815
+ ]))
1816
+ const selectedPath = isGlobal ? data.cwd : preset !== null ? preset.path : ''
1817
+ children.push(h('div', { className: 'dswb-paths', key: 'paths' }, [
1818
+ h('p', { className: 'dswb-note', key: 'target' }, targetName + presetStatus + sessionNote),
1819
+ selectedPath === '' ? null : h('p', { className: 'dswb-note', key: 'path', title: selectedPath }, selectedPath),
1820
+ isGlobal || preset === null || preset.broken === '' ? null : h('p', { className: 'dswb-error', key: 'broken', role: 'alert' }, preset.broken),
1821
+ ]))
1822
+
1823
+ if (!isGlobal && preset !== null) {
1824
+ const sharedCount = shared === null ? 0 : shared.sources.reduce(function (total, source) {
1825
+ return total + source.presets.filter(function (item) { return item.status !== 'same' }).length
1826
+ }, 0)
1827
+ const tabs = [
1828
+ ['skills', '技能 · ' + enabledSkills + '/' + skills.length],
1829
+ ['markdown', 'Markdown'],
1830
+ ['repo', '技能仓库'],
1831
+ ['shared', '预设同步' + (sharedCount > 0 ? ' · ' + sharedCount : '')],
1832
+ ]
1833
+ children.push(h('div', { className: 'dswb-tabs', key: 'tabs' }, tabs.map(function (tab) {
1834
+ return h('button', {
1835
+ key: tab[0], type: 'button',
1836
+ className: 'dswb-tab' + (view === tab[0] ? ' dswb-tabActive' : ''),
1837
+ onClick: function () { setView(tab[0]); setError(''); setNotice('') },
1838
+ }, tab[1])
1839
+ })))
1840
+ }
1841
+
1842
+ const body = []
1843
+ if (isGlobal || view === 'markdown') {
1844
+ if (filesState === 'loading') {
1845
+ body.push(h('p', { className: 'dswb-note', key: 'filesLoading' }, '正在读取 Markdown 文件…'))
1846
+ } else if (files.length === 0) {
1847
+ body.push(h('p', { className: 'dswb-note', key: 'filesEmpty' }, '这个目标下没有 Markdown 文件。'))
1848
+ } else {
1849
+ body.push(h('select', {
1850
+ className: 'dswb-select', key: 'fileSelect', value: selectedFileId,
1851
+ 'aria-label': '选择 Markdown 文件', onChange: function (event) { openFile(event.target.value) },
1852
+ }, files.map(function (file) {
1853
+ return h('option', { key: file.id, value: file.id }, file.label + (file.exists ? '' : '(未创建)'))
1854
+ })))
1855
+ if (currentFile !== null) {
1856
+ body.push(h('div', { className: 'dswb-fileBar', key: 'fileBar' }, [
1857
+ h('span', { className: 'dswb-filePath', key: 'path', title: currentFile.path }, currentFile.path),
1858
+ currentFile.exists ? null : h('span', { className: 'dswb-badge', key: 'new' }, '新文件'),
1859
+ currentFile.editable ? null : h('span', { className: 'dswb-badge', key: 'readonly' }, '不可写'),
1860
+ wbDirty(drafts, baseline, selectedFileId) ? h('span', { className: 'dswb-badge dswb-badgeOn', key: 'dirty' }, '未保存') : null,
1861
+ ]))
1862
+ body.push(h('textarea', {
1863
+ className: 'dswb-editor', key: 'editor',
1864
+ value: readState === 'ready' ? draftText : '',
1865
+ disabled: !editable,
1866
+ spellCheck: false,
1867
+ placeholder: currentFile.editable ? '在此编辑 Markdown;Ctrl/Cmd+S 保存。' : '这个文件不可编辑。',
1868
+ onChange: function (event) { updateDraft(event.target.value) },
1869
+ onKeyDown: function (event) {
1870
+ if ((event.metaKey || event.ctrlKey) && String(event.key).toLowerCase() === 's') {
1871
+ event.preventDefault()
1872
+ save()
1873
+ }
1874
+ },
1875
+ }))
1876
+ body.push(h('div', { className: 'dswb-actions', key: 'addActions' }, [
1877
+ h('button', {
1878
+ className: 'dswb-btn dswb-primary', key: 'save', type: 'button',
1879
+ disabled: !dirty || !editable || saving, onClick: save,
1880
+ }, saving ? '保存中…' : '保存'),
1881
+ h('button', { className: 'dswb-btn', key: 'reset', type: 'button', disabled: !dirty, onClick: reset }, '还原'),
1882
+ h('button', { className: 'dswb-btn', key: 'reload', type: 'button', disabled: readState === 'reading', onClick: refresh }, '重读'),
1883
+ h('span', { className: 'dswb-status', key: 'status' }, readState === 'reading' ? '读取中…' : dirty ? '有未保存修改' : '已同步'),
1884
+ ]))
1885
+ }
1886
+ }
1887
+ } else if (view === 'skills') {
1888
+ if (skills.length === 0) {
1889
+ body.push(h('div', { className: 'dswb-empty', key: 'skillsEmpty' }, [
1890
+ h('p', { className: 'dswb-note', key: 'empty' }, '这个预设还没有技能。'),
1891
+ h('p', { className: 'dswb-note', key: 'hint' }, '去“技能仓库”把仓库拉进 skills/,或手动放入 SKILL.md。'),
1892
+ h('button', { className: 'dswb-btn', key: 'goRepo', type: 'button', onClick: function () { setView('repo') } }, '去技能仓库'),
1893
+ ]))
1894
+ } else {
1895
+ body.push(h('div', { className: 'dswb-list', key: 'skillsList' }, skills.map(function (skill) {
1896
+ return h('div', { className: 'dswb-skill', key: skill.path }, [
1897
+ h('div', { className: 'dswb-skillHead', key: 'head' }, [
1898
+ h('span', { className: 'dswb-skillName', key: 'name' }, skill.name),
1899
+ h('span', { className: 'dswb-badge ' + (skill.enabled ? 'dswb-badgeOn' : 'dswb-badgeOff'), key: 'state' }, skill.enabled ? '已启用' : '已关闭'),
1900
+ ]),
1901
+ skill.description === '' ? null : h('p', { className: 'dswb-note', key: 'desc' }, skill.description),
1902
+ h('span', { className: 'dswb-skillPath', key: 'path', title: skill.path }, skill.path),
1903
+ h('div', { className: 'dswb-skillActions', key: 'actions' }, [
1904
+ h('button', {
1905
+ className: 'dswb-linkBtn', key: 'toggle', type: 'button',
1906
+ disabled: busy !== '', onClick: function () { toggleSkill(skill) },
1907
+ }, busy === 'skill:' + skill.path ? '处理中…' : skill.enabled ? '关闭' : '启用'),
1908
+ h('button', {
1909
+ className: 'dswb-linkBtn', key: 'edit', type: 'button',
1910
+ onClick: function () { openSkill(skill) },
1911
+ }, '编辑 SKILL.md'),
1912
+ ]),
1913
+ ])
1914
+ })))
1915
+ }
1916
+ } else if (view === 'shared') {
1917
+ if (sharedState === 'loading') {
1918
+ body.push(h('p', { className: 'dswb-note', key: 'sharedLoading' }, '正在读取技能仓库里的 .dsh…'))
1919
+ } else if (shared === null) {
1920
+ body.push(h('p', { className: 'dswb-note', key: 'sharedEmpty' }, '共享预设不可用。'))
1921
+ } else {
1922
+ if (sharedRepoState === 'loading') {
1923
+ body.push(h('p', { className: 'dswb-note', key: 'sharedRepoLoading' }, '正在读取共享技能仓库设置…'))
1924
+ } else if (sharedRepo !== null && sharedRepoDraft !== null) {
1925
+ body.push(h('div', { className: 'dswb-kv', key: 'sharedRepo' }, [
1926
+ h('p', { className: 'dswb-note', key: 'title' }, '共享技能仓库(私有仓库填 Deploy Key)'),
1927
+ h('label', { className: 'dswb-field', key: 'repoUrl' }, [
1928
+ h('span', { className: 'dswb-label' }, '仓库地址'),
1929
+ h('input', {
1930
+ className: 'dswb-input', value: sharedRepoDraft.repoUrl,
1931
+ onChange: function (event) { setSharedRepoField('repoUrl', event.target.value) },
1932
+ }),
1933
+ ]),
1934
+ h('label', { className: 'dswb-field', key: 'branch' }, [
1935
+ h('span', { className: 'dswb-label' }, '分支'),
1936
+ h('input', {
1937
+ className: 'dswb-input', value: sharedRepoDraft.branch,
1938
+ onChange: function (event) { setSharedRepoField('branch', event.target.value) },
1939
+ }),
1940
+ ]),
1941
+ h('label', { className: 'dswb-field', key: 'targetDir' }, [
1942
+ h('span', { className: 'dswb-label' }, '检出目录(仓库根,任意绝对路径)'),
1943
+ h('input', {
1944
+ className: 'dswb-input', value: sharedRepoDraft.targetDir,
1945
+ onChange: function (event) { setSharedRepoField('targetDir', event.target.value) },
1946
+ placeholder: '例如 ~/core/projects/skills;预设读 <检出目录>/.dsh/preset',
1947
+ }),
1948
+ h('span', { className: 'dswb-note' }, '检出的就是这个仓库本身,不需要也不建议指向 ~/.dsh;.dsh/preset 在仓库内部。'),
1949
+ ]),
1950
+ h('label', { className: 'dswb-field', key: 'keyPath' }, [
1951
+ h('span', { className: 'dswb-label' }, '密钥路径(可选,优先于下面的 Deploy Key)'),
1952
+ h('input', {
1953
+ className: 'dswb-input', value: sharedRepoDraft.keyPath,
1954
+ onChange: function (event) { setSharedRepoField('keyPath', event.target.value) },
1955
+ placeholder: '~/.ssh/deploy_key',
1956
+ }),
1957
+ ]),
1958
+ h('label', { className: 'dswb-check', key: 'submodules' }, [
1959
+ h('input', {
1960
+ type: 'checkbox', checked: sharedRepoDraft.recurseSubmodules,
1961
+ onChange: function (event) { setSharedRepoField('recurseSubmodules', event.target.checked) },
1962
+ }),
1963
+ '递归子模块',
1964
+ ]),
1965
+ h('div', { className: 'dswb-actions', key: 'repoActions' }, [
1966
+ h('button', { className: 'dswb-btn dswb-primary', key: 'save', type: 'button', disabled: busy !== '', onClick: saveSharedRepo }, '保存设置'),
1967
+ h('button', { className: 'dswb-btn', key: 'pull', type: 'button', disabled: busy !== '', onClick: pullSharedRepo }, busy === 'shared-pull' ? '拉取中…' : '拉取(clone / 快进)'),
1968
+ ]),
1969
+ h('label', { className: 'dswb-field', key: 'deployKey' }, [
1970
+ h('span', { className: 'dswb-label' }, 'Deploy Key 私钥(保存后不回显)'),
1971
+ h('textarea', {
1972
+ className: 'dswb-textarea', value: sharedRepoKeyDraft,
1973
+ onChange: function (event) { setSharedRepoKeyDraft(event.target.value) },
1974
+ placeholder: '粘贴 OpenSSH 私钥;留空并点“保存”等于清除。',
1975
+ }),
1976
+ ]),
1977
+ h('div', { className: 'dswb-actions', key: 'keyActions' }, [
1978
+ h('button', { className: 'dswb-btn', key: 'saveKey', type: 'button', disabled: busy !== '', onClick: function () { saveSharedRepoKey(false) } }, '保存 Deploy Key'),
1979
+ h('button', { className: 'dswb-btn', key: 'clearKey', type: 'button', disabled: busy !== '', onClick: function () { saveSharedRepoKey(true) } }, '清除'),
1980
+ h('span', { className: 'dswb-status', key: 'keyState' }, '密钥来源:' + wbKeyText(sharedRepo.key)),
1981
+ ]),
1982
+ h('p', { className: 'dswb-note', key: 'target', title: sharedRepo.state.targetDir }, '检出:' + (sharedRepo.target.exists
1983
+ ? (sharedRepo.target.isRepo ? '分支 ' + (sharedRepo.target.branch || '-') + ' · commit ' + sharedRepo.target.commit.slice(0, 7) + ' · 技能 ' + sharedRepo.target.skills + ' 个' : '目录存在但不是 Git 仓库')
1984
+ : '尚未 clone')),
1985
+ h('p', { className: 'dswb-note', key: 'last' }, '上次拉取:' + wbSyncText(sharedRepo.state.lastSync)),
1986
+ h('p', { className: 'dswb-note', key: 'hint' }, '拉取后,仓库根目录的 .dsh/preset 会出现在下面的来源列表。'),
1987
+ ]))
1988
+ }
1989
+ if (nativeView !== null) {
1990
+ const importable = nativeView.presets.filter(function (row) { return row.importable }).length
1991
+ const nativeRows = nativeView.presets.map(function (row) {
1992
+ return h('div', { className: 'dswb-skill', key: 'np:' + row.id }, [
1993
+ h('div', { className: 'dswb-skillHead', key: 'head' }, [
1994
+ h('span', { className: 'dswb-skillName', key: 'name' }, row.name),
1995
+ h('span', {
1996
+ className: 'dswb-badge ' + (row.builtin || row.directory ? 'dswb-badgeOff' : 'dswb-badgeOn'),
1997
+ key: 'state',
1998
+ }, row.builtin ? '内置 · 保留' : row.directory ? '已是目录预设' : '可导入'),
1999
+ ]),
2000
+ h('span', { className: 'dswb-skillPath', key: 'id' }, row.id),
2001
+ row.importable ? h('div', { className: 'dswb-skillActions', key: 'actions' }, [
2002
+ h('button', {
2003
+ className: 'dswb-linkBtn', key: 'import', type: 'button',
2004
+ disabled: busy !== '', onClick: function () { importNative([row.id]) },
2005
+ }, '导入到本地预设'),
2006
+ ]) : null,
2007
+ ])
2008
+ })
2009
+ nativeRows.push(h('div', { className: 'dswb-actions', key: 'importAll' }, [
2010
+ h('button', {
2011
+ className: 'dswb-btn', key: 'all', type: 'button',
2012
+ disabled: busy !== '' || importable === 0, onClick: function () { importNative(null) },
2013
+ }, busy === 'native' ? '导入中…' : '导入全部非内置(' + importable + ')'),
2014
+ ]))
2015
+ body.push(h('div', { className: 'dswb-kv', key: 'native' }, [
2016
+ h('p', { className: 'dswb-note', key: 'title' }, '原生预设接管'),
2017
+ h('p', { className: 'dswb-note', key: 'builtin' }, '保留原生:' + (nativeView.builtin.length === 0 ? '无' : nativeView.builtin.join(', '))),
2018
+ ].concat(nativeRows)))
2019
+ }
2020
+ body.push(h('div', { className: 'dswb-kv', key: 'publish' }, [
2021
+ h('p', { className: 'dswb-note', key: 'title' }, '发布到共享仓库(.dsh/preset)'),
2022
+ h('label', { className: 'dswb-field', key: 'message' }, [
2023
+ h('span', { className: 'dswb-label' }, '提交信息'),
2024
+ h('input', {
2025
+ className: 'dswb-input', value: publishMessage,
2026
+ onChange: function (event) { setPublishMessage(event.target.value) },
2027
+ }),
2028
+ ]),
2029
+ h('label', { className: 'dswb-check', key: 'push' }, [
2030
+ h('input', {
2031
+ type: 'checkbox', checked: publishPush,
2032
+ onChange: function (event) { setPublishPush(event.target.checked) },
2033
+ }),
2034
+ '提交后推送到 origin',
2035
+ ]),
2036
+ h('div', { className: 'dswb-actions', key: 'actions' }, [
2037
+ h('button', {
2038
+ className: 'dswb-btn dswb-primary', key: 'go', type: 'button',
2039
+ disabled: busy !== '', onClick: publishPresets,
2040
+ }, busy === 'publish' ? '发布中…' : '发布非内置预设'),
2041
+ ]),
2042
+ h('p', { className: 'dswb-note', key: 'hint' }, '只提交共享仓库的 .dsh/preset;需先在上面配置并拉取共享技能仓库。'),
2043
+ ]))
2044
+ body.push(h('div', { className: 'dswb-actions', key: 'sharedActions' }, [
2045
+ h('button', {
2046
+ className: 'dswb-btn dswb-primary', key: 'syncAll', type: 'button',
2047
+ disabled: busy !== '', onClick: function () { syncShared(null) },
2048
+ }, busy === 'shared' ? '同步中…' : '同步全部'),
2049
+ h('label', { className: 'dswb-check', key: 'prune' }, [
2050
+ h('input', {
2051
+ type: 'checkbox', checked: pruneShared,
2052
+ onChange: function (event) { setPruneShared(event.target.checked) },
2053
+ }),
2054
+ '删除源中已移除的文件',
2055
+ ]),
2056
+ h('span', { className: 'dswb-status', key: 'localRoot', title: shared.localRoot }, '目标:' + shared.localRoot),
2057
+ ]))
2058
+ const sources = shared.sources
2059
+ const total = sources.reduce(function (count, source) { return count + source.presets.length }, 0)
2060
+ if (total === 0) {
2061
+ body.push(h('div', { className: 'dswb-empty', key: 'noShared' }, [
2062
+ h('p', { className: 'dswb-note', key: 'hint' }, '没有找到 .dsh 预设。'),
2063
+ h('p', { className: 'dswb-note', key: 'format' }, '仓库里放 .dsh/preset/<id>/(推荐)或让 .dsh/preset/ 本身就是一个预设;也兼容 .dsh/presets/<id>/ 与带 preset.yml 的 .dsh/<id>/。'),
2064
+ ]))
2065
+ }
2066
+ sources.forEach(function (source) {
2067
+ body.push(h('div', { className: 'dswb-kv', key: 'src:' + source.kind + ':' + source.path }, [
2068
+ h('p', { className: 'dswb-note', key: 'kind' }, wbSharedKindText(source.kind) + (source.exists ? '' : ' · 目录不存在')),
2069
+ h('p', { className: 'dswb-note', key: 'path', title: source.path }, source.path),
2070
+ ]))
2071
+ if (source.presets.length === 0) {
2072
+ body.push(h('p', { className: 'dswb-note', key: 'empty:' + source.path }, '这个来源下没有 .dsh 预设。'))
2073
+ return
2074
+ }
2075
+ source.presets.forEach(function (item) {
2076
+ body.push(h('div', { className: 'dswb-skill', key: 'sp:' + source.path + ':' + item.id }, [
2077
+ h('div', { className: 'dswb-skillHead', key: 'head' }, [
2078
+ h('span', { className: 'dswb-skillName', key: 'name' }, item.name),
2079
+ h('span', {
2080
+ className: 'dswb-badge ' + (item.status === 'same' ? 'dswb-badgeOn' : item.status === 'invalid' ? 'dswb-badgeOff' : ''),
2081
+ key: 'status',
2082
+ }, wbSharedStatusText(item.status)),
2083
+ item.managed ? h('span', { className: 'dswb-badge', key: 'managed' }, '已接管') : null,
2084
+ ]),
2085
+ item.description === '' ? null : h('p', { className: 'dswb-note', key: 'desc' }, item.description),
2086
+ h('span', { className: 'dswb-skillPath', key: 'meta', title: item.sourcePath }, item.id + ' · ' + item.files + ' 个文件 · 技能 ' + item.skills),
2087
+ item.status === 'invalid' && item.reason !== '' ? h('p', { className: 'dswb-error', key: 'reason' }, item.reason) : null,
2088
+ h('div', { className: 'dswb-skillActions', key: 'actions' }, [
2089
+ h('button', {
2090
+ className: 'dswb-linkBtn', key: 'sync', type: 'button',
2091
+ disabled: busy !== '' || item.status === 'invalid' || item.status === 'same',
2092
+ onClick: function () { syncShared([item.id]) },
2093
+ }, item.status === 'same' ? '已是最新' : '同步这个预设'),
2094
+ ]),
2095
+ ]))
2096
+ })
2097
+ })
2098
+ }
2099
+ } else {
2100
+ if (repoState === 'loading') {
2101
+ body.push(h('p', { className: 'dswb-note', key: 'repoLoading' }, '正在读取仓库设置…'))
2102
+ } else if (repo === null || repoDraft === null) {
2103
+ body.push(h('p', { className: 'dswb-note', key: 'repoEmpty' }, '仓库设置不可用。'))
2104
+ } else {
2105
+ body.push(h('label', { className: 'dswb-field', key: 'repoUrl' }, [
2106
+ h('span', { className: 'dswb-label' }, '仓库地址'),
2107
+ h('input', {
2108
+ className: 'dswb-input', value: repoDraft.repoUrl,
2109
+ onChange: function (event) { setRepoField('repoUrl', event.target.value) },
2110
+ }),
2111
+ ]))
2112
+ body.push(h('label', { className: 'dswb-field', key: 'branch' }, [
2113
+ h('span', { className: 'dswb-label' }, '分支'),
2114
+ h('input', {
2115
+ className: 'dswb-input', value: repoDraft.branch,
2116
+ onChange: function (event) { setRepoField('branch', event.target.value) },
2117
+ }),
2118
+ ]))
2119
+ body.push(h('label', { className: 'dswb-field', key: 'subdir' }, [
2120
+ h('span', { className: 'dswb-label' }, '目标子目录(skills/ 下)'),
2121
+ h('input', {
2122
+ className: 'dswb-input', value: repoDraft.targetSubdir,
2123
+ onChange: function (event) { setRepoField('targetSubdir', event.target.value) },
2124
+ }),
2125
+ ]))
2126
+ body.push(h('label', { className: 'dswb-field', key: 'keyPath' }, [
2127
+ h('span', { className: 'dswb-label' }, '密钥路径(可选)'),
2128
+ h('input', {
2129
+ className: 'dswb-input', value: repoDraft.keyPath,
2130
+ onChange: function (event) { setRepoField('keyPath', event.target.value) },
2131
+ placeholder: '~/.ssh/deploy_key;留空则用下面保存的 Deploy Key',
2132
+ }),
2133
+ ]))
2134
+ body.push(h('label', { className: 'dswb-check', key: 'submodules' }, [
2135
+ h('input', {
2136
+ type: 'checkbox', checked: repoDraft.recurseSubmodules,
2137
+ onChange: function (event) { setRepoField('recurseSubmodules', event.target.checked) },
2138
+ }),
2139
+ '递归子模块',
2140
+ ]))
2141
+ body.push(h('div', { className: 'dswb-actions', key: 'repoActions' }, [
2142
+ h('button', { className: 'dswb-btn dswb-primary', key: 'saveRepo', type: 'button', disabled: busy !== '', onClick: saveRepo }, '保存设置'),
2143
+ h('button', { className: 'dswb-btn', key: 'sync', type: 'button', disabled: busy !== '', onClick: syncNow }, busy === 'sync' ? '同步中…' : '同步(拉取)'),
2144
+ ]))
2145
+ body.push(h('label', { className: 'dswb-field', key: 'key' }, [
2146
+ h('span', { className: 'dswb-label' }, 'Deploy Key 私钥(保存后不回显)'),
2147
+ h('textarea', {
2148
+ className: 'dswb-textarea', value: keyDraft,
2149
+ onChange: function (event) { setKeyDraft(event.target.value) },
2150
+ placeholder: '粘贴 OpenSSH 私钥;留空并点“保存”等于清除。',
2151
+ }),
2152
+ ]))
2153
+ body.push(h('div', { className: 'dswb-actions', key: 'keyActions' }, [
2154
+ h('button', { className: 'dswb-btn', key: 'saveKey', type: 'button', disabled: busy !== '', onClick: function () { saveKey(false) } }, '保存 Deploy Key'),
2155
+ h('button', { className: 'dswb-btn', key: 'clearKey', type: 'button', disabled: busy !== '', onClick: function () { saveKey(true) } }, '清除'),
2156
+ h('span', { className: 'dswb-status', key: 'keyState' }, '密钥来源:' + wbKeyText(repo.key)),
2157
+ ]))
2158
+ body.push(h('div', { className: 'dswb-kv', key: 'status' }, [
2159
+ h('p', { className: 'dswb-note', key: 'target' }, '目标:' + repo.target),
2160
+ h('p', { className: 'dswb-note', key: 'state' }, repo.status.exists
2161
+ ? (repo.status.isRepo ? '分支 ' + (repo.status.branch || '-') + ' · commit ' + repo.status.commit.slice(0, 7) + ' · ' + (repo.status.dirty ? '工作区有改动' : '工作区干净') + ' · 技能 ' + repo.status.skills + ' 个' : '目标存在但不是 Git 仓库')
2162
+ : '目标尚未克隆,首次同步会 clone'),
2163
+ h('p', { className: 'dswb-note', key: 'last' }, '上次同步:' + wbSyncText(repo.state.lastSync)),
2164
+ ]))
2165
+ }
2166
+ }
2167
+
2168
+ children.push(h('div', { className: 'dswb-body', key: 'body' }, body))
2169
+ if (deployKeyState !== 'unsupported') {
2170
+ children.push(h('div', { className: 'dswb-kv', key: 'deployKey' }, [
2171
+ h('p', { className: 'dswb-note', key: 'title' }, 'Deploy Key(拉取私有仓库)'),
2172
+ h('label', { className: 'dswb-field', key: 'draft' }, [
2173
+ h('span', { className: 'dswb-label' }, '通用 Deploy Key 私钥(保存后不回显)'),
2174
+ h('textarea', {
2175
+ className: 'dswb-textarea', value: deployKeyDraft,
2176
+ onChange: function (event) { setDeployKeyDraft(event.target.value) },
2177
+ placeholder: '粘贴 OpenSSH 私钥;留空并点“保存”等于清除。未配置密钥路径或该仓库自己的 Deploy Key 时使用。',
2178
+ }),
2179
+ ]),
2180
+ h('div', { className: 'dswb-actions', key: 'actions' }, [
2181
+ h('button', {
2182
+ className: 'dswb-btn dswb-primary', key: 'save', type: 'button', disabled: busy !== '',
2183
+ onClick: function () { saveDeployKey(false) },
2184
+ }, busy === 'deploy-key' ? '保存中…' : '保存通用 Deploy Key'),
2185
+ h('button', {
2186
+ className: 'dswb-btn', key: 'clear', type: 'button', disabled: busy !== '',
2187
+ onClick: function () { saveDeployKey(true) },
2188
+ }, '清除'),
2189
+ h('span', { className: 'dswb-status', key: 'state' }, '当前:' + (deployKeyState === 'loading' ? '读取中…' : deployKey !== null && deployKey.hasStoredKey ? '已保存通用 Deploy Key' : '未设置')),
2190
+ ]),
2191
+ h('p', { className: 'dswb-note', key: 'hint' }, '查找顺序:密钥路径 → 该仓库保存的 Deploy Key → 这里的通用 Deploy Key。HTTPS 地址在有密钥时改写为 SSH。'),
2192
+ ]))
2193
+ }
2194
+ }
2195
+
2196
+ if (notice !== '') children.push(h('p', { className: 'dswb-ok', key: 'notice', role: 'status' }, notice))
2197
+ if (error !== '' && status !== 'error') children.push(h('p', { className: 'dswb-error', key: 'error', role: 'alert' }, error))
2198
+ children.push(h('p', { className: 'dswb-note', key: 'foot' }, '预设里的技能与 Markdown 直接写入该目录,是否被会话加载取决于使用它的 preset;全局/项目 AGENTS.md 由 dsh-agent-instructions 读取,改动在会话恢复或模型再次读写该目录后生效。'))
2199
+
2200
+ return h('div', { className: 'dswb-root' }, children)
2201
+ }
2202
+
2203
+ /** One component's own configuration page, opened from its row. */
2204
+ function RowPage(config) {
2205
+ return function ComponentPage() {
2206
+ return h('div', { className: 'dsu-root' }, [
2207
+ h('style', { key: 'style' }, STYLE),
2208
+ h(Section, {
2209
+ key: 'section', form: config.form, fields: config.fields,
2210
+ title: config.title, intro: config.intro,
2211
+ }),
2212
+ ])
2213
+ }
2214
+ }
2215
+
2216
+ function apply(ctx) {
2217
+ const skillForm = ctx.configForms.get(SKILL_NS)
2218
+ const approvalForm = ctx.configForms.get(APPROVAL_NS)
2219
+ const notifyForm = ctx.configForms.get(NOTIFY_NS)
2220
+ let skillPanelForm = null
2221
+ try {
2222
+ skillPanelForm = ctx.configForms.get(SKILL_PANEL_NS)
2223
+ } catch {
2224
+ skillPanelForm = null
2225
+ }
2226
+ let agentsForm = null
2227
+ try {
2228
+ agentsForm = ctx.configForms.get(AGENTS_NS) || null
2229
+ } catch {
2230
+ agentsForm = null
2231
+ }
2232
+ ctx.effect(() => () => {
2233
+ skillForm.dispose()
2234
+ approvalForm.dispose()
2235
+ notifyForm.dispose()
2236
+ if (skillPanelForm) skillPanelForm.dispose()
2237
+ if (agentsForm) agentsForm.dispose()
2238
+ }, 'dsh-utils: configuration forms')
2239
+ const SkillRowPage = RowPage({
2240
+ form: skillForm, fields: SKILL_FIELDS,
2241
+ title: '递归技能发现',
2242
+ intro: '嵌套目录里的 SKILL.md 递归发现。改动即时生效,并写入 dsh 的配置文档。',
2243
+ })
2244
+ const ApprovalRowPage = RowPage({
2245
+ form: approvalForm, fields: APPROVAL_FIELDS,
2246
+ title: '无人值守审批门控',
2247
+ intro: '给 subagent/定时/cron 的审批请求设定应答窗口,超时按 fail-closed 落定。',
2248
+ })
2249
+ const NotifyRowPage = RowPage({
2250
+ form: notifyForm, fields: NOTIFY_FIELDS,
2251
+ title: '会话通知',
2252
+ intro: '会话结束、等待回答或等待授权时推送一条消息;出口是 Gotify 网关,多台设备共用一个 QQ 也能分清是谁。',
2253
+ })
2254
+ const AgentsRowPage = agentsForm === null ? null : RowPage({
2255
+ form: agentsForm, fields: AGENTS_FIELDS,
2256
+ title: 'utils-agents',
2257
+ intro: '右侧栏的 utils-agents 面板按预设统一管理 skills、技能仓库与 AGENTS.md。',
2258
+ })
2259
+
2260
+ // The row page and the right-sidebar body mount the same panel; the
2261
+ // sidebar body receives its Session as a standard slot prop.
2262
+ const SkillPanelRowPage = () => h('div', { className: 'dsu-root' }, [
2263
+ h('style', { key: 'style' }, STYLE + PANEL_STYLE),
2264
+ h(SkillPanel, { key: 'panel', form: skillPanelForm }),
2265
+ ])
2266
+ // One utils-agents tab now carries what used to be three separate sidebar
2267
+ // cards: preset skills, the per-preset skill repository, and Markdown.
2268
+ const AgentsBody = (props) => h('div', { className: 'dswb-host' }, [
2269
+ h('style', { key: 'style' }, WB_STYLE),
2270
+ h(AgentsPanel, { key: 'panel', sessionId: props?.['sessionId'] }),
2271
+ ])
2272
+
2273
+ if (ctx.sidebarRightTabs && typeof ctx.sidebarRightTabs.register === 'function') {
2274
+ ctx.effect(() => ctx.sidebarRightTabs.register({
2275
+ id: WB_TAB,
2276
+ kind: WB_TAB,
2277
+ title: () => 'utils-agents',
2278
+ guide: [{
2279
+ id: 'utils-agents',
2280
+ order: 30,
2281
+ title: () => 'utils-agents',
2282
+ description: () => '按预设管理技能、技能仓库与 AGENTS.md',
2283
+ }],
2284
+ }), 'dsh-utils: utils-agents tab type')
2285
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
2286
+ name: 'sidebar.right.pane.tab', key: WB_TAB,
2287
+ }, AgentsBody)), 'dsh-utils: utils-agents tab body')
2288
+ }
2289
+
2290
+ // Each component owns one page, keyed the way the Plugins page addresses a
2291
+ // row's configuration: `${bundle}#${rowId}`.
2292
+ ctx.effect(() => ctx.configForms.whileServed([SKILL_NS, APPROVAL_NS, NOTIFY_NS, SKILL_PANEL_NS, AGENTS_NS], (served) => {
2293
+ const offs = []
2294
+ if (served.has(SKILL_NS)) {
2295
+ offs.push(ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
2296
+ name: 'plugins.row.config', key: `${BUNDLE}#${SKILL_NS}`,
2297
+ }, SkillRowPage)))
2298
+ }
2299
+ if (served.has(APPROVAL_NS)) {
2300
+ offs.push(ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
2301
+ name: 'plugins.row.config', key: `${BUNDLE}#${APPROVAL_NS}`,
2302
+ }, ApprovalRowPage)))
2303
+ }
2304
+ if (served.has(NOTIFY_NS)) {
2305
+ offs.push(ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
2306
+ name: 'plugins.row.config', key: `${BUNDLE}#${NOTIFY_NS}`,
2307
+ }, NotifyRowPage)))
2308
+ }
2309
+ if (served.has(SKILL_PANEL_NS)) {
2310
+ offs.push(ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
2311
+ name: 'plugins.row.config', key: `${BUNDLE}#${SKILL_PANEL_NS}`,
2312
+ }, SkillPanelRowPage)))
2313
+ }
2314
+ if (served.has(AGENTS_NS) && AgentsRowPage !== null) {
2315
+ offs.push(ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
2316
+ name: 'plugins.row.config', key: `${BUNDLE}#${AGENTS_NS}`,
2317
+ }, AgentsRowPage)))
2318
+ }
2319
+ return () => {
2320
+ for (const off of offs) off()
2321
+ }
2322
+ }))
2323
+ }
2324
+
2325
+ return {
2326
+ inject: ['slots', 'configForms', 'sidebarRightTabs'],
2327
+ apply,
2328
+ }
2329
+ },
2330
+ })