Compare commits

...

9 Commits
v0.9.5 ... main

Author SHA1 Message Date
newbie 8e5145349d Revert "docs(readme): 重写为清爽入口页,详情迁移到 docs/(0.9.10)"
This reverts commit 6d868abb28.
2026-11-19 10:06:25 +08:00
newbie 6d868abb28 docs(readme): 重写为清爽入口页,详情迁移到 docs/(0.9.10) 2026-11-19 09:52:17 +08:00
QQ 7d053b2fe9 Merge pull request 'feat(skills): 同步冲突支持批量处理(0.9.10)' (#3) from feat/sync-batch-resolve into main 2026-11-14 16:05:20 +08:00
newbie d2bd955aa9 feat(skills): batch resolve all sync conflicts (0.9.10)
Adds POST /dsh-brain/sync/resolve-all {action: keep_local|take_cloud} and 全部保留本地 / 全部采用云端 buttons with an inline confirmation step. Partial failures are reported per item (resolved / failed lists) instead of aborting the batch; per-item resolution stays available.
2026-11-14 16:05:09 +08:00
QQ 4123d9de9e Merge pull request 'feat(skills): 同步冲突按内容与时间自动取较新(0.9.9)' (#2) from feat/skill-sync-auto-newer into main 2026-11-14 14:24:57 +08:00
newbie dbf39339c2 feat(skills): auto-resolve sync conflicts by content and newer timestamp (0.9.9)
Same-name skills no longer always stop for a human: identical bytes adopt the delivery marker in place, differing bytes compare local file mtime with the center updated_at and the newer side wins (cloud overwrite backs the local folder up first). Equal or missing timestamps, unsupported upload layouts and script-review flags still surface as per-item conflicts, so there is no batch action.
2026-11-14 14:24:36 +08:00
newbie 881f822c69 refactor(mcp): skeleton connection rows with details toggle, collapse the two heavy sections (0.9.8) 2026-11-13 11:50:17 +08:00
newbie d9339a9094 feat(skills,mcp): searchable import panel with batch import; compact MCP toolbar with contextual batch actions (0.9.7) 2026-11-13 11:33:27 +08:00
newbie f64d96f5e4 feat(mcp): drop the embedded MCP marketplace panel (host catalog answers 405) (0.9.6) 2026-11-13 11:17:38 +08:00
20 changed files with 1930 additions and 321 deletions

View File

@ -125,17 +125,20 @@ v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被 端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
别人先改过就报冲突、不强行覆盖。 别人先改过就报冲突、不强行覆盖。
防事故的规矩:云端交付的技能从不回传,本地改动它只报 防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会 不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占, 先备份本地再覆盖,本地文件 mtime 更新就发布新修订;只有时间相同或缺
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`, 失时才报冲突(`locally_modified` / `name_collision` / `cloud_newer`),
等面板里逐项确认。本地删除不删云端,且同版本不会被重新拉回(云端出
了新版才会再下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用
云端」批量处理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有 `SKILL.md`,
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单, 其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报 单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
`unsupported_layout`,不会为了迁就而裁剪文件。 `unsupported_layout`,不会为了迁就而裁剪文件。
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通 验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、 下行安装、上行发布与修订、按时间自动上行/下行、内容一致自动认领、
布局拒绝、删除不传播全流程)。 同名同时间保留冲突、脚本待审、布局拒绝、删除不传播全流程)。
## 技能管理(内置) ## 技能管理(内置)
@ -219,7 +222,7 @@ pnpm publish --access public --no-git-checks
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。 - 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。 - **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。 - **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
- **同步冲突(P3)**:`sync/status|run|resolve` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。 - **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 / 全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。 - **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。 接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。

View File

@ -305,8 +305,8 @@ window.__ModuleLoader__.load({
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
gap: '4px', gap: '4px',
flex: '1 1 220px', flex: '1 1 auto',
minWidth: 0, minWidth: '220px',
}, },
label: { label: {
fontSize: '12px', fontSize: '12px',
@ -392,6 +392,8 @@ window.__ModuleLoader__.load({
border: '1px solid rgba(127,127,127,0.35)', border: '1px solid rgba(127,127,127,0.35)',
fontSize: '12px', fontSize: '12px',
maxWidth: '100%', maxWidth: '100%',
whiteSpace: 'nowrap',
flex: '0 0 auto',
}, },
table: { table: {
width: '100%', width: '100%',
@ -913,7 +915,7 @@ window.__ModuleLoader__.load({
// ---- P3: interactive sync conflict resolution ------------------------- // ---- P3: interactive sync conflict resolution -------------------------
function SyncResolveSection(props) { function SyncResolveSection(props) {
var tuple = React.useState({ status: 'idle', data: null, busy: '', error: null, notice: null }) var tuple = React.useState({ status: 'idle', data: null, busy: '', error: null, notice: null, pendingAll: null })
var state = tuple[0] var state = tuple[0]
var setState = tuple[1] var setState = tuple[1]
function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) } function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) }
@ -942,6 +944,19 @@ window.__ModuleLoader__.load({
else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '同步失败') } }) else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '同步失败') } })
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) }) }, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
} }
function resolveAll(action) {
if (conflicts.length === 0) { patch({ pendingAll: null }); return }
patch({ busy: 'all:' + action, notice: null })
postJson(API.sync + '/resolve-all', { action: action }).then(function (res) {
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
var resolved = Array.isArray(res.body.resolved) ? res.body.resolved : []
var failed = Array.isArray(res.body.failed) ? res.body.failed : []
var text = '批量处理完成:成功 ' + resolved.length + ' 项' + (failed.length === 0 ? '。' : ',失败 ' + failed.length + ' 项(' + failed.map(function (item) { return item.name + ':' + item.error }).join('、') + ')。')
patch({ busy: '', pendingAll: null, data: { stats: res.body.stats, conflicts: res.body.conflicts || [] }, notice: { tone: failed.length === 0 ? 'ok' : 'warn', text: text } })
if (typeof props.onResolved === 'function') props.onResolved()
} else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '批量处理冲突失败') } })
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
}
var data = state.data var data = state.data
var stats = data === null || data === undefined ? null : data.stats var stats = data === null || data === undefined ? null : data.stats
var conflicts = data === null || data === undefined || !Array.isArray(data.conflicts) ? [] : data.conflicts var conflicts = data === null || data === undefined || !Array.isArray(data.conflicts) ? [] : data.conflicts
@ -972,89 +987,44 @@ window.__ModuleLoader__.load({
), ),
) )
}) })
return h(Section, { title: '云端同步与冲突', hint: '同步冲突不会被静默覆盖;逐项选择保留本地(上传为新版本)、采用云端(先备份本地)或手动合并。', aside: h(Btn, { label: state.busy === 'run' ? '同步中…' : '立即同步', variant: 'small', disabled: state.busy !== '', onClick: runNow }) }, var batchRow = null
if (conflicts.length > 0) {
batchRow = h('div', { style: styles.actions },
h(Btn, { label: '全部保留本地', variant: 'small', disabled: state.busy !== '' || !conflicts.some(function (item) { return item.canKeepLocal === true }), onClick: function () { patch({ pendingAll: 'keep_local', notice: null }) } }),
h(Btn, { label: '全部采用云端', variant: 'small', disabled: state.busy !== '' || !conflicts.some(function (item) { return item.canTakeCloud === true }), onClick: function () { patch({ pendingAll: 'take_cloud', notice: null }) } }),
)
}
var confirmAllRow = null
if (state.pendingAll !== null && conflicts.length > 0) {
var pendingText = state.pendingAll === 'keep_local' ? '把全部本地版本上传为新版本' : '用云端版本覆盖全部本地(覆盖前自动备份)'
confirmAllRow = h('div', { style: styles.nested },
h('p', { style: styles.hint }, '确认' + pendingText + '?共 ' + conflicts.length + ' 项。'),
h('div', { style: styles.actions },
h(Btn, { variant: 'primary', label: state.busy === 'all:keep_local' || state.busy === 'all:take_cloud' ? '处理中…' : '确认批量', disabled: state.busy !== '', onClick: function () { resolveAll(state.pendingAll) } }),
h(Btn, { variant: 'small', label: '取消', disabled: state.busy !== '', onClick: function () { patch({ pendingAll: null }) } }),
),
)
}
return h(Section, { title: '云端同步与冲突', hint: '同步先比内容与更新时间:一致直接认领,不同则自动采用较新的一边(覆盖云端前先备份本地);只有时间相同/缺失或目录结构不支持时才逐项询问,也可用批量按钮一次处理。', aside: h(Btn, { label: state.busy === 'run' ? '同步中…' : '立即同步', variant: 'small', disabled: state.busy !== '', onClick: runNow }) },
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
state.error === null ? null : h(Banner, { tone: 'bad' }, state.error), state.error === null ? null : h(Banner, { tone: 'bad' }, state.error),
state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text), state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text),
statPills, statPills,
batchRow,
confirmAllRow,
conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows), conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows),
), ),
) )
} }
// ---- P4: MCP market / custom connection / edit / scope / policy ------- // ---- P4: custom connection / edit / scope / policy ---------------------
function McpMarketSection(props) { // The MCP marketplace section was removed in 0.9.6: the host's `catalog`
var tuple = React.useState({ status: 'loading', items: [], keyword: '', busy: '', notice: null, credValue: '' }) // method answers 405 on current dsh-mcp-connector builds, so the card only
var s = tuple[0] // rendered an error banner. Discover/install stays in the host's own
var set = tuple[1] // plugin market instead of a broken embedded panel.
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
React.useEffect(function () { load() }, [])
function load() {
patch({ status: 'loading' })
bridgeCall('catalog', { keyword: s.keyword }).then(function (res) {
if (res.status === 200 && res.body !== null && res.body.ok === true) {
var items = res.body.detail !== undefined && Array.isArray(res.body.detail.items) ? res.body.detail.items : []
patch({ status: 'ready', items: items })
} else {
patch({ status: 'error', notice: { tone: 'bad', text: '读取 MCP 市场失败:' + bridgeMessage(res) } })
}
})
}
function connect(item) {
var credential = item.authMode === 'bearer' || item.authMode === 'api-key'
var method = credential ? 'configure' : 'connect'
var params = { connectorId: item.id }
if (credential) {
if (String(s.credValue).trim() === '') { patch({ notice: { tone: 'warn', text: '请先填写凭据。' } }); return }
if (item.authMode === 'api-key') params.apiKeyValue = String(s.credValue).trim()
else params.bearerToken = String(s.credValue).trim()
}
patch({ busy: item.id, notice: null })
bridgeCall(method, params).then(function (res) {
var ok = res.status === 200 && res.body !== null && res.body.ok === true
patch({ busy: '', notice: ok ? { tone: 'ok', text: (item.name || item.id) + ':' + bridgeMessage(res) } : { tone: 'bad', text: (item.name || item.id) + ':' + bridgeMessage(res) } })
if (typeof props.onChanged === 'function') props.onChanged()
})
}
var rows = s.items.map(function (item) {
var connected = Array.isArray(item.connected) ? item.connected.length : 0
var credential = item.authMode === 'bearer' || item.authMode === 'api-key'
return h('div', { key: item.id, style: styles.row },
h('div', { style: styles.rowHead },
h('span', { style: styles.rowTitle }, String(item.name || item.id)),
h('div', { style: styles.pills },
h(Pill, { label: '分类', value: String(item.category || '—'), tone: 'muted' }),
h(Pill, { label: '鉴权', value: String(item.authMode || 'none'), tone: 'muted' }),
connected > 0 ? h(Pill, { label: '已连接', value: connected, tone: 'ok' }) : null,
h(Pill, { label: '状态', value: String(item.connectionLabel || item.connectionState || '未连接'), tone: connected > 0 ? 'ok' : 'muted' }),
),
),
h('p', { style: styles.hint }, String(item.summary || item.description || '')),
credential
? h('div', { style: { display: 'flex', gap: '8px', alignItems: 'flex-end', flexWrap: 'wrap', marginTop: '6px' } },
h('div', { style: { flex: '1 1 200px', minWidth: 0 } }, h(Field, { label: '凭据(' + String(item.authMode) + ',只保存到宿主)', type: 'password', value: s.credValue, placeholder: String(item.credentialPlaceholder || '填入 ' + String(item.authMode) + ' 凭据'), onChange: function (value) { patch({ credValue: value }) } })),
h(Btn, { variant: 'primary', label: s.busy === item.id ? '连接中…' : '配置并连接', disabled: s.busy !== '', onClick: function () { connect(item) } }),
)
: h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: s.busy === item.id ? '连接中…' : (String(item.authMode) === 'oauth2-pkce' ? '授权并连接(浏览器)' : '连接'), disabled: s.busy !== '', onClick: function () { connect(item) } })),
)
})
return h(Section, {
title: 'MCP 市场',
hint: '目录来自宿主 dsh-mcp-connector 的公开接口;条目、示例与远端文本均为不可信内容。凭据只写宿主,本卡不回显。',
aside: h(Btn, { label: '刷新目录', variant: 'small', disabled: s.busy !== '', onClick: load }),
},
h('div', { style: { display: 'flex', gap: '8px', alignItems: 'flex-end', flexWrap: 'wrap' } },
h('div', { style: { flex: '1 1 220px', minWidth: 0 } }, h(Field, { label: '搜索目录', value: s.keyword, placeholder: '关键词 / 分类', onChange: function (value) { patch({ keyword: value }) } })),
h(Btn, { label: '搜索', disabled: s.status === 'loading', onClick: load }),
),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
s.status === 'loading' ? h('p', { style: styles.hint }, '正在读取目录…') : null,
s.status === 'ready' && s.items.length === 0 ? h('p', { style: styles.hint }, '目录没有匹配条目。') : null,
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, rows),
)
}
function McpCustomSection(props) { function McpCustomSection(props) {
var open = React.useState(false)
var tuple = React.useState({ transport: 'streamable-http', name: '', serverName: '', url: '', command: '', args: '', cwd: '', authMode: 'none', bearerToken: '', apiKeyHeader: 'X-Api-Key', apiKeyValue: '', importJson: '', busy: '', notice: null }) var tuple = React.useState({ transport: 'streamable-http', name: '', serverName: '', url: '', command: '', args: '', cwd: '', authMode: 'none', bearerToken: '', apiKeyHeader: 'X-Api-Key', apiKeyValue: '', importJson: '', busy: '', notice: null })
var s = tuple[0] var s = tuple[0]
var set = tuple[1] var set = tuple[1]
@ -1089,8 +1059,17 @@ window.__ModuleLoader__.load({
if (ok && typeof props.onChanged === 'function') props.onChanged() if (ok && typeof props.onChanged === 'function') props.onChanged()
}) })
} }
return h(Section, { title: '新增 / 导入连接', hint: 'HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。' }, return h(Section, {
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, title: '新增 / 导入连接',
hint: 'HTTP 与 stdio 都由宿主校验并保存凭据;本卡不回显已有密钥。stdio 的启动命令由你显式填写,云端不会执行任何本机命令。',
aside: h(Btn, {
label: open[0] ? '收起' : '展开',
ariaLabel: '展开新增连接',
variant: 'small',
onClick: function () { open[1](!open[0]) },
}),
},
open[0] ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
h('div', { style: styles.grid }, h('div', { style: styles.grid },
h(Field, { label: '名称', value: s.name, onChange: function (v) { patch({ name: v }) } }), h(Field, { label: '名称', value: s.name, onChange: function (v) { patch({ name: v }) } }),
h(Field, { label: 'Server 名(可选)', value: s.serverName, onChange: function (v) { patch({ serverName: v }) } }), h(Field, { label: 'Server 名(可选)', value: s.serverName, onChange: function (v) { patch({ serverName: v }) } }),
@ -1129,12 +1108,13 @@ window.__ModuleLoader__.load({
h('textarea', { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { fontFamily: 'monospace', resize: 'vertical' }), placeholder: '{"mcpServers":{"name":{"url":"…"}}}', onChange: function (e) { patch({ importJson: e.target.value }) } }), h('textarea', { value: s.importJson, rows: 5, style: Object.assign({}, styles.input, { fontFamily: 'monospace', resize: 'vertical' }), placeholder: '{"mcpServers":{"name":{"url":"…"}}}', onChange: function (e) { patch({ importJson: e.target.value }) } }),
h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'import' ? '导入中…' : '导入 JSON', disabled: s.busy !== '', onClick: importJson })), h('div', { style: styles.actions }, h(Btn, { label: s.busy === 'import' ? '导入中…' : '导入 JSON', disabled: s.busy !== '', onClick: importJson })),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
), ) : null,
) )
} }
function McpConfigSection(props) { function McpConfigSection(props) {
var items = Array.isArray(props.items) ? props.items : [] var items = Array.isArray(props.items) ? props.items : []
var open = React.useState(false)
var tuple = React.useState({ key: '', json: '', busy: '', notice: null, scopePreview: null, targetScope: 'global', workspaceId: '', gov: null, policyPreview: null }) var tuple = React.useState({ key: '', json: '', busy: '', notice: null, scopePreview: null, targetScope: 'global', workspaceId: '', gov: null, policyPreview: null })
var s = tuple[0] var s = tuple[0]
var set = tuple[1] var set = tuple[1]
@ -1203,8 +1183,17 @@ window.__ModuleLoader__.load({
}) })
} }
var gov = s.gov var gov = s.gov
return h(Section, { title: '连接配置、范围与治理', hint: '配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。' }, return h(Section, {
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } }, title: '连接配置、范围与治理',
hint: '配置编辑使用宿主的保留标记合并,空输入不会清空已有密钥;作用域与策略都带 revision 预览后再提交。',
aside: h(Btn, {
label: open[0] ? '收起' : '展开',
ariaLabel: '展开连接配置',
variant: 'small',
onClick: function () { open[1](!open[0]) },
}),
},
open[0] ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
itemSelect(items, s.key, choose), itemSelect(items, s.key, choose),
s.key === '' ? h('p', { style: styles.hint }, '选择一条连接后可编辑配置、调整范围或设置治理策略。') : h('div', { style: styles.nested }, s.key === '' ? h('p', { style: styles.hint }, '选择一条连接后可编辑配置、调整范围或设置治理策略。') : h('div', { style: styles.nested },
h('p', { style: styles.hint }, '可编辑配置(保留标记 <KEEP_EXISTING> 表示保留原密钥):'), h('p', { style: styles.hint }, '可编辑配置(保留标记 <KEEP_EXISTING> 表示保留原密钥):'),
@ -1240,7 +1229,7 @@ window.__ModuleLoader__.load({
), ),
), ),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
), ) : null,
) )
} }
@ -1257,7 +1246,7 @@ window.__ModuleLoader__.load({
// ---- import skills from other tools ------------------------------- // ---- import skills from other tools -------------------------------
function ImportSection(props) { function ImportSection(props) {
var onImported = props && typeof props.onImported === 'function' ? props.onImported : null var onImported = props && typeof props.onImported === 'function' ? props.onImported : null
var tuple = React.useState({ expanded: false, status: 'idle', sources: [], open: {}, busy: '', notice: null, imported: {} }) var tuple = React.useState({ expanded: false, status: 'idle', sources: [], open: {}, busy: '', notice: null, imported: {}, search: '', selection: [], progress: null })
var s = tuple[0] var s = tuple[0]
var set = tuple[1] var set = tuple[1]
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) } function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
@ -1290,19 +1279,97 @@ window.__ModuleLoader__.load({
} }
function toggleSource(sourceId) { function toggleSource(sourceId) {
var next = Object.assign({}, s.open) var next = Object.assign({}, s.open)
next[sourceId] = next[sourceId] !== true var open = s.open[sourceId] !== false
next[sourceId] = !open
patch({ open: next }) patch({ open: next })
} }
function doImport(source, skill) { var mine = dshFolders()
patch({ busy: source.id + ':' + skill.folder }) var others = s.sources.filter(function (source) { return !source.writable })
postJson(API.skills + '/import', { sourceId: source.id, folder: skill.folder }).then(function (res) { var needle = String(s.search).trim().toLowerCase()
function skillsOf(source) {
var list = []
var groups = source.groups || []
groups.forEach(function (group) {
var items = group.skills || []
items.forEach(function (skill) { list.push(skill) })
})
return list
}
function importedYet(skill) {
return mine[skill.folder] === true || s.imported[skill.folder] === true
}
var candidates = []
others.forEach(function (source) {
if (!source.exists) return
skillsOf(source).forEach(function (skill) {
candidates.push({ source: source, skill: skill })
})
})
var matches = needle === '' ? candidates : candidates.filter(function (entry) {
var hay = String(entry.skill.name || '') + ' ' + String(entry.skill.folder || '') + ' ' + String(entry.skill.description || '')
return hay.toLowerCase().indexOf(needle) >= 0
})
var importable = matches.filter(function (entry) { return !importedYet(entry.skill) })
var alreadyCount = candidates.length - candidates.filter(function (entry) { return !importedYet(entry.skill) }).length
function keyOf(entry) {
return String(entry.source.id) + ':' + String(entry.skill.folder)
}
var chosen = s.selection
function isChosen(entry) {
return chosen.indexOf(keyOf(entry)) >= 0
}
function chooseMany(list, on) {
var next = chosen.slice()
list.forEach(function (entry) {
var key = keyOf(entry)
var at = next.indexOf(key)
if (on === true && at < 0) next.push(key)
if (on !== true && at >= 0) next.splice(at, 1)
})
patch({ selection: next })
}
var chosenEntries = candidates.filter(function (entry) {
return chosen.indexOf(keyOf(entry)) >= 0 && !importedYet(entry.skill)
})
function importSelected() {
var targets = chosenEntries
if (targets.length === 0) return Promise.resolve()
patch({ busy: 'batch', notice: null, progress: { done: 0, total: targets.length } })
var done = 0
var failures = []
var importedMap = Object.assign({}, s.imported)
var chain = Promise.resolve()
targets.forEach(function (entry) {
chain = chain.then(function () {
return postJson(API.skills + '/import', { sourceId: entry.source.id, folder: entry.skill.folder }).then(
function (res) {
if (res.body !== null && res.body !== undefined && res.body.ok === true) { if (res.body !== null && res.body !== undefined && res.body.ok === true) {
var imported = Object.assign({}, s.imported) done += 1
imported[skill.folder] = true importedMap[entry.skill.folder] = true
patch({ busy: '', imported: imported, notice: { tone: 'ok', text: '已导入「' + skill.name + '」到 DSH,技能文件夹里就能看到。' } }) } else failures.push(String(entry.skill.name) + '(' + bodyError(res, '失败') + ')')
patch({ progress: { done: done + failures.length, total: targets.length } })
},
function (error) {
failures.push(String(entry.skill.name) + '(' + messageOf(error) + ')')
patch({ progress: { done: done + failures.length, total: targets.length } })
},
)
})
})
return chain.then(function () {
patch({
busy: '',
progress: null,
selection: [],
imported: importedMap,
notice: {
tone: failures.length === 0 ? 'ok' : 'warn',
text: '已导入 ' + String(done) + ' / ' + String(targets.length) + ' 个技能到 DSH' + (failures.length === 0 ? '。' : ';失败:' + failures.join('、')),
},
})
if (onImported !== null) onImported() if (onImported !== null) onImported()
} else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '导入失败') } }) load()
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) }) })
} }
if (!s.expanded) { if (!s.expanded) {
return h( return h(
@ -1316,40 +1383,73 @@ window.__ModuleLoader__.load({
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
) )
} }
var mine = dshFolders() function describe(skill) {
var others = s.sources.filter(function (source) { return !source.writable }) var text = String(skill.description === undefined || skill.description === null ? '' : skill.description).trim()
var rows = others.map(function (source) { if (/^[>|][+-]?$/.test(text)) return ''
var skills = [] return text
var groups = source.groups || [] }
groups.forEach(function (group) { var blocks = others.map(function (source) {
var list = group.skills || [] var all = skillsOf(source)
list.forEach(function (skill) { skills.push(skill) }) var visible = matches.filter(function (entry) { return entry.source.id === source.id })
}) var open = s.open[source.id] !== false
var open = s.open[source.id] === true var selectable = visible.filter(function (entry) { return !importedYet(entry.skill) })
return h('div', { key: source.id, style: styles.row }, return h('div', { key: source.id, style: styles.row },
h('div', { style: styles.rowHead }, h('div', { style: styles.rowHead },
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } }, h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } },
h('span', { style: styles.sourceGlyph }, source.label.slice(0, 1)), h('span', { style: styles.sourceGlyph }, String(source.label).slice(0, 1)),
h('span', { style: styles.sourceTitle }, source.label), h('span', { style: styles.sourceTitle }, String(source.label)),
h('span', { style: styles.hint }, source.exists ? skills.length + ' 个技能' : '未安装'), h(
'span',
{ style: styles.hint },
source.exists
? String(all.length) + ' 个技能' + (needle === '' ? '' : ' · 匹配 ' + String(visible.length)) + ' · 可导入 ' + String(selectable.length)
: '未安装',
), ),
source.exists ? h(Btn, { label: open ? '收起' : '展开', variant: 'small', onClick: function () { toggleSource(source.id) } }) : null,
), ),
h('span', { style: styles.mono }, source.root), source.exists
!source.exists || !open ? null : skills.length === 0 ? h('div', { style: styles.actions },
? h('p', { style: styles.hint }, '这个来源里还没有技能。') h(Btn, {
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: '2px' } }, skills.map(function (skill) { label: '全选本来源(' + String(selectable.length) + ')',
var has = mine[skill.folder] === true || s.imported[skill.folder] === true ariaLabel: '全选本来源 ' + String(source.label),
return h('div', { key: skill.folder, style: styles.skillRow }, variant: 'small',
h('span', { style: { minWidth: 0 } }, disabled: selectable.length === 0 || s.busy !== '',
h('span', { style: styles.rowTitle }, skill.name), onClick: function () { chooseMany(visible, true) },
skill.description ? h('span', { style: Object.assign({}, styles.hint, { display: 'block' }) }, skill.description) : null, }),
), h(Btn, { label: open ? '收起' : '展开', variant: 'small', onClick: function () { toggleSource(source.id) } }),
has
? h(Pill, { label: 'DSH', value: '已导入', tone: 'muted' })
: h(Btn, { label: s.busy === source.id + ':' + skill.folder ? '导入中…' : '导入', variant: 'small', disabled: s.busy !== '', onClick: function () { doImport(source, skill) } }),
) )
})), : null,
),
h('span', { style: styles.mono }, String(source.root)),
!source.exists || !open
? null
: visible.length === 0
? h('p', { style: styles.hint }, needle === '' ? '这个来源里还没有技能。' : '没有匹配「' + s.search + '」的技能。')
: h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '2px', maxHeight: '320px', overflow: 'auto' } },
visible.map(function (entry) {
var skill = entry.skill
var has = importedYet(skill)
return h(
'label',
{ key: String(skill.folder), style: styles.checkboxRow },
h('input', {
type: 'checkbox',
checked: has || isChosen(entry),
disabled: has || s.busy !== '',
'aria-label': '选择技能 ' + String(skill.name),
onChange: function (event) { chooseMany([entry], event.target.checked === true) },
}),
h(
'span',
{ style: { minWidth: 0, flex: '1 1 auto' } },
h('span', { style: styles.rowTitle }, String(skill.name)),
describe(skill) === '' ? null : h('span', { style: Object.assign({}, styles.hint, styles.clamp1) }, describe(skill)),
),
has ? h(Pill, { label: 'DSH', value: '已导入', tone: 'muted' }) : null,
)
}),
),
) )
}) })
return h( return h(
@ -1366,7 +1466,72 @@ window.__ModuleLoader__.load({
}, },
s.status === 'loading' ? h('p', { style: styles.hint }, '正在读取来源…') s.status === 'loading' ? h('p', { style: styles.hint }, '正在读取来源…')
: others.length === 0 ? h('p', { style: styles.hint }, '没有检测到其他软件的技能目录。') : others.length === 0 ? h('p', { style: styles.hint }, '没有检测到其他软件的技能目录。')
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, rows), : h(
'div',
{ style: styles.root },
h(
'div',
{ style: styles.pills },
h(Pill, { label: '来源', value: String(others.length), tone: 'muted' }),
h(Pill, { label: '可导入', value: String(candidates.length - alreadyCount), tone: 'muted' }),
s.search === '' ? null : h(Pill, { label: '匹配', value: String(matches.length), tone: matches.length === 0 ? 'muted' : 'ok' }),
h(Pill, { label: '已选', value: String(chosenEntries.length), tone: chosenEntries.length === 0 ? 'muted' : 'ok' }),
alreadyCount === 0 ? null : h(Pill, { label: '已在 DSH', value: String(alreadyCount), tone: 'muted' }),
),
h(
'div',
{ style: { display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' } },
h('input', {
type: 'search',
style: Object.assign({}, styles.input, { flex: '1 1 220px', minWidth: 0 }),
value: s.search,
placeholder: '搜索技能:名称 / 目录 / 描述',
'aria-label': '搜索要导入的技能',
onChange: function (event) { patch({ search: event.target.value }) },
}),
s.search === '' ? null : h(Btn, {
label: '清空搜索',
variant: 'small',
onClick: function () { patch({ search: '' }) },
}),
),
h(
'div',
{ style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) },
h(Btn, {
label: '全选匹配可导入(' + String(importable.length) + ')',
ariaLabel: '全选匹配可导入',
variant: 'small',
disabled: importable.length === 0 || s.busy !== '',
onClick: function () { chooseMany(importable, true) },
}),
h(Btn, {
label: '全选全部(' + String(candidates.length - alreadyCount) + ')',
ariaLabel: '全选全部',
variant: 'small',
disabled: candidates.length - alreadyCount === 0 || s.busy !== '',
onClick: function () {
chooseMany(candidates.filter(function (entry) { return !importedYet(entry.skill) }), true)
},
}),
h(Btn, {
label: '清空已选',
ariaLabel: '清空已选',
variant: 'small',
disabled: chosenEntries.length === 0,
onClick: function () { patch({ selection: [] }) },
}),
h(Btn, {
variant: 'primary',
label: s.busy === 'batch' ? '导入中…' : '导入所选(' + String(chosenEntries.length) + ')',
ariaLabel: '导入所选',
disabled: s.busy !== '' || chosenEntries.length === 0,
onClick: importSelected,
}),
),
s.progress === null ? null : h('p', { style: styles.hint }, '正在导入:' + String(s.progress.done) + ' / ' + String(s.progress.total)),
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } }, blocks),
),
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
) )
} }
@ -1424,7 +1589,7 @@ window.__ModuleLoader__.load({
var skills = skillsState[0] var skills = skillsState[0]
var setSkills = skillsState[1] var setSkills = skillsState[1]
var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null, search: '', filter: 'all', selection: [], bulk: null, confirmBulk: false }) var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null, search: '', filter: 'all', selection: [], bulk: null, confirmBulk: false, details: {} })
var mcp = mcpState[0] var mcp = mcpState[0]
var setMcp = mcpState[1] var setMcp = mcpState[1]
@ -3165,6 +3330,7 @@ window.__ModuleLoader__.load({
{ style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) }, { style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) },
h(Btn, { h(Btn, {
label: '全选匹配结果(' + String(visibleItems.length) + ')', label: '全选匹配结果(' + String(visibleItems.length) + ')',
ariaLabel: '全选匹配结果',
variant: 'small', variant: 'small',
disabled: visibleItems.length === 0, disabled: visibleItems.length === 0,
onClick: function () { onClick: function () {
@ -3173,6 +3339,7 @@ window.__ModuleLoader__.load({
}), }),
h(Btn, { h(Btn, {
label: '全选全部(' + String(items.length) + ')', label: '全选全部(' + String(items.length) + ')',
ariaLabel: '全选全部',
variant: 'small', variant: 'small',
disabled: items.length === 0 || mcpChosen.length === items.length, disabled: items.length === 0 || mcpChosen.length === items.length,
onClick: function () { onClick: function () {
@ -3181,6 +3348,7 @@ window.__ModuleLoader__.load({
}), }),
h(Btn, { h(Btn, {
label: '取消勾选匹配项(' + String(matchedSelected) + ')', label: '取消勾选匹配项(' + String(matchedSelected) + ')',
ariaLabel: '取消勾选匹配项',
variant: 'small', variant: 'small',
disabled: matchedSelected === 0, disabled: matchedSelected === 0,
onClick: function () { onClick: function () {
@ -3189,6 +3357,7 @@ window.__ModuleLoader__.load({
}), }),
h(Btn, { h(Btn, {
label: '清空已选', label: '清空已选',
ariaLabel: '清空已选',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0, disabled: mcpChosen.length === 0,
onClick: function () { onClick: function () {
@ -3196,65 +3365,77 @@ window.__ModuleLoader__.load({
}, },
}), }),
), ),
h( mcpChosen.length === 0
? h('p', { style: styles.hint }, '勾选左侧连接后,这里会出现批量健康检查、启停、重连与移除。')
: h(
'div', 'div',
{ style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) }, { style: Object.assign({}, styles.actions, { flexWrap: 'wrap' }) },
h('span', { style: styles.hint }, '批量操作(已选 ' + String(mcpChosen.length) + '):'),
h(Btn, { h(Btn, {
label: '批量健康检查', label: '健康检查',
ariaLabel: '批量健康检查',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
runMcpBulk('批量健康检查', 'healthCheck', function (item) { return { connectorId: item.connectorId } }) runMcpBulk('批量健康检查', 'healthCheck', function (item) { return { connectorId: item.connectorId } })
}, },
}), }),
h(Btn, { h(Btn, {
label: '批量启用', label: '启用',
ariaLabel: '批量启用',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
runMcpBulk('批量启用', 'setEnabled', function (item) { return { key: item.key, enabled: true } }) runMcpBulk('批量启用', 'setEnabled', function (item) { return { key: item.key, enabled: true } })
}, },
}), }),
h(Btn, { h(Btn, {
label: '批量停用', label: '停用',
ariaLabel: '批量停用',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
runMcpBulk('批量停用', 'setEnabled', function (item) { return { key: item.key, enabled: false } }) runMcpBulk('批量停用', 'setEnabled', function (item) { return { key: item.key, enabled: false } })
}, },
}), }),
h(Btn, { h(Btn, {
label: '批量重连', label: '重连',
ariaLabel: '批量重连',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
runMcpBulk('批量重连', 'reconnect', function (item) { return { key: item.key } }) runMcpBulk('批量重连', 'reconnect', function (item) { return { key: item.key } })
}, },
}), }),
mcp.confirmBulk === true mcp.confirmBulk === true
? h(Btn, { ? h(Btn, {
label: '确认批量移除(' + String(mcpChosen.length) + ')', label: '确认移除(' + String(mcpChosen.length) + ')',
ariaLabel: '确认批量移除',
variant: 'danger', variant: 'danger',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
runMcpBulk('批量移除', 'disconnect', function (item) { return { key: item.key } }) runMcpBulk('批量移除', 'disconnect', function (item) { return { key: item.key } })
}, },
}) })
: h(Btn, { : h(Btn, {
label: '批量移除…', label: '移除…',
ariaLabel: '批量移除',
variant: 'small', variant: 'small',
disabled: mcpChosen.length === 0 || mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
patchMcp({ confirmBulk: true }) patchMcp({ confirmBulk: true })
setNotice({ tone: 'warn', text: '批量移除会断开所选 ' + String(mcpChosen.length) + ' 条连接定义;再点一次「确认批量移除」才执行。' }) setNotice({ tone: 'warn', text: '批量移除会断开所选 ' + String(mcpChosen.length) + ' 条连接定义;再点一次「确认移除」才执行。' })
}, },
}), }),
), ),
mcpBulk === null ? null : h('p', { style: styles.hint }, String(mcpBulk.label) + ' 进行中:' + String(mcpBulk.done) + ' / ' + String(mcpBulk.total)), mcpBulk === null ? null : h('p', { style: styles.hint }, String(mcpBulk.label) + ' 进行中:' + String(mcpBulk.done) + ' / ' + String(mcpBulk.total)),
visibleItems.length === 0 ? h('p', { style: styles.hint }, '没有匹配「' + mcpSearch + '」的连接。换个关键词或切回「全部」筛选。') : null, visibleItems.length === 0 ? h('p', { style: styles.hint }, '没有匹配「' + mcpSearch + '」的连接。换个关键词或切回「全部」筛选。') : null,
visibleItems.map(function (item) { visibleItems.map(function (item) {
var state = String(item.connectionState === undefined ? 'unknown' : item.connectionState) var state = stateOf(item)
var tools = mcp.tools[item.key] var tools = mcp.tools[item.key]
var details = mcp.details === null || mcp.details === undefined ? {} : mcp.details
var open = details[item.key] === true
var label = String(item.name === undefined ? item.key : item.name)
return h( return h(
'div', 'div',
{ key: String(item.key), style: styles.row }, { key: String(item.key), style: styles.row },
@ -3263,46 +3444,60 @@ window.__ModuleLoader__.load({
{ style: styles.rowHead }, { style: styles.rowHead },
h( h(
'label', 'label',
{ style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } }, { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0, flex: '1 1 auto' } },
h('input', { h('input', {
type: 'checkbox', type: 'checkbox',
checked: mcpChosen.indexOf(item.key) >= 0, checked: mcpChosen.indexOf(item.key) >= 0,
'aria-label': '选择连接 ' + String(item.name === undefined ? item.key : item.name), 'aria-label': '选择连接 ' + label,
onChange: function (event) { onChange: function (event) {
selectMcpMany([item], event.target.checked === true) selectMcpMany([item], event.target.checked === true)
}, },
}), }),
h('span', { style: styles.rowTitle }, String(item.name === undefined ? item.key : item.name)), h('span', { style: styles.rowTitle }, label),
h(Pill, { label: '状态', value: MCP_STATE_LABELS[state] === undefined ? state : MCP_STATE_LABELS[state], tone: state === 'connected' ? 'ok' : state === 'disabled' ? 'muted' : 'warn' }),
h(Pill, { label: '传输', value: String(item.transport === undefined ? '—' : item.transport), tone: 'muted' }),
), ),
h(Btn, {
label: open ? '收起' : '详情',
ariaLabel: (open ? '收起详情 ' : '详情 ') + label,
variant: 'small',
onClick: function () {
patchMcp({ details: Object.assign({}, details, { [String(item.key)]: !open }) })
},
}),
),
open
? h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
h( h(
'div', 'div',
{ style: styles.pills }, { style: styles.pills },
h(Pill, { label: '状态', value: MCP_STATE_LABELS[state] === undefined ? state : MCP_STATE_LABELS[state], tone: state === 'connected' ? 'ok' : state === 'disabled' ? 'muted' : 'warn' }),
h(Pill, { label: '传输', value: String(item.transport === undefined ? '—' : item.transport), tone: 'muted' }),
h(Pill, { label: '鉴权', value: String(item.authMode === undefined ? 'none' : item.authMode), tone: 'muted' }), h(Pill, { label: '鉴权', value: String(item.authMode === undefined ? 'none' : item.authMode), tone: 'muted' }),
h(Pill, { label: '注入', value: String(item.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }), h(Pill, { label: '注入', value: String(item.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }),
h(Pill, { label: '范围', value: item.scope === undefined || item.scope === null ? '未知' : String(item.scope.visibility === undefined ? JSON.stringify(item.scope) : item.scope.visibility), tone: 'muted' }),
h(Pill, { label: '健康检查', value: formatIso(item.healthCheckedAt), tone: 'muted' }),
), ),
), item.lastError === null || item.lastError === undefined
h( ? null
'p', : h('p', { style: styles.hint }, '最近错误:' + String(item.lastError)),
{ style: styles.hint },
'范围:' + (item.scope === undefined || item.scope === null ? '未知' : String(item.scope.visibility === undefined ? JSON.stringify(item.scope) : item.scope.visibility)) + ' · 健康检查:' + formatIso(item.healthCheckedAt) + (item.lastError === null || item.lastError === undefined ? '' : ' · 最近错误:' + String(item.lastError)),
),
h( h(
'div', 'div',
{ style: styles.actions }, { style: styles.actions },
h(Btn, { h(Btn, {
label: '健康检查', label: '健康检查',
ariaLabel: '健康检查 ' + label,
variant: 'small', variant: 'small',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
mcpAction('健康检查 ' + String(item.name), 'healthCheck', { connectorId: item.connectorId }).then(function () { mcpAction('健康检查 ' + label, 'healthCheck', { connectorId: item.connectorId }).then(function () {
probeMcp() probeMcp()
}) })
}, },
}), }),
h(Btn, { h(Btn, {
label: '工具列表', label: '工具列表',
ariaLabel: '工具列表 ' + label,
variant: 'small', variant: 'small',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
@ -3311,6 +3506,7 @@ window.__ModuleLoader__.load({
}), }),
h(Btn, { h(Btn, {
label: item.enabled === false ? '启用' : '停用', label: item.enabled === false ? '启用' : '停用',
ariaLabel: '启停 ' + label,
variant: 'small', variant: 'small',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
@ -3321,6 +3517,7 @@ window.__ModuleLoader__.load({
}), }),
h(Btn, { h(Btn, {
label: '重连', label: '重连',
ariaLabel: '重连 ' + label,
variant: 'small', variant: 'small',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
@ -3332,6 +3529,7 @@ window.__ModuleLoader__.load({
mcp.confirm === item.key mcp.confirm === item.key
? h(Btn, { ? h(Btn, {
label: '确认移除', label: '确认移除',
ariaLabel: '确认移除 ' + label,
variant: 'danger', variant: 'danger',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
@ -3343,6 +3541,7 @@ window.__ModuleLoader__.load({
}) })
: h(Btn, { : h(Btn, {
label: '移除连接…', label: '移除连接…',
ariaLabel: '移除连接 ' + label,
variant: 'small', variant: 'small',
disabled: mcp.busy !== '', disabled: mcp.busy !== '',
onClick: function () { onClick: function () {
@ -3353,11 +3552,9 @@ window.__ModuleLoader__.load({
), ),
tools === undefined tools === undefined
? null ? null
: h( : h('p', { style: styles.hint }, '工具缓存(' + formatTime(tools.at) + '):' + (tools.items.length === 0 ? '空' : tools.items.map(function (tool) { return String(tool.name === undefined ? tool : tool.name) }).join('、'))),
'div', )
{ style: styles.nested }, : null,
h('p', { style: styles.hint }, '工具缓存(' + formatTime(tools.at) + '):' + (tools.items.length === 0 ? '空' : tools.items.map(function (tool) { return String(tool.name === undefined ? tool : tool.name) }).join('、'))),
),
) )
}), }),
h('p', { style: styles.hint }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'), h('p', { style: styles.hint }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'),
@ -3365,7 +3562,6 @@ window.__ModuleLoader__.load({
: null, : null,
), ),
h(McpMarketSection, { onChanged: probeMcp }),
h(McpCustomSection, { onChanged: probeMcp }), h(McpCustomSection, { onChanged: probeMcp }),
h(McpConfigSection, { items: items, onChanged: probeMcp }), h(McpConfigSection, { items: items, onChanged: probeMcp }),
) )

View File

@ -74,7 +74,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。 - 技能市场:无经验证来源,`features.skillsMarketplace=false`。
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。 - 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
- 自动更新与版本回退:未实现(无来源清单与制品基线)。 - 自动更新与版本回退:未实现(无来源清单与制品基线)。
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。 - MCP 市场的内嵌浏览与安装:**0.9.6 起从卡片移除**(宿主 `catalog` 返回 405,只留错误条没有意义),目录浏览回到宿主插件市场。
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。 - 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。 - 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
@ -165,23 +165,24 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
### 6.3 同步冲突交互 ### 6.3 同步冲突交互
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置: `SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
| 方法 | 路径 | 说明 | | 方法 | 路径 | 说明 |
|---|---|---| |---|---|---|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 | | GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 | | POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` | | POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
| POST | `/cloud-memory/sync/resolve-all` | `{action}`:对当前全部冲突批量 `keep_local` / `take_cloud`,返回 `{resolved[], failed[{name,error}]}` |
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。 - `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。 - `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
- `manual`:只返回两侧信息,不改任何文件。 - `manual`:只返回两侧信息,不改任何文件。
### 6.4 验证 ### 6.4 验证
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。 - `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。 - `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。 - `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
## 7. P4:MCP 管理与市场(0.6.0) ## 7. P4:MCP 管理与市场(0.6.0)
@ -199,8 +200,8 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| 区块 | 能力 | | 区块 | 能力 |
|---|---| |---|---|
| 我的连接 | 读取连接(名称/传输/鉴权/启用/状态/注入方式/范围/健康时间/最近错误)、健康检查、工具缓存、启停、重连、两段式移除 | | 我的连接 | 默认一行骨架(名称 + 状态 + 传输 + 「详情」),展开后才显示鉴权/注入/范围/健康检查/最近错误与单条操作;上方有搜索、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除 |
| MCP 市场 | `catalog` 目录浏览与搜索;无认证直接 `connect`;OAuth 走浏览器授权 `connect`;bearer / api-key 通过 `configure` 填凭据(只写宿主,不回显) | | ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 |
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 | | 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 | | 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 | | 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
@ -236,7 +237,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
| `skills/install/plan` `install/commit` | `sync_running` | | `skills/install/plan` `install/commit` | `sync_running` |
| `skills/toggle` `skills/remove` | `sync_running` | | `skills/toggle` `skills/remove` | `sync_running` |
| `skills/update/apply` `skills/rollback` | `sync_running` | | `skills/update/apply` `skills/rollback` | `sync_running` |
| `sync/resolve` | `sync_running` | | `sync/resolve` `sync/resolve-all` | `sync_running` |
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。 HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。

View File

@ -26,7 +26,7 @@ export const name = 'dsh-brain';
/** Services required before `apply` runs. */ /** Services required before `apply` runs. */
export const inject = ['webServer']; export const inject = ['webServer'];
/** Version reported by the status card. */ /** Version reported by the status card. */
const VERSION = '0.9.5'; const VERSION = '0.9.10';
/** How often the skill directory is reconciled with the cloud center. */ /** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000; const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
/** How often queued reports are retried. */ /** How often queued reports are retried. */

View File

@ -17,7 +17,7 @@ import { descriptor } from "./descriptor.js";
import { LongMemoryProvider } from "./driver.js"; import { LongMemoryProvider } from "./driver.js";
export { LongMemoryProvider, descriptor }; export { LongMemoryProvider, descriptor };
/** Keep in sync with the package version (asserted by the verify script). */ /** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.9.5'; const PROVIDER_VERSION = '0.9.8';
export const definition = defineMemorySpaceProviderDefinition({ export const definition = defineMemorySpaceProviderDefinition({
manifest: { manifest: {
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION, apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,

View File

@ -749,6 +749,7 @@ async function serveMarket(deps, req, res) {
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
*/ */
async function serveSync(deps, req, res) { async function serveSync(deps, req, res) {
const sync = deps.sync; const sync = deps.sync;
@ -788,6 +789,18 @@ async function serveSync(deps, req, res) {
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }); json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
return; return;
} }
if (suffix === '/resolve-all') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const result = await sync.resolveConflicts(body.action);
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
return;
}
fail(res, 404, 'unknown-sync-route'); fail(res, 404, 'unknown-sync-route');
} }
catch (error) { catch (error) {

View File

@ -15,12 +15,14 @@
* revisions, guarded by the center's `expected_revision` check. * revisions, guarded by the center's `expected_revision` check.
* *
* Safety rules (deliberate, in order): * Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded. If its local files no * 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* longer match the delivery manifest, the skill is flagged as a * newer than the center's `updated_at`; before any cloud overwrite the
* conflict and left completely alone. * local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 2. A local deletion never deletes the cloud copy. * 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked; * 3. A same-name skill is never hijacked silently: byte-identical copies are
* it is reported as a conflict for a human to resolve. * adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed * 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the * until the change is acknowledged in the dashboard, mirroring the
* center's own review flag. * center's own review flag.
@ -59,6 +61,24 @@ export function linkedSkillManifest(files) {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort(); const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8')); return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
} }
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value) {
if (typeof value === 'number' && Number.isFinite(value))
return value < 1e12 ? value * 1000 : value;
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files) {
let newest = 0;
for (const file of files)
if (file.mtimeMs > newest)
newest = file.mtimeMs;
return newest;
}
/** True when the cloud center would accept this relative file path. */ /** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel) { export function isCloudSkillPath(rel) {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
@ -197,7 +217,10 @@ export class SkillSync {
await walk(rel); await walk(rel);
} }
else if (entry.isFile()) { else if (entry.isFile()) {
out.push({ rel, buffer: await readFile(join(dir, rel)) }); const absolute = join(dir, rel);
const buffer = await readFile(absolute);
const info = await stat(absolute);
out.push({ rel, buffer, mtimeMs: info.mtimeMs });
} }
} }
}; };
@ -263,6 +286,145 @@ export class SkillSync {
} }
return undefined; return undefined;
} }
/** Center's last-change time for one listed skill (ISO string or epoch). */
cloudUpdatedAt(item) {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at);
}
/** Manifest over every local file, including files the center would reject. */
localManifest(files) {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })));
}
/** Copy a local skill aside before an automatic cloud overwrite. */
async backupLocal(dir, name) {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') });
return backup;
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
async adoptIdenticalDelivery(home, item, files) {
const delivery = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
};
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2));
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
async autoTakeCloud(item, home, installRoot, state, stats, client) {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
const bundle = await client.skillBundle(item.name);
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`);
return 'conflict';
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch');
return 'conflict';
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
await this.backupLocal(home, item.name);
await this.install(item, bundle.data, installRoot);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
delete state.removed[item.name];
stats.updated.push(item.name);
return 'resolved';
}
/** Upload the locally-newer copy as the next cloud revision. */
async autoUploadLocal(skill, folder, dir, cloud, state, stats, client) {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
});
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`;
this.conflict(stats, skill.name, reason);
return 'conflict';
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
delete state.removed[skill.name];
stats.updated.push(skill.name);
return 'resolved';
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
async autoResolveCollision(item, home, installRoot, state, stats, client) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (!localFiles.some((file) => file.rel === 'SKILL.md'))
return 'unresolved';
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
async autoResolveLocalDrift(item, home, state, stats, client, installRoot) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client);
}
/** One full pass; never throws — outcomes land in the stats. */ /** One full pass; never throws — outcomes land in the stats. */
async syncOnce() { async syncOnce() {
if (this.running) if (this.running)
@ -366,6 +528,11 @@ export class SkillSync {
if (exists && delivery !== undefined) { if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download. // Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) { if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'locally_modified'); this.conflict(stats, item.name, 'locally_modified');
continue; continue;
} }
@ -380,6 +547,14 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update. // Intact but the cloud moved on: fall through and install the update.
} }
if (exists && delivery === undefined) { if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
this.conflict(stats, item.name, 'name_collision'); this.conflict(stats, item.name, 'name_collision');
continue; continue;
} }
@ -407,6 +582,10 @@ export class SkillSync {
(exists ? stats.updated : stats.downloaded).push(item.name); (exists ? stats.updated : stats.downloaded).push(item.name);
} }
// ---- UP: local originals -> cloud center --------------------------- // ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name));
const folders = await readdir(root, { withFileTypes: true }).catch(() => []); const folders = await readdir(root, { withFileTypes: true }).catch(() => []);
const seenFolders = new Set(); const seenFolders = new Set();
for (const entry of folders) { for (const entry of folders) {
@ -420,12 +599,37 @@ export class SkillSync {
if (skill === undefined) if (skill === undefined)
continue; continue;
if (typeof skill === 'string') { if (typeof skill === 'string') {
if (!knownConflicts.has(entry.name))
this.conflict(stats, entry.name, skill); this.conflict(stats, entry.name, skill);
continue; continue;
} }
const record = state.uploaded[skill.name]; const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name); const cloud = cloudByName.get(skill.name);
if (cloud !== undefined && record === undefined) { if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name))
continue;
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
this.conflict(stats, skill.name, 'name_collision'); this.conflict(stats, skill.name, 'name_collision');
continue; continue;
} }
@ -464,6 +668,32 @@ export class SkillSync {
} }
else { else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) { if (cloud.revision !== undefined && cloud.revision !== record.revision) {
// The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
if (!knownConflicts.has(skill.name))
this.conflict(stats, skill.name, 'cloud_newer'); this.conflict(stats, skill.name, 'cloud_newer');
continue; continue;
} }
@ -577,6 +807,31 @@ export class SkillSync {
dropConflict(name) { dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }; this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
} }
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput) {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))];
const resolved = [];
const failed = [];
for (const name of names) {
try {
await this.resolveConflict(name, action);
resolved.push(name);
}
catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) });
}
}
return { action, resolved, failed };
}
/** /**
* Both sides of every conflict from the last pass, so a human can decide. * Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything. * Read-only: it never changes a file or uploads anything.
@ -641,7 +896,7 @@ export class SkillSync {
}, },
canKeepLocal: location !== 'none', canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined, canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。', note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
}); });
} }
return out; return out;

View File

@ -1,6 +1,6 @@
{ {
"name": "dsh-brain", "name": "dsh-brain",
"version": "0.9.5", "version": "0.9.10",
"description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.", "description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",

360
preview-import.mjs Normal file
View File

@ -0,0 +1,360 @@
// Renders the redesigned 「从其他软件导入」 panel to a PNG so the layout can be
// reviewed before DSH is restarted. It reads the *live* skill sources through
// the built plugin (read-only), expands the import panel, and screenshots the
// result with headless Chrome.
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
// ── real data ───────────────────────────────────────────────────────────
const { SkillAdmin, skillsHoldingDir } = await import('./lib/skill-admin.js')
const { SkillGroupManager, detectSources } = await import('./lib/skill-groups.js')
const { SettingsStore } = await import('./lib/store.js')
const store = new SettingsStore({})
const admin = new SkillAdmin({
skillsRoot: () => join(store.path, '..', 'skills'),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => join(store.path, '..', 'dsh-brain-skills.json'),
syncRunning: () => false,
log: () => {},
})
const groups = new SkillGroupManager({ sources: () => detectSources(), admin, log: () => {} })
const overview = await groups.overview()
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: true,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
],
},
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
}
// ── minimal React + HTML serializer ─────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function walk(node, visit) {
if (node === null || node === undefined || node === false || node === true) return
if (typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
function styleOf(style) {
const parts = []
for (const [key, value] of Object.entries(style ?? {})) {
if (value === null || value === undefined) continue
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
}
return parts.join(';')
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function toHtml(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
if (Array.isArray(node)) return node.map(toHtml).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
return toHtml(instance.render())
}
return toHtml(type({ ...props, children }))
}
const attrs = []
const style = styleOf(props.style)
if (style !== '') attrs.push(`style="${style}"`)
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
if (props.disabled === true) attrs.push('disabled')
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
for (const [key, value] of Object.entries(props)) {
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
}
if (type === 'input') {
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
return `<input ${attrs.filter(Boolean).join(' ')}>`
}
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
}
// ── drive the real bundle ───────────────────────────────────────────────
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? 'skills' : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject: (_seat, fn) => fn(),
register: (_options, component) => {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
const fakeFetch = async (url) => {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/dsh-brain/status') body = statusBody
else if (path === '/dsh-brain/skills/sources') body = { ok: true, ...overview }
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
else if (path.startsWith('/dsh-brain/skills/api')) {
body = { ok: true, skills: overview.sources[0]?.groups.flatMap((group) => group.skills) ?? [], plans: [] }
}
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}
function loadCard() {
registered = null
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
AbortController,
)
return registered
}
async function settle(element, passes) {
let text = ''
for (let pass = 0; pass < passes; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = toHtml(element)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
return text
}
function clickLabel(root, prefix) {
let clicked = false
walk(root, (node) => {
if (clicked) return
const props = node.props ?? {}
const label = props['aria-label']
const text = typeof props.children === 'string' ? props.children : ''
const matches = (typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)
if (matches && typeof props.onClick === 'function') {
props.onClick()
clicked = true
}
})
return clicked
}
function typeInto(root, label, value) {
let typed = false
walk(root, (node) => {
if (typed) return
const props = node.props ?? {}
if (props['aria-label'] === label && typeof props.onChange === 'function') {
props.onChange({ target: { value } })
typed = true
}
})
return typed
}
const card = loadCard()
const treeEl = React.createElement(card, null)
const firstBody = await settle(treeEl, 6)
if (!firstBody.includes('技能文件夹')) console.log('debug body head:', firstBody.slice(0, 600))
cursor = 0
pendingEffects = []
if (!clickLabel(treeEl, '从其他软件导入')) throw new Error('preview: could not find the import button')
const body = await settle(treeEl, 6)
if (body.includes('渲染失败')) throw new Error('the card rendered its error boundary')
// Second view: search filters the candidate list, then select-all-matched.
cursor = 0
pendingEffects = []
if (!typeInto(treeEl, '搜索要导入的技能', 'nature')) throw new Error('preview: could not find the import search box')
await settle(treeEl, 6)
cursor = 0
pendingEffects = []
if (!clickLabel(treeEl, '全选匹配可导入')) console.warn('preview: select-all was not clickable')
const searchBody = await settle(treeEl, 6)
// Third view: dark theme, default (unfiltered) state.
cursor = 0
pendingEffects = []
typeInto(treeEl, '搜索要导入的技能', '')
clickLabel(treeEl, '清空已选')
const darkBody = await settle(treeEl, 6)
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
<style>
html,body{margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
.panel{border-radius:14px;padding:16px;
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
button{font-family:inherit}
input{font-family:inherit;color:inherit}
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
const outDir = join(here, '_preview')
mkdirSync(outDir, { recursive: true })
const lightPath = join(outDir, 'import-light.html')
const searchPath = join(outDir, 'import-search.html')
const darkPath = join(outDir, 'import-dark.html')
writeFileSync(lightPath, page(body, 'light'), 'utf8')
writeFileSync(searchPath, page(searchBody, 'light'), 'utf8')
writeFileSync(darkPath, page(darkBody, 'dark'), 'utf8')
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
for (const [input, output, height] of [
[lightPath, join(outDir, 'import-light.png'), 2600],
[searchPath, join(outDir, 'import-search.png'), 1600],
[darkPath, join(outDir, 'import-dark.png'), 2600],
]) {
execFileSync(chrome, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=2',
`--window-size=640,${height}`,
`--screenshot=${output}`,
`file:///${input.replace(/\\/g, '/')}`,
], { stdio: 'ignore' })
console.log(`wrote ${output}`)
}
console.log('sources:', overview.sources.map((item) => `${item.label}=${item.total}`).join(', '))

344
preview-mcp.mjs Normal file
View File

@ -0,0 +1,344 @@
// Renders the MCP management tab to a PNG so the search / select-all / batch
// layout can be reviewed before DSH is restarted. Data is a representative
// catalogue (no real host bridge is called); the render tree is the real one.
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, 'client', 'index.js'), 'utf8')
const statusBody = {
ok: true,
settings: {
enabled: true,
baseUrl: 'https://your-memory-host/api/longmemory',
baseUrlConfigured: true,
baseUrlOrigin: 'https://your-memory-host',
clientId: 'dsh-desktop',
requestTimeoutMs: 5000,
defaultK: 10,
summaryEnabled: true,
summaryMaxChars: 6000,
skillsSyncEnabled: true,
skillsDir: '',
},
tokens: {
activity: { configured: true, masked: 'cmt_9f2c1a…7d4e' },
memory: { configured: true, masked: 'cmt_3b81cc…22a9' },
summary: { configured: true, masked: 'cmt_71ad02…9f10' },
},
settingsPath: '%USERPROFILE%/.dsh/dsh-brain.json',
reporter: { attempted: 12, recorded: 11, duplicate: 1, failed: 0, skipped: 0, queued: 0, recent: [] },
lastCheck: {
at: Date.now(),
checks: [
{ id: 'network', label: '服务地址', state: 'ok', message: '服务可达(HTTP 200)' },
{ id: 'activity', label: '活动上报权限(activity:write)', state: 'ok', message: '鉴权通过' },
{ id: 'memory', label: '记忆读写权限(memory:write)', state: 'ok', message: '鉴权通过(3 个项目)' },
{ id: 'summary', label: '摘要权限(summary:write)', state: 'ok', message: '鉴权通过' },
],
},
capabilities: { version: '0.9.7', features: { skills: true, skillsMarketplace: false, mcpBridge: 'host-plugin' }, notes: [] },
skills: { running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0 },
}
const connections = [
{ key: 'github', connectorId: 'c-github', name: 'github', transport: 'streamable-http', authMode: 'bearer', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'workspace' }, healthCheckedAt: Date.now() - 120000, lastError: null },
{ key: 'notion', connectorId: 'c-notion', name: 'notion', transport: 'streamable-http', authMode: 'oauth2', injectionLabel: '会话级', connectionState: 'connected', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: Date.now() - 900000, lastError: null },
{ key: 'chrome-devtools', connectorId: 'c-chrome', name: 'chrome-devtools', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'connected', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 60000, lastError: null },
{ key: 'filesystem', connectorId: 'c-fs', name: 'filesystem', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'disabled', enabled: false, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 86400000, lastError: null },
{ key: 'postgres', connectorId: 'c-pg', name: 'postgres', transport: 'stdio', authMode: 'none', injectionLabel: '全局', connectionState: 'error', enabled: true, scope: { visibility: 'global' }, healthCheckedAt: Date.now() - 3600000, lastError: 'spawn postgres-mcp ENOENT' },
{ key: 'brave-search', connectorId: 'c-brave', name: 'brave-search', transport: 'streamable-http', authMode: 'api-key', injectionLabel: '会话级', connectionState: 'unknown', enabled: true, scope: { visibility: 'session' }, healthCheckedAt: null, lastError: null },
]
// ── minimal React + HTML serializer ─────────────────────────────────────
let hooks = []
let cursor = 0
let pendingEffects = []
let scheduled = false
const React = {
createElement(type, props, ...children) {
const flat = []
const push = (value) => {
if (Array.isArray(value)) value.forEach(push)
else if (value !== null && value !== undefined && value !== false && value !== true) flat.push(value)
}
push(children)
return { type, props: { ...(props ?? {}), children: flat.length === 1 ? flat[0] : flat }, children: flat }
},
useState(initial) {
const index = cursor++
if (!(index in hooks)) hooks[index] = typeof initial === 'function' ? initial() : initial
const setter = (next) => {
const value = typeof next === 'function' ? next(hooks[index]) : next
if (value !== hooks[index]) {
hooks[index] = value
scheduled = true
}
}
return [hooks[index], setter]
},
useEffect(fn) {
pendingEffects.push(fn)
},
useCallback(fn) {
return fn
},
Component: function Component(props) {
this.props = props
},
}
React.Component.prototype.setState = function setState(patch) {
this.state = { ...this.state, ...patch }
scheduled = true
}
function walk(node, visit) {
if (node === null || node === undefined || node === false || node === true) return
if (typeof node === 'string' || typeof node === 'number') return
if (Array.isArray(node)) {
node.forEach((child) => walk(child, visit))
return
}
if (typeof node.type === 'function') {
if (node.type.prototype && typeof node.type.prototype.render === 'function') {
const instance = new node.type(node.props)
instance.props = node.props
if (instance.state === undefined) instance.state = {}
instance.setState = function setState(patch) {
instance.state = { ...instance.state, ...patch }
scheduled = true
}
walk(instance.render(), visit)
return
}
walk(node.type({ ...node.props, children: node.children }), visit)
return
}
visit(node)
node.children.forEach((child) => walk(child, visit))
}
const UNITLESS = new Set(['fontWeight', 'opacity', 'lineHeight', 'flex', 'zIndex', 'flexGrow', 'flexShrink'])
function styleOf(style) {
const parts = []
for (const [key, value] of Object.entries(style ?? {})) {
if (value === null || value === undefined) continue
const name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
parts.push(`${name}:${typeof value === 'number' && !UNITLESS.has(key) ? `${value}px` : String(value)}`)
}
return parts.join(';')
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function toHtml(node) {
if (node === null || node === undefined || node === false || node === true) return ''
if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node)
if (Array.isArray(node)) return node.map(toHtml).join('')
const { type, props, children } = node
if (typeof type === 'function') {
if (type.prototype && typeof type.prototype.render === 'function') {
const instance = new type(props)
instance.props = props
if (instance.state === undefined) instance.state = {}
return toHtml(instance.render())
}
return toHtml(type({ ...props, children }))
}
const attrs = []
const style = styleOf(props.style)
if (style !== '') attrs.push(`style="${style}"`)
if (props.id !== undefined) attrs.push(`id="${escapeHtml(props.id)}"`)
if (props.role !== undefined) attrs.push(`role="${escapeHtml(props.role)}"`)
if (props.title !== undefined) attrs.push(`title="${escapeHtml(props.title)}"`)
if (props.disabled === true) attrs.push('disabled')
if (props.type === 'checkbox') attrs.push(props.checked === true ? 'checked' : '')
for (const [key, value] of Object.entries(props)) {
if (key.startsWith('aria-')) attrs.push(`${key}="${escapeHtml(value)}"`)
}
if (type === 'input') {
attrs.push(`value="${escapeHtml(props.value === undefined ? '' : props.value)}"`)
attrs.push(`placeholder="${escapeHtml(props.placeholder === undefined ? '' : props.placeholder)}"`)
attrs.push(`type="${escapeHtml(props.type === undefined ? 'text' : props.type)}"`)
return `<input ${attrs.filter(Boolean).join(' ')}>`
}
return `<${type} ${attrs.filter(Boolean).join(' ')}>${children.map(toHtml).join('')}</${type}>`
}
// ── drive the real bundle ───────────────────────────────────────────────
const localStorageStub = {
getItem: (key) => (String(key).endsWith(':tab') ? 'mcp' : null),
setItem: () => {},
}
let registered = null
globalThis.window = {
localStorage: localStorageStub,
addEventListener: () => {},
removeEventListener: () => {},
__ModuleLoader__: {
load(spec) {
const exportsObject = spec.factory(requireShim)
const captured = []
exportsObject.apply({
slots: {
inject: (_seat, fn) => fn(),
register: (_options, component) => {
captured.push(component)
return () => {}
},
},
})
registered = captured[0]
},
},
}
function requireShim(id) {
if (id === 'react') return React
throw new Error(`unexpected require: ${id}`)
}
const fakeFetch = async (url, init) => {
const path = String(url).split('?')[0]
let body = { ok: false }
if (path === '/dsh-brain/status') body = statusBody
else if (path === '/dsh-brain/sync/status') body = { ok: true, stats: { running: false, lastRunAt: Date.now(), uploaded: [], downloaded: [] }, conflicts: [] }
else if (path === '/mcp-connector/api') {
let method = 'status'
try {
method = JSON.parse(init?.body ?? '{}').method ?? 'status'
} catch {
method = 'status'
}
body = method === 'status'
? { ok: true, message: '共 ' + connections.length + ' 条连接', detail: { items: connections, scope: {} } }
: { ok: true, message: '演示数据:' + method + ' 已受理' }
}
return { status: body.ok === false ? 404 : 200, json: async () => body, text: async () => JSON.stringify(body) }
}
function loadCard() {
registered = null
new Function('window', 'require', 'document', 'localStorage', 'fetch', 'console', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'AbortController', source)(
globalThis.window,
requireShim,
{ visibilityState: 'visible' },
localStorageStub,
fakeFetch,
{ warn: () => {}, log: () => {} },
() => 0,
() => {},
() => 0,
() => {},
AbortController,
)
return registered
}
async function settle(element, passes) {
let text = ''
for (let pass = 0; pass < passes; pass += 1) {
cursor = 0
pendingEffects = []
scheduled = false
text = toHtml(element)
const effects = pendingEffects
pendingEffects = []
for (const effect of effects) {
const cleanup = effect()
if (typeof cleanup === 'function') cleanup()
}
await new Promise((resolve) => setTimeout(resolve, 0))
if (!scheduled) break
}
return text
}
function clickLabel(root, prefix) {
let clicked = false
walk(root, (node) => {
if (clicked) return
const props = node.props ?? {}
const label = props['aria-label']
const text = typeof props.children === 'string' ? props.children : ''
if (((typeof label === 'string' && label.startsWith(prefix)) || text.startsWith(prefix)) && typeof props.onClick === 'function') {
props.onClick()
clicked = true
}
})
return clicked
}
function typeInto(root, label, value) {
let typed = false
walk(root, (node) => {
if (typed) return
const props = node.props ?? {}
if (props['aria-label'] === label && typeof props.onChange === 'function') {
props.onChange({ target: { value } })
typed = true
}
})
return typed
}
const card = loadCard()
const treeEl = React.createElement(card, null)
const firstBody = await settle(treeEl, 6)
if (!firstBody.includes('我的连接')) throw new Error('preview: MCP tab did not render')
// View 2: filter to streamable-http connections and select them all.
cursor = 0
pendingEffects = []
typeInto(treeEl, '搜索 MCP 连接', 'search')
await settle(treeEl, 6)
cursor = 0
pendingEffects = []
clickLabel(treeEl, '全选匹配结果')
const chosenBody = await settle(treeEl, 6)
const page = (content, theme) => `<!doctype html><html><head><meta charset="utf-8">
<style>
html,body{margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
background:${theme === 'dark' ? '#101216' : '#f3f5f9'};color:${theme === 'dark' ? '#e8eaee' : '#1a1d21'}}
.frame{width:600px;margin:0 auto;padding:18px 20px 24px}
.panel{border-radius:14px;padding:16px;
background:${theme === 'dark' ? '#191c22' : '#ffffff'};
box-shadow:0 10px 30px rgba(0,0,0,${theme === 'dark' ? '0.45' : '0.10'})}
button{font-family:inherit}
input{font-family:inherit;color:inherit}
</style></head><body><div class="frame"><div class="panel">${content}</div></div></body></html>`
const outDir = join(here, '_preview')
mkdirSync(outDir, { recursive: true })
const lightPath = join(outDir, 'mcp-light.html')
const chosenPath = join(outDir, 'mcp-selected.html')
const darkPath = join(outDir, 'mcp-dark.html')
writeFileSync(lightPath, page(firstBody, 'light'), 'utf8')
writeFileSync(chosenPath, page(chosenBody, 'light'), 'utf8')
writeFileSync(darkPath, page(chosenBody, 'dark'), 'utf8')
const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
for (const [input, output, height] of [
[lightPath, join(outDir, 'mcp-light.png'), 2200],
[chosenPath, join(outDir, 'mcp-selected.png'), 2200],
[darkPath, join(outDir, 'mcp-dark.png'), 2200],
]) {
execFileSync(chrome, [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--force-device-scale-factor=2',
`--window-size=640,${height}`,
`--screenshot=${output}`,
`file:///${input.replace(/\\/g, '/')}`,
], { stdio: 'ignore' })
console.log(`wrote ${output}`)
}

View File

@ -118,6 +118,10 @@ export interface SkillSummary {
files?: number files?: number
bytes?: number bytes?: number
script_changed?: boolean script_changed?: boolean
/** Center creation time (ISO string; older servers may send epoch seconds). */
created_at?: string | number
/** Center last-change time — the timestamp the sync engine compares against local mtimes. */
updated_at?: string | number
[key: string]: unknown [key: string]: unknown
} }

