dsh-skill-pool 0.0.0-stage → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,4434 @@
1
+ /**
2
+ * dsh-skill-pool — Settings panel (browser half), contract v3.
3
+ *
4
+ * One page under `settings.section` with three tabs — Resources / Sources /
5
+ * Settings. There is a single global pool: importing a skill or an MCP server
6
+ * makes it a pool member immediately, and every member carries its own Agent
7
+ * mode and workspace conditions (both dimensions must match; empty = any).
8
+ *
9
+ * All reads and writes go through the Host routes under `/dsh-skill-pool`,
10
+ * so the browser never touches the state file or browser storage. React is the
11
+ * only package required.
12
+ */
13
+ // The module id MUST be the package name: the module system indexes bundle
14
+ // factories by `window.__ModuleLoader__.load({id})` and looks each one up under
15
+ // the package name in the composed graph. A mismatch leaves the row registered
16
+ // but never activated, which fails the whole client-plugin load with
17
+ // "1 entry did not activate". Keep this string equal to package.json's `name`.
18
+ window.__ModuleLoader__.load({
19
+ id: 'dsh-skill-pool',
20
+ factory(require) {
21
+ const React = require('react')
22
+ const h = React.createElement
23
+ const { useState, useEffect, useCallback, useMemo, useRef } = React
24
+
25
+ const ZH = typeof navigator !== 'undefined' && String(navigator.language || '').toLowerCase().startsWith('zh')
26
+
27
+ const TEXT = {
28
+ zh: {
29
+ navTitle: '技能池',
30
+ title: '技能池',
31
+ subtitle: '一个全局技能池:导入即入池。每个资源单独设置 Agent 模式与工作区,两者同时满足才可见;都留空表示所有模式与工作区。',
32
+ refresh: '刷新',
33
+ refreshing: '刷新中…',
34
+ loading: '加载中…',
35
+ retry: '重试',
36
+ retryHint: '无法读取技能池数据。确认插件已启用后重试。',
37
+ networkFailed: '网络请求失败',
38
+ badResponse: '响应格式异常',
39
+ rowFailed: '这一行渲染失败',
40
+ close: '关闭',
41
+ cancel: '取消',
42
+ done: '完成',
43
+ confirm: '确认',
44
+ enabled: '已启用',
45
+ disabled: '已关闭',
46
+ on: '开',
47
+ off: '关',
48
+ saving: '保存中…',
49
+ tabResources: '资源',
50
+ tabSources: '来源',
51
+ tabSettings: '设置',
52
+ // resources tab
53
+ cardSkills: '技能',
54
+ cardMcp: 'MCP Server',
55
+ countUnit: '项',
56
+ importResource: '导入资源',
57
+ previewMode: 'Agent 模式',
58
+ previewWorkspace: '工作区',
59
+ previewAllModes: '全部模式',
60
+ previewAllWorkspaces: '全部工作区',
61
+ previewAvailable: '此处可用 {count} 项',
62
+ previewSkills: '技能',
63
+ previewMcp: 'MCP',
64
+ previewNone: '无',
65
+ previewGateSkills: '技能门控',
66
+ previewGateMcp: 'MCP 门控',
67
+ previewGated: '已门控',
68
+ previewNotGated: '未门控',
69
+ previewBusy: '解析中…',
70
+ previewFailed: '解析失败',
71
+ rowModes: '模式',
72
+ rowWorkspaces: '工作区',
73
+ allModes: '全部模式',
74
+ allWorkspaces: '全部工作区',
75
+ editConditions: '设置条件',
76
+ hideConditions: '收起条件',
77
+ groupInherit: '继承',
78
+ groupInheritTag: '(继承)',
79
+ groupSelf: '单独设置',
80
+ groupInheritFrom: '继承来源',
81
+ groupUngrouped: '未分组',
82
+ groupImports: '{count} 次导入',
83
+ groupImportOne: '{count} 次导入',
84
+ groupExpand: '展开',
85
+ groupCollapse: '收起',
86
+ settingsGroups: '分组开关',
87
+ settingsGroupsHint: '关掉一个仓库组等于关闭它下面所有资源;成员自己的开关保持不变,重新打开即恢复。',
88
+ groupDisabledTag: '整组已关闭',
89
+ groupHint: '同仓库成员默认继承这组条件;单个资源可以改为单独设置。',
90
+ addPathPlaceholder: '/root/workspace/foo 回车添加',
91
+ addPath: '+',
92
+ addPathLabel: '添加工作区路径',
93
+ savingItem: '保存中…',
94
+ removeItem: '删除',
95
+ removing: '删除中…',
96
+ confirmRemove: '确认删除',
97
+ itemRemoved: '已删除',
98
+ toolsUnit: '个工具',
99
+ mountMounting: '挂载中…',
100
+ mountReady: '已就绪',
101
+ mountFailed: '挂载失败',
102
+ sourceFrom: '来源',
103
+ sourceNone: '无来源',
104
+ skillMissing: '(清单中已不存在,可能已被删除)',
105
+ emptyTitle: '还没有资源',
106
+ emptyHint: '用右上角的「导入资源」上传技能文件、ZIP 包、从 Git 导入,或粘贴 MCP JSON。导入后立即成为技能池成员,条件在资源行上单独设置。',
107
+ systemSkillsTitle: '系统技能',
108
+ systemSkillsHint: '这些技能由宿主或预设提供,不归技能池管理,仅作展示。',
109
+ systemSkillsEmpty: '没有系统技能。',
110
+ modelInvocableOff: '模型不可调用',
111
+ groupEmptySkills: '还没有技能资源。',
112
+ groupEmptyMcp: '还没有 MCP 资源。',
113
+ // import dialog
114
+ importTitle: '导入资源',
115
+ importSubtitle: '导入后立即成为技能池成员,默认对所有模式与工作区生效;条件在资源行上单独设置。',
116
+ segFiles: '文件',
117
+ segZip: 'ZIP',
118
+ segGit: 'Git',
119
+ segMcp: 'MCP',
120
+ overwrite: '覆盖同名资源',
121
+ filesPick: '选择 .md 文件',
122
+ filesPickFolder: '选择技能文件夹',
123
+ filesChosen: '已选',
124
+ filesName: '技能名(留空 = 文件名)',
125
+ filesNamePlaceholder: 'my-skill',
126
+ filesDesc: '描述(留空 = frontmatter)',
127
+ filesDescPlaceholder: '一句话描述这个技能',
128
+ filesBody: '或直接粘贴 Markdown 内容',
129
+ filesBodyPlaceholder: '---\nname: my-skill\ndescription: One line\n---\n\n# Instructions',
130
+ filesNeed: '先选择文件或粘贴内容',
131
+ filesTooLarge: '文件过大(上限 5 MB)',
132
+ filesReadFailed: '读取文件失败',
133
+ zipPick: '选择 .zip 文件',
134
+ zipChosen: '已选',
135
+ zipLabel: '来源名称(留空 = 自动识别)',
136
+ zipNeed: '先选择 ZIP 文件',
137
+ zipTooLarge: '压缩包过大(上限 20 MB)',
138
+ gitUrl: '仓库地址',
139
+ gitUrlPlaceholder: 'https://gitlab.company.com/group/repo 或 …/-/tree/main/skills',
140
+ gitBranch: '分支 / 标签',
141
+ gitSubdir: '子目录(可选)',
142
+ gitType: '仓库类型',
143
+ gitTypeAuto: '自动识别',
144
+ gitTypeGitlab: 'GitLab(含自建)',
145
+ gitTypeGithub: 'GitHub / GHE',
146
+ gitTypeHint: '自建 GitLab 直接粘贴仓库或 /-/tree/ 链接即可;私有仓库填访问令牌。',
147
+ gitToken: '访问令牌(私有仓库,可选)',
148
+ gitTokenHint: '令牌写入宿主凭据库,状态文件只保存名字。',
149
+ gitLabel: '来源名称(可选)',
150
+ gitNeedUrl: '先填写仓库地址',
151
+ gitRunning: '正在拉取仓库…(最多 45 秒)',
152
+ mcpJson: 'mcpServers JSON',
153
+ mcpJsonHint: '立即返回,后台挂载;下方实时刷新挂载状态。',
154
+ mcpJsonInvalid: '请先填写 JSON',
155
+ mcpJsonBad: 'JSON 解析失败',
156
+ mcpNotice: '已提交导入:',
157
+ mcpMountBackground: '挂载在后台继续,可在资源列表查看状态。',
158
+ importSubmit: '导入',
159
+ importing: '导入中…',
160
+ importInstalled: '已导入',
161
+ importFailures: '失败',
162
+ importPartial: '部分导入成功',
163
+ importDone: '完成',
164
+ importRetryHint: '可修正后重试;已成功的资源已入池。',
165
+ // sources tab
166
+ sourcesHint: 'Git 来源可检查更新与更新;ZIP / 文件来源只读展示。',
167
+ checkAll: '检查全部更新',
168
+ checkingAll: '检查中…',
169
+ sourceCheck: '检查更新',
170
+ sourceChecking: '检查中…',
171
+ sourceUpdate: '更新',
172
+ sourceUpdating: '更新中…',
173
+ sourceDelete: '删除',
174
+ sourceDeleting: '删除中…',
175
+ sourceDeleteConfirm: '只删除没有被其它来源引用的技能',
176
+ sourceDeleteYes: '确认删除',
177
+ sourceDeleteCancel: '取消',
178
+ sourceKindGit: 'Git',
179
+ sourceKindZip: 'ZIP',
180
+ sourceKindFiles: '文件',
181
+ sourceKindUnknown: '来源',
182
+ sourceSkillsUnit: '个技能',
183
+ sourceSkillsUnitOne: '个技能',
184
+ sourceSha: '提交',
185
+ sourceDigest: '摘要',
186
+ sourceCreatedAt: '创建于',
187
+ sourceReadOnly: '只读',
188
+ sourceNotGit: '该来源不支持检查更新',
189
+ lastCheck: '上次检查',
190
+ neverChecked: '未检查',
191
+ statusUpToDate: '已是最新',
192
+ statusUpdateAvailable: '有更新',
193
+ statusError: '检查失败',
194
+ sourcesEmpty: '还没有导入来源。导入 ZIP / 文件 / Git 时会自动记录。',
195
+ checkResult: '检查完成:{updated} 个有更新,{upToDate} 个最新,{failed} 个失败',
196
+ noticeSourceUpdated: '来源已更新',
197
+ sourceExcluded: '已排除 {count} 个',
198
+ sourceRestore: '恢复已排除',
199
+ sourceRestoreHint: '这些技能被删除后不再随更新安装;恢复会把它们重新装回来',
200
+ sourceRestoring: '恢复中…',
201
+ noticeSourceRestored: '已恢复被排除的技能',
202
+ noticeGroupUpdated: '组内导入已更新({count} 个技能)',
203
+ noticeSourceUpToDate: '来源已是最新',
204
+ noticeSourceDeleted: '来源已删除',
205
+ sourceSkipped: '(保留 {count} 个仍被其它来源引用的技能)',
206
+ noticeSourceChecked: '检查完成',
207
+ // settings tab
208
+ settingsHint: '改动即时生效;已存在的会话保留启动时的状态。',
209
+ setEnabled: '总开关',
210
+ setEnabledHint: '关闭后完全不干预任何会话。',
211
+ setMcpGate: 'MCP 门控',
212
+ setMcpGateHint: '隐藏未命中条件的 MCP 工具。',
213
+ setInjectSummary: '注入资源摘要',
214
+ setInjectSummaryHint: '在系统提示中说明可用技能与 MCP。',
215
+ setGateDefaultSkills: '系统技能严格隐藏',
216
+ setGateDefaultSkillsHint: '暂未启用(系统技能始终可用)。',
217
+ stateFile: '状态文件',
218
+ version: '版本',
219
+ settingsSaved: '设置已保存',
220
+ settingsSaving: '保存中…',
221
+ notAvailable: '暂未启用',
222
+ missingFile: '文件缺失',
223
+ missingFileHint: '磁盘上找不到这个技能文件;可以重新导入,或删除该行。',
224
+ deleteSkillConfirm: '确认删除?会删除磁盘上的技能文件,且此来源以后更新不再安装它',
225
+ deleteMcpConfirm: '确认删除?会同时卸载该 MCP Server',
226
+ selectAll: '全选',
227
+ clearAll: '清空',
228
+ noMatches: '没有匹配项。',
229
+ addNoneSelected: '还没有选择',
230
+ },
231
+ en: {
232
+ navTitle: 'Skill Pool',
233
+ title: 'Skill Pool',
234
+ subtitle: 'One global pool: importing a resource puts it in the pool. Every member carries its own Agent mode and workspace conditions (both must match; empty = any).',
235
+ refresh: 'Refresh',
236
+ refreshing: 'Refreshing…',
237
+ loading: 'Loading…',
238
+ retry: 'Retry',
239
+ retryHint: 'Could not read the skill pool. Make sure the plugin is enabled, then retry.',
240
+ networkFailed: 'Network request failed',
241
+ badResponse: 'Unexpected response',
242
+ rowFailed: 'This row failed to render',
243
+ close: 'Close',
244
+ cancel: 'Cancel',
245
+ done: 'Done',
246
+ confirm: 'Confirm',
247
+ enabled: 'Enabled',
248
+ disabled: 'Disabled',
249
+ on: 'on',
250
+ off: 'off',
251
+ saving: 'Saving…',
252
+ tabResources: 'Resources',
253
+ tabSources: 'Sources',
254
+ tabSettings: 'Settings',
255
+ cardSkills: 'Skills',
256
+ cardMcp: 'MCP servers',
257
+ countUnit: 'items',
258
+ importResource: 'Import',
259
+ previewMode: 'Agent mode',
260
+ previewWorkspace: 'Workspace',
261
+ previewAllModes: 'All modes',
262
+ previewAllWorkspaces: 'All workspaces',
263
+ previewAvailable: '{count} available here',
264
+ previewSkills: 'Skills',
265
+ previewMcp: 'MCP',
266
+ previewNone: 'none',
267
+ previewGateSkills: 'Skill gate',
268
+ previewGateMcp: 'MCP gate',
269
+ previewGated: 'gated',
270
+ previewNotGated: 'not gated',
271
+ previewBusy: 'Resolving…',
272
+ previewFailed: 'Resolve failed',
273
+ rowModes: 'Modes',
274
+ rowWorkspaces: 'Workspaces',
275
+ allModes: 'All modes',
276
+ allWorkspaces: 'All workspaces',
277
+ editConditions: 'Conditions',
278
+ hideConditions: 'Hide conditions',
279
+ groupInherit: 'inherit',
280
+ groupInheritTag: ' (inherited)',
281
+ groupSelf: 'custom',
282
+ groupInheritFrom: 'Inherits from source',
283
+ groupUngrouped: 'Ungrouped',
284
+ groupImports: '{count} imports',
285
+ groupImportOne: '{count} import',
286
+ groupExpand: 'Expand',
287
+ groupCollapse: 'Collapse',
288
+ settingsGroups: 'Group switches',
289
+ settingsGroupsHint: 'Turning a repository group off disables every member; each member keeps its own switch.',
290
+ groupDisabledTag: 'group off',
291
+ groupHint: 'Members of one repository inherit this scope by default; a single resource can opt out.',
292
+ addPathPlaceholder: '/root/workspace/foo then Enter',
293
+ addPath: '+',
294
+ addPathLabel: 'Add workspace path',
295
+ savingItem: 'Saving…',
296
+ removeItem: 'Delete',
297
+ removing: 'Deleting…',
298
+ confirmRemove: 'Confirm delete',
299
+ itemRemoved: 'Deleted',
300
+ toolsUnit: 'tools',
301
+ mountMounting: 'Mounting…',
302
+ mountReady: 'Ready',
303
+ mountFailed: 'Mount failed',
304
+ sourceFrom: 'Source',
305
+ sourceNone: 'No source',
306
+ skillMissing: '(no longer in the inventory; it may have been deleted)',
307
+ emptyTitle: 'No resources yet',
308
+ emptyHint: 'Use “Import” in the top-right corner to upload skill files, a ZIP archive, import from Git, or paste MCP JSON. Everything you import joins the pool immediately; conditions are set on its row.',
309
+ systemSkillsTitle: 'System skills',
310
+ systemSkillsHint: 'These skills come from the host or a preset. They are not managed by the pool and are listed for reference only.',
311
+ systemSkillsEmpty: 'No system skills.',
312
+ modelInvocableOff: 'not model-invocable',
313
+ groupEmptySkills: 'No skill resources yet.',
314
+ groupEmptyMcp: 'No MCP resources yet.',
315
+ importTitle: 'Import resources',
316
+ importSubtitle: 'Imported items join the pool immediately and apply to every mode and workspace by default. Set conditions on the resource row afterwards.',
317
+ segFiles: 'Files',
318
+ segZip: 'ZIP',
319
+ segGit: 'Git',
320
+ segMcp: 'MCP',
321
+ overwrite: 'Overwrite resources with the same name',
322
+ filesPick: 'Choose .md files',
323
+ filesPickFolder: 'Choose a skill folder',
324
+ filesChosen: 'Selected',
325
+ filesName: 'Skill name (empty = file name)',
326
+ filesNamePlaceholder: 'my-skill',
327
+ filesDesc: 'Description (empty = frontmatter)',
328
+ filesDescPlaceholder: 'One line about this skill',
329
+ filesBody: 'Or paste Markdown content',
330
+ filesBodyPlaceholder: '---\nname: my-skill\ndescription: One line\n---\n\n# Instructions',
331
+ filesNeed: 'Choose a file or paste content',
332
+ filesTooLarge: 'File too large (5 MB max)',
333
+ filesReadFailed: 'Could not read the file',
334
+ zipPick: 'Choose a .zip file',
335
+ zipChosen: 'Selected',
336
+ zipLabel: 'Source name (empty = auto-detect)',
337
+ zipNeed: 'Choose a ZIP file first',
338
+ zipTooLarge: 'Archive too large (20 MB max)',
339
+ gitUrl: 'Repository URL',
340
+ gitUrlPlaceholder: 'https://gitlab.company.com/group/repo or …/-/tree/main/skills',
341
+ gitBranch: 'Branch / tag',
342
+ gitSubdir: 'Subdirectory (optional)',
343
+ gitType: 'Repository type',
344
+ gitTypeAuto: 'Detect automatically',
345
+ gitTypeGitlab: 'GitLab (incl. self-hosted)',
346
+ gitTypeGithub: 'GitHub / GHE',
347
+ gitTypeHint: 'Paste a self-hosted GitLab repository or /-/tree/ link directly; add a token for private repos.',
348
+ gitToken: 'Access token (private repos, optional)',
349
+ gitTokenHint: 'The token goes to the Host credential store; the state file keeps only its name.',
350
+ gitLabel: 'Source name (optional)',
351
+ gitNeedUrl: 'Enter a repository URL first',
352
+ gitRunning: 'Fetching repository… (45 s max)',
353
+ mcpJson: 'mcpServers JSON',
354
+ mcpJsonHint: 'Import returns immediately; servers mount in the background and the status refreshes live.',
355
+ mcpJsonInvalid: 'Enter JSON first',
356
+ mcpJsonBad: 'Could not parse JSON',
357
+ mcpNotice: 'Import submitted:',
358
+ mcpMountBackground: 'Mounting continues in the background; check the resource list for status.',
359
+ importSubmit: 'Import',
360
+ importing: 'Importing…',
361
+ importInstalled: 'Imported',
362
+ importFailures: 'Failed',
363
+ importPartial: 'Partially imported',
364
+ importDone: 'Done',
365
+ importRetryHint: 'Fix the input and retry; successful resources are already in the pool.',
366
+ sourcesHint: 'Git sources support checking for updates and updating; ZIP / file sources are read-only.',
367
+ checkAll: 'Check all for updates',
368
+ checkingAll: 'Checking…',
369
+ sourceCheck: 'Check',
370
+ sourceChecking: 'Checking…',
371
+ sourceUpdate: 'Update',
372
+ sourceUpdating: 'Updating…',
373
+ sourceDelete: 'Delete',
374
+ sourceDeleting: 'Deleting…',
375
+ sourceDeleteConfirm: 'Only skills not referenced by another source are deleted',
376
+ sourceDeleteYes: 'Confirm delete',
377
+ sourceDeleteCancel: 'Cancel',
378
+ sourceKindGit: 'Git',
379
+ sourceKindZip: 'ZIP',
380
+ sourceKindFiles: 'Files',
381
+ sourceKindUnknown: 'Source',
382
+ sourceSkillsUnit: 'skills',
383
+ sourceSkillsUnitOne: 'skill',
384
+ sourceSha: 'commit',
385
+ sourceDigest: 'digest',
386
+ sourceCreatedAt: 'created',
387
+ sourceReadOnly: 'read-only',
388
+ sourceNotGit: 'This source does not support update checks',
389
+ lastCheck: 'Last check',
390
+ neverChecked: 'Not checked',
391
+ statusUpToDate: 'Up to date',
392
+ statusUpdateAvailable: 'Update available',
393
+ statusError: 'Check failed',
394
+ sourcesEmpty: 'No sources yet. Importing a ZIP / files / Git repository records one automatically.',
395
+ checkResult: 'Checked: {updated} with updates, {upToDate} up to date, {failed} failed',
396
+ noticeSourceUpdated: 'Source updated',
397
+ sourceExcluded: 'excluded: {count}',
398
+ sourceRestore: 'Restore excluded',
399
+ sourceRestoreHint: 'Deleted skills are no longer installed by updates; restore installs them again',
400
+ sourceRestoring: 'Restoring…',
401
+ noticeSourceRestored: 'Excluded skills restored',
402
+ noticeGroupUpdated: 'Group updated ({count} skills)',
403
+ noticeSourceUpToDate: 'Source already up to date',
404
+ noticeSourceDeleted: 'Source deleted',
405
+ sourceSkipped: ' ({count} skills kept because another source references them)',
406
+ noticeSourceChecked: 'Check completed',
407
+ settingsHint: 'Changes apply immediately; sessions that already started keep the state they began with.',
408
+ setEnabled: 'Master switch',
409
+ setEnabledHint: 'Off leaves every session completely untouched.',
410
+ setMcpGate: 'MCP gate',
411
+ setMcpGateHint: 'Hide the tools of MCP servers that do not match.',
412
+ setInjectSummary: 'Inject resource summary',
413
+ setInjectSummaryHint: 'State the available skills and MCP servers in the system prompt.',
414
+ setGateDefaultSkills: 'Strictly hide system skills',
415
+ setGateDefaultSkillsHint: 'Not enabled yet (system skills are always available).',
416
+ stateFile: 'State file',
417
+ version: 'Version',
418
+ settingsSaved: 'Settings saved',
419
+ settingsSaving: 'Saving…',
420
+ notAvailable: 'not enabled yet',
421
+ missingFile: 'Missing files',
422
+ missingFileHint: 'The skill files are gone from disk; import it again or delete this row.',
423
+ deleteSkillConfirm: 'Delete? Its files are removed and this source will not install it again',
424
+ deleteMcpConfirm: 'Delete? This MCP server is unmounted too',
425
+ selectAll: 'Select all',
426
+ clearAll: 'Clear',
427
+ noMatches: 'No matches.',
428
+ addNoneSelected: 'Nothing selected',
429
+ },
430
+ }[ZH ? 'zh' : 'en']
431
+
432
+ const t = (key) => {
433
+ const value = TEXT[key]
434
+ return typeof value === 'string' ? value : String(key)
435
+ }
436
+
437
+ /** Interpolate `{name}` placeholders in a localized string. */
438
+ function tf(key, vars) {
439
+ const template = t(key)
440
+ const source = vars && typeof vars === 'object' ? vars : {}
441
+ return template.replace(/\{(\w+)\}/g, (match, name) =>
442
+ Object.prototype.hasOwnProperty.call(source, name) ? String(source[name]) : match,
443
+ )
444
+ }
445
+
446
+ /** Absolute route prefix (contract v3 §6). */
447
+ const API = '/dsh-skill-pool'
448
+ const DEFAULT_SETTINGS = Object.freeze({
449
+ enabled: true,
450
+ mcpGate: true,
451
+ injectSummary: true,
452
+ gateDefaultSkills: false,
453
+ })
454
+ const EMPTY_INVENTORY = Object.freeze({
455
+ skills: [],
456
+ nativeSkills: [],
457
+ mcp: [],
458
+ modes: [],
459
+ workspaces: [],
460
+ defaultMode: '',
461
+ })
462
+ const EMPTY_STATE = Object.freeze({
463
+ version: 4,
464
+ settings: DEFAULT_SETTINGS,
465
+ skills: {},
466
+ mcp: {},
467
+ sources: {},
468
+ groups: {},
469
+ })
470
+ const TABS = Object.freeze([
471
+ ['resources', 'tabResources'],
472
+ ['sources', 'tabSources'],
473
+ ['settings', 'tabSettings'],
474
+ ])
475
+ const SKILL = 'skill'
476
+ const MCP = 'mcp'
477
+ const ITEM_DEBOUNCE_MS = 320
478
+ const MOUNT_POLL_MS = 1600
479
+ const MAX_UPLOAD_BYTES = 5 * 1024 * 1024
480
+ const MAX_ZIP_BYTES = 20 * 1024 * 1024
481
+
482
+ /**
483
+ * Read the branch and sub-directory out of a pasted repository web URL.
484
+ *
485
+ * Mirrors `parseRepoUrl` in `src/library.js`, which is the authority for the
486
+ * Host; this copy exists only so the form can prefill the two fields. Both
487
+ * shapes must be handled here or the fields stay empty while the import still
488
+ * works, which reads as "the URL was not recognised":
489
+ *
490
+ * GitLab <host>/<group>/<repo>/-/tree/<branch>/<subdir>
491
+ * GitHub <host>/<owner>/<repo>/tree/<branch>/<subdir>
492
+ *
493
+ * @param {string} value - raw text from the URL field.
494
+ * @returns {{branch: string, subdir: string}|undefined} parsed hint, if any.
495
+ */
496
+ function deepLinkHint(value) {
497
+ const text = asString(value).trim()
498
+ if (text.length === 0) return undefined
499
+ const gitlab = /\/-\/(?:tree|blob|src)\/([^/?#]+)(?:\/([^?#]+))?/.exec(text)
500
+ const github = /^https?:\/\/[^/]+\/[^/]+\/[^/]+\/(?:tree|blob|raw)\/([^/?#]+)(?:\/([^?#]+))?/.exec(text)
501
+ const match = gitlab ?? github
502
+ if (match === null) return undefined
503
+ const branch = asString(match[1]).replace(/\/+$/, '')
504
+ let subdir = asString(match[2]).replace(/\/+$/, '')
505
+ // A link to a file names its directory for the importer.
506
+ if (/\.md$/i.test(subdir)) subdir = subdir.split('/').slice(0, -1).join('/')
507
+ return { branch, subdir }
508
+ }
509
+
510
+ // ------------------------------------------------------------------ utils
511
+
512
+ function asArray(value) {
513
+ return Array.isArray(value) ? value : []
514
+ }
515
+
516
+ function asObject(value) {
517
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
518
+ }
519
+
520
+ function asString(value, fallback) {
521
+ if (typeof value === 'string') return value
522
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value)
523
+ return fallback === undefined ? '' : fallback
524
+ }
525
+
526
+ function asNumber(value, fallback) {
527
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback
528
+ }
529
+
530
+ function asBool(value, fallback) {
531
+ return typeof value === 'boolean' ? value : fallback
532
+ }
533
+
534
+ function uniqueStrings(values) {
535
+ const seen = new Set()
536
+ const out = []
537
+ for (const item of asArray(values)) {
538
+ if (typeof item !== 'string') continue
539
+ const text = item.trim()
540
+ if (text.length === 0 || seen.has(text)) continue
541
+ seen.add(text)
542
+ out.push(text)
543
+ }
544
+ return out
545
+ }
546
+
547
+ function asStringArray(value) {
548
+ return uniqueStrings(value)
549
+ }
550
+
551
+ function messageOf(cause) {
552
+ if (cause instanceof Error) return cause.message || String(cause)
553
+ return String(cause === undefined || cause === null ? '' : cause)
554
+ }
555
+
556
+ function baseName(path) {
557
+ const text = asString(path).replace(/\\/g, '/')
558
+ const parts = text.split('/').filter((part) => part.length > 0)
559
+ return parts.length > 0 ? parts[parts.length - 1] : text
560
+ }
561
+
562
+ function normalizePath(value) {
563
+ const text = asString(value).trim().replace(/\\/g, '/')
564
+ if (text.length === 0) return ''
565
+ const trimmed = text.replace(/\/+$/, '')
566
+ return trimmed.length === 0 ? '/' : trimmed
567
+ }
568
+
569
+ function formatTime(value) {
570
+ const text = asString(value)
571
+ if (text.length === 0) return ''
572
+ const date = new Date(text)
573
+ if (Number.isNaN(date.getTime())) return text
574
+ return date.toLocaleString()
575
+ }
576
+
577
+ function shortDigest(value) {
578
+ const text = asString(value).replace(/^sha256:/, '')
579
+ return text.length > 10 ? text.slice(0, 8) + '…' : text
580
+ }
581
+
582
+ function blankEntry() {
583
+ return {
584
+ enabled: true,
585
+ modes: [],
586
+ workspaces: [],
587
+ modesFrom: 'group',
588
+ workspacesFrom: 'group',
589
+ sourceId: '',
590
+ digest: '',
591
+ installedAt: '',
592
+ }
593
+ }
594
+
595
+ function normalizeEntry(raw) {
596
+ const source = asObject(raw)
597
+ return {
598
+ enabled: source.enabled !== false,
599
+ modes: asStringArray(source.modes),
600
+ workspaces: uniqueStrings(asArray(source.workspaces).map(normalizePath)),
601
+ modesFrom: asString(source.modesFrom) === 'self' ? 'self' : 'group',
602
+ workspacesFrom: asString(source.workspacesFrom) === 'self' ? 'self' : 'group',
603
+ sourceId: asString(source.sourceId),
604
+ digest: asString(source.digest),
605
+ installedAt: asString(source.installedAt),
606
+ }
607
+ }
608
+
609
+ function normalizeSettings(raw) {
610
+ const source = asObject(raw)
611
+ return {
612
+ enabled: source.enabled !== false,
613
+ mcpGate: source.mcpGate !== false,
614
+ injectSummary: source.injectSummary !== false,
615
+ gateDefaultSkills: source.gateDefaultSkills === true,
616
+ }
617
+ }
618
+
619
+ function normalizeScope(raw) {
620
+ const source = asObject(raw)
621
+ return {
622
+ modes: asStringArray(source.modes),
623
+ workspaces: uniqueStrings(asArray(source.workspaces).map(normalizePath)),
624
+ }
625
+ }
626
+
627
+ function normalizeItemMap(raw) {
628
+ const source = asObject(raw)
629
+ const out = {}
630
+ for (const [name, entry] of Object.entries(source)) {
631
+ const key = asString(name).trim()
632
+ if (key.length === 0) continue
633
+ out[key] = normalizeEntry(entry)
634
+ }
635
+ return out
636
+ }
637
+
638
+ function normalizeLastCheck(raw) {
639
+ const source = asObject(raw)
640
+ const status = asString(source.status)
641
+ return {
642
+ at: asString(source.at),
643
+ status:
644
+ status === 'up-to-date' || status === 'update-available' || status === 'error' ? status : '',
645
+ remote: asString(source.remote),
646
+ error: asString(source.error),
647
+ }
648
+ }
649
+
650
+ function normalizeSource(raw, fallbackId) {
651
+ const source = asObject(raw)
652
+ return {
653
+ id: asString(source.id) || asString(fallbackId),
654
+ kind: asString(source.kind) || 'files',
655
+ label: asString(source.label),
656
+ provider: asString(source.provider),
657
+ project: asString(source.project),
658
+ branch: asString(source.branch),
659
+ subdir: asString(source.subdir),
660
+ skills: asStringArray(source.skills),
661
+ excluded: asStringArray(source.excluded),
662
+ digest: asString(source.digest),
663
+ sha: asString(source.sha),
664
+ lastCheck: normalizeLastCheck(source.lastCheck),
665
+ createdAt: asString(source.createdAt),
666
+ updatedAt: asString(source.updatedAt),
667
+ }
668
+ }
669
+
670
+ function normalizeGroup(raw, fallbackKey) {
671
+ const source = asObject(raw)
672
+ const key = asString(source.key) || asString(fallbackKey)
673
+ if (key.length === 0) return null
674
+ return {
675
+ key,
676
+ kind: asString(source.kind) === 'import' || key.startsWith('import:') ? 'import' : 'repo',
677
+ enabled: source.enabled !== false,
678
+ modes: asStringArray(source.modes),
679
+ workspaces: uniqueStrings(asArray(source.workspaces).map(normalizePath)),
680
+ }
681
+ }
682
+
683
+ function normalizeGroups(raw) {
684
+ const source = asObject(raw)
685
+ const out = {}
686
+ for (const [key, value] of Object.entries(source)) {
687
+ const group = normalizeGroup(value, key)
688
+ if (group) out[group.key] = group
689
+ }
690
+ return out
691
+ }
692
+
693
+ function normalizeState(raw) {
694
+ const source = asObject(raw)
695
+ const sourcesRaw = asObject(source.sources)
696
+ const sources = {}
697
+ for (const [id, item] of Object.entries(sourcesRaw)) {
698
+ const entry = normalizeSource(item, id)
699
+ const key = entry.id || asString(id)
700
+ if (key.length === 0) continue
701
+ sources[key] = entry
702
+ }
703
+ return {
704
+ version: asNumber(source.version, 4),
705
+ settings: normalizeSettings(source.settings),
706
+ skills: normalizeItemMap(source.skills),
707
+ mcp: normalizeItemMap(source.mcp),
708
+ sources,
709
+ groups: normalizeGroups(source.groups),
710
+ }
711
+ }
712
+
713
+ /** Modes come back as `string[]` in v3; objects are accepted defensively. */
714
+ function normalizeModeList(raw) {
715
+ const out = []
716
+ const seen = new Set()
717
+ for (const item of asArray(raw)) {
718
+ const row = typeof item === 'string' ? { id: item } : asObject(item)
719
+ const id = asString(row.id || row.value || row.name).trim()
720
+ if (id.length === 0 || seen.has(id)) continue
721
+ seen.add(id)
722
+ out.push({ id, name: asString(row.name) || id })
723
+ }
724
+ return out
725
+ }
726
+
727
+ /** Workspaces come back as `string[]` (absolute paths) in v3. */
728
+ function normalizeWorkspaceList(raw) {
729
+ const out = []
730
+ const seen = new Set()
731
+ for (const item of asArray(raw)) {
732
+ const row = typeof item === 'string' ? { path: item } : asObject(item)
733
+ const path = normalizePath(row.path || row.value)
734
+ if (path.length === 0 || seen.has(path)) continue
735
+ seen.add(path)
736
+ out.push({ id: asString(row.id), name: asString(row.name) || baseName(path), path })
737
+ }
738
+ return out
739
+ }
740
+
741
+ function normalizeInventory(raw) {
742
+ const source = asObject(raw)
743
+ const skills = []
744
+ for (const item of asArray(source.skills)) {
745
+ const row = asObject(item)
746
+ const name = asString(row.name).trim()
747
+ if (name.length === 0) continue
748
+ skills.push({
749
+ name,
750
+ description: asString(row.description),
751
+ path: asString(row.path),
752
+ dir: asString(row.dir),
753
+ missing: row.missing === true,
754
+ sourceId: asString(row.sourceId),
755
+ sourceLabel: asString(row.sourceLabel),
756
+ enabled: row.enabled !== false,
757
+ modes: asStringArray(row.modes),
758
+ workspaces: uniqueStrings(asArray(row.workspaces).map(normalizePath)),
759
+ modesFrom: asString(row.modesFrom) === 'self' ? 'self' : 'group',
760
+ workspacesFrom: asString(row.workspacesFrom) === 'self' ? 'self' : 'group',
761
+ groupKey: asString(row.groupKey),
762
+ groupName: asString(row.groupName),
763
+ effectiveModes: asStringArray(row.effectiveModes),
764
+ effectiveWorkspaces: uniqueStrings(asArray(row.effectiveWorkspaces).map(normalizePath)),
765
+ digest: asString(row.digest),
766
+ installedAt: asString(row.installedAt),
767
+ modelInvocable: row.modelInvocable !== false,
768
+ })
769
+ }
770
+ skills.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
771
+
772
+ const nativeSkills = []
773
+ for (const item of asArray(source.nativeSkills)) {
774
+ const row = asObject(item)
775
+ const name = asString(row.name).trim()
776
+ if (name.length === 0) continue
777
+ nativeSkills.push({
778
+ name,
779
+ description: asString(row.description),
780
+ source: asString(row.source),
781
+ provider: asString(row.provider),
782
+ })
783
+ }
784
+ nativeSkills.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
785
+
786
+ // v3 field is `mcp[].server`; `mcpServers[].serverName` is tolerated only for reads.
787
+ const mcpRows = asArray(source.mcp).length > 0 ? asArray(source.mcp) : asArray(source.mcpServers)
788
+ const mcp = []
789
+ for (const item of mcpRows) {
790
+ const row = asObject(item)
791
+ const server = asString(row.server || row.serverName).trim()
792
+ if (server.length === 0) continue
793
+ const tools = asStringArray(row.tools)
794
+ mcp.push({
795
+ server,
796
+ tools,
797
+ toolCount: asNumber(row.toolCount, tools.length),
798
+ managed: row.managed === true,
799
+ entryId: asString(row.entryId),
800
+ enabled: row.enabled !== false,
801
+ modes: asStringArray(row.modes),
802
+ workspaces: uniqueStrings(asArray(row.workspaces).map(normalizePath)),
803
+ installedAt: asString(row.installedAt),
804
+ })
805
+ }
806
+ mcp.sort((left, right) => (left.server < right.server ? -1 : left.server > right.server ? 1 : 0))
807
+
808
+ return {
809
+ skills,
810
+ nativeSkills,
811
+ mcp,
812
+ modes: normalizeModeList(source.modes),
813
+ workspaces: normalizeWorkspaceList(source.workspaces),
814
+ defaultMode: asString(source.defaultMode),
815
+ }
816
+ }
817
+
818
+ function normalizeMount(raw) {
819
+ const out = {}
820
+ const rows = Array.isArray(raw)
821
+ ? raw.map((item) => {
822
+ const row = asObject(item)
823
+ return [asString(row.server || row.serverName || row.name), row]
824
+ })
825
+ : Object.entries(asObject(raw))
826
+ for (const [rawKey, value] of rows) {
827
+ const key = asString(rawKey).trim()
828
+ if (key.length === 0) continue
829
+ const row = typeof value === 'string' ? { state: value } : asObject(value)
830
+ const state = asString(row.state)
831
+ out[key] = {
832
+ state: state === 'mounting' || state === 'failed' ? state : 'ready',
833
+ error: asString(row.error),
834
+ }
835
+ }
836
+ return out
837
+ }
838
+
839
+ function normalizePool(raw) {
840
+ const source = asObject(raw)
841
+ return {
842
+ mode: asString(source.mode),
843
+ cwd: asString(source.cwd),
844
+ gated: source.gated === true,
845
+ gateSkills: source.gateSkills === true,
846
+ gateMcp: source.gateMcp === true,
847
+ skills: asStringArray(source.skills),
848
+ mcpServers: asStringArray(source.mcpServers),
849
+ }
850
+ }
851
+
852
+ async function request(path, options) {
853
+ const init = {
854
+ method: asString(options && options.method, 'GET'),
855
+ headers: { accept: 'application/json' },
856
+ cache: 'no-store',
857
+ credentials: 'same-origin',
858
+ }
859
+ if (init.method !== 'GET') {
860
+ init.headers['content-type'] = 'application/json'
861
+ init.body = JSON.stringify((options && options.body) || {})
862
+ }
863
+ let response
864
+ try {
865
+ response = await fetch(path, init)
866
+ } catch (cause) {
867
+ throw new Error(`${TEXT.networkFailed}: ${messageOf(cause)}`)
868
+ }
869
+ const payload = await response.json().catch(() => null)
870
+ const apiError =
871
+ payload && typeof payload === 'object' && payload.error && typeof payload.error.message === 'string'
872
+ ? payload.error.message
873
+ : ''
874
+ if (!response.ok) throw new Error(apiError || `HTTP ${response.status}`)
875
+ if (!payload || typeof payload !== 'object' || payload.ok !== true) {
876
+ throw new Error(apiError || TEXT.badResponse)
877
+ }
878
+ return payload
879
+ }
880
+
881
+ function withEntry(state, kind, name, entry) {
882
+ const key = kind === MCP ? 'mcp' : 'skills'
883
+ return { ...state, [key]: { ...state[key], [name]: entry } }
884
+ }
885
+
886
+ function withoutEntry(state, kind, name) {
887
+ const key = kind === MCP ? 'mcp' : 'skills'
888
+ const next = { ...state[key] }
889
+ delete next[name]
890
+ return { ...state, [key]: next }
891
+ }
892
+
893
+ function summarizeList(values, allLabel, labeler, limit) {
894
+ const list = asStringArray(values)
895
+ if (list.length === 0) return allLabel
896
+ const labels = list.map((value) => (typeof labeler === 'function' ? labeler(value) : value))
897
+ const max = typeof limit === 'number' ? limit : 2
898
+ if (labels.length <= max) return labels.join(' / ')
899
+ return `${labels.slice(0, max).join(' / ')} +${labels.length - max}`
900
+ }
901
+
902
+ function kindLabel(kind) {
903
+ if (kind === 'git') return TEXT.sourceKindGit
904
+ if (kind === 'zip') return TEXT.sourceKindZip
905
+ if (kind === 'files') return TEXT.sourceKindFiles
906
+ return TEXT.sourceKindUnknown
907
+ }
908
+
909
+ function mountLabel(state) {
910
+ if (state === 'mounting') return TEXT.mountMounting
911
+ if (state === 'failed') return TEXT.mountFailed
912
+ return TEXT.mountReady
913
+ }
914
+
915
+ function mountDotStyle(state) {
916
+ if (state === 'mounting') return S.dotMounting
917
+ if (state === 'failed') return S.dotFailed
918
+ return S.dotReady
919
+ }
920
+
921
+ function statusLabel(status) {
922
+ if (status === 'up-to-date') return TEXT.statusUpToDate
923
+ if (status === 'update-available') return TEXT.statusUpdateAvailable
924
+ if (status === 'error') return TEXT.statusError
925
+ return TEXT.neverChecked
926
+ }
927
+
928
+ /** Combined check status of one repository group ('' when nothing checked). */
929
+ function sourceGroupStatus(rows) {
930
+ const checked = (Array.isArray(rows) ? rows : []).filter(
931
+ (row) => row && row.lastCheck && asString(row.lastCheck.status).length > 0,
932
+ )
933
+ if (checked.length === 0) return ''
934
+ if (checked.some((row) => row.lastCheck.status === 'update-available')) return 'update-available'
935
+ if (checked.some((row) => row.lastCheck.status === 'error')) return 'error'
936
+ return 'up-to-date'
937
+ }
938
+
939
+ function statusBadgeStyle(status) {
940
+ if (status === 'up-to-date') return { ...S.badge, ...S.badgeOn }
941
+ if (status === 'update-available') return { ...S.badge, ...S.badgeWarn }
942
+ if (status === 'error') return { ...S.badge, ...S.badgeError }
943
+ return S.badge
944
+ }
945
+
946
+ // ------------------------------------------------------------- file utils
947
+
948
+ function bytesToBase64(bytes) {
949
+ let binary = ''
950
+ const chunk = 0x8000
951
+ for (let index = 0; index < bytes.length; index += chunk) {
952
+ binary += String.fromCharCode.apply(null, bytes.subarray(index, index + chunk))
953
+ }
954
+ return btoa(binary)
955
+ }
956
+
957
+ function encodeTextBase64(text) {
958
+ return bytesToBase64(new TextEncoder().encode(asString(text)))
959
+ }
960
+
961
+ function readFileBase64(file) {
962
+ return Promise.resolve()
963
+ .then(() => file.arrayBuffer())
964
+ .then((buffer) => bytesToBase64(new Uint8Array(buffer)))
965
+ }
966
+ // ----------------------------------------------------------------- styles
967
+
968
+ const S = {
969
+ page: {
970
+ display: 'flex',
971
+ flexDirection: 'column',
972
+ gap: '12px',
973
+ minHeight: 0,
974
+ fontSize: '13px',
975
+ lineHeight: 1.5,
976
+ color: 'var(--dsw-alias-label-primary)',
977
+ // The Host sets this token on <body>; form controls do not inherit it,
978
+ // so the panel declares it here and resets controls in the style block.
979
+ fontFamily:
980
+ 'var(--dsw-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif)',
981
+ },
982
+ headerRow: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px' },
983
+ titleWrap: { minWidth: 0 },
984
+ title: { margin: 0, fontSize: '18px', fontWeight: 600, lineHeight: 1.3 },
985
+ subtitle: { margin: '4px 0 0', fontSize: '13px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.5, maxWidth: '760px' },
986
+ toolbar: { display: 'flex', alignItems: 'flex-start', gap: '8px', flex: '0 0 auto', paddingTop: '2px' },
987
+ statusBar: {
988
+ display: 'flex',
989
+ flexWrap: 'wrap',
990
+ alignItems: 'center',
991
+ justifyContent: 'space-between',
992
+ gap: '10px',
993
+ border: '1px solid var(--rp-line)',
994
+ background: 'var(--rp-card-2)',
995
+ borderRadius: '10px',
996
+ padding: '8px 12px',
997
+ },
998
+ statusMain: { display: 'flex', alignItems: 'center', gap: '8px', flex: '0 0 auto' },
999
+ statusLabel: { fontSize: '13px', fontWeight: 500 },
1000
+ onText: { fontSize: '13px', color: 'var(--dsw-alias-state-success-primary)' },
1001
+ offText: { fontSize: '13px', color: 'var(--dsw-alias-state-error-primary)' },
1002
+ chipRow: { display: 'flex', flexWrap: 'wrap', gap: '6px' },
1003
+ chip: {
1004
+ display: 'inline-flex',
1005
+ alignItems: 'center',
1006
+ gap: '6px',
1007
+ padding: '2px 9px',
1008
+ borderRadius: '999px',
1009
+ border: '1px solid var(--rp-line)',
1010
+ background: 'var(--rp-card)',
1011
+ fontSize: '12px',
1012
+ color: 'var(--dsw-alias-label-secondary)',
1013
+ maxWidth: '460px',
1014
+ overflow: 'hidden',
1015
+ textOverflow: 'ellipsis',
1016
+ whiteSpace: 'nowrap',
1017
+ },
1018
+ chipDot: { width: '6px', height: '6px', borderRadius: '999px', background: 'var(--rp-accent)' },
1019
+ // Tabs are pills, never underlines. An underline needs a border on the
1020
+ // container or on every tab, and any of those can survive a state change and
1021
+ // read as a stray white line. A tinted pill has exactly one source of truth:
1022
+ // the active tab's own background.
1023
+ tabs: { display: 'flex', gap: '4px' },
1024
+ tab: {
1025
+ appearance: 'none',
1026
+ border: 'none',
1027
+ background: 'transparent',
1028
+ color: 'var(--dsw-alias-label-secondary)',
1029
+ padding: '5px 12px',
1030
+ borderRadius: '7px',
1031
+ fontSize: '13px',
1032
+ lineHeight: 1.4,
1033
+ cursor: 'pointer',
1034
+ outline: 'none',
1035
+ },
1036
+ tabActive: {
1037
+ background: 'var(--rp-accent-weak)',
1038
+ color: 'var(--rp-accent)',
1039
+ fontWeight: 600,
1040
+ },
1041
+ error: {
1042
+ border: '1px solid var(--dsw-alias-state-error-primary)',
1043
+ background: 'var(--rp-card)',
1044
+ color: 'var(--dsw-alias-state-error-primary)',
1045
+ borderRadius: '8px',
1046
+ padding: '7px 10px',
1047
+ fontSize: '13px',
1048
+ lineHeight: 1.5,
1049
+ wordBreak: 'break-word',
1050
+ },
1051
+ notice: {
1052
+ border: '1px solid var(--dsw-alias-state-success-primary)',
1053
+ background: 'var(--rp-card)',
1054
+ color: 'var(--dsw-alias-state-success-primary)',
1055
+ borderRadius: '8px',
1056
+ padding: '7px 10px',
1057
+ fontSize: '13px',
1058
+ },
1059
+ noticeText: { fontSize: '13px', color: 'var(--dsw-alias-state-success-primary)', alignSelf: 'center' },
1060
+ empty: { fontSize: '13px', color: 'var(--dsw-alias-label-secondary)', padding: '14px 4px', lineHeight: 1.6 },
1061
+ loadingRow: { fontSize: '13px', color: 'var(--dsw-alias-label-secondary)' },
1062
+ button: {
1063
+ appearance: 'none',
1064
+ display: 'inline-flex',
1065
+ alignItems: 'center',
1066
+ justifyContent: 'center',
1067
+ flex: '0 0 auto',
1068
+ height: '30px',
1069
+ whiteSpace: 'nowrap',
1070
+ lineHeight: 1,
1071
+ border: '1px solid var(--rp-line)',
1072
+ background: 'var(--rp-card)',
1073
+ color: 'var(--dsw-alias-label-primary)',
1074
+ borderRadius: '8px',
1075
+ padding: '0 12px',
1076
+ fontSize: '13px',
1077
+ cursor: 'pointer',
1078
+ },
1079
+ buttonSmall: {
1080
+ appearance: 'none',
1081
+ display: 'inline-flex',
1082
+ alignItems: 'center',
1083
+ justifyContent: 'center',
1084
+ flex: '0 0 auto',
1085
+ height: '26px',
1086
+ whiteSpace: 'nowrap',
1087
+ lineHeight: 1,
1088
+ border: '1px solid var(--rp-line)',
1089
+ background: 'var(--rp-card)',
1090
+ color: 'var(--dsw-alias-label-primary)',
1091
+ borderRadius: '7px',
1092
+ padding: '0 9px',
1093
+ fontSize: '12px',
1094
+ cursor: 'pointer',
1095
+ },
1096
+ buttonPrimary: {
1097
+ appearance: 'none',
1098
+ display: 'inline-flex',
1099
+ alignItems: 'center',
1100
+ justifyContent: 'center',
1101
+ flex: '0 0 auto',
1102
+ height: '30px',
1103
+ whiteSpace: 'nowrap',
1104
+ lineHeight: 1,
1105
+ border: '1px solid var(--rp-accent)',
1106
+ background: 'var(--rp-accent)',
1107
+ // White on the blue accent in both themes; the inverted-label token would
1108
+ // turn dark-on-blue in the light theme.
1109
+ color: '#fff',
1110
+ borderRadius: '8px',
1111
+ padding: '0 12px',
1112
+ fontSize: '13px',
1113
+ fontWeight: 500,
1114
+ cursor: 'pointer',
1115
+ },
1116
+ buttonDanger: {
1117
+ appearance: 'none',
1118
+ display: 'inline-flex',
1119
+ alignItems: 'center',
1120
+ justifyContent: 'center',
1121
+ flex: '0 0 auto',
1122
+ height: '28px',
1123
+ whiteSpace: 'nowrap',
1124
+ lineHeight: 1,
1125
+ border: '1px solid var(--dsw-alias-state-error-primary)',
1126
+ background: 'var(--rp-card-2)',
1127
+ color: 'var(--dsw-alias-state-error-primary)',
1128
+ borderRadius: '8px',
1129
+ padding: '0 12px',
1130
+ fontSize: '13px',
1131
+ fontWeight: 500,
1132
+ cursor: 'pointer',
1133
+ },
1134
+ linkButton: {
1135
+ appearance: 'none',
1136
+ border: 'none',
1137
+ background: 'transparent',
1138
+ color: 'var(--rp-accent)',
1139
+ cursor: 'pointer',
1140
+ fontSize: '12px',
1141
+ padding: '0 2px',
1142
+ fontFamily: 'inherit',
1143
+ },
1144
+ ghostDanger: {
1145
+ appearance: 'none',
1146
+ display: 'inline-flex',
1147
+ alignItems: 'center',
1148
+ justifyContent: 'center',
1149
+ height: '22px',
1150
+ whiteSpace: 'nowrap',
1151
+ border: '1px solid var(--rp-line)',
1152
+ background: 'transparent',
1153
+ color: 'var(--dsw-alias-label-secondary)',
1154
+ borderRadius: '6px',
1155
+ padding: '0 8px',
1156
+ fontSize: '12px',
1157
+ cursor: 'pointer',
1158
+ flex: '0 0 auto',
1159
+ },
1160
+ toggleTrack: {
1161
+ appearance: 'none',
1162
+ display: 'inline-flex',
1163
+ alignItems: 'center',
1164
+ flex: '0 0 auto',
1165
+ width: '38px',
1166
+ height: '20px',
1167
+ padding: '2px',
1168
+ border: '1px solid var(--rp-line-strong)',
1169
+ borderRadius: '999px',
1170
+ background: 'var(--rp-card)',
1171
+ cursor: 'pointer',
1172
+ },
1173
+ toggleTrackOn: {
1174
+ borderColor: 'var(--rp-accent)',
1175
+ background: 'var(--rp-accent)',
1176
+ justifyContent: 'flex-end',
1177
+ },
1178
+ toggleKnob: { display: 'block', width: '14px', height: '14px', borderRadius: '999px', background: 'var(--dsw-alias-label-secondary)' },
1179
+ toggleKnobOn: { background: '#fff' },
1180
+ switchRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', padding: '6px 0' },
1181
+ switchText: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0 },
1182
+ switchLabel: { fontSize: '13px', fontWeight: 500 },
1183
+ stack: { display: 'flex', flexDirection: 'column', gap: '12px', minWidth: 0 },
1184
+ card: {
1185
+ border: '1px solid var(--rp-line)',
1186
+ borderRadius: '12px',
1187
+ background: 'var(--rp-card)',
1188
+ padding: '14px 16px',
1189
+ display: 'flex',
1190
+ flexDirection: 'column',
1191
+ gap: '12px',
1192
+ minWidth: 0,
1193
+ },
1194
+ // A namespace accent stripe: skills are content (brand), MCP is a connection
1195
+ // (amber). The stripe is the fastest way to tell the two groups apart.
1196
+ cardSkill: { borderLeft: '3px solid var(--rp-accent)' },
1197
+ cardMcp: { borderLeft: '3px solid var(--rp-mcp)' },
1198
+ cardSystem: { borderLeft: '3px solid var(--rp-line-strong)' },
1199
+ cardHead: {
1200
+ display: 'flex',
1201
+ alignItems: 'center',
1202
+ justifyContent: 'space-between',
1203
+ gap: '10px',
1204
+ flexWrap: 'wrap',
1205
+ paddingBottom: '8px',
1206
+ borderBottom: '1px solid var(--rp-line)',
1207
+ },
1208
+ cardTitleRow: { display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0 },
1209
+ cardTitle: { fontSize: '14px', fontWeight: 600 },
1210
+ countBadge: {
1211
+ fontSize: '11px',
1212
+ color: 'var(--dsw-alias-label-secondary)',
1213
+ border: '1px solid var(--rp-line)',
1214
+ borderRadius: '999px',
1215
+ padding: '0 7px',
1216
+ lineHeight: '16px',
1217
+ },
1218
+ cardDesc: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.5, marginTop: '-4px' },
1219
+ rowItem: {
1220
+ display: 'flex',
1221
+ flexDirection: 'column',
1222
+ gap: '6px',
1223
+ padding: '9px 2px',
1224
+ borderBottom: '1px solid var(--rp-line)',
1225
+ minWidth: 0,
1226
+ },
1227
+ rowItemLast: { borderBottom: 'none' },
1228
+ rowMain: { display: 'flex', alignItems: 'flex-start', gap: '10px', minWidth: 0 },
1229
+ rowText: { flex: 1, minWidth: 0 },
1230
+ rowName: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px', fontSize: '13px', fontWeight: 600, minWidth: 0 },
1231
+ // Real skill descriptions can run for paragraphs (some list every command).
1232
+ // Clamp them so one resource never swallows the whole panel; the full text
1233
+ // stays available as the row's hover title.
1234
+ rowDesc: {
1235
+ fontSize: '12px',
1236
+ color: 'var(--dsw-alias-label-secondary)',
1237
+ lineHeight: 1.5,
1238
+ marginTop: '2px',
1239
+ wordBreak: 'break-word',
1240
+ display: '-webkit-box',
1241
+ WebkitLineClamp: 2,
1242
+ WebkitBoxOrient: 'vertical',
1243
+ overflow: 'hidden',
1244
+ },
1245
+ rowMeta: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px', marginTop: '5px' },
1246
+ rowActions: { display: 'flex', alignItems: 'center', gap: '6px', flex: '0 0 auto' },
1247
+ condChip: {
1248
+ display: 'inline-flex',
1249
+ alignItems: 'center',
1250
+ gap: '4px',
1251
+ border: '1px solid var(--rp-line)',
1252
+ background: 'var(--rp-card-2)',
1253
+ borderRadius: '999px',
1254
+ padding: '1px 8px',
1255
+ fontSize: '12px',
1256
+ color: 'var(--dsw-alias-label-secondary)',
1257
+ maxWidth: '320px',
1258
+ overflow: 'hidden',
1259
+ textOverflow: 'ellipsis',
1260
+ whiteSpace: 'nowrap',
1261
+ },
1262
+ condPanel: {
1263
+ display: 'grid',
1264
+ gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
1265
+ gap: '10px',
1266
+ background: 'var(--rp-card-2)',
1267
+ border: '1px solid var(--rp-line)',
1268
+ borderRadius: '8px',
1269
+ padding: '10px',
1270
+ },
1271
+ badge: {
1272
+ flex: '0 0 auto',
1273
+ fontSize: '11px',
1274
+ color: 'var(--dsw-alias-label-secondary)',
1275
+ border: '1px solid var(--rp-line)',
1276
+ borderRadius: '5px',
1277
+ padding: '1px 6px',
1278
+ },
1279
+ badgeOn: {
1280
+ flex: '0 0 auto',
1281
+ fontSize: '11px',
1282
+ color: 'var(--rp-ok)',
1283
+ background: 'var(--rp-ok-weak)',
1284
+ border: '1px solid transparent',
1285
+ borderRadius: '5px',
1286
+ padding: '1px 6px',
1287
+ },
1288
+ badgeWarn: {
1289
+ flex: '0 0 auto',
1290
+ fontSize: '11px',
1291
+ color: 'var(--rp-warn, var(--dsw-alias-label-secondary))',
1292
+ background: 'var(--rp-mcp-weak)',
1293
+ border: '1px solid transparent',
1294
+ borderRadius: '5px',
1295
+ padding: '1px 6px',
1296
+ },
1297
+ badgeError: {
1298
+ flex: '0 0 auto',
1299
+ fontSize: '11px',
1300
+ color: 'var(--rp-err)',
1301
+ background: 'var(--rp-err-weak)',
1302
+ border: '1px solid transparent',
1303
+ borderRadius: '5px',
1304
+ padding: '1px 6px',
1305
+ },
1306
+ managedTag: {
1307
+ flex: '0 0 auto',
1308
+ fontSize: '11px',
1309
+ color: 'var(--rp-accent)',
1310
+ border: '1px solid var(--rp-accent)',
1311
+ borderRadius: '4px',
1312
+ padding: '0 5px',
1313
+ },
1314
+ savingDot: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)' },
1315
+ field: { display: 'flex', flexDirection: 'column', gap: '6px', minWidth: 0 },
1316
+ fieldLabel: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)' },
1317
+ fieldHint: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', opacity: 0.85, lineHeight: 1.5 },
1318
+ input: {
1319
+ flex: 1,
1320
+ minWidth: 0,
1321
+ border: '1px solid var(--rp-line-strong)',
1322
+ background: 'var(--rp-control)',
1323
+ color: 'var(--dsw-alias-label-primary)',
1324
+ borderRadius: '8px',
1325
+ padding: '7px 10px',
1326
+ fontSize: '13px',
1327
+ lineHeight: 1.2,
1328
+ outline: 'none',
1329
+ fontFamily: 'inherit',
1330
+ },
1331
+ inputSearch: {
1332
+ flex: '0 1 320px',
1333
+ minWidth: '180px',
1334
+ border: '1px solid var(--rp-line-strong)',
1335
+ background: 'var(--rp-control)',
1336
+ color: 'var(--dsw-alias-label-primary)',
1337
+ borderRadius: '8px',
1338
+ padding: '7px 10px',
1339
+ fontSize: '13px',
1340
+ lineHeight: 1.2,
1341
+ outline: 'none',
1342
+ fontFamily: 'inherit',
1343
+ },
1344
+ textarea: {
1345
+ minWidth: 0,
1346
+ resize: 'vertical',
1347
+ border: '1px solid var(--rp-line-strong)',
1348
+ background: 'var(--rp-control)',
1349
+ color: 'var(--dsw-alias-label-primary)',
1350
+ borderRadius: '8px',
1351
+ padding: '7px 10px',
1352
+ fontSize: '13px',
1353
+ lineHeight: 1.2,
1354
+ outline: 'none',
1355
+ fontFamily: 'inherit',
1356
+ lineHeight: 1.5,
1357
+ },
1358
+ select: {
1359
+ appearance: 'none',
1360
+ height: '30px',
1361
+ flex: '0 0 auto',
1362
+ border: '1px solid var(--rp-line-strong)',
1363
+ background: 'var(--rp-control)',
1364
+ color: 'var(--dsw-alias-label-primary)',
1365
+ borderRadius: '8px',
1366
+ padding: '0 26px 0 10px',
1367
+ fontSize: '13px',
1368
+ cursor: 'pointer',
1369
+ backgroundImage:
1370
+ 'linear-gradient(45deg, transparent 50%, var(--dsw-alias-label-secondary) 50%), linear-gradient(135deg, var(--dsw-alias-label-secondary) 50%, transparent 50%)',
1371
+ backgroundPosition: 'calc(100% - 13px) 50%, calc(100% - 9px) 50%',
1372
+ backgroundSize: '4px 4px, 4px 4px',
1373
+ backgroundRepeat: 'no-repeat',
1374
+ },
1375
+ row: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', minWidth: 0 },
1376
+ rowWrap: { display: 'flex', alignItems: 'flex-end', flexWrap: 'wrap', gap: '10px', minWidth: 0 },
1377
+ searchRow: { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap', minWidth: 0 },
1378
+ multi: {
1379
+ display: 'flex',
1380
+ flexDirection: 'column',
1381
+ gap: '6px',
1382
+ border: '1px solid var(--rp-line-strong)',
1383
+ borderRadius: '8px',
1384
+ padding: '8px',
1385
+ background: 'var(--rp-control)',
1386
+ minWidth: 0,
1387
+ },
1388
+ multiChips: { display: 'flex', flexWrap: 'wrap', gap: '4px' },
1389
+ mchip: {
1390
+ display: 'inline-flex',
1391
+ alignItems: 'center',
1392
+ gap: '4px',
1393
+ border: '1px solid var(--rp-line)',
1394
+ background: 'var(--rp-card-2)',
1395
+ borderRadius: '999px',
1396
+ padding: '1px 8px',
1397
+ fontSize: '12px',
1398
+ color: 'var(--dsw-alias-label-primary)',
1399
+ maxWidth: '100%',
1400
+ },
1401
+ mchipLabel: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1402
+ mchipX: {
1403
+ appearance: 'none',
1404
+ border: 'none',
1405
+ background: 'transparent',
1406
+ color: 'var(--dsw-alias-label-secondary)',
1407
+ cursor: 'pointer',
1408
+ fontSize: '13px',
1409
+ lineHeight: 1,
1410
+ padding: '0 0 1px',
1411
+ },
1412
+ multiList: {
1413
+ display: 'flex',
1414
+ flexDirection: 'column',
1415
+ gap: '2px',
1416
+ maxHeight: '200px',
1417
+ overflow: 'auto',
1418
+ borderTop: '1px solid var(--rp-line)',
1419
+ paddingTop: '4px',
1420
+ },
1421
+ multiRow: {
1422
+ display: 'flex',
1423
+ alignItems: 'center',
1424
+ gap: '8px',
1425
+ appearance: 'none',
1426
+ border: '1px solid transparent',
1427
+ background: 'transparent',
1428
+ color: 'var(--dsw-alias-label-primary)',
1429
+ borderRadius: '6px',
1430
+ padding: '4px 6px',
1431
+ fontSize: '13px',
1432
+ cursor: 'pointer',
1433
+ textAlign: 'left',
1434
+ width: '100%',
1435
+ minWidth: 0,
1436
+ fontFamily: 'inherit',
1437
+ },
1438
+ multiRowActive: { background: 'var(--rp-card-2)', borderColor: 'var(--rp-line-strong)' },
1439
+ itemName: { fontSize: '13px', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1440
+ multiHint: {
1441
+ flex: 1,
1442
+ minWidth: 0,
1443
+ fontSize: '11px',
1444
+ color: 'var(--dsw-alias-label-secondary)',
1445
+ overflow: 'hidden',
1446
+ textOverflow: 'ellipsis',
1447
+ whiteSpace: 'nowrap',
1448
+ textAlign: 'right',
1449
+ },
1450
+ check: {
1451
+ display: 'inline-flex',
1452
+ alignItems: 'center',
1453
+ justifyContent: 'center',
1454
+ width: '14px',
1455
+ height: '14px',
1456
+ flex: '0 0 auto',
1457
+ borderRadius: '4px',
1458
+ border: '1px solid var(--rp-line-strong)',
1459
+ fontSize: '11px',
1460
+ color: 'var(--rp-accent)',
1461
+ lineHeight: 1,
1462
+ },
1463
+ checkOn: { borderColor: 'var(--rp-accent)', background: 'var(--rp-accent)', color: '#fff' },
1464
+ hintBlock: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.6 },
1465
+ previewBox: {
1466
+ border: '1px solid var(--rp-accent-line)',
1467
+ borderRadius: '8px',
1468
+ background: 'var(--rp-accent-weak)',
1469
+ padding: '10px 12px',
1470
+ display: 'flex',
1471
+ flexDirection: 'column',
1472
+ gap: '8px',
1473
+ minWidth: 0,
1474
+ },
1475
+ resourceLine: { display: 'flex', alignItems: 'flex-start', gap: '8px', flexWrap: 'wrap', minWidth: 0 },
1476
+ resourceLabel: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', flex: '0 0 auto', paddingTop: '2px' },
1477
+ importBar: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: '10px' },
1478
+ importTile: {
1479
+ appearance: 'none',
1480
+ textAlign: 'left',
1481
+ display: 'flex',
1482
+ flexDirection: 'column',
1483
+ gap: '3px',
1484
+ border: '1px solid var(--rp-line)',
1485
+ background: 'var(--rp-card-2)',
1486
+ color: 'var(--dsw-alias-label-primary)',
1487
+ borderRadius: '9px',
1488
+ padding: '10px 12px',
1489
+ cursor: 'pointer',
1490
+ fontFamily: 'inherit',
1491
+ minWidth: 0,
1492
+ },
1493
+ importTileTitle: { fontSize: '13px', fontWeight: 600 },
1494
+ importTileHint: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.4 },
1495
+ sourceRow: {
1496
+ display: 'flex',
1497
+ alignItems: 'flex-start',
1498
+ gap: '10px',
1499
+ padding: '9px 2px',
1500
+ borderBottom: '1px solid var(--rp-line)',
1501
+ minWidth: 0,
1502
+ },
1503
+ sourceMain: { flex: 1, minWidth: 0 },
1504
+ sourceName: { display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap', fontSize: '13px', fontWeight: 600, minWidth: 0 },
1505
+ sourceMeta: { display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap', marginTop: '4px', minWidth: 0 },
1506
+ mono: {
1507
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
1508
+ fontSize: '12px',
1509
+ color: 'var(--dsw-alias-label-secondary)',
1510
+ wordBreak: 'break-all',
1511
+ minWidth: 0,
1512
+ },
1513
+ mountRow: {
1514
+ display: 'flex',
1515
+ alignItems: 'center',
1516
+ justifyContent: 'space-between',
1517
+ gap: '10px',
1518
+ flexWrap: 'wrap',
1519
+ padding: '7px 2px',
1520
+ borderBottom: '1px solid var(--rp-line)',
1521
+ },
1522
+ mountMain: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', minWidth: 0 },
1523
+ dot: { width: '7px', height: '7px', borderRadius: '999px', flex: '0 0 auto', background: 'var(--dsw-alias-label-secondary)' },
1524
+ dotMounting: { background: 'var(--rp-accent)' },
1525
+ dotReady: { background: 'var(--dsw-alias-state-success-primary)' },
1526
+ dotFailed: { background: 'var(--dsw-alias-state-error-primary)' },
1527
+ overlay: {
1528
+ position: 'fixed',
1529
+ inset: 0,
1530
+ background: 'rgba(0, 0, 0, 0.45)',
1531
+ display: 'flex',
1532
+ alignItems: 'center',
1533
+ justifyContent: 'center',
1534
+ zIndex: 40,
1535
+ padding: '24px',
1536
+ },
1537
+ modal: {
1538
+ width: 'min(720px, 100%)',
1539
+ maxHeight: '84vh',
1540
+ display: 'flex',
1541
+ flexDirection: 'column',
1542
+ gap: '14px',
1543
+ background: 'var(--rp-card)',
1544
+ color: 'var(--dsw-alias-label-primary)',
1545
+ border: '1px solid var(--rp-line-strong)',
1546
+ borderRadius: '14px',
1547
+ padding: '18px',
1548
+ overflow: 'auto',
1549
+ boxShadow: '0 24px 64px rgba(0, 0, 0, 0.38)',
1550
+ },
1551
+ modalWide: { width: 'min(820px, 100%)' },
1552
+ // A divider under the title separates "what am I doing" from "the form".
1553
+ modalHead: {
1554
+ display: 'flex',
1555
+ alignItems: 'center',
1556
+ justifyContent: 'space-between',
1557
+ gap: '12px',
1558
+ paddingBottom: '12px',
1559
+ borderBottom: '1px solid var(--rp-line)',
1560
+ },
1561
+ modalTitle: { margin: 0, fontSize: '16px', fontWeight: 600 },
1562
+ modalFoot: { display: 'flex', alignItems: 'center', gap: '8px', justifyContent: 'flex-end', flexWrap: 'wrap' },
1563
+ uploadTextarea: { minHeight: '150px', resize: 'vertical', lineHeight: 1.5 },
1564
+ fileRow: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', minWidth: 0 },
1565
+ addList: {
1566
+ display: 'flex',
1567
+ flexDirection: 'column',
1568
+ gap: '2px',
1569
+ maxHeight: '320px',
1570
+ overflow: 'auto',
1571
+ border: '1px solid var(--rp-line)',
1572
+ borderRadius: '8px',
1573
+ padding: '4px',
1574
+ },
1575
+ addRow: {
1576
+ display: 'flex',
1577
+ alignItems: 'flex-start',
1578
+ gap: '8px',
1579
+ appearance: 'none',
1580
+ border: '1px solid transparent',
1581
+ background: 'transparent',
1582
+ color: 'var(--dsw-alias-label-primary)',
1583
+ borderRadius: '6px',
1584
+ padding: '5px 6px',
1585
+ fontSize: '13px',
1586
+ cursor: 'pointer',
1587
+ textAlign: 'left',
1588
+ width: '100%',
1589
+ minWidth: 0,
1590
+ fontFamily: 'inherit',
1591
+ },
1592
+ addRowActive: { background: 'var(--rp-card-2)', borderColor: 'var(--rp-line-strong)' },
1593
+ addText: { flex: 1, minWidth: 0 },
1594
+ addName: { fontSize: '13px', fontWeight: 500 },
1595
+ addDesc: { fontSize: '11px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.4, marginTop: '1px', wordBreak: 'break-word' },
1596
+ pills: { display: 'flex', flexWrap: 'wrap', gap: '4px' },
1597
+ wizStep: { display: 'flex', flexDirection: 'column', gap: '8px', border: '1px solid var(--rp-line)', borderRadius: '8px', padding: '10px' },
1598
+ }
1599
+
1600
+ // ------------------------------------------------------------ components
1601
+
1602
+ function Chip(props) {
1603
+ const label = asString(props.label)
1604
+ const value = asString(props.value)
1605
+ return h(
1606
+ 'span',
1607
+ { style: S.chip, title: asString(props.title) || `${label}: ${value}` },
1608
+ props.dot ? h('span', { style: { ...S.chipDot, background: props.dot } }) : null,
1609
+ `${label}: ${value}`,
1610
+ )
1611
+ }
1612
+
1613
+ function Toggle(props) {
1614
+ const on = props.checked === true
1615
+ const disabled = props.disabled === true
1616
+ return h(
1617
+ 'button',
1618
+ {
1619
+ type: 'button',
1620
+ role: 'switch',
1621
+ 'aria-checked': on ? 'true' : 'false',
1622
+ 'aria-label': asString(props.label) || (on ? TEXT.enabled : TEXT.disabled),
1623
+ title: asString(props.title) || asString(props.label),
1624
+ disabled,
1625
+ style: {
1626
+ ...S.toggleTrack,
1627
+ ...(on ? S.toggleTrackOn : null),
1628
+ ...(disabled ? { opacity: 0.55, cursor: 'default' } : null),
1629
+ },
1630
+ onClick: () => {
1631
+ if (!disabled && typeof props.onChange === 'function') props.onChange(!on)
1632
+ },
1633
+ },
1634
+ h('span', { style: { ...S.toggleKnob, ...(on ? S.toggleKnobOn : null) } }),
1635
+ )
1636
+ }
1637
+
1638
+ function SwitchRow(props) {
1639
+ return h(
1640
+ 'div',
1641
+ { style: S.switchRow },
1642
+ h(
1643
+ 'div',
1644
+ { style: S.switchText },
1645
+ h('span', { style: S.switchLabel }, asString(props.label)),
1646
+ props.hint ? h('span', { style: S.fieldHint }, asString(props.hint)) : null,
1647
+ ),
1648
+ h(Toggle, {
1649
+ checked: props.checked === true,
1650
+ disabled: props.disabled === true,
1651
+ onChange: props.onChange,
1652
+ label: asString(props.label),
1653
+ }),
1654
+ )
1655
+ }
1656
+
1657
+ /** Render one or more children as keyed fragments so arrays never warn. */
1658
+ function renderChildren(children) {
1659
+ if (children === undefined || children === null) return null
1660
+ const list = Array.isArray(children) ? children : [children]
1661
+ return list.map((child, index) => h(React.Fragment, { key: `child-${index}` }, child))
1662
+ }
1663
+
1664
+ function Field(props) {
1665
+ return h(
1666
+ 'div',
1667
+ { style: S.field },
1668
+ h('span', { style: S.fieldLabel }, asString(props.label)),
1669
+ ...renderChildren(props.children),
1670
+ props.hint ? h('span', { style: S.fieldHint }, asString(props.hint)) : null,
1671
+ )
1672
+ }
1673
+
1674
+ function MultiSelect(props) {
1675
+ const items = useMemo(() => asArray(props.items), [props.items])
1676
+ const selected = useMemo(() => asStringArray(props.selected), [props.selected])
1677
+ const [search, setSearch] = useState('')
1678
+ const query = search.trim().toLowerCase()
1679
+ const labelOf = useMemo(() => {
1680
+ const map = new Map()
1681
+ for (const item of items) map.set(asString(item.value), asString(item.label) || asString(item.value))
1682
+ return map
1683
+ }, [items])
1684
+ const filtered = useMemo(() => {
1685
+ const list = items.filter((item) => {
1686
+ if (query.length === 0) return true
1687
+ const haystack = `${asString(item.label)} ${asString(item.hint)}`.toLowerCase()
1688
+ return haystack.includes(query)
1689
+ })
1690
+ return list
1691
+ }, [items, query])
1692
+ const toggleValue = (value) => {
1693
+ const next = selected.filter((candidate) => candidate !== value)
1694
+ if (!selected.includes(value)) next.push(value)
1695
+ if (typeof props.onChange === 'function') props.onChange(next)
1696
+ }
1697
+ const selectVisible = () => {
1698
+ const next = selected.slice()
1699
+ for (const item of filtered) {
1700
+ const value = asString(item.value)
1701
+ if (value.length > 0 && !next.includes(value)) next.push(value)
1702
+ }
1703
+ if (typeof props.onChange === 'function') props.onChange(next)
1704
+ }
1705
+ const clearAll = () => {
1706
+ if (typeof props.onChange === 'function') props.onChange([])
1707
+ }
1708
+ return h(
1709
+ 'div',
1710
+ { style: S.multi },
1711
+ selected.length === 0
1712
+ ? h('span', { style: S.fieldHint }, asString(props.emptyHint) || TEXT.addNoneSelected)
1713
+ : h(
1714
+ 'div',
1715
+ { style: S.multiChips },
1716
+ ...selected.map((value) =>
1717
+ h(
1718
+ 'span',
1719
+ { key: value, style: S.mchip },
1720
+ h('span', { style: S.mchipLabel }, labelOf.get(value) || value),
1721
+ h(
1722
+ 'button',
1723
+ {
1724
+ type: 'button',
1725
+ style: S.mchipX,
1726
+ title: asString(props.removeLabel) || '×',
1727
+ onClick: () => toggleValue(value),
1728
+ },
1729
+ '×',
1730
+ ),
1731
+ ),
1732
+ ),
1733
+ ),
1734
+ h(
1735
+ 'div',
1736
+ { style: S.row },
1737
+ h('input', {
1738
+ style: { ...S.input, minWidth: '100px' },
1739
+ value: search,
1740
+ placeholder: asString(props.searchPlaceholder),
1741
+ onChange: (event) => setSearch(asString(event.target.value)),
1742
+ }),
1743
+ h('button', { type: 'button', style: S.buttonSmall, onClick: selectVisible }, asString(props.selectAllLabel) || TEXT.selectAll),
1744
+ h('button', { type: 'button', style: S.buttonSmall, onClick: clearAll }, asString(props.clearAllLabel) || TEXT.clearAll),
1745
+ ),
1746
+ filtered.length === 0
1747
+ ? h('div', { style: S.empty }, items.length === 0 ? asString(props.emptyText) || TEXT.noMatches : TEXT.noMatches)
1748
+ : h(
1749
+ 'div',
1750
+ { style: S.multiList },
1751
+ ...filtered.map((item) => {
1752
+ const value = asString(item.value)
1753
+ const active = selected.includes(value)
1754
+ return h(
1755
+ 'button',
1756
+ {
1757
+ key: value,
1758
+ type: 'button',
1759
+ style: { ...S.multiRow, ...(active ? S.multiRowActive : null) },
1760
+ title: asString(item.hint) || value,
1761
+ onClick: () => toggleValue(value),
1762
+ },
1763
+ h('span', { style: { ...S.check, ...(active ? S.checkOn : null) } }, active ? '✓' : ''),
1764
+ h('span', { style: S.itemName }, asString(item.label) || value),
1765
+ // The hint only earns its space when it adds information: for a
1766
+ // mode it would just repeat the label on the right.
1767
+ item.hint && asString(item.hint) !== (asString(item.label) || value)
1768
+ ? h('span', { style: S.multiHint }, asString(item.hint))
1769
+ : null,
1770
+ )
1771
+ }),
1772
+ ),
1773
+ )
1774
+ }
1775
+
1776
+ function AddPathRow(props) {
1777
+ const [value, setValue] = useState('')
1778
+ const add = () => {
1779
+ const path = normalizePath(value)
1780
+ if (path.length === 0) return
1781
+ if (typeof props.onAdd === 'function') props.onAdd(path)
1782
+ setValue('')
1783
+ }
1784
+ return h(
1785
+ 'div',
1786
+ { style: S.row },
1787
+ h('input', {
1788
+ style: { ...S.input, minWidth: '140px' },
1789
+ value,
1790
+ placeholder: asString(props.placeholder),
1791
+ onChange: (event) => setValue(asString(event.target.value)),
1792
+ onKeyDown: (event) => {
1793
+ if (event.key === 'Enter') add()
1794
+ },
1795
+ }),
1796
+ h('button', { type: 'button', style: S.buttonSmall, onClick: add }, asString(props.label) || '+'),
1797
+ )
1798
+ }
1799
+
1800
+ function Modal(props) {
1801
+ const wide = props.wide === true
1802
+ return h(
1803
+ 'div',
1804
+ { style: S.overlay, role: 'dialog', 'aria-modal': 'true', 'aria-label': asString(props.title) },
1805
+ h(
1806
+ 'div',
1807
+ {
1808
+ style: { ...S.modal, ...(wide ? S.modalWide : null) },
1809
+ onMouseDown: (event) => event.stopPropagation(),
1810
+ },
1811
+ h(
1812
+ 'div',
1813
+ { style: S.modalHead },
1814
+ h('h3', { style: S.modalTitle }, asString(props.title)),
1815
+ h(
1816
+ 'button',
1817
+ { type: 'button', style: S.buttonSmall, onClick: props.onClose, disabled: props.busy === true },
1818
+ TEXT.close,
1819
+ ),
1820
+ ),
1821
+ props.subtitle ? h('p', { style: S.subtitle }, asString(props.subtitle)) : null,
1822
+ props.error ? h('div', { style: S.error, role: 'alert' }, asString(props.error)) : null,
1823
+ h('div', { style: S.stack }, ...renderChildren(props.children)),
1824
+ props.footer ? h('div', { style: S.modalFoot }, props.footer) : null,
1825
+ ),
1826
+ )
1827
+ }
1828
+
1829
+ function safeNode(key, render) {
1830
+ try {
1831
+ return h(React.Fragment, { key }, render())
1832
+ } catch (cause) {
1833
+ return h(React.Fragment, { key }, h('div', { style: S.error }, `${TEXT.rowFailed}: ${messageOf(cause)}`))
1834
+ }
1835
+ }
1836
+ // ------------------------------------------------------- v3 style extras
1837
+
1838
+ // Palette. Every colour is derived from the Host theme tokens with color-mix,
1839
+ // so the panel follows the light and dark themes instead of hard-coding values.
1840
+ // The plain token before each color-mix is the fallback for engines without
1841
+ // color-mix support: the later declaration wins only when it is valid.
1842
+ //
1843
+ // The accent is `--dsw-alias-link` (the DeepSeek blue, which flips between the
1844
+ // 400 and 500 step per theme) and NOT `--dsw-alias-brand-primary`: that token is
1845
+ // the primary-button FILL, i.e. near-white in the dark theme and near-black in
1846
+ // the light one, so using it as an accent painted white-on-dark "markers".
1847
+ const RP_VARS = [
1848
+ '--rp-card:var(--dsw-alias-bg-layer-1)',
1849
+ '--rp-card:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 94%,var(--dsw-alias-link))',
1850
+ '--rp-card-2:var(--dsw-alias-bg-layer-2)',
1851
+ '--rp-card-2:color-mix(in srgb,var(--dsw-alias-bg-layer-2) 92%,var(--dsw-alias-link))',
1852
+ '--rp-control:var(--dsw-alias-bg-layer-2)',
1853
+ '--rp-control:color-mix(in srgb,var(--dsw-alias-bg-layer-2) 90%,var(--dsw-alias-link))',
1854
+ '--rp-line:var(--dsw-alias-border-l1)',
1855
+ '--rp-line-strong:var(--dsw-alias-border-l2)',
1856
+ '--rp-accent:var(--dsw-alias-link)',
1857
+ '--rp-accent-weak:var(--dsw-alias-bg-layer-2)',
1858
+ '--rp-accent-weak:color-mix(in srgb,var(--dsw-alias-link) 16%,transparent)',
1859
+ '--rp-accent-line:var(--dsw-alias-link)',
1860
+ '--rp-accent-line:color-mix(in srgb,var(--dsw-alias-link) 45%,transparent)',
1861
+ // MCP is a different kind of resource (a connection, not content), so it gets
1862
+ // its own hue instead of competing with the skill accent.
1863
+ '--rp-mcp:var(--dsw-static-amber-500)',
1864
+ '--rp-mcp-weak:color-mix(in srgb,var(--dsw-static-amber-500) 16%,transparent)',
1865
+ '--rp-mcp-line:color-mix(in srgb,var(--dsw-static-amber-500) 40%,transparent)',
1866
+ '--rp-ok:var(--dsw-alias-state-success-primary)',
1867
+ '--rp-ok-weak:color-mix(in srgb,var(--dsw-alias-state-success-primary) 14%,transparent)',
1868
+ '--rp-err:var(--dsw-alias-state-error-primary)',
1869
+ '--rp-err-weak:color-mix(in srgb,var(--dsw-alias-state-error-primary) 14%,transparent)',
1870
+ '--rp-warn:var(--dsw-alias-state-warn-primary)',
1871
+ ].join(';')
1872
+
1873
+ const PAGE_CSS =
1874
+ // Form controls do not inherit the page font from the Host, so establish it
1875
+ // here. Never use the `font` shorthand for this: it also resets font-size,
1876
+ // which silently made every control render at the host body size (≈16px)
1877
+ // while the surrounding labels stayed small.
1878
+ '.dsh-rp-root button,.dsh-rp-root input,.dsh-rp-root select,.dsh-rp-root textarea{font-family:inherit}' +
1879
+ '.dsh-rp-root button,.dsh-rp-root input,.dsh-rp-root select,.dsh-rp-root textarea{font-size:inherit}' +
1880
+ '.dsh-rp-root button{letter-spacing:inherit}' +
1881
+ '.dsh-rp-root{' + RP_VARS + '}' +
1882
+ // Every control the panel renders is a styled <button>, <label> or input. A
1883
+ // UA or host focus ring on any of them leaves a box behind after a click and
1884
+ // reads as "the button I pressed keeps a white border". Suppressing it here
1885
+ // is deliberate: the panels convey state with fills, and the only control
1886
+ // that needs a ring is a text field, which gets one below.
1887
+ '.dsh-rp-root button:focus,.dsh-rp-root button:focus-visible,' +
1888
+ '.dsh-rp-root label:focus,.dsh-rp-root label:focus-visible,' +
1889
+ '.dsh-rp-root label:focus-within,' +
1890
+ '.dsh-rp-root input[type="file"]:focus,.dsh-rp-root input[type="file"]:focus-visible' +
1891
+ '{outline:none !important;box-shadow:none !important}' +
1892
+ // A text field still needs a visible focus state.
1893
+ '.dsh-rp-root input:not([type="file"]):focus-visible,.dsh-rp-root select:focus-visible,' +
1894
+ '.dsh-rp-root textarea:focus-visible' +
1895
+ '{outline:2px solid var(--rp-accent);outline-offset:1px}' +
1896
+ '@keyframes dsh-rp-pulse{0%,100%{opacity:.35}50%{opacity:1}}'
1897
+
1898
+ const SX = {
1899
+ previewBox: {
1900
+ display: 'flex',
1901
+ flexDirection: 'column',
1902
+ gap: '6px',
1903
+ border: '1px solid var(--rp-accent-line)',
1904
+ borderLeft: '3px solid var(--rp-accent)',
1905
+ background: 'var(--rp-accent-weak)',
1906
+ borderRadius: '10px',
1907
+ padding: '8px 12px',
1908
+ minWidth: 0,
1909
+ },
1910
+ previewBar: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px', minWidth: 0 },
1911
+ previewMeta: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px', minWidth: 0 },
1912
+ previewCount: {
1913
+ display: 'inline-flex',
1914
+ alignItems: 'center',
1915
+ padding: '2px 10px',
1916
+ borderRadius: '999px',
1917
+ border: '1px solid var(--rp-accent)',
1918
+ background: 'var(--rp-card)',
1919
+ color: 'var(--rp-accent)',
1920
+ fontSize: '12px',
1921
+ fontWeight: 600,
1922
+ whiteSpace: 'nowrap',
1923
+ },
1924
+ spacer: { flex: 1, minWidth: 0 },
1925
+ condChipOn: { borderColor: 'var(--rp-accent-line)', background: 'var(--rp-accent-weak)', color: 'var(--rp-accent)' },
1926
+ groupBox: { borderTop: '1px solid var(--rp-line)', paddingTop: '2px', minWidth: 0 },
1927
+ groupHead: {
1928
+ display: 'flex',
1929
+ alignItems: 'center',
1930
+ flexWrap: 'wrap',
1931
+ gap: '8px',
1932
+ padding: '9px 2px 7px',
1933
+ minWidth: 0,
1934
+ },
1935
+ groupName: {
1936
+ fontSize: '13px',
1937
+ fontWeight: 700,
1938
+ minWidth: 0,
1939
+ overflow: 'hidden',
1940
+ textOverflow: 'ellipsis',
1941
+ whiteSpace: 'nowrap',
1942
+ cursor: 'pointer',
1943
+ },
1944
+ groupSwitchRow: {
1945
+ display: 'flex',
1946
+ alignItems: 'center',
1947
+ gap: '10px',
1948
+ padding: '8px 2px',
1949
+ borderBottom: '1px solid var(--rp-line)',
1950
+ minWidth: 0,
1951
+ },
1952
+ groupCaret: {
1953
+ width: '14px',
1954
+ flex: '0 0 auto',
1955
+ textAlign: 'center',
1956
+ cursor: 'pointer',
1957
+ color: 'var(--dsw-alias-label-secondary)',
1958
+ transition: 'transform 120ms ease',
1959
+ userSelect: 'none',
1960
+ },
1961
+ inheritOn: {
1962
+ borderColor: 'var(--rp-accent-line)',
1963
+ background: 'var(--rp-accent-weak)',
1964
+ color: 'var(--rp-accent)',
1965
+ },
1966
+ rowError: {
1967
+ marginTop: '6px',
1968
+ border: '1px solid var(--dsw-alias-state-error-primary)',
1969
+ background: 'var(--rp-card)',
1970
+ color: 'var(--dsw-alias-state-error-primary)',
1971
+ borderRadius: '8px',
1972
+ padding: '6px 9px',
1973
+ fontSize: '12px',
1974
+ lineHeight: 1.5,
1975
+ wordBreak: 'break-word',
1976
+ },
1977
+ inlineError: {
1978
+ fontSize: '12px',
1979
+ color: 'var(--dsw-alias-state-error-primary)',
1980
+ lineHeight: 1.5,
1981
+ wordBreak: 'break-word',
1982
+ },
1983
+ groupEmpty: { fontSize: '13px', color: 'var(--dsw-alias-label-secondary)', padding: '8px 2px' },
1984
+ emptyBox: {
1985
+ display: 'flex',
1986
+ flexDirection: 'column',
1987
+ alignItems: 'flex-start',
1988
+ gap: '6px',
1989
+ border: '1px dashed var(--rp-line-strong)',
1990
+ borderRadius: '10px',
1991
+ background: 'var(--rp-card)',
1992
+ padding: '16px',
1993
+ },
1994
+ emptyTitle: { fontSize: '14px', fontWeight: 600 },
1995
+ seg: {
1996
+ display: 'inline-flex',
1997
+ alignSelf: 'flex-start',
1998
+ gap: '4px',
1999
+ padding: '0',
2000
+ // No container border and no per-segment border: the selected segment is
2001
+ // marked by its own tint, so nothing white is ever drawn.
2002
+ border: 'none',
2003
+ borderRadius: '9px',
2004
+ background: 'transparent',
2005
+ flexWrap: 'wrap',
2006
+ },
2007
+ segBtn: {
2008
+ appearance: 'none',
2009
+ border: '1px solid transparent',
2010
+ background: 'transparent',
2011
+ color: 'var(--dsw-alias-label-secondary)',
2012
+ borderRadius: '7px',
2013
+ padding: '4px 12px',
2014
+ fontSize: '13px',
2015
+ cursor: 'pointer',
2016
+ fontFamily: 'inherit',
2017
+ outline: 'none',
2018
+ },
2019
+ segActive: {
2020
+ background: 'var(--rp-accent-weak)',
2021
+ borderColor: 'transparent',
2022
+ color: 'var(--rp-accent)',
2023
+ fontWeight: 600,
2024
+ },
2025
+ confirmRow: { display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap', marginTop: '6px' },
2026
+ confirmText: { fontSize: '12px', color: 'var(--dsw-alias-state-error-primary)', lineHeight: 1.5 },
2027
+ scopeBox: {
2028
+ display: 'grid',
2029
+ gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))',
2030
+ gap: '14px',
2031
+ borderTop: '1px solid var(--rp-line)',
2032
+ paddingTop: '12px',
2033
+ },
2034
+ resultBox: {
2035
+ display: 'flex',
2036
+ flexDirection: 'column',
2037
+ gap: '6px',
2038
+ border: '1px solid var(--rp-line)',
2039
+ background: 'var(--rp-card-2)',
2040
+ borderRadius: '8px',
2041
+ padding: '10px',
2042
+ },
2043
+ resultLine: { fontSize: '12px', lineHeight: 1.5, wordBreak: 'break-word' },
2044
+ mountLine: { display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', minWidth: 0 },
2045
+ nativeRow: {
2046
+ display: 'flex',
2047
+ flexDirection: 'column',
2048
+ gap: '2px',
2049
+ padding: '6px 2px',
2050
+ borderBottom: '1px solid var(--rp-line)',
2051
+ minWidth: 0,
2052
+ },
2053
+ nativeRowLast: { borderBottom: 'none' },
2054
+ sectionHint: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: 1.5 },
2055
+ }
2056
+
2057
+ // ------------------------------------------------------------------ panel
2058
+
2059
+ function Panel() {
2060
+ const [board, setBoard] = useState(null)
2061
+ const [loading, setLoading] = useState(true)
2062
+ const [error, setError] = useState('')
2063
+ const [notice, setNotice] = useState('')
2064
+ const [tab, setTab] = useState('resources')
2065
+ const [expanded, setExpanded] = useState({})
2066
+ const [groupOpen, setGroupOpen] = useState({})
2067
+ const [busy, setBusy] = useState({})
2068
+ const [saving, setSaving] = useState({})
2069
+ const [rowErrors, setRowErrors] = useState({})
2070
+ const [confirmItem, setConfirmItem] = useState('')
2071
+ const [confirmSource, setConfirmSource] = useState('')
2072
+ const [dialog, setDialog] = useState(false)
2073
+ const [previewMode, setPreviewMode] = useState('')
2074
+ const [previewCwd, setPreviewCwd] = useState('')
2075
+ const [pool, setPool] = useState(null)
2076
+ const [previewBusy, setPreviewBusy] = useState(false)
2077
+ const [previewError, setPreviewError] = useState('')
2078
+ const mounted = useRef(true)
2079
+ const loadingRef = useRef(false)
2080
+ const pendingRef = useRef(new Map())
2081
+ const timersRef = useRef(new Map())
2082
+ const groupTimersRef = useRef(new Map())
2083
+ const noticeTimer = useRef(null)
2084
+ const previewInitialized = useRef(false)
2085
+ const boardRef = useRef(null)
2086
+ const loadBoardRef = useRef(null)
2087
+ boardRef.current = board
2088
+
2089
+ useEffect(() => {
2090
+ mounted.current = true
2091
+ return () => {
2092
+ mounted.current = false
2093
+ for (const timer of timersRef.current.values()) clearTimeout(timer)
2094
+ timersRef.current.clear()
2095
+ pendingRef.current.clear()
2096
+ if (noticeTimer.current) clearTimeout(noticeTimer.current)
2097
+ }
2098
+ }, [])
2099
+
2100
+ const flash = useCallback((message) => {
2101
+ const text = asString(message)
2102
+ if (text.length === 0) return
2103
+ setNotice(text)
2104
+ if (noticeTimer.current) clearTimeout(noticeTimer.current)
2105
+ noticeTimer.current = setTimeout(() => {
2106
+ if (mounted.current) setNotice('')
2107
+ }, 3200)
2108
+ }, [])
2109
+
2110
+ const setBusyKey = useCallback((key, value) => {
2111
+ const name = asString(key)
2112
+ if (name.length === 0) return
2113
+ setBusy((current) => {
2114
+ const active = current[name] === true
2115
+ if (value === true && active) return current
2116
+ if (value !== true && !active) return current
2117
+ const next = { ...current }
2118
+ if (value === true) next[name] = true
2119
+ else delete next[name]
2120
+ return next
2121
+ })
2122
+ }, [])
2123
+
2124
+ const isBusy = useCallback((key) => busy[asString(key)] === true, [busy])
2125
+
2126
+ const markSaving = useCallback((key, value) => {
2127
+ setSaving((current) => {
2128
+ const active = current[key] === true
2129
+ if (value === true && active) return current
2130
+ if (value !== true && !active) return current
2131
+ const next = { ...current }
2132
+ if (value === true) next[key] = true
2133
+ else delete next[key]
2134
+ return next
2135
+ })
2136
+ }, [])
2137
+
2138
+ const setRowError = useCallback((key, message) => {
2139
+ setRowErrors((current) => ({ ...current, [key]: message }))
2140
+ }, [])
2141
+
2142
+ const clearRowError = useCallback((key) => {
2143
+ setRowErrors((current) => {
2144
+ if (!Object.prototype.hasOwnProperty.call(current, key)) return current
2145
+ const next = { ...current }
2146
+ delete next[key]
2147
+ return next
2148
+ })
2149
+ }, [])
2150
+
2151
+ // --------------------------------------------------------- autosave
2152
+
2153
+ const flushItem = useCallback(
2154
+ async (key) => {
2155
+ const job = pendingRef.current.get(key)
2156
+ if (!job) {
2157
+ markSaving(key, false)
2158
+ return
2159
+ }
2160
+ pendingRef.current.delete(key)
2161
+ markSaving(key, true)
2162
+ const entry = job.entry
2163
+ try {
2164
+ const payload = await request(`${API}/item`, {
2165
+ method: 'POST',
2166
+ body: {
2167
+ kind: job.kind,
2168
+ name: job.name,
2169
+ enabled: entry.enabled !== false,
2170
+ modes: asStringArray(entry.modes),
2171
+ workspaces: uniqueStrings(asArray(entry.workspaces).map(normalizePath)),
2172
+ modesFrom: entry.modesFrom === 'self' ? 'self' : 'group',
2173
+ workspacesFrom: entry.workspacesFrom === 'self' ? 'self' : 'group',
2174
+ },
2175
+ })
2176
+ if (!mounted.current) return
2177
+ clearRowError(key)
2178
+ if (payload.state) {
2179
+ const nextState = normalizeState(payload.state)
2180
+ const canonical = job.kind === MCP ? nextState.mcp[job.name] : nextState.skills[job.name]
2181
+ setBoard((current) => {
2182
+ if (!current) return current
2183
+ return { ...current, state: canonical ? withEntry(current.state, job.kind, job.name, canonical) : nextState }
2184
+ })
2185
+ }
2186
+ } catch (cause) {
2187
+ if (mounted.current) {
2188
+ setRowError(key, messageOf(cause))
2189
+ if (loadBoardRef.current) void loadBoardRef.current({ silent: true })
2190
+ }
2191
+ } finally {
2192
+ if (mounted.current && !pendingRef.current.has(key)) markSaving(key, false)
2193
+ }
2194
+ },
2195
+ [clearRowError, markSaving, setRowError],
2196
+ )
2197
+
2198
+ const queueItem = useCallback(
2199
+ (kind, name, entry) => {
2200
+ const key = `${kind}:${name}`
2201
+ pendingRef.current.set(key, { kind, name, entry })
2202
+ const timer = timersRef.current.get(key)
2203
+ if (timer) clearTimeout(timer)
2204
+ markSaving(key, true)
2205
+ timersRef.current.set(
2206
+ key,
2207
+ setTimeout(() => {
2208
+ timersRef.current.delete(key)
2209
+ void flushItem(key)
2210
+ }, ITEM_DEBOUNCE_MS),
2211
+ )
2212
+ },
2213
+ [flushItem, markSaving],
2214
+ )
2215
+
2216
+ const flushPending = useCallback(async () => {
2217
+ const keys = [...pendingRef.current.keys()]
2218
+ for (const key of keys) {
2219
+ const timer = timersRef.current.get(key)
2220
+ if (timer) {
2221
+ clearTimeout(timer)
2222
+ timersRef.current.delete(key)
2223
+ }
2224
+ await flushItem(key)
2225
+ }
2226
+ }, [flushItem])
2227
+
2228
+ // ---------------------------------------------------------- loading
2229
+
2230
+ const runResolve = useCallback(async (mode, cwd, options) => {
2231
+ setPreviewBusy(true)
2232
+ setPreviewError('')
2233
+ try {
2234
+ const allModes = options && options.allModes === true
2235
+ const allWorkspaces = options && options.allWorkspaces === true
2236
+ const query =
2237
+ `?mode=${encodeURIComponent(asString(mode))}&cwd=${encodeURIComponent(asString(cwd).trim())}` +
2238
+ (allModes ? '&allModes=1' : '') +
2239
+ (allWorkspaces ? '&allWorkspaces=1' : '')
2240
+ const payload = await request(`${API}/resolve${query}`, { method: 'GET' })
2241
+ if (mounted.current) setPool(normalizePool(payload.pool || payload.resolved))
2242
+ } catch (cause) {
2243
+ if (mounted.current) setPreviewError(messageOf(cause))
2244
+ } finally {
2245
+ if (mounted.current) setPreviewBusy(false)
2246
+ }
2247
+ }, [])
2248
+
2249
+ const loadBoard = useCallback(
2250
+ async (options) => {
2251
+ const silent = options && options.silent === true
2252
+ if (pendingRef.current.size > 0) await flushPending()
2253
+ if (loadingRef.current) return
2254
+ loadingRef.current = true
2255
+ if (!silent) {
2256
+ setLoading(true)
2257
+ setError('')
2258
+ }
2259
+ try {
2260
+ const payload = await request(API, { method: 'GET' })
2261
+ if (!mounted.current) return
2262
+ const nextState = normalizeState(payload.state)
2263
+ const nextInventory = normalizeInventory(payload.inventory)
2264
+ const nextMounts = normalizeMount(payload.mounts || payload.mount)
2265
+ setBoard({
2266
+ state: nextState,
2267
+ inventory: nextInventory,
2268
+ mounts: nextMounts,
2269
+ meta: asObject(payload.meta),
2270
+ })
2271
+ if (!previewInitialized.current) {
2272
+ previewInitialized.current = true
2273
+ const mode =
2274
+ asString(nextInventory.defaultMode) || (nextInventory.modes[0] && nextInventory.modes[0].id) || ''
2275
+ const cwd = (nextInventory.workspaces[0] && nextInventory.workspaces[0].path) || ''
2276
+ setPreviewMode(mode)
2277
+ setPreviewCwd(cwd)
2278
+ }
2279
+ } catch (cause) {
2280
+ if (mounted.current && !silent) setError(messageOf(cause))
2281
+ } finally {
2282
+ loadingRef.current = false
2283
+ if (mounted.current && !silent) setLoading(false)
2284
+ }
2285
+ },
2286
+ [flushPending],
2287
+ )
2288
+
2289
+ loadBoardRef.current = loadBoard
2290
+
2291
+ useEffect(() => {
2292
+ void loadBoard()
2293
+ }, [loadBoard])
2294
+
2295
+ const state = board ? board.state : EMPTY_STATE
2296
+ const inventory = board ? board.inventory : EMPTY_INVENTORY
2297
+ const mounts = board ? board.mounts : {}
2298
+ const meta = board ? board.meta : {}
2299
+ const settings = state.settings
2300
+
2301
+ const skillMeta = useMemo(() => {
2302
+ const map = new Map()
2303
+ for (const row of inventory.skills) map.set(row.name, row)
2304
+ return map
2305
+ }, [inventory.skills])
2306
+
2307
+ const mcpMeta = useMemo(() => {
2308
+ const map = new Map()
2309
+ for (const row of inventory.mcp) map.set(row.server, row)
2310
+ return map
2311
+ }, [inventory.mcp])
2312
+
2313
+ const skillNames = useMemo(
2314
+ () => Object.keys(state.skills).sort((left, right) => left.localeCompare(right)),
2315
+ [state.skills],
2316
+ )
2317
+ const mcpNames = useMemo(
2318
+ () => Object.keys(state.mcp).sort((left, right) => left.localeCompare(right)),
2319
+ [state.mcp],
2320
+ )
2321
+ const sourceList = useMemo(() => {
2322
+ const rows = Object.values(state.sources || {})
2323
+ rows.sort((left, right) => asString(right.createdAt).localeCompare(asString(left.createdAt)))
2324
+ return rows
2325
+ }, [state.sources])
2326
+
2327
+ // Skills grouped by the repository (or import) their source names.
2328
+ const groupList = useMemo(() => {
2329
+ const groups = state.groups || {}
2330
+ const byKey = new Map()
2331
+ for (const name of skillNames) {
2332
+ const info = skillMeta.get(name)
2333
+ const key = info ? asString(info.groupKey) : ''
2334
+ if (key.length === 0) continue
2335
+ if (!byKey.has(key)) byKey.set(key, { key, name: asString(info.groupName) || key, names: [] })
2336
+ byKey.get(key).names.push(name)
2337
+ }
2338
+ return [...byKey.values()]
2339
+ .map((row) => ({ ...row, group: groups[row.key] || null }))
2340
+ .sort((left, right) => left.name.localeCompare(right.name))
2341
+ }, [skillNames, skillMeta, state.groups])
2342
+
2343
+ const ungroupedSkills = useMemo(
2344
+ () =>
2345
+ skillNames.filter((name) => {
2346
+ const info = skillMeta.get(name)
2347
+ return info === undefined || asString(info.groupKey).length === 0
2348
+ }),
2349
+ [skillNames, skillMeta],
2350
+ )
2351
+
2352
+ const sourceSections = useMemo(() => {
2353
+ const byKey = new Map()
2354
+ for (const source of sourceList) {
2355
+ const project = asString(source.project)
2356
+ const key = project.length > 0 ? 'repo:' + project : 'import:' + source.id
2357
+ if (!byKey.has(key)) {
2358
+ byKey.set(key, {
2359
+ key,
2360
+ name: project.length > 0 ? project : asString(source.label) || source.id,
2361
+ rows: [],
2362
+ })
2363
+ }
2364
+ byKey.get(key).rows.push(source)
2365
+ }
2366
+ return [...byKey.values()].sort((left, right) => left.name.localeCompare(right.name))
2367
+ }, [sourceList])
2368
+
2369
+ // Re-resolve the preview whenever the selection or the pool changes.
2370
+ useEffect(() => {
2371
+ if (!board) return undefined
2372
+ const timer = setTimeout(() => {
2373
+ void runResolve(previewMode, previewCwd, {
2374
+ allModes: previewMode === '',
2375
+ allWorkspaces: previewCwd === '',
2376
+ })
2377
+ }, 180)
2378
+ return () => clearTimeout(timer)
2379
+ }, [board, previewMode, previewCwd, runResolve])
2380
+
2381
+ // Poll `/mounts` every 1.6 s while any server is still mounting.
2382
+ const mountingCount = useMemo(() => {
2383
+ let count = 0
2384
+ for (const value of Object.values(mounts)) if (value && value.state === 'mounting') count += 1
2385
+ return count
2386
+ }, [mounts])
2387
+
2388
+ useEffect(() => {
2389
+ if (mountingCount === 0) return undefined
2390
+ let cancelled = false
2391
+ const timer = setInterval(() => {
2392
+ void (async () => {
2393
+ try {
2394
+ const payload = await request(`${API}/mounts`, { method: 'GET' })
2395
+ if (cancelled || !mounted.current) return
2396
+ const next = normalizeMount(payload.mounts || payload.mount)
2397
+ setBoard((current) => (current ? { ...current, mounts: { ...current.mounts, ...next } } : current))
2398
+ const stillMounting = Object.values(next).some((value) => value && value.state === 'mounting')
2399
+ if (!stillMounting) void loadBoardRef.current({ silent: true })
2400
+ } catch {
2401
+ /* keep the current status and retry on the next tick */
2402
+ }
2403
+ })()
2404
+ }, MOUNT_POLL_MS)
2405
+ return () => {
2406
+ cancelled = true
2407
+ clearInterval(timer)
2408
+ }
2409
+ }, [mountingCount])
2410
+
2411
+ // ---------------------------------------------------------- mutations
2412
+
2413
+ const toggleExpanded = useCallback((key) => {
2414
+ setExpanded((current) => ({ ...current, [key]: current[key] !== true }))
2415
+ }, [])
2416
+
2417
+ // Groups start folded: the panel's first job is showing which repositories
2418
+ // are in the pool, and 25 rows of one repository would hide the others.
2419
+ const toggleGroupOpen = useCallback((key) => {
2420
+ setGroupOpen((current) => ({ ...current, [key]: current[key] !== true }))
2421
+ }, [])
2422
+
2423
+ const updateEntry = useCallback(
2424
+ (kind, name, patch) => {
2425
+ const source =
2426
+ kind === MCP
2427
+ ? boardRef.current && boardRef.current.state.mcp[name]
2428
+ : boardRef.current && boardRef.current.state.skills[name]
2429
+ const base = source || blankEntry()
2430
+ const next = {
2431
+ ...base,
2432
+ enabled: typeof patch.enabled === 'boolean' ? patch.enabled : base.enabled,
2433
+ modes: patch.modes !== undefined ? asStringArray(patch.modes) : base.modes,
2434
+ workspaces:
2435
+ patch.workspaces !== undefined
2436
+ ? uniqueStrings(asArray(patch.workspaces).map(normalizePath))
2437
+ : base.workspaces,
2438
+ modesFrom: patch.modesFrom === 'self' || patch.modesFrom === 'group' ? patch.modesFrom : base.modesFrom,
2439
+ workspacesFrom:
2440
+ patch.workspacesFrom === 'self' || patch.workspacesFrom === 'group'
2441
+ ? patch.workspacesFrom
2442
+ : base.workspacesFrom,
2443
+ }
2444
+ setBoard((current) => (current ? { ...current, state: withEntry(current.state, kind, name, next) } : current))
2445
+ clearRowError(`${kind}:${name}`)
2446
+ queueItem(kind, name, next)
2447
+ },
2448
+ [clearRowError, queueItem],
2449
+ )
2450
+
2451
+ const removeItem = useCallback(
2452
+ async (kind, name) => {
2453
+ const key = `${kind}:${name}`
2454
+ if (pendingRef.current.size > 0) await flushPending()
2455
+ const timer = timersRef.current.get(key)
2456
+ if (timer) {
2457
+ clearTimeout(timer)
2458
+ timersRef.current.delete(key)
2459
+ }
2460
+ pendingRef.current.delete(key)
2461
+ markSaving(key, false)
2462
+ setBusyKey('remove:' + key, true)
2463
+ setError('')
2464
+ try {
2465
+ const payload = await request(`${API}/item/remove`, { method: 'POST', body: { kind, name } })
2466
+ if (!mounted.current) return
2467
+ if (payload.state) {
2468
+ setBoard((current) => (current ? { ...current, state: normalizeState(payload.state) } : current))
2469
+ } else {
2470
+ setBoard((current) =>
2471
+ current ? { ...current, state: withoutEntry(current.state, kind, name) } : current,
2472
+ )
2473
+ }
2474
+ clearRowError(key)
2475
+ setConfirmItem('')
2476
+ const removedInfo = asObject(payload.removed)
2477
+ if (asString(removedInfo.warning).length > 0) setError(asString(removedInfo.warning))
2478
+ else flash(TEXT.itemRemoved)
2479
+ await loadBoard({ silent: true })
2480
+ } catch (cause) {
2481
+ if (mounted.current) setRowError(key, messageOf(cause))
2482
+ } finally {
2483
+ if (mounted.current) setBusyKey('remove:' + key, false)
2484
+ }
2485
+ },
2486
+ [clearRowError, flash, flushPending, loadBoard, markSaving, setBusyKey, setRowError],
2487
+ )
2488
+
2489
+ const saveSettings = useCallback(
2490
+ async (patch) => {
2491
+ const base = boardRef.current ? boardRef.current.state.settings : DEFAULT_SETTINGS
2492
+ const nextSettings = normalizeSettings({ ...base, ...asObject(patch) })
2493
+ setBoard((current) =>
2494
+ current ? { ...current, state: { ...current.state, settings: nextSettings } } : current,
2495
+ )
2496
+ setBusyKey('settings', true)
2497
+ try {
2498
+ const payload = await request(`${API}/settings`, { method: 'POST', body: { patch: nextSettings } })
2499
+ if (!mounted.current) return
2500
+ const nextState = payload.state ? normalizeState(payload.state) : null
2501
+ if (nextState) {
2502
+ setBoard((current) =>
2503
+ current ? { ...current, state: { ...current.state, settings: nextState.settings } } : current,
2504
+ )
2505
+ }
2506
+ flash(TEXT.settingsSaved)
2507
+ } catch (cause) {
2508
+ if (mounted.current) {
2509
+ setError(messageOf(cause))
2510
+ void loadBoard({ silent: true })
2511
+ }
2512
+ } finally {
2513
+ if (mounted.current) setBusyKey('settings', false)
2514
+ }
2515
+ },
2516
+ [flash, loadBoard, setBusyKey],
2517
+ )
2518
+
2519
+ /** Persist the pending scope of one group (debounced by `updateGroup`). */
2520
+ const sendGroup = useCallback(
2521
+ async (key) => {
2522
+ const current = boardRef.current
2523
+ const group = current && current.state.groups ? current.state.groups[key] : null
2524
+ if (!group) return
2525
+ setBusyKey('group:' + key, true)
2526
+ setError('')
2527
+ try {
2528
+ const payload = await request(`${API}/group`, {
2529
+ method: 'POST',
2530
+ body: {
2531
+ key,
2532
+ enabled: group.enabled !== false,
2533
+ modes: asStringArray(group.modes),
2534
+ workspaces: uniqueStrings(asArray(group.workspaces).map(normalizePath)),
2535
+ },
2536
+ })
2537
+ if (!mounted.current) return
2538
+ if (payload.state) {
2539
+ setBoard((board) => (board ? { ...board, state: normalizeState(payload.state) } : board))
2540
+ }
2541
+ } catch (cause) {
2542
+ if (mounted.current) {
2543
+ setError(messageOf(cause))
2544
+ if (loadBoardRef.current) void loadBoardRef.current({ silent: true })
2545
+ }
2546
+ } finally {
2547
+ if (mounted.current) setBusyKey('group:' + key, false)
2548
+ }
2549
+ },
2550
+ [setBusyKey],
2551
+ )
2552
+
2553
+ /** Optimistically edit a group, then persist it once the user pauses. */
2554
+ const updateGroup = useCallback(
2555
+ (key, patch) => {
2556
+ setBoard((current) => {
2557
+ if (!current) return current
2558
+ const base =
2559
+ current.state.groups[key] || {
2560
+ key,
2561
+ kind: key.startsWith('import:') ? 'import' : 'repo',
2562
+ modes: [],
2563
+ workspaces: [],
2564
+ }
2565
+ const next = {
2566
+ ...base,
2567
+ key,
2568
+ enabled: patch.enabled !== undefined ? patch.enabled === true : base.enabled !== false,
2569
+ modes: patch.modes !== undefined ? asStringArray(patch.modes) : base.modes,
2570
+ workspaces:
2571
+ patch.workspaces !== undefined
2572
+ ? uniqueStrings(asArray(patch.workspaces).map(normalizePath))
2573
+ : base.workspaces,
2574
+ }
2575
+ return {
2576
+ ...current,
2577
+ state: { ...current.state, groups: { ...current.state.groups, [key]: next } },
2578
+ }
2579
+ })
2580
+ const timer = groupTimersRef.current.get(key)
2581
+ if (timer) clearTimeout(timer)
2582
+ groupTimersRef.current.set(
2583
+ key,
2584
+ setTimeout(() => {
2585
+ groupTimersRef.current.delete(key)
2586
+ void sendGroup(key)
2587
+ }, 350),
2588
+ )
2589
+ },
2590
+ [sendGroup],
2591
+ )
2592
+
2593
+ // ------------------------------------------------------------ imports
2594
+
2595
+ const submitImport = useCallback(
2596
+ async (seg, body) => {
2597
+ const route =
2598
+ seg === 'files'
2599
+ ? '/skill/upload'
2600
+ : seg === 'zip'
2601
+ ? '/skill/zip'
2602
+ : seg === 'git'
2603
+ ? '/source/git'
2604
+ : '/mcp/import'
2605
+ setBusyKey('import', true)
2606
+ try {
2607
+ const payload = await request(`${API}${route}`, { method: 'POST', body })
2608
+ if (mounted.current && payload.state) {
2609
+ const nextState = normalizeState(payload.state)
2610
+ const nextMounts = normalizeMount(payload.mounts || payload.mount)
2611
+ setBoard((current) =>
2612
+ current
2613
+ ? { ...current, state: nextState, mounts: { ...current.mounts, ...nextMounts } }
2614
+ : current,
2615
+ )
2616
+ }
2617
+ if (seg === 'mcp') {
2618
+ if (mounted.current) void loadBoard({ silent: true })
2619
+ }
2620
+ return payload
2621
+ } finally {
2622
+ if (mounted.current) setBusyKey('import', false)
2623
+ }
2624
+ },
2625
+ [loadBoard, setBusyKey],
2626
+ )
2627
+
2628
+ const pollMounts = useCallback(async () => {
2629
+ const payload = await request(`${API}/mounts`, { method: 'GET' })
2630
+ const next = normalizeMount(payload.mounts || payload.mount)
2631
+ if (mounted.current) {
2632
+ setBoard((current) => (current ? { ...current, mounts: { ...current.mounts, ...next } } : current))
2633
+ }
2634
+ return next
2635
+ }, [])
2636
+
2637
+ const afterImport = useCallback(
2638
+ async (message) => {
2639
+ setDialog(false)
2640
+ if (message) flash(message)
2641
+ setTab('resources')
2642
+ await loadBoard({ silent: true })
2643
+ },
2644
+ [flash, loadBoard],
2645
+ )
2646
+
2647
+ // ------------------------------------------------------------ sources
2648
+
2649
+ const checkSources = useCallback(
2650
+ async (ids) => {
2651
+ const list = asStringArray(ids)
2652
+ const busyKey = 'sources:check:' + (list.length > 0 ? list.join(',') : 'all')
2653
+ setBusyKey(busyKey, true)
2654
+ setError('')
2655
+ try {
2656
+ const payload = await request(`${API}/source/check`, {
2657
+ method: 'POST',
2658
+ body: list.length > 0 ? { ids: list } : {},
2659
+ })
2660
+ if (!mounted.current) return
2661
+ if (payload.state) {
2662
+ setBoard((current) => (current ? { ...current, state: normalizeState(payload.state) } : current))
2663
+ }
2664
+ const results = asArray(payload.results)
2665
+ const updated = results.filter((row) => asString(row && row.status) === 'update-available').length
2666
+ const upToDate = results.filter((row) => asString(row && row.status) === 'up-to-date').length
2667
+ const failed = results.filter((row) => asString(row && row.status) === 'error').length
2668
+ flash(tf('checkResult', { updated, upToDate, failed }))
2669
+ await loadBoard({ silent: true })
2670
+ } catch (cause) {
2671
+ if (mounted.current) setError(messageOf(cause))
2672
+ } finally {
2673
+ if (mounted.current) setBusyKey(busyKey, false)
2674
+ }
2675
+ },
2676
+ [flash, loadBoard, setBusyKey],
2677
+ )
2678
+
2679
+ const updateSource = useCallback(
2680
+ async (id, options) => {
2681
+ const restore = options && options.restore === true
2682
+ const force = restore || (options && options.force === true)
2683
+ setBusyKey('source:update:' + id, true)
2684
+ setError('')
2685
+ try {
2686
+ const payload = await request(`${API}/source/update`, {
2687
+ method: 'POST',
2688
+ body: { id, ...(force ? { force: true } : {}), ...(restore ? { restore: true } : {}) },
2689
+ })
2690
+ if (!mounted.current) return
2691
+ if (payload.state) {
2692
+ setBoard((current) => (current ? { ...current, state: normalizeState(payload.state) } : current))
2693
+ }
2694
+ const failures = asArray(payload.failures)
2695
+ if (failures.length > 0) {
2696
+ setError(
2697
+ `${TEXT.importPartial}: ${failures
2698
+ .map((row) => `${asString(row && row.name)}: ${asString(row && row.error)}`)
2699
+ .join('; ')}`,
2700
+ )
2701
+ } else {
2702
+ flash(
2703
+ restore
2704
+ ? TEXT.noticeSourceRestored
2705
+ : payload.changed === false
2706
+ ? TEXT.noticeSourceUpToDate
2707
+ : TEXT.noticeSourceUpdated,
2708
+ )
2709
+ }
2710
+ await loadBoard({ silent: true })
2711
+ } catch (cause) {
2712
+ if (mounted.current) setError(messageOf(cause))
2713
+ } finally {
2714
+ if (mounted.current) setBusyKey('source:update:' + id, false)
2715
+ }
2716
+ },
2717
+ [flash, loadBoard, setBusyKey],
2718
+ )
2719
+
2720
+ /** Update every Git import of one repository group, one after another. */
2721
+ const updateGroupSources = useCallback(
2722
+ async (groupKey, ids) => {
2723
+ const list = asStringArray(ids)
2724
+ const busyKey = 'group:update:' + groupKey
2725
+ setBusyKey(busyKey, true)
2726
+ setError('')
2727
+ let installed = 0
2728
+ let failures = 0
2729
+ let changed = 0
2730
+ try {
2731
+ for (const id of list) {
2732
+ try {
2733
+ const payload = await request(`${API}/source/update`, { method: 'POST', body: { id } })
2734
+ if (!mounted.current) return
2735
+ if (payload.state) {
2736
+ setBoard((current) => (current ? { ...current, state: normalizeState(payload.state) } : current))
2737
+ }
2738
+ if (payload.changed !== false) changed += 1
2739
+ installed += asArray(payload.installed).length
2740
+ failures += asArray(payload.failures).length
2741
+ } catch (cause) {
2742
+ failures += 1
2743
+ if (mounted.current) setError(messageOf(cause))
2744
+ }
2745
+ }
2746
+ if (!mounted.current) return
2747
+ if (failures === 0) {
2748
+ flash(changed === 0 ? TEXT.noticeSourceUpToDate : tf('noticeGroupUpdated', { count: installed }))
2749
+ }
2750
+ await loadBoard({ silent: true })
2751
+ } finally {
2752
+ if (mounted.current) setBusyKey(busyKey, false)
2753
+ }
2754
+ },
2755
+ [flash, loadBoard, setBusyKey],
2756
+ )
2757
+
2758
+ const deleteSource = useCallback(
2759
+ async (id) => {
2760
+ setBusyKey('source:delete:' + id, true)
2761
+ setError('')
2762
+ try {
2763
+ const payload = await request(`${API}/source/delete`, { method: 'POST', body: { id } })
2764
+ if (!mounted.current) return
2765
+ if (payload.state) {
2766
+ setBoard((current) => (current ? { ...current, state: normalizeState(payload.state) } : current))
2767
+ }
2768
+ setConfirmSource('')
2769
+ const skipped = asArray(payload.skipped)
2770
+ flash(
2771
+ skipped.length > 0
2772
+ ? TEXT.noticeSourceDeleted + tf('sourceSkipped', { count: skipped.length })
2773
+ : TEXT.noticeSourceDeleted,
2774
+ )
2775
+ await loadBoard({ silent: true })
2776
+ } catch (cause) {
2777
+ if (mounted.current) setError(messageOf(cause))
2778
+ } finally {
2779
+ if (mounted.current) setBusyKey('source:delete:' + id, false)
2780
+ }
2781
+ },
2782
+ [flash, loadBoard, setBusyKey],
2783
+ )
2784
+
2785
+ // ----------------------------------------------------------- renderers
2786
+
2787
+ function renderPreview() {
2788
+ const modeOptions = [{ id: '', name: TEXT.previewAllModes }, ...inventory.modes.slice()]
2789
+ if (previewMode && !modeOptions.some((mode) => mode.id === previewMode)) {
2790
+ modeOptions.push({ id: previewMode, name: previewMode })
2791
+ }
2792
+ const workspaceOptions = inventory.workspaces.slice()
2793
+ if (previewCwd && !workspaceOptions.some((row) => row.path === previewCwd)) {
2794
+ workspaceOptions.push({ id: '', name: baseName(previewCwd), path: previewCwd })
2795
+ }
2796
+ const total = pool ? asArray(pool.skills).length + asArray(pool.mcpServers).length : 0
2797
+ return h(
2798
+ 'div',
2799
+ { style: SX.previewBox },
2800
+ h(
2801
+ 'div',
2802
+ { style: SX.previewBar },
2803
+ h('span', { style: SX.sectionHint }, TEXT.previewMode),
2804
+ h(
2805
+ 'select',
2806
+ {
2807
+ style: S.select,
2808
+ value: previewMode,
2809
+ 'aria-label': TEXT.previewMode,
2810
+ onChange: (event) => setPreviewMode(asString(event.target.value)),
2811
+ },
2812
+ ...modeOptions.map((mode) => h('option', { key: mode.id, value: mode.id }, mode.name || mode.id)),
2813
+ ),
2814
+ h('span', { style: SX.sectionHint }, TEXT.previewWorkspace),
2815
+ h(
2816
+ 'select',
2817
+ {
2818
+ style: S.select,
2819
+ value: previewCwd,
2820
+ 'aria-label': TEXT.previewWorkspace,
2821
+ onChange: (event) => setPreviewCwd(asString(event.target.value)),
2822
+ },
2823
+ h('option', { value: '' }, TEXT.previewAllWorkspaces),
2824
+ ...workspaceOptions.map((row) =>
2825
+ h('option', { key: row.path, value: row.path }, row.name || baseName(row.path)),
2826
+ ),
2827
+ ),
2828
+ h(
2829
+ 'span',
2830
+ { style: SX.previewCount },
2831
+ previewBusy
2832
+ ? TEXT.previewBusy
2833
+ : pool
2834
+ ? tf('previewAvailable', { count: total })
2835
+ : previewError
2836
+ ? TEXT.previewFailed
2837
+ : '—',
2838
+ ),
2839
+ ),
2840
+ previewError
2841
+ ? h('div', { style: SX.inlineError }, `${TEXT.previewFailed}: ${previewError}`)
2842
+ : pool
2843
+ ? h(
2844
+ 'div',
2845
+ { style: SX.previewMeta },
2846
+ h(
2847
+ 'span',
2848
+ { style: SX.sectionHint },
2849
+ `${TEXT.previewSkills}: ${
2850
+ asArray(pool.skills).length > 0 ? asArray(pool.skills).join(', ') : TEXT.previewNone
2851
+ }`,
2852
+ ),
2853
+ h(
2854
+ 'span',
2855
+ { style: SX.sectionHint },
2856
+ `${TEXT.previewMcp}: ${
2857
+ asArray(pool.mcpServers).length > 0 ? asArray(pool.mcpServers).join(', ') : TEXT.previewNone
2858
+ }`,
2859
+ ),
2860
+ h(
2861
+ 'span',
2862
+ { style: S.badge },
2863
+ `${TEXT.previewGateSkills}: ${pool.gateSkills ? TEXT.previewGated : TEXT.previewNotGated}`,
2864
+ ),
2865
+ h(
2866
+ 'span',
2867
+ { style: S.badge },
2868
+ `${TEXT.previewGateMcp}: ${pool.gateMcp ? TEXT.previewGated : TEXT.previewNotGated}`,
2869
+ ),
2870
+ )
2871
+ : null,
2872
+ )
2873
+ }
2874
+
2875
+ function renderEmptyState() {
2876
+ return h(
2877
+ 'div',
2878
+ { style: SX.emptyBox },
2879
+ h('div', { style: SX.emptyTitle }, TEXT.emptyTitle),
2880
+ // No button here: importing is a page-level action in the header, so the
2881
+ // tab body stays a pure view of what the pool contains.
2882
+ h('div', { style: S.empty }, TEXT.emptyHint),
2883
+ )
2884
+ }
2885
+
2886
+ function renderCondEditor(kind, name, entry) {
2887
+ const isMcp = kind === MCP
2888
+ const info = isMcp ? undefined : skillMeta.get(name)
2889
+ const groupKey = info ? asString(info.groupKey) : ''
2890
+ const group = groupKey.length > 0 ? state.groups[groupKey] || null : null
2891
+ const modeItems = inventory.modes.map((mode) => ({ value: mode.id, label: mode.name, hint: mode.id }))
2892
+ const workspaceItems = inventory.workspaces.map((row) => ({
2893
+ value: row.path,
2894
+ label: row.name || baseName(row.path),
2895
+ hint: row.path,
2896
+ }))
2897
+ const modeLabels = new Map(inventory.modes.map((mode) => [mode.id, mode.name]))
2898
+ const groupModeText = summarizeList(group ? asStringArray(group.modes) : [], TEXT.allModes, (value) => modeLabels.get(value) || value)
2899
+ const groupWorkspaceText = summarizeList(group ? asStringArray(group.workspaces) : [], TEXT.allWorkspaces, (value) => baseName(value))
2900
+ const inheritsModes = group !== null && entry.modesFrom === 'group'
2901
+ const inheritsWorkspaces = group !== null && entry.workspacesFrom === 'group'
2902
+ const selfModes = inheritsModes ? asStringArray(group.modes) : entry.modes
2903
+ const selfWorkspaces = inheritsWorkspaces ? asStringArray(group.workspaces) : entry.workspaces
2904
+
2905
+ // A member of a group chooses per dimension: follow the group, or keep
2906
+ // its own list. The choice is stored, so "inherit" and "explicitly all"
2907
+ // never look the same.
2908
+ const inheritToggle = (inheriting, inheritLabel, onInherit, onSelf) =>
2909
+ h(
2910
+ 'div',
2911
+ { style: S.row },
2912
+ h(
2913
+ 'button',
2914
+ {
2915
+ type: 'button',
2916
+ style: { ...S.buttonSmall, ...(inheriting ? SX.inheritOn : null) },
2917
+ onClick: onInherit,
2918
+ },
2919
+ `${TEXT.groupInherit} · ${inheritLabel}`,
2920
+ ),
2921
+ h(
2922
+ 'button',
2923
+ {
2924
+ type: 'button',
2925
+ style: { ...S.buttonSmall, ...(inheriting ? null : SX.inheritOn) },
2926
+ onClick: onSelf,
2927
+ },
2928
+ TEXT.groupSelf,
2929
+ ),
2930
+ )
2931
+
2932
+ return h(
2933
+ 'div',
2934
+ { style: S.condPanel },
2935
+ h(
2936
+ Field,
2937
+ { label: TEXT.rowModes, hint: group ? TEXT.groupInheritFrom : TEXT.allModes },
2938
+ group ? inheritToggle(inheritsModes, groupModeText, () => updateEntry(kind, name, { modesFrom: 'group' }), () => updateEntry(kind, name, { modesFrom: 'self', modes: selfModes })) : null,
2939
+ inheritsModes
2940
+ ? null
2941
+ : h(MultiSelect, {
2942
+ items: modeItems,
2943
+ selected: entry.modes,
2944
+ onChange: (values) => updateEntry(kind, name, { modes: values, modesFrom: 'self' }),
2945
+ searchPlaceholder: TEXT.previewAllModes,
2946
+ emptyHint: TEXT.allModes,
2947
+ emptyText: TEXT.noMatches,
2948
+ selectAllLabel: TEXT.selectAll,
2949
+ clearAllLabel: TEXT.clearAll,
2950
+ }),
2951
+ ),
2952
+ h(
2953
+ Field,
2954
+ { label: TEXT.rowWorkspaces, hint: group ? TEXT.groupInheritFrom : TEXT.allWorkspaces },
2955
+ group
2956
+ ? inheritToggle(
2957
+ inheritsWorkspaces,
2958
+ groupWorkspaceText,
2959
+ () => updateEntry(kind, name, { workspacesFrom: 'group' }),
2960
+ () => updateEntry(kind, name, { workspacesFrom: 'self', workspaces: selfWorkspaces }),
2961
+ )
2962
+ : null,
2963
+ inheritsWorkspaces
2964
+ ? null
2965
+ : h(MultiSelect, {
2966
+ items: workspaceItems,
2967
+ selected: entry.workspaces,
2968
+ onChange: (values) => updateEntry(kind, name, { workspaces: values, workspacesFrom: 'self' }),
2969
+ searchPlaceholder: TEXT.previewAllWorkspaces,
2970
+ emptyHint: TEXT.allWorkspaces,
2971
+ emptyText: TEXT.noMatches,
2972
+ selectAllLabel: TEXT.selectAll,
2973
+ clearAllLabel: TEXT.clearAll,
2974
+ }),
2975
+ inheritsWorkspaces
2976
+ ? null
2977
+ : h(AddPathRow, {
2978
+ placeholder: TEXT.addPathPlaceholder,
2979
+ label: TEXT.addPath,
2980
+ onAdd: (path) =>
2981
+ updateEntry(kind, name, {
2982
+ workspaces: uniqueStrings([...entry.workspaces, path]),
2983
+ workspacesFrom: 'self',
2984
+ }),
2985
+ }),
2986
+ ),
2987
+ )
2988
+ }
2989
+
2990
+ function renderItemRow(kind, name, isLast) {
2991
+ const isMcp = kind === MCP
2992
+ const entry = (isMcp ? state.mcp[name] : state.skills[name]) || blankEntry()
2993
+ const info = isMcp ? mcpMeta.get(name) : skillMeta.get(name)
2994
+ const key = `${kind}:${name}`
2995
+ const open = expanded[key] === true
2996
+ const confirming = confirmItem === key
2997
+ const removeBusy = isBusy('remove:' + key)
2998
+ const mountState = isMcp ? mounts[name] : null
2999
+ const modeLabels = new Map(inventory.modes.map((mode) => [mode.id, mode.name]))
3000
+ const groupInfo = !isMcp && info && asString(info.groupKey).length > 0 ? state.groups[asString(info.groupKey)] || null : null
3001
+ const inheritsModes = groupInfo !== null && entry.modesFrom === 'group'
3002
+ const inheritsWorkspaces = groupInfo !== null && entry.workspacesFrom === 'group'
3003
+ const effectiveModes = inheritsModes ? asStringArray(groupInfo.modes) : entry.modes
3004
+ const effectiveWorkspaces = inheritsWorkspaces ? asStringArray(groupInfo.workspaces) : entry.workspaces
3005
+ const modeText = summarizeList(effectiveModes, TEXT.allModes, (value) => modeLabels.get(value) || value)
3006
+ const workspaceText = summarizeList(effectiveWorkspaces, TEXT.allWorkspaces, (value) => baseName(value))
3007
+ const sourceLabel = info ? info.sourceLabel || info.sourceId : ''
3008
+ const groupOff = groupInfo !== null && groupInfo.enabled === false
3009
+ return h(
3010
+ 'div',
3011
+ { style: { ...S.rowItem, ...(isLast ? S.rowItemLast : null) } },
3012
+ h(
3013
+ 'div',
3014
+ {
3015
+ style: S.rowMain,
3016
+ // The whole left block answers "what does this do?" on hover.
3017
+ title: info && info.description ? asString(info.description) : undefined,
3018
+ },
3019
+ h(
3020
+ 'div',
3021
+ { style: S.rowText },
3022
+ h(
3023
+ 'div',
3024
+ { style: S.rowName },
3025
+ h('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } }, name),
3026
+ isMcp && info
3027
+ ? h(
3028
+ 'span',
3029
+ {
3030
+ style: {
3031
+ ...S.badge,
3032
+ color: 'var(--rp-mcp)',
3033
+ background: 'var(--rp-mcp-weak)',
3034
+ borderColor: 'var(--rp-mcp-line)',
3035
+ },
3036
+ },
3037
+ `${asNumber(info.toolCount, 0)} ${TEXT.toolsUnit}`,
3038
+ )
3039
+ : null,
3040
+ isMcp && mountState ? h('span', { style: S.badge }, mountLabel(mountState.state)) : null,
3041
+ !isMcp && sourceLabel ? h('span', { style: S.badge }, `${TEXT.sourceFrom}: ${sourceLabel}`) : null,
3042
+ !isMcp && info && info.missing
3043
+ ? h('span', { style: { ...S.badge, ...S.badgeError } }, TEXT.missingFile)
3044
+ : null,
3045
+ !isMcp && info && info.modelInvocable === false
3046
+ ? h('span', { style: S.badge }, TEXT.modelInvocableOff)
3047
+ : null,
3048
+ saving[key] === true ? h('span', { style: S.savingDot }, TEXT.savingItem) : null,
3049
+ ),
3050
+ // The description is intentionally not printed in the list: real skill
3051
+ // descriptions run for paragraphs, and a list of them stops being a
3052
+ // list. It is reachable on hover (the row carries it as its title).
3053
+ !info ? h('div', { style: S.rowDesc }, TEXT.skillMissing) : null,
3054
+ isMcp && mountState && mountState.state === 'failed' && mountState.error
3055
+ ? h('div', { style: SX.inlineError }, mountState.error)
3056
+ : null,
3057
+ !isMcp && info && info.missing ? h('div', { style: SX.inlineError }, TEXT.missingFileHint) : null,
3058
+ ),
3059
+ h(
3060
+ 'div',
3061
+ { style: S.rowActions },
3062
+ h(
3063
+ 'span',
3064
+ {
3065
+ role: 'button',
3066
+ tabIndex: 0,
3067
+ style: {
3068
+ ...S.condChip,
3069
+ cursor: 'pointer',
3070
+ ...(effectiveModes.length > 0 ? SX.condChipOn : null),
3071
+ },
3072
+ title: TEXT.editConditions,
3073
+ onClick: () => toggleExpanded(key),
3074
+ },
3075
+ `${TEXT.rowModes}: ${modeText}${inheritsModes ? TEXT.groupInheritTag : ''}`,
3076
+ ),
3077
+ groupOff ? h('span', { style: S.badgeWarn }, TEXT.groupDisabledTag) : null,
3078
+ h(
3079
+ 'span',
3080
+ {
3081
+ role: 'button',
3082
+ tabIndex: 0,
3083
+ style: {
3084
+ ...S.condChip,
3085
+ cursor: 'pointer',
3086
+ ...(effectiveWorkspaces.length > 0 ? SX.condChipOn : null),
3087
+ },
3088
+ title: TEXT.editConditions,
3089
+ onClick: () => toggleExpanded(key),
3090
+ },
3091
+ `${TEXT.rowWorkspaces}: ${workspaceText}${inheritsWorkspaces ? TEXT.groupInheritTag : ''}`,
3092
+ ),
3093
+ h(Toggle, {
3094
+ checked: entry.enabled === true,
3095
+ label: name,
3096
+ title: entry.enabled === true ? TEXT.enabled : TEXT.disabled,
3097
+ onChange: (value) => updateEntry(kind, name, { enabled: value }),
3098
+ }),
3099
+ h(
3100
+ 'button',
3101
+ {
3102
+ type: 'button',
3103
+ style: S.ghostDanger,
3104
+ disabled: removeBusy,
3105
+ onClick: () => setConfirmItem(confirming ? '' : key),
3106
+ },
3107
+ removeBusy ? TEXT.removing : TEXT.removeItem,
3108
+ ),
3109
+ ),
3110
+ ),
3111
+ confirming
3112
+ ? h(
3113
+ 'div',
3114
+ { style: SX.confirmRow },
3115
+ h('span', { style: SX.confirmText }, isMcp ? TEXT.deleteMcpConfirm : TEXT.deleteSkillConfirm),
3116
+ h(
3117
+ 'button',
3118
+ {
3119
+ type: 'button',
3120
+ style: S.buttonDanger,
3121
+ disabled: removeBusy,
3122
+ onClick: () => void removeItem(kind, name),
3123
+ },
3124
+ removeBusy ? TEXT.removing : TEXT.sourceDeleteYes,
3125
+ ),
3126
+ h(
3127
+ 'button',
3128
+ { type: 'button', style: S.buttonSmall, onClick: () => setConfirmItem('') },
3129
+ TEXT.sourceDeleteCancel,
3130
+ ),
3131
+ )
3132
+ : null,
3133
+ open ? renderCondEditor(kind, name, entry) : null,
3134
+ rowErrors[key] ? h('div', { style: SX.rowError, role: 'alert' }, rowErrors[key]) : null,
3135
+ )
3136
+ }
3137
+
3138
+ function groupScopeText(group, dimension) {
3139
+ const modeLabels = new Map(inventory.modes.map((mode) => [mode.id, mode.name]))
3140
+ if (dimension === 'modes') {
3141
+ return summarizeList(group ? asStringArray(group.modes) : [], TEXT.allModes, (value) => modeLabels.get(value) || value)
3142
+ }
3143
+ return summarizeList(group ? asStringArray(group.workspaces) : [], TEXT.allWorkspaces, (value) => baseName(value))
3144
+ }
3145
+
3146
+ function renderGroupHead(key, name, count) {
3147
+ const group = state.groups[key] || null
3148
+ const open = expanded['group:' + key] === true
3149
+ const folded = groupOpen[key] !== true
3150
+ return h(
3151
+ 'div',
3152
+ { style: SX.groupHead },
3153
+ h(
3154
+ 'span',
3155
+ {
3156
+ role: 'button',
3157
+ tabIndex: 0,
3158
+ 'aria-label': folded ? TEXT.groupExpand : TEXT.groupCollapse,
3159
+ title: folded ? TEXT.groupExpand : TEXT.groupCollapse,
3160
+ style: { ...SX.groupCaret, transform: folded ? 'none' : 'rotate(90deg)' },
3161
+ onClick: () => toggleGroupOpen(key),
3162
+ },
3163
+ '▸',
3164
+ ),
3165
+ h(
3166
+ 'span',
3167
+ { style: SX.groupName, title: name, onClick: () => toggleGroupOpen(key) },
3168
+ name,
3169
+ ),
3170
+ group !== null && group.enabled === false
3171
+ ? h('span', { style: S.badgeWarn }, TEXT.groupDisabledTag)
3172
+ : null,
3173
+ h('span', { style: S.countBadge }, `${count} ${TEXT.countUnit}`),
3174
+ h(
3175
+ 'span',
3176
+ {
3177
+ role: 'button',
3178
+ tabIndex: 0,
3179
+ style: {
3180
+ ...S.condChip,
3181
+ cursor: 'pointer',
3182
+ ...(groupScopeText(group, 'modes').length > 0 && group && asStringArray(group.modes).length > 0 ? SX.condChipOn : null),
3183
+ },
3184
+ title: TEXT.editConditions,
3185
+ onClick: () => toggleExpanded('group:' + key),
3186
+ },
3187
+ `${TEXT.rowModes}: ${groupScopeText(group, 'modes')}`,
3188
+ ),
3189
+ h(
3190
+ 'span',
3191
+ {
3192
+ role: 'button',
3193
+ tabIndex: 0,
3194
+ style: {
3195
+ ...S.condChip,
3196
+ cursor: 'pointer',
3197
+ ...(group && asStringArray(group.workspaces).length > 0 ? SX.condChipOn : null),
3198
+ },
3199
+ title: TEXT.editConditions,
3200
+ onClick: () => toggleExpanded('group:' + key),
3201
+ },
3202
+ `${TEXT.rowWorkspaces}: ${groupScopeText(group, 'workspaces')}`,
3203
+ ),
3204
+ h(Toggle, {
3205
+ checked: group === null || group.enabled !== false,
3206
+ label: `${TEXT.settingsGroups} ${name}`,
3207
+ title: group !== null && group.enabled === false ? TEXT.disabled : TEXT.enabled,
3208
+ onChange: (value) => updateGroup(key, { enabled: value }),
3209
+ }),
3210
+ )
3211
+ }
3212
+
3213
+ function renderGroupEditor(key, group) {
3214
+ const modeItems = inventory.modes.map((mode) => ({ value: mode.id, label: mode.name, hint: mode.id }))
3215
+ const workspaceItems = inventory.workspaces.map((row) => ({
3216
+ value: row.path,
3217
+ label: row.name || baseName(row.path),
3218
+ hint: row.path,
3219
+ }))
3220
+ return h(
3221
+ 'div',
3222
+ { style: { ...S.condPanel, marginBottom: '6px' } },
3223
+ h(
3224
+ Field,
3225
+ { label: TEXT.rowModes, hint: TEXT.groupHint },
3226
+ h(MultiSelect, {
3227
+ items: modeItems,
3228
+ selected: group ? asStringArray(group.modes) : [],
3229
+ onChange: (values) => updateGroup(key, { modes: values }),
3230
+ searchPlaceholder: TEXT.previewAllModes,
3231
+ emptyHint: TEXT.allModes,
3232
+ emptyText: TEXT.noMatches,
3233
+ selectAllLabel: TEXT.selectAll,
3234
+ clearAllLabel: TEXT.clearAll,
3235
+ }),
3236
+ ),
3237
+ h(
3238
+ Field,
3239
+ { label: TEXT.rowWorkspaces, hint: TEXT.groupHint },
3240
+ h(MultiSelect, {
3241
+ items: workspaceItems,
3242
+ selected: group ? asStringArray(group.workspaces) : [],
3243
+ onChange: (values) => updateGroup(key, { workspaces: values }),
3244
+ searchPlaceholder: TEXT.previewAllWorkspaces,
3245
+ emptyHint: TEXT.allWorkspaces,
3246
+ emptyText: TEXT.noMatches,
3247
+ selectAllLabel: TEXT.selectAll,
3248
+ clearAllLabel: TEXT.clearAll,
3249
+ }),
3250
+ h(AddPathRow, {
3251
+ placeholder: TEXT.addPathPlaceholder,
3252
+ label: TEXT.addPath,
3253
+ onAdd: (path) =>
3254
+ updateGroup(key, {
3255
+ workspaces: uniqueStrings([...(group ? asStringArray(group.workspaces) : []), path]),
3256
+ }),
3257
+ }),
3258
+ ),
3259
+ )
3260
+ }
3261
+
3262
+ function renderSkillSection(row) {
3263
+ const editorOpen = expanded['group:' + row.key] === true
3264
+ const folded = groupOpen[row.key] !== true
3265
+ return h(
3266
+ 'div',
3267
+ { key: row.key, style: SX.groupBox },
3268
+ renderGroupHead(row.key, row.name, row.names.length),
3269
+ editorOpen ? renderGroupEditor(row.key, row.group) : null,
3270
+ folded
3271
+ ? null
3272
+ : row.names.map((name, index) =>
3273
+ safeNode(`skill:${name}`, () => renderItemRow(SKILL, name, index === row.names.length - 1)),
3274
+ ),
3275
+ )
3276
+ }
3277
+
3278
+ function renderUngroupedSection() {
3279
+ const folded = groupOpen.ungrouped !== true
3280
+ return h(
3281
+ 'div',
3282
+ { key: 'ungrouped', style: SX.groupBox },
3283
+ h(
3284
+ 'div',
3285
+ { style: SX.groupHead },
3286
+ h(
3287
+ 'span',
3288
+ {
3289
+ role: 'button',
3290
+ tabIndex: 0,
3291
+ 'aria-label': folded ? TEXT.groupExpand : TEXT.groupCollapse,
3292
+ title: folded ? TEXT.groupExpand : TEXT.groupCollapse,
3293
+ style: { ...SX.groupCaret, transform: folded ? 'none' : 'rotate(90deg)' },
3294
+ onClick: () => toggleGroupOpen('ungrouped'),
3295
+ },
3296
+ '▸',
3297
+ ),
3298
+ h(
3299
+ 'span',
3300
+ { style: SX.groupName, title: TEXT.groupUngrouped, onClick: () => toggleGroupOpen('ungrouped') },
3301
+ TEXT.groupUngrouped,
3302
+ ),
3303
+ h('span', { style: S.countBadge }, `${ungroupedSkills.length} ${TEXT.countUnit}`),
3304
+ ),
3305
+ folded
3306
+ ? null
3307
+ : ungroupedSkills.map((name, index) =>
3308
+ safeNode(`skill:${name}`, () => renderItemRow(SKILL, name, index === ungroupedSkills.length - 1)),
3309
+ ),
3310
+ )
3311
+ }
3312
+
3313
+ function renderSkillSections() {
3314
+ return h(
3315
+ 'div',
3316
+ null,
3317
+ ...groupList.map((row) => renderSkillSection(row)),
3318
+ ungroupedSkills.length > 0 ? renderUngroupedSection() : null,
3319
+ )
3320
+ }
3321
+
3322
+ function renderGroup(kind) {
3323
+ const isMcp = kind === MCP
3324
+ const names = isMcp ? mcpNames : skillNames
3325
+ return h(
3326
+ 'div',
3327
+ { style: { ...S.card, ...(isMcp ? S.cardMcp : S.cardSkill) } },
3328
+ h(
3329
+ 'div',
3330
+ { style: S.cardHead },
3331
+ h(
3332
+ 'div',
3333
+ { style: S.cardTitleRow },
3334
+ h('span', { style: S.cardTitle }, isMcp ? TEXT.cardMcp : TEXT.cardSkills),
3335
+ h('span', { style: S.countBadge }, String(names.length)),
3336
+ ),
3337
+ ),
3338
+ !isMcp && names.length > 0 ? h('div', { style: S.cardDesc }, TEXT.groupHint) : null,
3339
+ names.length === 0
3340
+ ? h('div', { style: SX.groupEmpty }, isMcp ? TEXT.groupEmptyMcp : TEXT.groupEmptySkills)
3341
+ : isMcp
3342
+ ? names.map((name, index) =>
3343
+ safeNode(`${kind}:${name}`, () => renderItemRow(kind, name, index === names.length - 1)),
3344
+ )
3345
+ : renderSkillSections(),
3346
+ )
3347
+ }
3348
+
3349
+ function renderNativeSkills() {
3350
+ const rows = inventory.nativeSkills
3351
+ return h(
3352
+ 'div',
3353
+ { style: { ...S.card, ...S.cardSystem } },
3354
+ h(
3355
+ 'div',
3356
+ { style: S.cardHead },
3357
+ h(
3358
+ 'div',
3359
+ { style: S.cardTitleRow },
3360
+ h('span', { style: S.cardTitle }, TEXT.systemSkillsTitle),
3361
+ h('span', { style: S.countBadge }, String(rows.length)),
3362
+ ),
3363
+ ),
3364
+ h('div', { style: S.cardDesc }, TEXT.systemSkillsHint),
3365
+ rows.length === 0
3366
+ ? h('div', { style: SX.groupEmpty }, TEXT.systemSkillsEmpty)
3367
+ : rows.map((row, index) =>
3368
+ h(
3369
+ 'div',
3370
+ {
3371
+ key: row.name,
3372
+ style: { ...SX.nativeRow, ...(index === rows.length - 1 ? SX.nativeRowLast : null) },
3373
+ // Same rule as pool rows: the description is a hover detail.
3374
+ title: row.description ? asString(row.description) : undefined,
3375
+ },
3376
+ h(
3377
+ 'div',
3378
+ { style: S.rowName },
3379
+ h('span', { style: S.mono }, row.name),
3380
+ row.provider ? h('span', { style: S.badge }, row.provider) : null,
3381
+ row.source ? h('span', { style: S.badge }, row.source) : null,
3382
+ ),
3383
+ ),
3384
+ ),
3385
+ )
3386
+ }
3387
+
3388
+ function renderResources() {
3389
+ const total = skillNames.length + mcpNames.length
3390
+ return h(
3391
+ 'div',
3392
+ { style: S.stack },
3393
+ renderPreview(),
3394
+ total === 0 ? renderEmptyState() : null,
3395
+ renderGroup(SKILL),
3396
+ renderGroup(MCP),
3397
+ renderNativeSkills(),
3398
+ )
3399
+ }
3400
+
3401
+ function renderSourceRow(source, isLast) {
3402
+ const check = source.lastCheck || { at: '', status: '', remote: '', error: '' }
3403
+ const status = asString(check.status)
3404
+ const isGit = source.kind === 'git'
3405
+ const checkKey = 'sources:check:' + source.id
3406
+ const updateKey = 'source:update:' + source.id
3407
+ const deleteKey = 'source:delete:' + source.id
3408
+ const checkBusy = isBusy(checkKey)
3409
+ const updateBusy = isBusy(updateKey)
3410
+ const deleteBusy = isBusy(deleteKey)
3411
+ const confirming = confirmSource === source.id
3412
+ return h(
3413
+ 'div',
3414
+ { style: { ...S.sourceRow, ...(isLast ? { borderBottom: 'none' } : null) } },
3415
+ h(
3416
+ 'div',
3417
+ { style: S.sourceMain },
3418
+ h(
3419
+ 'div',
3420
+ { style: S.sourceName },
3421
+ h('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } }, source.label || source.id),
3422
+ h('span', { style: S.badge }, kindLabel(source.kind)),
3423
+ h('span', { style: statusBadgeStyle(status) }, statusLabel(status)),
3424
+ check.at ? h('span', { style: S.savingDot }, `${TEXT.lastCheck} ${formatTime(check.at)}`) : null,
3425
+ ),
3426
+ h(
3427
+ 'div',
3428
+ { style: S.sourceMeta },
3429
+ h(
3430
+ 'span',
3431
+ { style: S.fieldHint },
3432
+ `${source.skills.length} ${source.skills.length === 1 ? TEXT.sourceSkillsUnitOne : TEXT.sourceSkillsUnit}`,
3433
+ ),
3434
+ isGit && asStringArray(source.excluded).length > 0
3435
+ ? h(
3436
+ 'span',
3437
+ { style: S.badgeWarn, title: TEXT.sourceRestoreHint },
3438
+ tf('sourceExcluded', { count: asStringArray(source.excluded).length }),
3439
+ )
3440
+ : null,
3441
+ isGit && source.project
3442
+ ? h(
3443
+ 'span',
3444
+ { style: S.fieldHint },
3445
+ `${source.project}${source.branch ? '@' + source.branch : ''}`,
3446
+ )
3447
+ : null,
3448
+ isGit && source.sha ? h('span', { style: S.mono }, `${TEXT.sourceSha} ${asString(source.sha).slice(0, 8)}`) : null,
3449
+ source.digest ? h('span', { style: S.mono }, `${TEXT.sourceDigest} ${shortDigest(source.digest)}`) : null,
3450
+ source.createdAt
3451
+ ? h('span', { style: S.fieldHint }, `${TEXT.sourceCreatedAt} ${formatTime(source.createdAt)}`)
3452
+ : null,
3453
+ ),
3454
+ status === 'error' && check.error ? h('div', { style: SX.inlineError }, check.error) : null,
3455
+ confirming
3456
+ ? h(
3457
+ 'div',
3458
+ { style: SX.confirmRow },
3459
+ h('span', { style: SX.confirmText }, TEXT.sourceDeleteConfirm),
3460
+ h(
3461
+ 'button',
3462
+ {
3463
+ type: 'button',
3464
+ style: S.buttonDanger,
3465
+ disabled: deleteBusy,
3466
+ onClick: () => void deleteSource(source.id),
3467
+ },
3468
+ deleteBusy ? TEXT.sourceDeleting : TEXT.sourceDeleteYes,
3469
+ ),
3470
+ h(
3471
+ 'button',
3472
+ { type: 'button', style: S.buttonSmall, onClick: () => setConfirmSource('') },
3473
+ TEXT.sourceDeleteCancel,
3474
+ ),
3475
+ )
3476
+ : null,
3477
+ ),
3478
+ h(
3479
+ 'div',
3480
+ { style: S.rowActions },
3481
+ isGit
3482
+ ? h(
3483
+ 'button',
3484
+ {
3485
+ type: 'button',
3486
+ style: S.buttonSmall,
3487
+ disabled: checkBusy || updateBusy,
3488
+ onClick: () => void checkSources([source.id]),
3489
+ title: TEXT.sourceCheck,
3490
+ },
3491
+ checkBusy ? TEXT.sourceChecking : TEXT.sourceCheck,
3492
+ )
3493
+ : h('span', { style: S.badge, title: TEXT.sourceNotGit }, TEXT.sourceReadOnly),
3494
+ isGit && asStringArray(source.excluded).length > 0
3495
+ ? h(
3496
+ 'button',
3497
+ {
3498
+ type: 'button',
3499
+ style: S.buttonSmall,
3500
+ disabled: updateBusy || checkBusy,
3501
+ title: TEXT.sourceRestoreHint,
3502
+ onClick: () => void updateSource(source.id, { restore: true }),
3503
+ },
3504
+ updateBusy ? TEXT.sourceRestoring : TEXT.sourceRestore,
3505
+ )
3506
+ : null,
3507
+ isGit
3508
+ ? h(
3509
+ 'button',
3510
+ {
3511
+ type: 'button',
3512
+ style: status === 'update-available' ? S.buttonPrimary : S.buttonSmall,
3513
+ disabled: updateBusy || checkBusy,
3514
+ onClick: () => void updateSource(source.id),
3515
+ },
3516
+ updateBusy ? TEXT.sourceUpdating : TEXT.sourceUpdate,
3517
+ )
3518
+ : null,
3519
+ h(
3520
+ 'button',
3521
+ { type: 'button', style: S.ghostDanger, onClick: () => setConfirmSource(confirming ? '' : source.id) },
3522
+ TEXT.sourceDelete,
3523
+ ),
3524
+ ),
3525
+ )
3526
+ }
3527
+
3528
+ function renderSources() {
3529
+ const checkAllBusy = isBusy('sources:check:all')
3530
+ return h(
3531
+ 'div',
3532
+ { style: S.stack },
3533
+ h(
3534
+ 'div',
3535
+ { style: S.card },
3536
+ h(
3537
+ 'div',
3538
+ { style: S.cardHead },
3539
+ h(
3540
+ 'div',
3541
+ { style: S.cardTitleRow },
3542
+ h('span', { style: S.cardTitle }, TEXT.tabSources),
3543
+ h('span', { style: S.countBadge }, String(sourceList.length)),
3544
+ ),
3545
+ h(
3546
+ 'div',
3547
+ { style: S.row },
3548
+ h(
3549
+ 'button',
3550
+ {
3551
+ type: 'button',
3552
+ style: S.buttonSmall,
3553
+ disabled: checkAllBusy || sourceList.length === 0,
3554
+ onClick: () => void checkSources([]),
3555
+ },
3556
+ checkAllBusy ? TEXT.checkingAll : TEXT.checkAll,
3557
+ ),
3558
+ h('button', { type: 'button', style: S.buttonSmall, onClick: () => void loadBoard() }, TEXT.refresh),
3559
+ ),
3560
+ ),
3561
+ h('div', { style: S.cardDesc }, TEXT.sourcesHint),
3562
+ sourceList.length === 0
3563
+ ? h('div', { style: S.empty }, TEXT.sourcesEmpty)
3564
+ : sourceSections.map((section) => {
3565
+ const openKey = 'src:' + section.key
3566
+ const folded = groupOpen[openKey] !== true
3567
+ const gitIds = section.rows.filter((row) => row.kind === 'git').map((row) => row.id)
3568
+ const groupCheckBusy = gitIds.length > 0 && isBusy('sources:check:' + gitIds.join(','))
3569
+ const groupUpdateBusy = isBusy('group:update:' + section.key)
3570
+ const groupStatus = sourceGroupStatus(section.rows)
3571
+ return h(
3572
+ 'div',
3573
+ { key: section.key, style: SX.groupBox },
3574
+ h(
3575
+ 'div',
3576
+ { style: SX.groupHead },
3577
+ h(
3578
+ 'span',
3579
+ {
3580
+ role: 'button',
3581
+ tabIndex: 0,
3582
+ 'aria-label': folded ? TEXT.groupExpand : TEXT.groupCollapse,
3583
+ title: folded ? TEXT.groupExpand : TEXT.groupCollapse,
3584
+ style: { ...SX.groupCaret, transform: folded ? 'none' : 'rotate(90deg)' },
3585
+ onClick: () => toggleGroupOpen(openKey),
3586
+ },
3587
+ '▸',
3588
+ ),
3589
+ h(
3590
+ 'span',
3591
+ { style: SX.groupName, title: section.name, onClick: () => toggleGroupOpen(openKey) },
3592
+ section.name,
3593
+ ),
3594
+ h(
3595
+ 'span',
3596
+ { style: S.countBadge },
3597
+ tf(section.rows.length === 1 ? 'groupImportOne' : 'groupImports', { count: section.rows.length }),
3598
+ ),
3599
+ groupStatus.length > 0
3600
+ ? h('span', { style: statusBadgeStyle(groupStatus) }, statusLabel(groupStatus))
3601
+ : null,
3602
+ gitIds.length > 0
3603
+ ? h(
3604
+ 'button',
3605
+ {
3606
+ type: 'button',
3607
+ style: S.buttonSmall,
3608
+ disabled: groupCheckBusy || groupUpdateBusy,
3609
+ onClick: () => void checkSources(gitIds),
3610
+ },
3611
+ groupCheckBusy ? TEXT.sourceChecking : TEXT.sourceCheck,
3612
+ )
3613
+ : null,
3614
+ gitIds.length > 0
3615
+ ? h(
3616
+ 'button',
3617
+ {
3618
+ type: 'button',
3619
+ style: groupStatus === 'update-available' ? S.buttonPrimary : S.buttonSmall,
3620
+ disabled: groupCheckBusy || groupUpdateBusy,
3621
+ onClick: () => void updateGroupSources(section.key, gitIds),
3622
+ },
3623
+ groupUpdateBusy ? TEXT.sourceUpdating : TEXT.sourceUpdate,
3624
+ )
3625
+ : null,
3626
+ ),
3627
+ folded
3628
+ ? null
3629
+ : section.rows.map((source, index) =>
3630
+ safeNode('source:' + source.id, () => renderSourceRow(source, index === section.rows.length - 1)),
3631
+ ),
3632
+ )
3633
+ }),
3634
+ ),
3635
+ )
3636
+ }
3637
+
3638
+ function renderGroupSwitches() {
3639
+ if (groupList.length === 0) return null
3640
+ return h(
3641
+ 'div',
3642
+ { style: S.card },
3643
+ h(
3644
+ 'div',
3645
+ { style: S.cardHead },
3646
+ h(
3647
+ 'div',
3648
+ { style: S.cardTitleRow },
3649
+ h('span', { style: S.cardTitle }, TEXT.settingsGroups),
3650
+ h('span', { style: S.countBadge }, String(groupList.length)),
3651
+ ),
3652
+ ),
3653
+ h('div', { style: S.cardDesc }, TEXT.settingsGroupsHint),
3654
+ groupList.map((row, index) =>
3655
+ h(
3656
+ 'div',
3657
+ {
3658
+ key: row.key,
3659
+ style: {
3660
+ ...SX.groupSwitchRow,
3661
+ ...(index === groupList.length - 1 ? { borderBottom: 'none' } : null),
3662
+ },
3663
+ },
3664
+ h(
3665
+ 'div',
3666
+ { style: S.rowText },
3667
+ h(
3668
+ 'div',
3669
+ { style: S.rowName },
3670
+ h(
3671
+ 'span',
3672
+ { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } },
3673
+ row.name,
3674
+ ),
3675
+ h('span', { style: S.countBadge }, `${row.names.length} ${TEXT.countUnit}`),
3676
+ row.group !== null && row.group.enabled === false
3677
+ ? h('span', { style: S.badgeWarn }, TEXT.groupDisabledTag)
3678
+ : null,
3679
+ ),
3680
+ h(
3681
+ 'div',
3682
+ { style: S.rowDesc },
3683
+ `${TEXT.rowModes}: ${groupScopeText(row.group, 'modes')} · ${TEXT.rowWorkspaces}: ${groupScopeText(row.group, 'workspaces')}`,
3684
+ ),
3685
+ ),
3686
+ h(Toggle, {
3687
+ checked: row.group === null || row.group.enabled !== false,
3688
+ label: row.name,
3689
+ title: row.group !== null && row.group.enabled === false ? TEXT.disabled : TEXT.enabled,
3690
+ onChange: (value) => updateGroup(row.key, { enabled: value }),
3691
+ }),
3692
+ ),
3693
+ ),
3694
+ )
3695
+ }
3696
+
3697
+ function renderSettings() {
3698
+ const savingSettings = isBusy('settings')
3699
+ return h(
3700
+ 'div',
3701
+ { style: S.stack },
3702
+ h(
3703
+ 'div',
3704
+ { style: S.card },
3705
+ h(
3706
+ 'div',
3707
+ { style: S.cardHead },
3708
+ h(
3709
+ 'div',
3710
+ { style: S.cardTitleRow },
3711
+ h('span', { style: S.cardTitle }, TEXT.tabSettings),
3712
+ savingSettings ? h('span', { style: S.savingDot }, TEXT.settingsSaving) : null,
3713
+ ),
3714
+ ),
3715
+ h(SwitchRow, {
3716
+ label: TEXT.setEnabled,
3717
+ hint: TEXT.setEnabledHint,
3718
+ checked: settings.enabled === true,
3719
+ disabled: savingSettings,
3720
+ onChange: (value) => void saveSettings({ enabled: value }),
3721
+ }),
3722
+ h(SwitchRow, {
3723
+ label: TEXT.setMcpGate,
3724
+ hint: TEXT.setMcpGateHint,
3725
+ checked: settings.mcpGate === true,
3726
+ disabled: savingSettings,
3727
+ onChange: (value) => void saveSettings({ mcpGate: value }),
3728
+ }),
3729
+ h(SwitchRow, {
3730
+ label: TEXT.setInjectSummary,
3731
+ hint: TEXT.setInjectSummaryHint,
3732
+ checked: settings.injectSummary === true,
3733
+ disabled: savingSettings,
3734
+ onChange: (value) => void saveSettings({ injectSummary: value }),
3735
+ }),
3736
+ h(SwitchRow, {
3737
+ label: `${TEXT.setGateDefaultSkills} · ${TEXT.notAvailable}`,
3738
+ hint: TEXT.setGateDefaultSkillsHint,
3739
+ checked: settings.gateDefaultSkills === true,
3740
+ disabled: true,
3741
+ onChange: () => {},
3742
+ }),
3743
+ h('div', { style: S.cardDesc }, TEXT.settingsHint),
3744
+ ),
3745
+ renderGroupSwitches(),
3746
+ h(
3747
+ 'div',
3748
+ { style: S.row },
3749
+ meta.file ? h('span', { style: S.fieldHint }, `${TEXT.stateFile}: ${asString(meta.file)}`) : null,
3750
+ meta.version !== undefined && asString(meta.version).length > 0
3751
+ ? h('span', { style: S.fieldHint }, `${TEXT.version}: ${asString(meta.version)}`)
3752
+ : null,
3753
+ h('button', { type: 'button', style: S.buttonSmall, onClick: () => void loadBoard() }, TEXT.refresh),
3754
+ ),
3755
+ )
3756
+ }
3757
+
3758
+ function renderDialog() {
3759
+ if (!dialog) return null
3760
+ return h(ImportDialog, {
3761
+ modes: inventory.modes,
3762
+ workspaces: inventory.workspaces,
3763
+ onSubmit: submitImport,
3764
+ pollMounts,
3765
+ onRefresh: async () => {
3766
+ await loadBoard({ silent: true })
3767
+ },
3768
+ onDone: (message) => void afterImport(message),
3769
+ onClose: () => setDialog(false),
3770
+ })
3771
+ }
3772
+
3773
+ return h(
3774
+ 'div',
3775
+ { style: S.page, className: 'dsh-rp-root' },
3776
+ h('style', null, PAGE_CSS),
3777
+ h(
3778
+ 'div',
3779
+ { style: S.headerRow },
3780
+ h(
3781
+ 'div',
3782
+ { style: S.titleWrap },
3783
+ h('h2', { style: S.title }, TEXT.title),
3784
+ h('p', { style: S.subtitle }, TEXT.subtitle),
3785
+ ),
3786
+ h(
3787
+ 'div',
3788
+ { style: S.toolbar },
3789
+ // Importing and scoping are two separate jobs: import lives with the
3790
+ // page actions, conditions are edited on each resource row.
3791
+ h('button', { type: 'button', style: S.buttonPrimary, onClick: () => setDialog(true) }, TEXT.importResource),
3792
+ h(
3793
+ 'button',
3794
+ { type: 'button', style: S.button, onClick: () => void loadBoard(), disabled: loading },
3795
+ loading ? TEXT.loading : TEXT.refresh,
3796
+ ),
3797
+ ),
3798
+ ),
3799
+ error
3800
+ ? h(
3801
+ 'div',
3802
+ { style: { ...S.error, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '10px' }, role: 'alert' },
3803
+ h('span', { style: { minWidth: 0 } }, error),
3804
+ h('button', { type: 'button', style: S.buttonSmall, onClick: () => setError('') }, TEXT.close),
3805
+ )
3806
+ : null,
3807
+ notice ? h('div', { style: S.notice, role: 'status' }, notice) : null,
3808
+ board
3809
+ ? h(
3810
+ React.Fragment,
3811
+ null,
3812
+ h(
3813
+ 'div',
3814
+ { style: S.tabs },
3815
+ ...TABS.map(([key, textKey]) =>
3816
+ h(
3817
+ 'button',
3818
+ {
3819
+ key,
3820
+ type: 'button',
3821
+ style: { ...S.tab, ...(tab === key ? S.tabActive : null) },
3822
+ onClick: (event) => {
3823
+ event.currentTarget.blur()
3824
+ setTab(key)
3825
+ },
3826
+ },
3827
+ t(textKey),
3828
+ ),
3829
+ ),
3830
+ ),
3831
+ tab === 'resources' ? renderResources() : null,
3832
+ tab === 'sources' ? renderSources() : null,
3833
+ tab === 'settings' ? renderSettings() : null,
3834
+ )
3835
+ : h(
3836
+ 'div',
3837
+ { style: S.stack },
3838
+ h('div', { style: S.empty }, loading ? TEXT.loading : TEXT.retryHint),
3839
+ loading
3840
+ ? null
3841
+ : h(
3842
+ 'div',
3843
+ null,
3844
+ h('button', { type: 'button', style: S.buttonPrimary, onClick: () => void loadBoard() }, TEXT.retry),
3845
+ ),
3846
+ ),
3847
+ renderDialog(),
3848
+ )
3849
+ }
3850
+
3851
+ // ---------------------------------------------------------------- dialog
3852
+
3853
+ /** Single import dialog with four segments (files / ZIP / Git / MCP). */
3854
+ function ImportDialog(props) {
3855
+ const [seg, setSeg] = useState('files')
3856
+ const [pickedFiles, setPickedFiles] = useState([])
3857
+ const [pickedNames, setPickedNames] = useState([])
3858
+ const [name, setName] = useState('')
3859
+ const [description, setDescription] = useState('')
3860
+ const [body, setBody] = useState('')
3861
+ const [zipFile, setZipFile] = useState(null)
3862
+ const [zipLabel, setZipLabel] = useState('')
3863
+ const [gitUrl, setGitUrl] = useState('')
3864
+ const [gitProvider, setGitProvider] = useState('auto')
3865
+ const [gitBranch, setGitBranch] = useState('')
3866
+ const [gitSubdir, setGitSubdir] = useState('')
3867
+ const [gitToken, setGitToken] = useState('')
3868
+ const [gitLabel, setGitLabel] = useState('')
3869
+ const [json, setJson] = useState(
3870
+ '{\n "mcpServers": {\n "my-server": {\n "url": "https://example.com/mcp"\n }\n }\n}',
3871
+ )
3872
+ const [overwrite, setOverwrite] = useState(false)
3873
+ const [busy, setBusy] = useState(false)
3874
+ const [error, setError] = useState('')
3875
+ const [result, setResult] = useState(null)
3876
+ const [mountRows, setMountRows] = useState(null)
3877
+ const mounted = useRef(true)
3878
+ const pollRef = useRef(null)
3879
+
3880
+ useEffect(() => {
3881
+ mounted.current = true
3882
+ return () => {
3883
+ mounted.current = false
3884
+ if (pollRef.current) clearInterval(pollRef.current)
3885
+ }
3886
+ }, [])
3887
+
3888
+ const modeItems = useMemo(
3889
+ () => asArray(props.modes).map((mode) => ({ value: mode.id, label: mode.name || mode.id, hint: mode.id })),
3890
+ [props.modes],
3891
+ )
3892
+ const workspaceItems = useMemo(
3893
+ () =>
3894
+ asArray(props.workspaces).map((row) => ({
3895
+ value: row.path,
3896
+ label: row.name || baseName(row.path),
3897
+ hint: row.path,
3898
+ })),
3899
+ [props.workspaces],
3900
+ )
3901
+
3902
+ const mountSettled =
3903
+ mountRows === null ||
3904
+ Object.values(mountRows).every((value) => !value || value.state !== 'mounting')
3905
+
3906
+ async function pickFiles(event, fromFolder) {
3907
+ const picked = [...(event.target.files || [])]
3908
+ // Drop focus so the wrapping label never shows a ring after the pick.
3909
+ event.target.blur()
3910
+ if (picked.length === 0) return
3911
+ setError('')
3912
+ setBusy(true)
3913
+ try {
3914
+ const out = []
3915
+ for (const file of picked) {
3916
+ if (Number(file.size) > MAX_UPLOAD_BYTES) {
3917
+ throw new Error(`${asString(file.name)}: ${TEXT.filesTooLarge}`)
3918
+ }
3919
+ out.push({
3920
+ path: asString(file.webkitRelativePath) || asString(file.name),
3921
+ contentBase64: await readFileBase64(file),
3922
+ })
3923
+ }
3924
+ setPickedFiles(out)
3925
+ setPickedNames(picked.map((file) => asString(file.name)))
3926
+ const primary = fromFolder
3927
+ ? picked.find((file) => asString(file.webkitRelativePath).endsWith('SKILL.md'))
3928
+ : picked.length === 1
3929
+ ? picked[0]
3930
+ : picked.find((file) => asString(file.name).toLowerCase().endsWith('.md'))
3931
+ if (primary && name.trim().length === 0) setName(asString(primary.name).replace(/\.md$/i, ''))
3932
+ } catch (cause) {
3933
+ if (mounted.current) setError(messageOf(cause))
3934
+ } finally {
3935
+ if (mounted.current) setBusy(false)
3936
+ }
3937
+ }
3938
+
3939
+ function startMountPolling() {
3940
+ if (pollRef.current) clearInterval(pollRef.current)
3941
+ let elapsed = 0
3942
+ pollRef.current = setInterval(() => {
3943
+ elapsed += MOUNT_POLL_MS
3944
+ void (async () => {
3945
+ try {
3946
+ const next = await props.pollMounts()
3947
+ if (!mounted.current) return
3948
+ setMountRows((current) => ({ ...(current || {}), ...next }))
3949
+ const stillMounting = Object.values(next).some((value) => value && value.state === 'mounting')
3950
+ if (!stillMounting) {
3951
+ clearInterval(pollRef.current)
3952
+ pollRef.current = null
3953
+ void props.onRefresh()
3954
+ }
3955
+ } catch {
3956
+ /* keep polling */
3957
+ }
3958
+ if (elapsed >= 30000 && pollRef.current) {
3959
+ clearInterval(pollRef.current)
3960
+ pollRef.current = null
3961
+ }
3962
+ })()
3963
+ }, MOUNT_POLL_MS)
3964
+ }
3965
+
3966
+ async function submit() {
3967
+ setError('')
3968
+ setResult(null)
3969
+ // Importing never asks for conditions: a new resource is admitted for every
3970
+ // mode and workspace, and its scope is edited on its row afterwards.
3971
+ const scopeBody = {}
3972
+ let payloadBody = null
3973
+ if (seg === 'files') {
3974
+ const files =
3975
+ pickedFiles.length > 0
3976
+ ? pickedFiles
3977
+ : body.trim().length > 0
3978
+ ? [{ path: 'SKILL.md', contentBase64: encodeTextBase64(body) }]
3979
+ : []
3980
+ if (files.length === 0) {
3981
+ setError(TEXT.filesNeed)
3982
+ return
3983
+ }
3984
+ payloadBody = { files, name: name.trim(), description: description.trim(), ...scopeBody, overwrite }
3985
+ } else if (seg === 'zip') {
3986
+ if (!zipFile) {
3987
+ setError(TEXT.zipNeed)
3988
+ return
3989
+ }
3990
+ setBusy(true)
3991
+ try {
3992
+ payloadBody = {
3993
+ archiveBase64: await readFileBase64(zipFile),
3994
+ label: zipLabel.trim(),
3995
+ ...scopeBody,
3996
+ overwrite,
3997
+ }
3998
+ } catch (cause) {
3999
+ if (mounted.current) {
4000
+ setError(`${TEXT.filesReadFailed}: ${messageOf(cause)}`)
4001
+ setBusy(false)
4002
+ }
4003
+ return
4004
+ }
4005
+ } else if (seg === 'git') {
4006
+ const url = gitUrl.trim()
4007
+ if (url.length === 0) {
4008
+ setError(TEXT.gitNeedUrl)
4009
+ return
4010
+ }
4011
+ payloadBody = {
4012
+ url,
4013
+ provider: gitProvider,
4014
+ branch: gitBranch.trim(),
4015
+ subdir: gitSubdir.trim(),
4016
+ token: gitToken.trim(),
4017
+ label: gitLabel.trim(),
4018
+ ...scopeBody,
4019
+ overwrite,
4020
+ }
4021
+ } else {
4022
+ const text = json.trim()
4023
+ if (text.length === 0) {
4024
+ setError(TEXT.mcpJsonInvalid)
4025
+ return
4026
+ }
4027
+ let parsed = null
4028
+ try {
4029
+ parsed = JSON.parse(text)
4030
+ } catch (cause) {
4031
+ setError(`${TEXT.mcpJsonBad}: ${messageOf(cause)}`)
4032
+ return
4033
+ }
4034
+ payloadBody = { payload: parsed, ...scopeBody }
4035
+ }
4036
+
4037
+ setBusy(true)
4038
+ try {
4039
+ const payload = await props.onSubmit(seg, payloadBody)
4040
+ if (!mounted.current) return
4041
+ if (seg === 'mcp') {
4042
+ const initial = normalizeMount(payload.mounts || payload.mount)
4043
+ const rows = {}
4044
+ for (const row of asArray(payload.servers)) {
4045
+ const serverName = asString(row && (row.server || row.serverName))
4046
+ if (serverName.length === 0) continue
4047
+ rows[serverName] = initial[serverName] || {
4048
+ state: asString(row.state) === 'failed' ? 'failed' : 'mounting',
4049
+ error: '',
4050
+ }
4051
+ }
4052
+ for (const [serverName, value] of Object.entries(initial)) {
4053
+ if (!rows[serverName]) rows[serverName] = value
4054
+ }
4055
+ setMountRows(rows)
4056
+ setResult({ installed: Object.keys(rows), failures: [] })
4057
+ startMountPolling()
4058
+ } else {
4059
+ const installed = asStringArray(payload.installed)
4060
+ const failures = asArray(payload.failures).map((row) => ({
4061
+ name: asString(row && row.name),
4062
+ error: asString(row && row.error),
4063
+ }))
4064
+ if (failures.length === 0) {
4065
+ props.onDone(installed.length > 0 ? `${TEXT.importInstalled}: ${installed.join(', ')}` : TEXT.importInstalled)
4066
+ return
4067
+ }
4068
+ setResult({ installed, failures })
4069
+ void props.onRefresh()
4070
+ }
4071
+ } catch (cause) {
4072
+ if (mounted.current) setError(messageOf(cause))
4073
+ } finally {
4074
+ if (mounted.current) setBusy(false)
4075
+ }
4076
+ }
4077
+
4078
+ function doneMessage() {
4079
+ const names = mountRows ? Object.keys(mountRows) : result ? result.installed : []
4080
+ return names.length > 0 ? `${TEXT.mcpNotice} ${names.join(', ')}` : TEXT.importInstalled
4081
+ }
4082
+
4083
+ function renderFiles() {
4084
+ return h(
4085
+ React.Fragment,
4086
+ null,
4087
+ h(
4088
+ 'div',
4089
+ { style: S.fileRow },
4090
+ h(
4091
+ 'label',
4092
+ { style: S.buttonSmall },
4093
+ TEXT.filesPick,
4094
+ h('input', {
4095
+ type: 'file',
4096
+ accept: '.md,.markdown,text/markdown',
4097
+ multiple: true,
4098
+ style: { display: 'none' },
4099
+ onChange: (event) => void pickFiles(event, false),
4100
+ }),
4101
+ ),
4102
+ h(
4103
+ 'label',
4104
+ { style: S.buttonSmall },
4105
+ TEXT.filesPickFolder,
4106
+ h('input', {
4107
+ type: 'file',
4108
+ multiple: true,
4109
+ webkitdirectory: '',
4110
+ style: { display: 'none' },
4111
+ onChange: (event) => void pickFiles(event, true),
4112
+ }),
4113
+ ),
4114
+ pickedNames.length > 0
4115
+ ? h('span', { style: S.fieldHint }, `${TEXT.filesChosen}: ${pickedNames.join(', ')}`)
4116
+ : null,
4117
+ ),
4118
+ h(
4119
+ Field,
4120
+ { label: TEXT.filesName },
4121
+ h('input', {
4122
+ style: S.input,
4123
+ value: name,
4124
+ placeholder: TEXT.filesNamePlaceholder,
4125
+ onChange: (event) => setName(asString(event.target.value)),
4126
+ }),
4127
+ ),
4128
+ h(
4129
+ Field,
4130
+ { label: TEXT.filesDesc },
4131
+ h('input', {
4132
+ style: S.input,
4133
+ value: description,
4134
+ placeholder: TEXT.filesDescPlaceholder,
4135
+ onChange: (event) => setDescription(asString(event.target.value)),
4136
+ }),
4137
+ ),
4138
+ pickedFiles.length > 0
4139
+ ? null
4140
+ : h(
4141
+ Field,
4142
+ { label: TEXT.filesBody },
4143
+ h('textarea', {
4144
+ style: { ...S.textarea, ...S.uploadTextarea },
4145
+ value: body,
4146
+ placeholder: TEXT.filesBodyPlaceholder,
4147
+ onChange: (event) => setBody(asString(event.target.value)),
4148
+ }),
4149
+ ),
4150
+ )
4151
+ }
4152
+
4153
+ function renderZip() {
4154
+ return h(
4155
+ React.Fragment,
4156
+ null,
4157
+ h(
4158
+ 'div',
4159
+ { style: S.fileRow },
4160
+ h(
4161
+ 'label',
4162
+ { style: S.buttonSmall },
4163
+ TEXT.zipPick,
4164
+ h('input', {
4165
+ type: 'file',
4166
+ accept: '.zip,application/zip',
4167
+ style: { display: 'none' },
4168
+ onChange: (event) => {
4169
+ const picked = (event.target.files || [])[0]
4170
+ if (!picked) return
4171
+ if (Number(picked.size) > MAX_ZIP_BYTES) {
4172
+ setZipFile(null)
4173
+ setError(TEXT.zipTooLarge)
4174
+ return
4175
+ }
4176
+ setZipFile(picked)
4177
+ setError('')
4178
+ if (zipLabel.trim().length === 0) setZipLabel(asString(picked.name).replace(/\.zip$/i, ''))
4179
+ },
4180
+ }),
4181
+ ),
4182
+ zipFile
4183
+ ? h('span', { style: S.fieldHint }, `${TEXT.zipChosen}: ${asString(zipFile.name)}`)
4184
+ : null,
4185
+ ),
4186
+ h(
4187
+ Field,
4188
+ { label: TEXT.zipLabel },
4189
+ h('input', {
4190
+ style: S.input,
4191
+ value: zipLabel,
4192
+ onChange: (event) => setZipLabel(asString(event.target.value)),
4193
+ }),
4194
+ ),
4195
+ )
4196
+ }
4197
+
4198
+ function renderGit() {
4199
+ return h(
4200
+ React.Fragment,
4201
+ null,
4202
+ h(
4203
+ Field,
4204
+ { label: TEXT.gitUrl },
4205
+ h('input', {
4206
+ style: S.input,
4207
+ value: gitUrl,
4208
+ placeholder: TEXT.gitUrlPlaceholder,
4209
+ onChange: (event) => {
4210
+ const next = asString(event.target.value)
4211
+ setGitUrl(next)
4212
+ // A pasted browser URL already carries the branch and folder, so
4213
+ // prefill them instead of making the user retype. Two shapes exist
4214
+ // and both must be recognised here, or the form looks empty while
4215
+ // the Host still parses the URL correctly:
4216
+ // GitLab: <host>/<group>/<repo>/-/tree/<branch>/<subdir>
4217
+ // GitHub: <host>/<owner>/<repo>/tree/<branch>/<subdir>
4218
+ // Keep in sync with `parseRepoUrl` in src/library.js.
4219
+ const hint = deepLinkHint(next)
4220
+ if (hint !== undefined) {
4221
+ if (hint.branch.length > 0) setGitBranch(hint.branch)
4222
+ if (hint.subdir.length > 0) setGitSubdir(hint.subdir)
4223
+ }
4224
+ },
4225
+ }),
4226
+ ),
4227
+ h(
4228
+ Field,
4229
+ { label: TEXT.gitType, hint: TEXT.gitTypeHint },
4230
+ h(
4231
+ 'select',
4232
+ {
4233
+ style: S.select,
4234
+ value: gitProvider,
4235
+ onChange: (event) => setGitProvider(asString(event.target.value)),
4236
+ },
4237
+ h('option', { value: 'auto' }, TEXT.gitTypeAuto),
4238
+ h('option', { value: 'gitlab' }, TEXT.gitTypeGitlab),
4239
+ h('option', { value: 'github' }, TEXT.gitTypeGithub),
4240
+ ),
4241
+ ),
4242
+ h(
4243
+ 'div',
4244
+ { style: S.row },
4245
+ h(
4246
+ Field,
4247
+ { label: TEXT.gitBranch },
4248
+ h('input', {
4249
+ style: { ...S.input, minWidth: '140px' },
4250
+ value: gitBranch,
4251
+ placeholder: 'main',
4252
+ onChange: (event) => setGitBranch(asString(event.target.value)),
4253
+ }),
4254
+ ),
4255
+ h(
4256
+ Field,
4257
+ { label: TEXT.gitSubdir },
4258
+ h('input', {
4259
+ style: { ...S.input, minWidth: '140px' },
4260
+ value: gitSubdir,
4261
+ onChange: (event) => setGitSubdir(asString(event.target.value)),
4262
+ }),
4263
+ ),
4264
+ ),
4265
+ h(
4266
+ Field,
4267
+ { label: TEXT.gitLabel },
4268
+ h('input', {
4269
+ style: S.input,
4270
+ value: gitLabel,
4271
+ onChange: (event) => setGitLabel(asString(event.target.value)),
4272
+ }),
4273
+ ),
4274
+ h(
4275
+ Field,
4276
+ { label: TEXT.gitToken, hint: TEXT.gitTokenHint },
4277
+ h('input', {
4278
+ style: S.input,
4279
+ type: 'password',
4280
+ autoComplete: 'new-password',
4281
+ value: gitToken,
4282
+ onChange: (event) => setGitToken(asString(event.target.value)),
4283
+ }),
4284
+ ),
4285
+ )
4286
+ }
4287
+
4288
+ function renderMcp() {
4289
+ return h(
4290
+ Field,
4291
+ { label: TEXT.mcpJson, hint: TEXT.mcpJsonHint },
4292
+ h('textarea', {
4293
+ style: { ...S.textarea, ...S.uploadTextarea, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace' },
4294
+ value: json,
4295
+ spellCheck: false,
4296
+ onChange: (event) => setJson(asString(event.target.value)),
4297
+ }),
4298
+ )
4299
+ }
4300
+
4301
+ function renderResult() {
4302
+ if (!result) return null
4303
+ const failed = asArray(result.failures)
4304
+ return h(
4305
+ 'div',
4306
+ { style: SX.resultBox },
4307
+ result.installed.length > 0
4308
+ ? h(
4309
+ 'div',
4310
+ { style: SX.resultLine },
4311
+ `${seg === 'mcp' ? TEXT.mcpNotice : TEXT.importInstalled}: ${result.installed.join(', ')}`,
4312
+ )
4313
+ : null,
4314
+ mountRows && !mountSettled
4315
+ ? h('div', { style: S.fieldHint }, TEXT.mcpMountBackground)
4316
+ : null,
4317
+ mountRows
4318
+ ? h(
4319
+ 'div',
4320
+ { style: SX.resultLine },
4321
+ ...Object.entries(mountRows).map(([serverName, value]) =>
4322
+ h(
4323
+ 'div',
4324
+ { key: serverName, style: SX.mountLine },
4325
+ h('span', { style: { ...S.dot, ...mountDotStyle(value.state) } }),
4326
+ h('span', { style: S.mono }, serverName),
4327
+ h('span', { style: S.fieldHint }, mountLabel(value.state)),
4328
+ value.state === 'failed' && value.error
4329
+ ? h('span', { style: SX.inlineError }, value.error)
4330
+ : null,
4331
+ ),
4332
+ ),
4333
+ )
4334
+ : null,
4335
+ failed.length > 0
4336
+ ? h(
4337
+ 'div',
4338
+ { style: SX.resultLine },
4339
+ `${TEXT.importFailures}: ${failed.map((row) => `${row.name}: ${row.error}`).join('; ')}`,
4340
+ h('div', { style: S.fieldHint }, TEXT.importRetryHint),
4341
+ )
4342
+ : null,
4343
+ )
4344
+ }
4345
+
4346
+ const segments = [
4347
+ ['files', TEXT.segFiles],
4348
+ ['zip', TEXT.segZip],
4349
+ ['git', TEXT.segGit],
4350
+ ['mcp', TEXT.segMcp],
4351
+ ]
4352
+ const showDone = Boolean(result) && asArray(result.failures).length === 0
4353
+
4354
+ return h(
4355
+ Modal,
4356
+ {
4357
+ title: TEXT.importTitle,
4358
+ subtitle: TEXT.importSubtitle,
4359
+ wide: true,
4360
+ error,
4361
+ busy,
4362
+ onClose: props.onClose,
4363
+ footer: [
4364
+ h(
4365
+ 'button',
4366
+ { key: 'cancel', type: 'button', style: S.buttonSmall, onClick: props.onClose, disabled: busy },
4367
+ TEXT.cancel,
4368
+ ),
4369
+ showDone
4370
+ ? h(
4371
+ 'button',
4372
+ { key: 'done', type: 'button', style: S.buttonPrimary, onClick: () => props.onDone(doneMessage()) },
4373
+ TEXT.done,
4374
+ )
4375
+ : h(
4376
+ 'button',
4377
+ { key: 'submit', type: 'button', style: S.buttonPrimary, onClick: () => void submit(), disabled: busy },
4378
+ busy ? TEXT.importing : TEXT.importSubmit,
4379
+ ),
4380
+ ],
4381
+ },
4382
+ h(
4383
+ 'div',
4384
+ { style: SX.seg, role: 'tablist' },
4385
+ ...segments.map(([key, label]) =>
4386
+ h(
4387
+ 'button',
4388
+ {
4389
+ key,
4390
+ type: 'button',
4391
+ role: 'tab',
4392
+ 'aria-selected': seg === key ? 'true' : 'false',
4393
+ style: { ...SX.segBtn, ...(seg === key ? SX.segActive : null) },
4394
+ disabled: busy,
4395
+ onClick: (event) => {
4396
+ // Blur explicitly: a focused button keeps whatever ring the
4397
+ // environment draws, and the user reads it as a stuck border.
4398
+ event.currentTarget.blur()
4399
+ setSeg(key)
4400
+ },
4401
+ },
4402
+ label,
4403
+ ),
4404
+ ),
4405
+ ),
4406
+ seg === 'files' ? renderFiles() : seg === 'zip' ? renderZip() : seg === 'git' ? renderGit() : renderMcp(),
4407
+ seg === 'mcp' ? null : h(
4408
+ 'div',
4409
+ { style: S.row },
4410
+ h(Toggle, { checked: overwrite, label: TEXT.overwrite, onChange: (value) => setOverwrite(value === true) }),
4411
+ h('span', { style: S.fieldHint }, TEXT.overwrite),
4412
+ ),
4413
+ renderResult(),
4414
+ )
4415
+ }
4416
+
4417
+ return {
4418
+ inject: ['slots'],
4419
+ apply(ctx) {
4420
+ ctx.slots.inject('settings.section', () =>
4421
+ ctx.slots.register(
4422
+ {
4423
+ name: 'settings.section',
4424
+ id: 'skill-pool',
4425
+ order: 26,
4426
+ label: () => t('navTitle'),
4427
+ },
4428
+ Panel,
4429
+ ),
4430
+ )
4431
+ },
4432
+ }
4433
+ },
4434
+ })