dsh-skill-pool 0.0.0-stage → 0.3.8

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