View File

@ -30,7 +30,7 @@ export const name = 'dsh-brain'
export const inject = ['webServer'] export const inject = ['webServer']
/** Version reported by the status card. */ /** Version reported by the status card. */
const VERSION = '0.9.5' const VERSION = '0.9.10'
/** How often the skill directory is reconciled with the cloud center. */ /** How often the skill directory is reconciled with the cloud center. */
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000 const SKILL_SYNC_INTERVAL_MS = 15 * 60_000

View File

@ -23,7 +23,7 @@ import { LongMemoryProvider } from './driver.ts'
export { LongMemoryProvider, descriptor } export { LongMemoryProvider, descriptor }
/** Keep in sync with the package version (asserted by the verify script). */ /** Keep in sync with the package version (asserted by the verify script). */
const PROVIDER_VERSION = '0.9.5' const PROVIDER_VERSION = '0.9.8'
export const definition = defineMemorySpaceProviderDefinition({ export const definition = defineMemorySpaceProviderDefinition({
manifest: { manifest: {

View File

@ -838,6 +838,7 @@ async function serveMarket(deps: RouteDeps, req: IncomingMessage, res: ServerRes
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } for every conflict
*/ */
async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> { async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const sync = deps.sync const sync = deps.sync
@ -867,6 +868,14 @@ async function serveSync(deps: RouteDeps, req: IncomingMessage, res: ServerRespo
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }) json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
return return
} }
if (suffix === '/resolve-all') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
const body = await jsonBody(req, res)
if (body === undefined) return
const result = await sync.resolveConflicts(body.action)
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() })
return
}
fail(res, 404, 'unknown-sync-route') fail(res, 404, 'unknown-sync-route')
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : String(error) const message = error instanceof Error ? error.message : String(error)

View File

@ -15,12 +15,14 @@
* revisions, guarded by the center's `expected_revision` check. * revisions, guarded by the center's `expected_revision` check.
* *
* Safety rules (deliberate, in order): * Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded. If its local files no * 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* longer match the delivery manifest, the skill is flagged as a * newer than the center's `updated_at`; before any cloud overwrite the
* conflict and left completely alone. * local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 2. A local deletion never deletes the cloud copy. * 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked; * 3. A same-name skill is never hijacked silently: byte-identical copies are
* it is reported as a conflict for a human to resolve. * adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed * 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the * until the change is acknowledged in the dashboard, mirroring the
* center's own review flag. * center's own review flag.
@ -65,6 +67,23 @@ export function linkedSkillManifest(files: readonly { path: string; sha256: stri
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8')) return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'))
} }
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return value < 1e12 ? value * 1000 : value
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : undefined
}
return undefined
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files: readonly { mtimeMs: number }[]): number {
let newest = 0
for (const file of files) if (file.mtimeMs > newest) newest = file.mtimeMs
return newest
}
/** True when the cloud center would accept this relative file path. */ /** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel: string): boolean { export function isCloudSkillPath(rel: string): boolean {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
@ -150,6 +169,8 @@ interface SyncState {
interface LocalFile { interface LocalFile {
rel: string rel: string
buffer: Buffer buffer: Buffer
/** Last-modified time; the automatic newer-side winner is chosen from these. */
mtimeMs: number
} }
/** Dependencies of one sync engine instance. */ /** Dependencies of one sync engine instance. */
@ -173,6 +194,14 @@ interface DeliveryManifest {
files?: { path: string; sha256: string }[] files?: { path: string; sha256: string }[]
} }
/**
* Result of an automatic two-sided resolution:
* - resolved: the newer side won and the state was updated;
* - conflict: a specific conflict was recorded (e.g. script review);
* - unresolved: timestamps missing/equal — the caller records a conflict.
*/
type AutoResolution = 'resolved' | 'conflict' | 'unresolved'
export class SkillSync { export class SkillSync {
private running = false private running = false
private current: SkillSyncStats = { private current: SkillSyncStats = {
@ -262,7 +291,10 @@ export class SkillSync {
if (entry.isDirectory()) { if (entry.isDirectory()) {
await walk(rel) await walk(rel)
} else if (entry.isFile()) { } else if (entry.isFile()) {
out.push({ rel, buffer: await readFile(join(dir, rel)) }) const absolute = join(dir, rel)
const buffer = await readFile(absolute)
const info = await stat(absolute)
out.push({ rel, buffer, mtimeMs: info.mtimeMs })
} }
} }
} }
@ -327,6 +359,175 @@ export class SkillSync {
return undefined return undefined
} }
/** Center's last-change time for one listed skill (ISO string or epoch). */
private cloudUpdatedAt(item: SkillSummary): number | undefined {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at)
}
/** Manifest over every local file, including files the center would reject. */
private localManifest(files: readonly LocalFile[]): string {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })))
}
/** Copy a local skill aside before an automatic cloud overwrite. */
private async backupLocal(dir: string, name: string): Promise<string> {
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp)
await mkdir(join(backup, '..'), { recursive: true })
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') })
return backup
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
private async adoptIdenticalDelivery(home: string, item: SkillSummary, files: readonly LocalFile[]): Promise<void> {
const delivery: DeliveryManifest & { synced_at: string } = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
}
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2))
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
private async autoTakeCloud(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
const bundle = await client.skillBundle(item.name)
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`)
return 'conflict'
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch')
return 'conflict'
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required')
return 'conflict'
}
await this.backupLocal(home, item.name)
await this.install(item, bundle.data, installRoot)
this.markDelivered(state, item.name, bundle.data.manifest_sha256)
delete state.removed[item.name]
stats.updated.push(item.name)
return 'resolved'
}
/** Upload the locally-newer copy as the next cloud revision. */
private async autoUploadLocal(
skill: { name: string; description: string; files: LocalFile[]; manifest: string; hasScripts: boolean },
folder: string,
dir: string,
cloud: SkillSummary,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
})
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`
this.conflict(stats, skill.name, reason)
return 'conflict'
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1
await rm(join(dir, '.manifest.json'), { force: true })
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
delete state.removed[skill.name]
stats.updated.push(skill.name)
return 'resolved'
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
private async autoResolveCollision(
item: SkillSummary,
home: string,
installRoot: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (!localFiles.some((file) => file.rel === 'SKILL.md')) return 'unresolved'
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
private async autoResolveLocalDrift(
item: SkillSummary,
home: string,
state: SyncState,
stats: SkillSyncStats,
client: CloudClient,
installRoot: string,
): Promise<AutoResolution> {
const localFiles = await this.readSkillFiles(home).catch(() => [])
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles)
this.markDelivered(state, item.name, item.manifest_sha256)
stats.skipped += 1
return 'resolved'
}
const cloudAt = this.cloudUpdatedAt(item)
const localAt = newestMtime(localFiles)
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt) return 'unresolved'
if (cloudAt > localAt) return this.autoTakeCloud(item, home, installRoot, state, stats, client)
const skill = await this.readLocalSkill(home, item.name)
if (skill === undefined) return 'unresolved'
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill)
return 'conflict'
}
return this.autoUploadLocal(skill, item.name, home, item, state, stats, client)
}
/** One full pass; never throws — outcomes land in the stats. */ /** One full pass; never throws — outcomes land in the stats. */
async syncOnce(): Promise<SkillSyncStats> { async syncOnce(): Promise<SkillSyncStats> {
if (this.running) return this.current if (this.running) return this.current
@ -420,6 +621,11 @@ export class SkillSync {
if (exists && delivery !== undefined) { if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download. // Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) { if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'locally_modified') this.conflict(stats, item.name, 'locally_modified')
continue continue
} }
@ -434,6 +640,14 @@ export class SkillSync {
// Intact but the cloud moved on: fall through and install the update. // Intact but the cloud moved on: fall through and install the update.
} }
if (exists && delivery === undefined) { if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
this.conflict(stats, item.name, 'name_collision') this.conflict(stats, item.name, 'name_collision')
continue continue
} }
@ -462,6 +676,10 @@ export class SkillSync {
} }
// ---- UP: local originals -> cloud center --------------------------- // ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name))
const folders = await readdir(root, { withFileTypes: true }).catch(() => []) const folders = await readdir(root, { withFileTypes: true }).catch(() => [])
const seenFolders = new Set<string>() const seenFolders = new Set<string>()
for (const entry of folders) { for (const entry of folders) {
@ -472,12 +690,35 @@ export class SkillSync {
const skill = await this.readLocalSkill(dir, entry.name) const skill = await this.readLocalSkill(dir, entry.name)
if (skill === undefined) continue if (skill === undefined) continue
if (typeof skill === 'string') { if (typeof skill === 'string') {
this.conflict(stats, entry.name, skill) if (!knownConflicts.has(entry.name)) this.conflict(stats, entry.name, skill)
continue continue
} }
const record = state.uploaded[skill.name] const record = state.uploaded[skill.name]
const cloud = cloudByName.get(skill.name) const cloud = cloudByName.get(skill.name)
if (cloud !== undefined && record === undefined) { if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name)) continue
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
this.conflict(stats, skill.name, 'name_collision') this.conflict(stats, skill.name, 'name_collision')
continue continue
} }
@ -512,7 +753,32 @@ export class SkillSync {
stats.uploaded.push(skill.name) stats.uploaded.push(skill.name)
} else { } else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) { if (cloud.revision !== undefined && cloud.revision !== record.revision) {
this.conflict(stats, skill.name, 'cloud_newer') // The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
})
stateDirty = true
stats.skipped += 1
continue
}
const cloudAt = this.cloudUpdatedAt(cloud)
const localAt = newestMtime(skill.files)
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client)
if (auto !== 'unresolved') {
stateDirty = true
continue
}
}
if (!knownConflicts.has(skill.name)) this.conflict(stats, skill.name, 'cloud_newer')
continue continue
} }
const updated = await client.updateSkill(skill.name, { const updated = await client.updateSkill(skill.name, {
@ -626,6 +892,29 @@ export class SkillSync {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) } this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) }
} }
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput: unknown): Promise<SyncResolveBatchResult> {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : ''
if (action === '') throw new Error('invalid_action')
if (this.running) throw new Error('sync_running')
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))]
const resolved: string[] = []
const failed: { name: string; error: string }[] = []
for (const name of names) {
try {
await this.resolveConflict(name, action)
resolved.push(name)
} catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) })
}
}
return { action, resolved, failed }
}
/** /**
* Both sides of every conflict from the last pass, so a human can decide. * Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything. * Read-only: it never changes a file or uploads anything.
@ -683,7 +972,7 @@ export class SkillSync {
}, },
canKeepLocal: location !== 'none', canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined, canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。', note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
}) })
} }
return out return out
@ -812,3 +1101,10 @@ export interface SyncResolveResult {
backup?: string backup?: string
note: string note: string
} }
/** Outcome of resolving every current conflict with one action. */
export interface SyncResolveBatchResult {
action: 'keep_local' | 'take_cloud'
resolved: string[]
failed: { name: string; error: string }[]
}

View File

@ -481,6 +481,12 @@ check('foreign sources start collapsed behind the import button',
const openedImport = await drive('skills', true, '从其他软件导入') const openedImport = await drive('skills', true, '从其他软件导入')
check('clicking the import button reveals foreign sources as import candidates', check('clicking the import button reveals foreign sources as import candidates',
openedImport.includes('Codex') && openedImport.includes('收起') && !openedImport.includes('仅本卡')) openedImport.includes('Codex') && openedImport.includes('收起') && !openedImport.includes('仅本卡'))
check('the import panel has search, select-all and batch import',
openedImport.includes('全选匹配可导入') &&
openedImport.includes('全选全部') &&
openedImport.includes('清空已选') &&
openedImport.includes('导入所选') &&
openedImport.includes('全选本来源'))
const openedAssign = await drive('skills', true, '把技能加入 QQ-Skill') const openedAssign = await drive('skills', true, '把技能加入 QQ-Skill')
check('clicking + on a category opens the inline skill assignment picker with search', check('clicking + on a category opens the inline skill assignment picker with search',
@ -504,19 +510,26 @@ check('no render boundary error on the skills tab', !skillsText.includes('渲染
const mcpText = await drive('mcp', true) const mcpText = await drive('mcp', true)
check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp')) check('the MCP tab renders the host connection', mcpText.includes('我的连接') && mcpText.includes('demo-mcp'))
check('MCP state, transport and auth are shown', mcpText.includes('已连接') && mcpText.includes('http') && mcpText.includes('bearer')) check('collapsed rows keep only name, state and transport',
check('MCP actions are offered', mcpText.includes('健康检查') && mcpText.includes('工具列表') && mcpText.includes('移除连接')) mcpText.includes('已连接') && mcpText.includes('http') && !mcpText.includes('bearer'))
check('the heavier MCP sections start collapsed',
!mcpText.includes('校验并保存连接') && !mcpText.includes('预览作用域') && mcpText.includes('展开'))
const mcpDetail = await drive('mcp', true, '详情 demo-mcp')
check('expanding a connection reveals auth, scope and actions',
mcpDetail.includes('bearer') && mcpDetail.includes('健康检查') && mcpDetail.includes('工具列表') && mcpDetail.includes('移除连接'))
check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用')) check('the injected tools cache starts empty', mcpText.includes('工具可见不等于业务可调用'))
check('the MCP list has search, filters and select-all', check('the MCP list has search, filters and select-all',
mcpText.includes('全选匹配结果') && mcpText.includes('全选匹配结果') &&
mcpText.includes('全选全部') && mcpText.includes('全选全部') &&
mcpText.includes('清空已选') && mcpText.includes('清空已选') &&
mcpText.includes('筛选:全部') && mcpText.includes('筛选:全部') &&
mcpText.includes('批量健康检查')) mcpText.includes('勾选左侧连接后'))
const mcpChosen = await drive('mcp', true, '全选匹配结果(1)') const mcpChosen = await drive('mcp', true, '全选匹配结果')
check('selecting all matched connections reveals the batch removal confirm', check('selecting all matched connections reveals the batch actions',
mcpChosen.includes('批量移除…') && mcpChosen.includes('批量停用')) mcpChosen.includes('批量操作(已选 1)') && mcpChosen.includes('移除…'))
check('the removed MCP marketplace panel no longer renders', !mcpText.includes('MCP 市场') && !mcpText.includes('读取 MCP 市场失败'))
const missing = await drive('mcp', false) const missing = await drive('mcp', false)
check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置')) check('a missing bridge becomes a stated capability gap', missing.includes('MCP 管理当前不可用') && missing.includes('MCP 服务器配置'))

View File

@ -57,7 +57,7 @@ async function post(path, body) {
} }
const caps = await get('/dsh-brain/capabilities') const caps = await get('/dsh-brain/capabilities')
check('capabilities answers with 0.9.5', caps.body?.version === '0.9.5', String(caps.body?.version)) check('capabilities answers with 0.9.8', caps.body?.version === '0.9.8', String(caps.body?.version))
check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1) check('P3 market is advertised with one provider', caps.body?.features?.skillsMarketplace === true && caps.body?.features?.marketProviders === 1)
check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true) check('P3 update and sync-resolve are advertised', caps.body?.features?.skillUpdate === true && caps.body?.features?.syncResolve === true)
check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'ready') check('P4/P5/v1.1 flags are advertised', caps.body?.features?.multiClient === true && caps.body?.features?.brainMigration === 'ready')

View File

@ -4,7 +4,7 @@
// bundles, linked manifest) — no DSH host, no real service, no real token. // bundles, linked manifest) — no DSH host, no real service, no real token.
import http from 'node:http' import http from 'node:http'
import { createHash } from 'node:crypto' import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os' import { tmpdir } from 'node:os'
import { join } from 'node:path' import { join } from 'node:path'
@ -27,16 +27,24 @@ function storeFiles(files) {
return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') } return { path: file.path, sha256: sha(buffer), size: buffer.length, encoding: file.content !== undefined ? 'utf8' : 'base64', data: buffer.toString('base64') }
}) })
} }
const DAY = 24 * 60 * 60 * 1000
const CLOUD_OLD = Date.parse('2026-01-01T00:00:00.000Z')
const CLOUD_EQUAL = Date.parse('2026-06-01T00:00:00.000Z')
const iso = (value) => new Date(value).toISOString()
function summaryOf(skill) { function summaryOf(skill) {
return { return {
name: skill.name, description: skill.description, execution_mode: skill.execution_mode, name: skill.name, description: skill.description, execution_mode: skill.execution_mode,
enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length, enabled: true, revision: skill.revision, manifest_sha256: linked(skill.files), files: skill.files.length,
script_changed: skill.script_changed, script_changed: skill.script_changed,
created_at: iso(skill.created_at ?? CLOUD_OLD), updated_at: iso(skill.updated_at ?? CLOUD_OLD),
} }
} }
function seed(name, files, extra = {}) { function seed(name, files, extra = {}) {
const stored = storeFiles(files) const stored = storeFiles(files)
center.set(name, { name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored, script_changed: false, ...extra }) center.set(name, {
name, description: `${name} desc`, execution_mode: 'prompt-only', revision: 1, files: stored,
script_changed: false, created_at: CLOUD_OLD, updated_at: CLOUD_OLD, ...extra,
})
} }
seed('cloud-one', [ seed('cloud-one', [
{ path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' }, { path: 'SKILL.md', content: '# cloud-one\n\n云端技能一。' },
@ -73,7 +81,11 @@ const server = http.createServer((req, res) => {
const body = await readBody() const body = await readBody()
if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' }) if (body.expected_revision !== 0) return send(400, { error: 'invalid_input', message: '必须提供 expected_revision' })
if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' }) if (center.has(body.name)) return send(409, { error: 'skill_exists', message: '同名技能已存在' })
const skill = { name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only', revision: 1, files: storeFiles(body.files ?? []), script_changed: false } const skill = {
name: body.name, description: body.description, execution_mode: body.execution_mode ?? 'prompt-only',
revision: 1, files: storeFiles(body.files ?? []), script_changed: false,
created_at: Date.now(), updated_at: Date.now(),
}
center.set(skill.name, skill) center.set(skill.name, skill)
return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) }) return send(201, { skill: summaryOf(skill), revision: 1, manifest_sha256: linked(skill.files) })
} }
@ -86,6 +98,7 @@ const server = http.createServer((req, res) => {
if (body.files) skill.files = storeFiles(body.files) if (body.files) skill.files = storeFiles(body.files)
if (body.description !== undefined) skill.description = body.description if (body.description !== undefined) skill.description = body.description
skill.revision += 1 skill.revision += 1
skill.updated_at = Date.now()
return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) }) return send(200, { skill: summaryOf(skill), revision: skill.revision, manifest_sha256: linked(skill.files) })
} }
return send(404, { error: 'unknown_route', path }) return send(404, { error: 'unknown_route', path })
@ -106,11 +119,12 @@ const engine = new SkillSync({
}) })
const root = join(process.env.DSH_HOME, 'skills') const root = join(process.env.DSH_HOME, 'skills')
const skillDir = (name) => join(root, name) const skillDir = (name) => join(root, name)
const writeLocal = (name, files) => { const writeLocal = (name, files, mtime = Date.now()) => {
for (const [rel, content] of Object.entries(files)) { for (const [rel, content] of Object.entries(files)) {
const target = join(skillDir(name), ...rel.split('/')) const target = join(skillDir(name), ...rel.split('/'))
mkdirSync(join(target, '..'), { recursive: true }) mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, content) writeFileSync(target, content)
utimesSync(target, new Date(mtime), new Date(mtime))
} }
} }
@ -145,23 +159,71 @@ writeLocal('local-one', { 'SKILL.md': '---\nname: local-one\ndescription: 本地
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2) check('edited local skill updates the center', stats.updated.includes('local-one') && center.get('local-one')?.revision === 2)
// 4. A locally modified cloud skill is flagged, never overwritten or uploaded. // 4. A local edit newer than the cloud is uploaded automatically.
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }) writeLocal('cloud-one', { 'SKILL.md': '# cloud-one\n\n我改了云端技能。' }, Date.now())
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('local edit of a cloud skill becomes a conflict', check('local edit newer than cloud auto-uploads',
stats.conflicts.some((c) => c.name === 'cloud-one' && c.reason === 'locally_modified'), JSON.stringify(stats.conflicts)) stats.updated.includes('cloud-one') && center.get('cloud-one')?.revision === 2, JSON.stringify(stats.conflicts))
check('the local edit is left untouched', check('the newer local edit stays on disk',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能')) readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('我改了云端技能'))
check('the center copy is untouched by the conflict', check('newer local edit is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
center.get('cloud-one')?.revision === 1)
// 5. A name collision on both sides is flagged, both copies untouched. // 4b. Cloud newer than a stale local copy: auto-download with a local backup.
seed('clash', [{ path: 'SKILL.md', content: '# clash cloud' }]) {
writeLocal('clash', { 'SKILL.md': '# clash local\n' }) const cloud = center.get('cloud-one')
cloud.revision += 1
cloud.files = storeFiles([{ path: 'SKILL.md', content: '# cloud-one v3 (cloud newer)' }])
cloud.updated_at = Date.now() + DAY
writeLocal('cloud-one', { 'SKILL.md': '# cloud-one local stale\n' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer auto-downloads over a stale local copy',
readFileSync(join(skillDir('cloud-one'), 'SKILL.md'), 'utf8').includes('cloud newer'))
const backupRoot = join(process.env.DSH_HOME, '.dsh-brain-backups', 'sync', 'cloud-one')
check('auto overwrite backs the local copy up', existsSync(backupRoot))
check('cloud newer overwrite is not a conflict', !stats.conflicts.some((c) => c.name === 'cloud-one'))
}
// 5a. Identical bytes on both sides: adopt silently, no transfer, no conflict.
seed('clash-same', [{ path: 'SKILL.md', content: '# clash same' }], { updated_at: CLOUD_OLD })
writeLocal('clash-same', { 'SKILL.md': '# clash same' }, CLOUD_OLD - DAY)
stats = await engine.syncOnce() stats = await engine.syncOnce()
check('name collision is flagged', stats.conflicts.some((c) => c.name === 'clash' && c.reason === 'name_collision')) check('identical collision auto-adopts without a conflict',
check('collision leaves local files alone', readFileSync(join(skillDir('clash'), 'SKILL.md'), 'utf8').includes('clash local')) !stats.conflicts.some((c) => c.name === 'clash-same') && existsSync(join(skillDir('clash-same'), '.manifest.json')))
check('collision leaves the center alone', center.get('clash')?.revision === 1) check('identical collision uploads nothing', center.get('clash-same')?.revision === 1)
// 5b. Local newer wins the collision.
seed('clash-local', [{ path: 'SKILL.md', content: '# clash cloud' }], { updated_at: CLOUD_OLD })
writeLocal('clash-local', { 'SKILL.md': '# clash local newer' }, CLOUD_OLD + DAY)
stats = await engine.syncOnce()
check('local newer collision auto-uploads',
center.get('clash-local')?.revision === 2 && stats.updated.includes('clash-local'))
check('local newer collision keeps the local file',
readFileSync(join(skillDir('clash-local'), 'SKILL.md'), 'utf8').includes('local newer'))
// 5c. Cloud newer wins the collision.
seed('clash-cloud', [{ path: 'SKILL.md', content: '# clash cloud newer' }], { updated_at: Date.now() + DAY })
writeLocal('clash-cloud', { 'SKILL.md': '# clash local stale' }, Date.now() - DAY)
stats = await engine.syncOnce()
check('cloud newer collision auto-downloads',
readFileSync(join(skillDir('clash-cloud'), 'SKILL.md'), 'utf8').includes('cloud newer'))
check('cloud newer collision is not a conflict', !stats.conflicts.some((c) => c.name === 'clash-cloud'))
// 5d. Same timestamp on both sides: still a human decision.
seed('clash-equal', [{ path: 'SKILL.md', content: '# clash cloud same-time' }], { updated_at: CLOUD_EQUAL })
writeLocal('clash-equal', { 'SKILL.md': '# clash local same-time' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
check('equal timestamps keep the name collision conflict',
stats.conflicts.some((c) => c.name === 'clash-equal' && c.reason === 'name_collision'))
check('equal-timestamp collision leaves both sides untouched',
readFileSync(join(skillDir('clash-equal'), 'SKILL.md'), 'utf8').includes('same-time') && center.get('clash-equal')?.revision === 1)
// 5e. A same-name conflict is reported once, not once per reason.
seed('bad-clash', [{ path: 'SKILL.md', content: '# bad cloud' }], { updated_at: CLOUD_EQUAL })
writeLocal('bad-clash', { 'SKILL.md': '# bad local', 'README.md': 'root file' }, CLOUD_EQUAL)
stats = await engine.syncOnce()
const badClashConflicts = stats.conflicts.filter((c) => c.name === 'bad-clash')
check('one card per same-name conflict',
badClashConflicts.length === 1 && badClashConflicts[0]?.reason === 'name_collision', JSON.stringify(badClashConflicts))
// 6. Script-changed cloud bundles wait for review. // 6. Script-changed cloud bundles wait for review.
check('script-changed bundle is not installed', check('script-changed bundle is not installed',

View File

@ -98,6 +98,59 @@ check('keep_local refuses a stale cloud revision', stale)
const remaining = await sync.conflictDetails() const remaining = await sync.conflictDetails()
check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false) check('resolved conflicts drop out of the list', remaining.some((d) => d.name === 'demo') === false && remaining.some((d) => d.name === 'demo2') === false)
// Batch: partial failures are reported per item, not fatal.
const batchKeep = await sync.resolveConflicts('keep_local')
check('batch keep_local resolves the good item and reports the stale one',
batchKeep.resolved.includes('demo3') && batchKeep.failed.some((f) => f.name === 'demo4' && f.error === 'stale_revision'),
JSON.stringify(batchKeep))
const afterBatch = await sync.conflictDetails()
check('batch leaves only the failed conflict', afterBatch.length === 1 && afterBatch[0].name === 'demo4')
let badAction = false
try { await sync.resolveConflicts('manual') } catch (error) { badAction = error.message === 'invalid_action' }
check('batch refuses a non-batch action', badAction)
// Second home: a clean batch over every conflict succeeds.
const secondHome = mkdtempSync(join(tmpdir(), 'brain-sync-batch-'))
process.env.DSH_HOME = secondHome
const root2 = join(secondHome, 'skills')
mkdirSync(root2, { recursive: true })
const cloudBody2 = '---\nname: b1\n---\n# b1 CLOUD\n'
const files2 = [{ path: 'SKILL.md', sha256: sha256Hex(cloudBody2), data: Buffer.from(cloudBody2).toString('base64') }]
const manifest2 = linkedSkillManifest(files2)
const items2 = [
{ name: 'b1', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
{ name: 'b2', enabled: true, revision: 2, manifest_sha256: manifest2, files: 1, bytes: cloudBody2.length },
]
function makeDrift(rootDir, folder) {
mkdirSync(join(rootDir, folder), { recursive: true })
writeFileSync(join(rootDir, folder, 'SKILL.md'), `# ${folder} local\n`)
writeFileSync(join(rootDir, folder, '.manifest.json'), JSON.stringify({
name: folder, revision: 1, manifest_sha256: 'old', files: [{ path: 'SKILL.md', sha256: 'deadbeef' }],
}))
}
makeDrift(root2, 'b1')
makeDrift(root2, 'b2')
const client2 = {
listSkills: async () => ({ ok: true, status: 200, data: { items: items2 } }),
skillBundle: async (name) => ({ ok: true, status: 200, data: { name, revision: 2, manifest_sha256: manifest2, files: [{ ...files2[0] }] } }),
createSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 1 } } }),
updateSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 3 } } }),
}
const sync2 = new SkillSync({
client: () => client2,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
log: () => {},
})
const stats2 = await sync2.syncOnce()
check('second pass reports two drift conflicts', stats2.conflicts.length === 2, JSON.stringify(stats2.conflicts))
const batchTake = await sync2.resolveConflicts('take_cloud')
check('batch take_cloud resolves every conflict',
batchTake.resolved.length === 2 && batchTake.failed.length === 0, JSON.stringify(batchTake))
const remaining2 = await sync2.conflictDetails()
check('batch take_cloud empties the conflict list', remaining2.length === 0)
check('batch take_cloud overwrote the local files', readFileSync(join(root2, 'b1', 'SKILL.md'), 'utf8').includes('CLOUD'))
const passed = results.filter((r) => r.ok).length const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`) console.log(`\n${passed}/${results.length} passed`)
process.exit(passed === results.length ? 0 : 1) process.exit(passed === results.length ? 0 : 1)

View File

@ -74,7 +74,7 @@ for (const name of readdirSync(libDir)) {
} }
check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(',')) check('no personal domain remains in shipped lib/', leaked.length === 0, leaked.join(','))
const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8')) const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'))
check('package version is the delivery version', pkg.version === '0.9.5', pkg.version) check('package version is the delivery version', pkg.version === '0.9.8', pkg.version)
const passed = results.filter((r) => r.ok).length const passed = results.filter((r) => r.ok).length
console.log(`\n${passed}/${results.length} passed`) console.log(`\n${passed}/${results.length} passed`)