dsh-brain/client/index.js

1923 lines
77 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// dsh-cloud-memory client bundle.
//
// Hand-written on purpose: the host loads this file through `require` shims it
// provides itself (react / react/jsx-runtime), so no bundler is involved. The
// module wrapper below is the contract the web loader expects — `id` has to
// match the package name, otherwise the module graph registers a second copy.
//
// Three tabs: 连接与上报 / 技能管理 / MCP 管理. Nothing here invents data: every
// number and state comes from the plugin's own routes or, for MCP, from the
// host `dsh-mcp-connector` plugin's public bridge on the same origin.
window.__ModuleLoader__.load({
id: 'dsh-cloud-memory',
factory: (require) => {
var module = { exports: {} }
var exports = module.exports
'use strict'
var React = require('react')
var h = React.createElement
var API = {
status: '/cloud-memory/status',
capabilities: '/cloud-memory/capabilities',
config: '/cloud-memory/config',
login: '/cloud-memory/login',
test: '/cloud-memory/test',
flush: '/cloud-memory/flush',
skills: '/cloud-memory/skills',
}
// The MCP bridge is another plugin's public surface, not ours: it is probed
// at runtime and the tab reports a capability gap when it is missing.
var MCP_BRIDGE = '/mcp-connector/api'
var MCP_PANEL = '/mcp-connector/ui'
var POLL_MS = 10000
var PROBE_TIMEOUT_MS = 5000
var inject = ['slots']
function request(url, init) {
var options = init || {}
options.cache = 'no-store'
options.headers = options.body === undefined
? { accept: 'application/json' }
: { accept: 'application/json', 'content-type': 'application/json' }
return fetch(url, options).then(function (response) {
return response.json().then(
function (body) {
return { status: response.status, body: body }
},
function () {
return { status: response.status, body: null }
},
)
})
}
function postJson(url, payload) {
return request(url, { method: 'POST', body: JSON.stringify(payload === undefined ? {} : payload) })
}
function messageOf(error) {
if (error === null || error === undefined) return '未知错误'
if (typeof error === 'string') return error
return typeof error.message === 'string' ? error.message : String(error)
}
// A 404/405 here means the host half on disk is newer than the one this
// window is talking to: the module is loaded into the running process and
// does not hot-reload, so the answer is a restart, not a retry.
function statusText(status) {
if (status === 404 || status === 405) {
return '插件后端还没加载这个接口(HTTP ' + String(status) + '):请完全退出并重启 DSH 后再试。'
}
return 'HTTP ' + String(status)
}
function bodyError(result, fallback) {
if (result.body !== null && result.body !== undefined && typeof result.body.error === 'string' && result.body.error !== '') {
return result.body.error
}
return fallback === undefined ? statusText(result.status) : fallback
}
function pickSettings(settings) {
var source = settings === undefined || settings === null ? {} : settings
return {
enabled: source.enabled === true,
baseUrl: String(source.baseUrl === undefined ? '' : source.baseUrl),
baseUrlConfigured: source.baseUrlConfigured !== false,
baseUrlOrigin: String(source.baseUrlOrigin === undefined ? '' : source.baseUrlOrigin),
clientId: String(source.clientId === undefined ? '' : source.clientId),
requestTimeoutMs: String(source.requestTimeoutMs === undefined ? 8000 : source.requestTimeoutMs),
defaultK: String(source.defaultK === undefined ? 10 : source.defaultK),
summaryEnabled: source.summaryEnabled === true,
skillsSyncEnabled: source.skillsSyncEnabled === true,
}
}
function emptyTokens() {
return { activity: '', memory: '', summary: '' }
}
function formatTime(value) {
if (typeof value !== 'number' || value <= 0) return '—'
var date = new Date(value)
var pad = function (n) {
return n < 10 ? '0' + String(n) : String(n)
}
return pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds())
}
function formatIso(value) {
if (typeof value !== 'string' || value === '') return '—'
var stamp = Date.parse(value)
if (!Number.isFinite(stamp)) return value
return formatTime(stamp)
}
function formatBytes(value) {
if (typeof value !== 'number' || value < 0) return '—'
if (value < 1024) return String(value) + ' B'
if (value < 1024 * 1024) return (value / 1024).toFixed(1) + ' KB'
return (value / (1024 * 1024)).toFixed(2) + ' MB'
}
function shortHash(value) {
if (typeof value !== 'string' || value === '') return '—'
return value.slice(0, 12)
}
function readStored(key, fallback) {
try {
var raw = window.localStorage.getItem('dsh-cloud-memory:' + key)
return raw === null || raw === '' ? fallback : raw
} catch {
return fallback
}
}
function store(key, value) {
try {
window.localStorage.setItem('dsh-cloud-memory:' + key, String(value))
} catch {
/* a locked-down window keeps the value in memory only */
}
}
var OUTCOME_LABELS = {
recorded: '已上报',
duplicate: '重复忽略',
failed: '失败',
queued: '待重试',
skipped: '已跳过',
}
var OUTCOME_TONES = {
recorded: 'ok',
duplicate: 'muted',
failed: 'bad',
queued: 'warn',
skipped: 'muted',
}
var ORIGIN_LABELS = {
cloud: '云端下发',
uploaded: '本地已上传',
local: '本机安装',
unknown: '来源未知',
}
var CHECK_TONES = {
ok: 'ok',
unconfigured: 'muted',
invalid: 'bad',
forbidden: 'bad',
unreachable: 'bad',
error: 'bad',
}
var CHECK_LABELS = {
ok: '可用',
unconfigured: '未配置',
invalid: '令牌失效',
forbidden: '权限不足',
unreachable: '不可达',
error: '出错',
}
var MCP_STATE_LABELS = {
connected: '已连接',
connecting: '连接中',
disabled: '已停用',
error: '异常',
expired: '授权过期',
unknown: '未知',
needs_auth: '待授权',
}
var styles = {
root: {
display: 'flex',
flexDirection: 'column',
gap: '16px',
padding: '4px 2px 20px',
fontSize: '13px',
lineHeight: 1.55,
minWidth: 0,
},
tabs: {
display: 'flex',
gap: '4px',
padding: '3px',
borderRadius: '12px',
border: '1px solid rgba(127,127,127,0.28)',
background: 'rgba(127,127,127,0.08)',
flexWrap: 'wrap',
},
tab: {
flex: '1 1 auto',
minWidth: '88px',
font: 'inherit',
fontSize: '12.5px',
padding: '6px 12px',
borderRadius: '9px',
border: '1px solid transparent',
background: 'transparent',
color: 'inherit',
cursor: 'pointer',
whiteSpace: 'nowrap',
},
tabActive: {
border: '1px solid rgba(37,99,235,0.5)',
background: 'rgba(37,99,235,0.16)',
fontWeight: 600,
},
section: {
display: 'flex',
flexDirection: 'column',
gap: '10px',
border: '1px solid rgba(127,127,127,0.28)',
borderRadius: '12px',
padding: '14px 16px',
minWidth: 0,
},
sectionHead: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '10px',
flexWrap: 'wrap',
},
sectionTitle: {
margin: 0,
fontSize: '13px',
fontWeight: 600,
letterSpacing: '0.02em',
},
hint: {
margin: 0,
fontSize: '12px',
opacity: 0.65,
},
grid: {
display: 'flex',
flexWrap: 'wrap',
gap: '12px 18px',
},
field: {
display: 'flex',
flexDirection: 'column',
gap: '4px',
flex: '1 1 220px',
minWidth: 0,
},
label: {
fontSize: '12px',
opacity: 0.75,
},
input: {
font: 'inherit',
fontSize: '13px',
padding: '6px 9px',
borderRadius: '8px',
border: '1px solid rgba(127,127,127,0.4)',
background: 'transparent',
color: 'inherit',
minWidth: 0,
width: '100%',
boxSizing: 'border-box',
},
checkboxRow: {
display: 'flex',
alignItems: 'flex-start',
gap: '8px',
},
actions: {
display: 'flex',
gap: '10px',
flexWrap: 'wrap',
alignItems: 'center',
},
button: {
font: 'inherit',
fontSize: '13px',
padding: '6px 16px',
borderRadius: '9px',
border: '1px solid rgba(127,127,127,0.45)',
background: 'transparent',
color: 'inherit',
cursor: 'pointer',
},
buttonPrimary: {
font: 'inherit',
fontSize: '13px',
padding: '6px 16px',
borderRadius: '9px',
border: '1px solid rgba(37,99,235,0.6)',
background: 'rgba(37,99,235,0.16)',
color: 'inherit',
cursor: 'pointer',
fontWeight: 600,
},
buttonDanger: {
font: 'inherit',
fontSize: '13px',
padding: '6px 16px',
borderRadius: '9px',
border: '1px solid rgba(220,38,38,0.6)',
background: 'rgba(220,38,38,0.14)',
color: 'inherit',
cursor: 'pointer',
},
buttonSmall: {
font: 'inherit',
fontSize: '12px',
padding: '3px 10px',
borderRadius: '7px',
border: '1px solid rgba(127,127,127,0.45)',
background: 'transparent',
color: 'inherit',
cursor: 'pointer',
},
pills: {
display: 'flex',
flexWrap: 'wrap',
gap: '8px',
},
pill: {
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
padding: '3px 10px',
borderRadius: '999px',
border: '1px solid rgba(127,127,127,0.35)',
fontSize: '12px',
maxWidth: '100%',
},
table: {
width: '100%',
borderCollapse: 'collapse',
fontSize: '12px',
tableLayout: 'fixed',
},
th: {
textAlign: 'left',
fontWeight: 600,
padding: '4px 8px 4px 0',
borderBottom: '1px solid rgba(127,127,127,0.28)',
whiteSpace: 'nowrap',
},
td: {
padding: '4px 8px 4px 0',
borderBottom: '1px solid rgba(127,127,127,0.14)',
verticalAlign: 'top',
overflowWrap: 'anywhere',
},
mono: {
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
fontSize: '11.5px',
wordBreak: 'break-all',
},
ok: { borderColor: 'rgba(22,163,74,0.55)', background: 'rgba(22,163,74,0.12)' },
bad: { borderColor: 'rgba(220,38,38,0.55)', background: 'rgba(220,38,38,0.12)' },
warn: { borderColor: 'rgba(217,119,6,0.55)', background: 'rgba(217,119,6,0.12)' },
muted: {},
banner: {
padding: '8px 12px',
borderRadius: '10px',
fontSize: '12.5px',
},
row: {
display: 'flex',
flexDirection: 'column',
gap: '6px',
border: '1px solid rgba(127,127,127,0.22)',
borderRadius: '10px',
padding: '10px 12px',
minWidth: 0,
},
rowHead: {
display: 'flex',
alignItems: 'baseline',
justifyContent: 'space-between',
gap: '8px',
flexWrap: 'wrap',
},
rowTitle: {
fontWeight: 600,
overflowWrap: 'anywhere',
},
code: {
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
fontSize: '11.5px',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
maxHeight: '260px',
overflow: 'auto',
margin: 0,
padding: '10px',
borderRadius: '8px',
background: 'rgba(127,127,127,0.1)',
},
chips: {
display: 'flex',
gap: '6px',
flexWrap: 'wrap',
},
chip: {
font: 'inherit',
fontSize: '12px',
padding: '2px 10px',
borderRadius: '999px',
border: '1px solid rgba(127,127,127,0.35)',
background: 'transparent',
color: 'inherit',
cursor: 'pointer',
},
chipActive: {
border: '1px solid rgba(37,99,235,0.6)',
background: 'rgba(37,99,235,0.16)',
},
nested: {
display: 'flex',
flexDirection: 'column',
gap: '8px',
paddingLeft: '12px',
borderLeft: '2px solid rgba(127,127,127,0.2)',
minWidth: 0,
},
}
function Pill(props) {
var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone]
return h(
'span',
{ style: Object.assign({}, styles.pill, tone) },
h('span', { style: { opacity: 0.75 } }, props.label),
h('span', { style: { fontWeight: 600 } }, String(props.value)),
)
}
function Banner(props) {
var tone = styles[props.tone] === undefined ? styles.muted : styles[props.tone]
return h('div', { style: Object.assign({}, styles.banner, tone), role: props.role }, props.children)
}
function Field(props) {
return h(
'label',
{ style: styles.field },
h('span', { style: styles.label }, props.label),
h('input', {
style: styles.input,
type: props.type === undefined ? 'text' : props.type,
value: props.value,
placeholder: props.placeholder === undefined ? '' : props.placeholder,
spellCheck: false,
autoComplete: 'off',
disabled: props.disabled === true,
onChange: function (event) {
props.onChange(event.target.value)
},
}),
props.hint === undefined ? null : h('span', { style: styles.hint }, props.hint),
)
}
function Btn(props) {
var style = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button
return h(
'button',
{
type: 'button',
style: style,
disabled: props.disabled === true,
onClick: props.onClick,
'aria-label': props.ariaLabel,
},
props.label,
)
}
function Switch(props) {
return h(
'div',
{ style: styles.tabs, role: 'tablist', 'aria-label': props.ariaLabel },
props.options.map(function (option) {
var active = option.value === props.value
return h(
'button',
{
key: option.value,
type: 'button',
role: 'tab',
'aria-selected': active,
style: Object.assign({}, styles.tab, active ? styles.tabActive : null),
onClick: function () {
props.onChange(option.value)
},
},
option.label,
)
}),
)
}
function Section(props) {
return h(
'div',
{ style: styles.section },
h(
'div',
{ style: styles.sectionHead },
h('h4', { style: styles.sectionTitle }, props.title),
props.aside === undefined ? null : h('div', { style: styles.actions }, props.aside),
),
props.hint === undefined ? null : h('p', { style: styles.hint }, props.hint),
props.children,
)
}
function findCheck(source, id) {
if (source === null || source === undefined || !Array.isArray(source.checks)) return undefined
for (var index = 0; index < source.checks.length; index += 1) {
if (source.checks[index] !== null && typeof source.checks[index] === 'object' && source.checks[index].id === id) {
return source.checks[index]
}
}
return undefined
}
function SettingsCard() {
var snapshotState = React.useState(null)
var snapshot = snapshotState[0]
var setSnapshot = snapshotState[1]
var draftState = React.useState(null)
var draft = draftState[0]
var setDraft = draftState[1]
var tokenState = React.useState(emptyTokens())
var tokenDraft = tokenState[0]
var setTokenDraft = tokenState[1]
var identityState = React.useState(readStored('identity', 'account'))
var identity = identityState[0]
var setIdentity = identityState[1]
var loginState = React.useState({ username: '', password: '' })
var loginDraft = loginState[0]
var setLoginDraft = loginState[1]
var loginResultState = React.useState(null)
var loginResult = loginResultState[0]
var setLoginResult = loginResultState[1]
var errorState = React.useState(null)
var error = errorState[0]
var setError = errorState[1]
var noticeState = React.useState(null)
var notice = noticeState[0]
var setNotice = noticeState[1]
var testState = React.useState(null)
var testResult = testState[0]
var setTestResult = testState[1]
var busyState = React.useState('')
var busy = busyState[0]
var setBusy = busyState[1]
var tabState = React.useState(readStored('tab', 'connection'))
var tab = tabState[0]
var setTab = tabState[1]
var advancedState = React.useState(readStored('advanced', 'closed') === 'open')
var advanced = advancedState[0]
var setAdvanced = advancedState[1]
var skillsState = React.useState({ status: 'idle', data: null, error: null, detail: null, uninstall: null, plan: null, selection: [], installUrl: '', search: '', filter: 'all', busy: '' })
var skills = skillsState[0]
var setSkills = skillsState[1]
var mcpState = React.useState({ status: 'idle', items: [], error: null, tools: {}, busy: '', confirm: null })
var mcp = mcpState[0]
var setMcp = mcpState[1]
function patchSkills(patch) {
setSkills(function (previous) {
return Object.assign({}, previous, patch)
})
}
function patchMcp(patch) {
setMcp(function (previous) {
return Object.assign({}, previous, patch)
})
}
var load = React.useCallback(
function (keepDraft) {
return request(API.status)
.then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
setError('读取插件状态失败(HTTP ' + String(result.status) + '),请重启 DSH 后再试。')
return
}
setError(null)
setSnapshot(result.body)
if (keepDraft !== true) setDraft(pickSettings(result.body.settings))
})
.catch(function (failure) {
setError('无法连接插件:' + messageOf(failure))
})
},
[],
)
React.useEffect(
function () {
load(false)
var timer = setInterval(function () {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
load(true)
}, POLL_MS)
return function () {
clearInterval(timer)
}
},
[load],
)
var dirty = snapshot !== null && draft !== null && JSON.stringify(draft) !== JSON.stringify(pickSettings(snapshot.settings))
React.useEffect(
function () {
if (!dirty) return undefined
var guard = function (event) {
event.preventDefault()
event.returnValue = '有未保存的改动'
return event.returnValue
}
window.addEventListener('beforeunload', guard)
return function () {
window.removeEventListener('beforeunload', guard)
}
},
[dirty],
)
function patchDraft(patch) {
setDraft(function (previous) {
return Object.assign({}, previous, patch)
})
}
function patchTokens(patch) {
setTokenDraft(function (previous) {
return Object.assign({}, previous, patch)
})
}
function run(label, task) {
setBusy(label)
setNotice(null)
return Promise.resolve()
.then(task)
.catch(function (failure) {
setNotice({ tone: 'bad', text: messageOf(failure) })
})
.then(function () {
setBusy('')
})
}
function save() {
return run('save', function () {
var payload = {
enabled: draft.enabled,
baseUrl: draft.baseUrl,
clientId: draft.clientId,
requestTimeoutMs: Number(draft.requestTimeoutMs),
defaultK: Number(draft.defaultK),
summaryEnabled: draft.summaryEnabled,
}
if (tokenDraft.activity.trim() !== '') payload.activityToken = tokenDraft.activity.trim()
if (tokenDraft.memory.trim() !== '') payload.memoryToken = tokenDraft.memory.trim()
if (tokenDraft.summary.trim() !== '') payload.summaryToken = tokenDraft.summary.trim()
return request(API.config, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error('保存失败:' + bodyError(result))
}
setTokenDraft(emptyTokens())
var cleared = Array.isArray(result.body.credentialsCleared) ? result.body.credentialsCleared : []
setNotice(
cleared.length === 0
? { tone: 'ok', text: '已保存到本机配置文件。' }
: { tone: 'warn', text: '服务地址的 origin 已变更,旧地址的令牌已清除(' + cleared.join('、') + '),请重新登录或填写新令牌。' },
)
setSnapshot(result.body)
setDraft(pickSettings(result.body.settings))
})
})
}
function clearToken(which) {
return run('clear-' + which, function () {
var payload = which === 'activity' ? { clearActivityToken: true } : which === 'memory' ? { clearMemoryToken: true } : { clearSummaryToken: true }
return request(API.config, { method: 'PUT', body: JSON.stringify(payload) }).then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error('清除令牌失败:' + bodyError(result))
}
setNotice({ tone: 'ok', text: '令牌已清除。' })
setSnapshot(result.body)
setDraft(pickSettings(result.body.settings))
})
})
}
function test() {
return run('test', function () {
setTestResult(null)
return request(API.test, { method: 'POST', body: '{}' }).then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error('测试失败(HTTP ' + String(result.status) + ')')
}
setTestResult(result.body)
load(true)
})
})
}
function flush() {
return run('flush', function () {
return request(API.flush, { method: 'POST', body: '{}' }).then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error('重试失败(HTTP ' + String(result.status) + ')')
}
setNotice({ tone: 'ok', text: '已重试 ' + String(result.body.sent) + ' 条,剩余 ' + String(result.body.remaining) + ' 条。' })
load(true)
})
})
}
function login() {
return run('login', function () {
setLoginResult(null)
var payload = { username: loginDraft.username.trim(), password: loginDraft.password }
if (payload.username === '' || payload.password === '') {
throw new Error('请填写用户名和密码')
}
return request(API.login, { method: 'POST', body: JSON.stringify(payload) }).then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error('登录失败:' + bodyError(result))
}
// Drop the password the moment the exchange succeeded.
setLoginDraft({ username: payload.username, password: '' })
setLoginResult(result.body.login || null)
setNotice({
tone: result.body.login !== null && result.body.login !== undefined && result.body.login.partial === true ? 'warn' : 'ok',
text: '登录成功,已写入可用的令牌。',
})
setSnapshot(result.body)
setDraft(pickSettings(result.body.settings))
})
})
}
function switchIdentity(next) {
setIdentity(next)
store('identity', next)
setLoginResult(null)
setNotice(null)
}
function switchTab(next) {
setTab(next)
store('tab', next)
if (next === 'skills' && skills.status === 'idle') loadSkills()
if (next === 'mcp' && mcp.status === 'idle') probeMcp()
}
function toggleAdvanced() {
setAdvanced(function (previous) {
store('advanced', previous ? 'closed' : 'open')
return !previous
})
}
// A panel that opens (or reopens) on the skills/MCP tab must fetch on its
// own: relying on the click handler alone would leave a stale empty view
// after a reload, when the tab is restored from local storage.
React.useEffect(
function () {
if (tab === 'skills' && skills.status === 'idle') void loadSkills()
if (tab === 'mcp' && mcp.status === 'idle') void probeMcp()
},
[tab, skills.status, mcp.status],
)
// ---- skills -------------------------------------------------------
function loadSkills() {
patchSkills({ status: 'loading', error: null })
return request(API.skills + '/api')
.then(function (result) {
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
patchSkills({ status: 'error', error: '读取技能列表失败:' + statusText(result.status) })
return
}
patchSkills({ status: 'ready', data: result.body, error: null })
})
.catch(function (failure) {
patchSkills({ status: 'error', error: '无法读取技能列表:' + messageOf(failure) })
})
}
function skillAction(path, payload, label) {
patchSkills({ busy: label })
return postJson(API.skills + path, payload)
.then(function (result) {
patchSkills({ busy: '' })
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
throw new Error(bodyError(result, statusText(result.status)))
}
return result.body
})
.catch(function (failure) {
patchSkills({ busy: '' })
patchSkills({ error: messageOf(failure) })
setNotice({ tone: 'bad', text: messageOf(failure) })
throw failure
})
}
function openDetail(folder) {
patchSkills({ detail: { folder: folder, data: null, error: null } })
return skillAction('/detail', { folder: folder }, 'detail').then(
function (body) {
patchSkills({ detail: { folder: folder, data: body, error: null } })
},
function () {
patchSkills({ detail: { folder: folder, data: null, error: '无法读取详情' } })
},
)
}
function toggleSkill(folder, enabled) {
return skillAction('/toggle', { folder: folder, enabled: enabled }, 'toggle').then(function (body) {
setNotice({ tone: 'ok', text: body.note === undefined ? '已更新。' : String(body.note) })
return loadSkills()
}, function () {})
}
function planUninstall(folder) {
return skillAction('/uninstall/plan', { folder: folder }, 'uninstall').then(function (body) {
patchSkills({ uninstall: body })
}, function () {})
}
function confirmUninstall() {
if (skills.uninstall === null) return Promise.resolve()
return skillAction('/remove', { folder: skills.uninstall.folder, token: skills.uninstall.token, confirmed: true }, 'remove').then(function (body) {
patchSkills({ uninstall: null })
setNotice({ tone: 'ok', text: '已删除本机技能 ' + String(body.folder) + '(' + String(body.files) + ' 个文件)。' })
return loadSkills()
}, function () {})
}
function prepareInstall() {
var url = String(skills.installUrl).trim()
if (url === '') {
setNotice({ tone: 'bad', text: '请填写 git 仓库地址。' })
return Promise.resolve()
}
return skillAction('/install/plan', { url: url }, 'plan').then(function (body) {
var selection = (body.candidates || [])
.filter(function (candidate) {
return candidate.conflict !== true && candidate.problem === undefined
})
.map(function (candidate) {
return candidate.folder
})
patchSkills({ plan: body, selection: selection })
}, function () {})
}
function commitInstall() {
if (skills.plan === null) return Promise.resolve()
return skillAction('/install/commit', { planId: skills.plan.planId, folders: skills.selection }, 'commit').then(function (body) {
var installed = Array.isArray(body.installed) ? body.installed : []
var skipped = Array.isArray(body.skipped) ? body.skipped : []
patchSkills({ plan: null, selection: [] })
setNotice({
tone: skipped.length === 0 ? 'ok' : 'warn',
text: '已安装 ' + String(installed.length) + ' 个技能' + (skipped.length === 0 ? '。' : ',跳过 ' + String(skipped.length) + ' 个:' + skipped.map(function (item) { return String(item.folder) + '(' + String(item.reason) + ')' }).join('、')),
})
return loadSkills()
}, function () {})
}
function cancelInstall() {
if (skills.plan === null) return Promise.resolve()
return skillAction('/install/cancel', { planId: skills.plan.planId }, 'cancel').then(function () {
patchSkills({ plan: null, selection: [] })
}, function () {})
}
// ---- mcp ----------------------------------------------------------
function mcpCall(method, params) {
var controller = typeof AbortController === 'function' ? new AbortController() : null
var timer = controller === null ? null : setTimeout(function () {
controller.abort()
}, PROBE_TIMEOUT_MS)
return fetch(MCP_BRIDGE, {
method: 'POST',
cache: 'no-store',
headers: { accept: 'application/json', 'content-type': 'application/json' },
body: JSON.stringify({ method: method, params: params === undefined ? {} : params }),
signal: controller === null ? undefined : controller.signal,
})
.then(function (response) {
if (timer !== null) clearTimeout(timer)
return response.json().then(
function (body) {
return { status: response.status, body: body }
},
function () {
return { status: response.status, body: null }
},
)
})
.catch(function (failure) {
if (timer !== null) clearTimeout(timer)
return { status: 0, body: null, error: messageOf(failure) }
})
}
function probeMcp() {
patchMcp({ status: 'probe', error: null })
return mcpCall('status', {}).then(function (result) {
if (result.status === 200 && result.body !== null && result.body.ok === true && result.body.detail !== undefined) {
patchMcp({ status: 'ok', items: Array.isArray(result.body.detail.items) ? result.body.detail.items : [], error: null })
return
}
patchMcp({
status: 'missing',
items: [],
error: result.status === 0 ? '探测超时或连接被拒绝' : '接口返回 HTTP ' + String(result.status) + (result.body !== null && typeof result.body.message === 'string' ? ':' + result.body.message : ''),
})
})
}
function mcpAction(label, method, params) {
patchMcp({ busy: label })
return mcpCall(method, params).then(function (result) {
patchMcp({ busy: '' })
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
var reason = result.body !== null && typeof result.body.message === 'string' ? result.body.message : 'HTTP ' + String(result.status)
setNotice({ tone: 'bad', text: 'MCP 操作失败:' + reason })
return null
}
setNotice({ tone: 'ok', text: 'MCP 操作已完成:' + label })
return result.body
})
}
function loadTools(item) {
return mcpAction('读取工具列表', 'toolsList', { connectorId: item.connectorId, connectionKey: item.key, cachedOnly: true }).then(function (body) {
if (body === null) return
var list = body.detail !== undefined && Array.isArray(body.detail.tools) ? body.detail.tools : Array.isArray(body.tools) ? body.tools : []
patchMcp(function (previous) {
var tools = Object.assign({}, previous.tools)
tools[item.key] = { items: list, at: Date.now() }
return Object.assign({}, previous, { tools: tools })
})
})
}
// ---- render -------------------------------------------------------
if (error !== null && snapshot === null) {
return h(
'div',
{ style: styles.root },
h(Banner, { tone: 'bad' }, error),
h(
'div',
{ style: styles.actions },
h(Btn, {
label: '重新加载',
onClick: function () {
load(false)
},
}),
),
)
}
if (snapshot === null || draft === null) {
return h('div', { style: styles.root }, h('p', { style: styles.hint }, '正在读取云端记忆插件状态…'))
}
var reporter = snapshot.reporter === undefined || snapshot.reporter === null ? {} : snapshot.reporter
var tokens = snapshot.tokens === undefined || snapshot.tokens === null ? { activity: {}, memory: {}, summary: {} } : snapshot.tokens
var caps = snapshot.capabilities === undefined || snapshot.capabilities === null ? { features: {} } : snapshot.capabilities
var features = caps.features === undefined ? {} : caps.features
var checkSource = testResult !== null ? testResult : snapshot.lastCheck === null || snapshot.lastCheck === undefined ? null : snapshot.lastCheck
var recent = Array.isArray(reporter.recent) ? reporter.recent.slice(0, 8) : []
var activityToken = tokens.activity === undefined ? {} : tokens.activity
var memoryToken = tokens.memory === undefined ? {} : tokens.memory
var summaryToken = tokens.summary === undefined ? {} : tokens.summary
var checkedAt = checkSource === null ? '—' : formatTime(checkSource.at === undefined ? checkSource.checkedAt : checkSource.at)
var connectivity = !draft.baseUrlConfigured
? { tone: 'warn', text: '未配置服务' }
: checkSource === null
? { tone: 'muted', text: '未测试' }
: findCheck(checkSource, 'network') === undefined
? { tone: 'muted', text: '未测试' }
: findCheck(checkSource, 'network').state === 'ok'
? { tone: 'ok', text: '可达' }
: { tone: 'bad', text: '不可达' }
var header = h(
'div',
{ style: styles.section, key: 'header' },
h(
'div',
{ style: styles.sectionHead },
h('h4', { style: styles.sectionTitle }, '云端记忆 · v' + String(caps.version === undefined ? '—' : caps.version)),
h(
'div',
{ style: styles.pills },
h(Pill, { label: '连接', value: connectivity.text, tone: connectivity.tone }),
h(Pill, { label: '最后检查', value: checkedAt, tone: 'muted' }),
dirty ? h(Pill, { label: '草稿', value: '未保存', tone: 'warn' }) : null,
),
),
h(
'div',
{ style: styles.pills },
h(Pill, { label: '已上报', value: reporter.recorded === undefined ? 0 : reporter.recorded, tone: 'ok' }),
h(Pill, { label: '待重试', value: reporter.queued === undefined ? 0 : reporter.queued, tone: reporter.queued > 0 ? 'warn' : 'muted' }),
h(Pill, { label: '失败', value: reporter.failed === undefined ? 0 : reporter.failed, tone: reporter.failed > 0 ? 'bad' : 'muted' }),
),
)
var tabBar = h(Switch, {
key: 'tabs',
ariaLabel: '云端记忆管理页签',
value: tab,
onChange: switchTab,
options: [
{ value: 'connection', label: '连接与上报' },
{ value: 'skills', label: '技能管理' },
{ value: 'mcp', label: 'MCP 管理' },
],
})
var noticeBox = notice === null ? null : h(Banner, { tone: notice.tone, role: 'status', key: 'notice' }, notice.text)
var connectionTab = null
if (tab === 'connection') {
var changedOrigin = draft.baseUrlConfigured && draft.baseUrlOrigin !== '' && String(draft.baseUrl) !== '' && String(draft.baseUrl).indexOf(draft.baseUrlOrigin) !== 0
connectionTab = h(
'div',
{ style: styles.root, key: 'connection' },
h(
Section,
{
title: '身份验证',
hint: '两种方式最终更新同一组配置;切换不会清除任何一种方式已保存的凭据,也不会自动发起请求。',
aside: h(Switch, {
ariaLabel: '身份验证方式',
value: identity,
onChange: switchIdentity,
options: [
{ value: 'account', label: '账号登录' },
{ value: 'token', label: '手动令牌' },
],
}),
},
identity === 'account'
? h(
'div',
{ style: styles.nested },
h(
'p',
{ style: styles.hint },
'用云端面板的普通用户账号登录,插件会用一次性会话换取活动与记忆令牌并写入本机。密码只在这一次请求里使用:不保存、不写日志、不回显。',
),
h(
'div',
{ style: styles.grid },
h(Field, {
label: '用户名',
value: loginDraft.username,
placeholder: '云端面板的账号',
onChange: function (value) {
setLoginDraft(function (previous) {
return Object.assign({}, previous, { username: value })
})
},
}),
h(Field, {
label: '密码',
type: 'password',
value: loginDraft.password,
placeholder: '只用于本次换取令牌',
hint: '成功后自动清空',
onChange: function (value) {
setLoginDraft(function (previous) {
return Object.assign({}, previous, { password: value })
})
},
}),
),
h(
'div',
{ style: styles.actions },
h(Btn, {
variant: 'primary',
label: busy === 'login' ? '登录中…' : '登录并获取令牌',
disabled: busy !== '',
onClick: login,
}),
loginResult === null
? null
: h(
'span',
{ style: styles.hint },
'当前账号:' + String(loginResult.user !== undefined && loginResult.user !== null && loginResult.user.username !== undefined ? loginResult.user.username : '未知') + (loginResult.warning === undefined ? '' : '(' + String(loginResult.warning) + ')'),
),
),
)
: h(
'div',
{ style: styles.nested },
h(
'p',
{ style: styles.hint },
'三个令牌各有独立权限:activity:write 只用于上报,memory:write 同时允许检索与写入,summary:write 用于自动摘要(可选)。空值表示不修改;清除是独立动作。',
),
h(
'div',
{ style: styles.grid },
h(Field, {
label: '活动上报令牌(activity:write)',
type: 'password',
value: tokenDraft.activity,
placeholder: activityToken.configured === true ? '已配置 ' + String(activityToken.masked) + ',留空表示不修改' : '未配置',
hint: activityToken.configured === true ? '当前:' + String(activityToken.masked) : undefined,
onChange: function (value) {
patchTokens({ activity: value })
},
}),
h(Field, {
label: '记忆读写令牌(memory:write)',
type: 'password',
value: tokenDraft.memory,
placeholder: memoryToken.configured === true ? '已配置 ' + String(memoryToken.masked) + ',留空表示不修改' : '未配置',
hint: memoryToken.configured === true ? '当前:' + String(memoryToken.masked) : undefined,
onChange: function (value) {
patchTokens({ memory: value })
},
}),
h(Field, {
label: '摘要令牌(summary:write,可选)',
type: 'password',
value: tokenDraft.summary,
placeholder: summaryToken.configured === true ? '已配置 ' + String(summaryToken.masked) + ',留空表示不修改' : '未配置',
hint: summaryToken.configured === true ? '当前:' + String(summaryToken.masked) : undefined,
onChange: function (value) {
patchTokens({ summary: value })
},
}),
),
h(
'div',
{ style: styles.actions },
h(Btn, {
label: '清除上报令牌',
variant: 'small',
disabled: activityToken.configured !== true || busy !== '',
onClick: function () {
clearToken('activity')
},
}),
h(Btn, {
label: '清除记忆令牌',
variant: 'small',
disabled: memoryToken.configured !== true || busy !== '',
onClick: function () {
clearToken('memory')
},
}),
h(Btn, {
label: '清除摘要令牌',
variant: 'small',
disabled: summaryToken.configured !== true || busy !== '',
onClick: function () {
clearToken('summary')
},
}),
),
),
),
h(
Section,
{
title: '服务地址',
hint: '账号登录会把密码发到该地址:仅接受 HTTPS(本机回环除外)。不同 origin 不会复用旧令牌。',
},
h(Field, {
label: '服务地址(baseUrl)',
value: draft.baseUrl,
placeholder: 'https://<你的域名>/api/longmemory',
hint: changedOrigin ? '地址已改成另一个 origin(当前 ' + draft.baseUrlOrigin + '):保存后旧令牌会被清除,需要重新认证。' : '当前 origin:' + (draft.baseUrlOrigin === '' ? '未配置' : draft.baseUrlOrigin),
onChange: function (value) {
patchDraft({ baseUrl: value })
},
}),
advanced
? h(
'div',
{ style: styles.nested },
h(
'div',
{ style: styles.grid },
h(Field, {
label: '客户端标识(client_id)',
value: draft.clientId,
onChange: function (value) {
patchDraft({ clientId: value })
},
}),
h(Field, {
label: '请求超时(毫秒)',
type: 'number',
value: draft.requestTimeoutMs,
onChange: function (value) {
patchDraft({ requestTimeoutMs: value })
},
}),
h(Field, {
label: '单次搜索返回上限',
type: 'number',
value: draft.defaultK,
hint: '只限制一次搜索返回多少条,不限制可搜索的历史范围。默认 10。',
onChange: function (value) {
patchDraft({ defaultK: value })
},
}),
),
h(
'div',
{ style: styles.checkboxRow },
h('input', {
type: 'checkbox',
checked: draft.enabled,
id: 'dsh-cloud-memory-enabled',
onChange: function (event) {
patchDraft({ enabled: event.target.checked })
},
}),
h('label', { htmlFor: 'dsh-cloud-memory-enabled', style: styles.label }, '启用每轮活动上报(只上报时间戳、会话 id 与状态,不上传对话内容)'),
),
h(
'div',
{ style: styles.checkboxRow },
h('input', {
type: 'checkbox',
checked: draft.summaryEnabled,
id: 'dsh-cloud-memory-summary',
onChange: function (event) {
patchDraft({ summaryEnabled: event.target.checked })
},
}),
h('label', { htmlFor: 'dsh-cloud-memory-summary', style: styles.label }, '启用自动摘要(会把该轮对话文本上传为待确认提案;与上面的元数据上报是两件事)'),
),
)
: h(
'div',
{ style: styles.actions },
h(Btn, { label: '高级设置', variant: 'small', onClick: toggleAdvanced }),
),
),
h(
Section,
{
title: '连接与权限检查',
aside: h(
'div',
{ style: styles.actions },
h(Btn, { variant: 'primary', label: busy === 'save' ? '保存中…' : '保存', disabled: busy !== '', onClick: save }),
h(Btn, { label: busy === 'test' ? '测试中…' : '测试连接', disabled: busy !== '', onClick: test }),
h(Btn, {
label: '重试上报队列',
disabled: busy !== '' || reporter.queued === undefined || reporter.queued === 0,
onClick: flush,
}),
),
},
checkSource === null
? h('p', { style: styles.hint }, '还没有检查记录。点「测试连接」做一次只读检查:网络 → 活动权限 → 记忆权限 → 摘要权限。')
: h(
'div',
{ style: styles.pills },
(checkSource.checks || []).map(function (check) {
return h(Pill, {
key: String(check.id),
label: String(check.label === undefined ? check.id : check.label),
value: CHECK_LABELS[check.state] === undefined ? String(check.state) : CHECK_LABELS[check.state],
tone: CHECK_TONES[check.state] === undefined ? 'muted' : CHECK_TONES[check.state],
})
}),
),
checkSource === null
? null
: h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
(checkSource.checks || []).map(function (check) {
return h(
'div',
{
key: 'detail-' + String(check.id),
style: Object.assign({}, styles.banner, styles[CHECK_TONES[check.state]] === undefined ? styles.muted : styles[CHECK_TONES[check.state]]),
},
String(check.label === undefined ? check.id : check.label) + ':' + String(check.message),
)
}),
),
h('p', { style: styles.hint }, '鉴权通过只代表令牌有效,不代表已经成功写入一条上报;两者在下面分开显示。'),
),
h(
Section,
{ title: '最近上报' },
recent.length === 0
? h('p', { style: styles.hint }, '还没有记录。发一条消息让它跑完一轮,这里就会出现一条。')
: h(
'table',
{ style: styles.table },
h('thead', null, h('tr', null, h('th', { style: styles.th }, '时间'), h('th', { style: styles.th }, '结果'), h('th', { style: styles.th }, 'turn_id'))),
h(
'tbody',
null,
recent.map(function (row, index) {
var outcome = String(row.outcome === undefined ? '' : row.outcome)
return h(
'tr',
{ key: String(row.turnId) + ':' + String(index) },
h('td', { style: styles.td }, formatTime(row.at)),
h(
'td',
{ style: styles.td },
h(
'span',
{ style: Object.assign({}, styles.pill, styles[OUTCOME_TONES[outcome]] === undefined ? styles.muted : styles[OUTCOME_TONES[outcome]]) },
OUTCOME_LABELS[outcome] === undefined ? outcome : OUTCOME_LABELS[outcome],
),
),
h('td', { style: Object.assign({}, styles.td, styles.mono) }, String(row.turnId === undefined ? '' : row.turnId)),
)
}),
),
),
reporter.lastError === undefined ? null : h('p', { style: styles.hint }, '最近一次错误:' + String(reporter.lastError)),
),
h(
'p',
{ style: styles.hint },
'配置保存在 ' + String(snapshot.settingsPath === undefined ? '本机配置文件' : snapshot.settingsPath) + '。页面地址 /cloud-memory 仍然可用。',
),
)
}
var skillsTab = null
if (tab === 'skills') {
var skillList = skills.data !== null && Array.isArray(skills.data.skills) ? skills.data.skills : []
var filter = skills.filter
var keyword = String(skills.search).trim().toLowerCase()
var filtered = skillList.filter(function (skill) {
if (filter === 'enabled' && skill.enabled !== true) return false
if (filter === 'disabled' && skill.enabled === true) return false
if (filter === 'cloud' && skill.origin !== 'cloud' && skill.origin !== 'uploaded') return false
if (keyword === '') return true
return (String(skill.folder) + ' ' + String(skill.name) + ' ' + String(skill.description)).toLowerCase().indexOf(keyword) >= 0
})
var detailBox = null
if (skills.detail !== null) {
var detail = skills.detail.data
detailBox = h(
'div',
{ style: styles.row },
h(
'div',
{ style: styles.rowHead },
h('span', { style: styles.rowTitle }, '详情:' + String(skills.detail.folder)),
h(Btn, {
label: '关闭',
variant: 'small',
onClick: function () {
patchSkills({ detail: null })
},
}),
),
detail === null
? h('p', { style: styles.hint }, '正在读取…')
: h(
'div',
{ style: styles.nested },
h(
'div',
{ style: styles.grid },
h(Field, { label: '目录', value: detail.dir, onChange: function () {} }),
h(Field, { label: 'SKILL.md 哈希', value: String(detail.skill !== undefined ? detail.skill.skillSha256 : ''), onChange: function () {} }),
),
h('p', { style: styles.hint }, '文件:' + String(Array.isArray(detail.files) ? detail.files.length : 0) + ' 个,共 ' + formatBytes(detail.totalBytes) + (detail.truncated ? '(SKILL.md 过长,已截断显示)' : '')),
h('pre', { style: styles.code }, String(detail.skillMd === undefined ? '' : detail.skillMd)),
h(
'p',
{ style: styles.hint },
'文件清单:' + (Array.isArray(detail.files) ? detail.files.map(function (file) { return String(file.path) + (file.script ? '(脚本)' : '') }).join('、') : ''),
),
),
)
}
var uninstallBox = null
if (skills.uninstall !== null) {
uninstallBox = h(
'div',
{ style: Object.assign({}, styles.row, styles.warn) },
h('div', { style: styles.rowHead }, h('span', { style: styles.rowTitle }, '卸载确认:' + String(skills.uninstall.folder))),
h(
'p',
{ style: styles.hint },
'将实际删除:' + String(skills.uninstall.dir) + '\n影响:' + String(skills.uninstall.files) + ' 个文件 / ' + formatBytes(skills.uninstall.bytes) + (Array.isArray(skills.uninstall.scripts) && skills.uninstall.scripts.length > 0 ? ';含脚本:' + skills.uninstall.scripts.join('、') : ''),
),
h('p', { style: styles.hint }, String(skills.uninstall.note)),
h(
'div',
{ style: styles.actions },
h(Btn, { variant: 'danger', label: skills.busy === 'remove' ? '删除中…' : '确认删除(不可恢复)', disabled: skills.busy !== '', onClick: confirmUninstall }),
h(Btn, {
label: '取消',
disabled: skills.busy !== '',
onClick: function () {
patchSkills({ uninstall: null })
},
}),
),
)
}
var planBox = null
if (skills.plan !== null) {
var candidates = Array.isArray(skills.plan.candidates) ? skills.plan.candidates : []
planBox = h(
'div',
{ style: styles.row },
h('div', { style: styles.rowHead }, h('span', { style: styles.rowTitle }, '安装预览:' + String(skills.plan.url))),
h(
'p',
{ style: styles.hint },
'计划 ' + String(skills.plan.planId) + ' 有效到 ' + formatTime(skills.plan.expiresAt) + '。默认不勾选冲突项;只安装勾选的技能,来源中的安装脚本不会执行。',
),
h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
candidates.map(function (candidate) {
var selected = skills.selection.indexOf(candidate.folder) >= 0
var blocked = candidate.conflict === true || candidate.problem !== undefined
return h(
'label',
{ key: String(candidate.id), style: styles.checkboxRow },
h('input', {
type: 'checkbox',
checked: selected,
disabled: blocked,
onChange: function (event) {
var next = skills.selection.slice()
var at = next.indexOf(candidate.folder)
if (event.target.checked && at < 0) next.push(candidate.folder)
if (!event.target.checked && at >= 0) next.splice(at, 1)
patchSkills({ selection: next })
},
}),
h(
'span',
{ style: { minWidth: 0 } },
h('span', { style: { fontWeight: 600 } }, String(candidate.name)),
h('span', { style: styles.hint }, ' · ' + String(candidate.folder) + ' · ' + String(candidate.files) + ' 个文件 · ' + formatBytes(candidate.bytes) + (candidate.conflict === true ? ' · 已存在(' + String(candidate.conflictLocation === 'holding' ? '已停用目录' : '技能目录') + '),不覆盖' : '') + (candidate.problem === undefined ? '' : ' · ' + String(candidate.problem)) + (Array.isArray(candidate.scripts) && candidate.scripts.length > 0 ? ' · 含脚本:' + candidate.scripts.join('、') : '')),
),
)
}),
),
h(
'div',
{ style: styles.actions },
h(Btn, {
variant: 'primary',
label: skills.busy === 'commit' ? '安装中…' : '安装所选(' + String(skills.selection.length) + ')',
disabled: skills.busy !== '' || skills.selection.length === 0,
onClick: commitInstall,
}),
h(Btn, { label: '放弃计划', variant: 'small', disabled: skills.busy !== '', onClick: cancelInstall }),
),
)
}
skillsTab = h(
'div',
{ style: styles.root, key: 'skills' },
h(
Section,
{
title: '本机技能',
hint: '启停是把目录移进 / 移出技能目录,属于新会话生效;卸载是真实删除,没有回收站。',
aside: h(Btn, { label: skills.status === 'loading' ? '刷新中…' : '刷新', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }),
},
skills.error === null ? null : h(Banner, { tone: 'bad' }, skills.error),
h(
'div',
{ style: styles.grid },
h(Field, {
label: '搜索',
value: skills.search,
placeholder: '按名称、目录或描述筛选',
onChange: function (value) {
patchSkills({ search: value })
},
}),
),
h(
'div',
{ style: styles.chips, role: 'group', 'aria-label': '技能筛选' },
[
{ value: 'all', label: '全部' },
{ value: 'enabled', label: '已启用' },
{ value: 'disabled', label: '已停用' },
{ value: 'cloud', label: '云端来源' },
].map(function (option) {
return h(
'button',
{
key: option.value,
type: 'button',
style: Object.assign({}, styles.chip, filter === option.value ? styles.chipActive : null),
onClick: function () {
patchSkills({ filter: option.value })
},
},
option.label,
)
}),
),
skills.status === 'loading' && skills.data === null
? h('p', { style: styles.hint }, '正在读取技能目录…')
: filtered.length === 0
? h('p', { style: styles.hint }, skillList.length === 0 ? '技能目录里没有技能。' : '没有符合筛选条件的技能。')
: h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
filtered.map(function (skill) {
return h(
'div',
{ key: String(skill.folder), style: styles.row },
h(
'div',
{ style: styles.rowHead },
h(
'span',
{ style: styles.rowTitle },
String(skill.name) + ' ',
h('span', { style: styles.hint }, '· ' + String(skill.folder)),
),
h(
'div',
{ style: styles.pills },
h(Pill, { label: '状态', value: skill.enabled === true ? '已启用' : '已停用', tone: skill.enabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '来源', value: ORIGIN_LABELS[skill.origin] === undefined ? String(skill.origin) : ORIGIN_LABELS[skill.origin], tone: skill.origin === 'cloud' ? 'warn' : 'muted' }),
skill.revision === undefined ? null : h(Pill, { label: 'revision', value: skill.revision, tone: 'muted' }),
),
),
skill.description === '' ? null : h('p', { style: styles.hint }, String(skill.description)),
h(
'p',
{ style: styles.hint },
String(skill.files) + ' 个文件 · ' + formatBytes(skill.bytes) + ' · 安装于 ' + formatIso(skill.installedAt) + ' · 所有者 ' + String(skill.ownerManager),
),
h(
'div',
{ style: styles.actions },
h(Btn, { label: '详情', variant: 'small', disabled: skills.busy !== '', onClick: function () { openDetail(skill.folder) } }),
h(Btn, {
label: skill.enabled === true ? '停用' : '启用',
variant: 'small',
disabled: skills.busy !== '',
onClick: function () {
toggleSkill(skill.folder, skill.enabled !== true)
},
}),
h(Btn, { label: '卸载…', variant: 'small', disabled: skills.busy !== '', onClick: function () { planUninstall(skill.folder) } }),
),
)
}),
),
),
detailBox,
uninstallBox,
h(
Section,
{
title: '从 Git 仓库安装',
hint: '先克隆到隔离暂存目录并列出候选技能,确认后才写入技能目录;不执行仓库里的任何脚本,符号链接不会跟随。仓库地址只接受 https:// 或 file://。',
},
h(Field, {
label: '仓库地址',
value: skills.installUrl,
placeholder: 'https://github.com/<owner>/<repo>.git',
onChange: function (value) {
patchSkills({ installUrl: value })
},
}),
h(
'div',
{ style: styles.actions },
h(Btn, {
variant: 'primary',
label: skills.busy === 'plan' ? '拉取中…' : '拉取并预览',
disabled: skills.busy !== '',
onClick: prepareInstall,
}),
h(Btn, { label: '刷新列表', variant: 'small', disabled: skills.status === 'loading', onClick: loadSkills }),
),
planBox,
),
h(
Section,
{
title: '技能市场',
hint: '本版没有接入经验证的市场来源,因此不提供搜索与安装入口,也不显示任何示例条目。',
},
h(
'p',
{ style: styles.hint },
features.skillsMarketplace === true
? 'capabilities 报告市场可用。'
: '能力缺口:capabilities.features.skillsMarketplace = false。下一步接入一个来源(MarketProvider:search / getDetail / resolveArtifact / checkUpdates)后再开放。',
),
),
h(
Section,
{
title: '云端同步状态',
hint: '同步仍由现有引擎负责:本地改动与云端改动冲突时会暂停该项,不会被覆盖。',
},
snapshot.skills === undefined || snapshot.skills === null
? h('p', { style: styles.hint }, '同步引擎未启用。')
: h(
'div',
{ style: styles.pills },
h(Pill, { label: '运行中', value: snapshot.skills.running === true ? '是' : '否', tone: snapshot.skills.running === true ? 'warn' : 'muted' }),
h(Pill, { label: '上次运行', value: formatIso(snapshot.skills.lastRunAt), tone: 'muted' }),
h(Pill, { label: '下载', value: (snapshot.skills.downloaded || []).length, tone: 'muted' }),
h(Pill, { label: '上传', value: (snapshot.skills.uploaded || []).length, tone: 'muted' }),
h(Pill, { label: '冲突', value: (snapshot.skills.conflicts || []).length, tone: (snapshot.skills.conflicts || []).length > 0 ? 'warn' : 'muted' }),
),
snapshot.skills === undefined || snapshot.skills === null || snapshot.skills.lastError === undefined
? null
: h('p', { style: styles.hint }, '最近一次同步错误:' + String(snapshot.skills.lastError)),
),
)
}
var mcpTab = null
if (tab === 'mcp') {
var items = Array.isArray(mcp.items) ? mcp.items : []
var bridgeBox = null
if (mcp.status === 'missing') {
bridgeBox = h(
Banner,
{ tone: 'warn' },
'MCP 管理当前不可用:没有探测到宿主 dsh-mcp-connector 的公开接口(' + MCP_BRIDGE + ')。' + (mcp.error === null ? '' : '原因:' + String(mcp.error)) + '。自定义 MCP Server 的权威位置仍是「设置 → 插件配置 → MCP 服务器配置」,本卡不会修改它的托管配置。',
)
}
mcpTab = h(
'div',
{ style: styles.root, key: 'mcp' },
h(
Section,
{
title: '我的连接',
hint: '数据来自宿主 dsh-mcp-connector 插件(同一 origin 的公开接口);本卡不保存任何 MCP 凭据,也不回显启动命令与密钥。',
aside: h(Btn, { label: mcp.status === 'probe' ? '探测中…' : '重新探测', variant: 'small', disabled: mcp.busy !== '', onClick: probeMcp }),
},
bridgeBox,
mcp.status === 'ok' && items.length === 0 ? h('p', { style: styles.hint }, '宿主还没有登记任何 MCP 连接。') : null,
mcp.status === 'ok'
? h(
'div',
{ style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
items.map(function (item) {
var state = String(item.connectionState === undefined ? 'unknown' : item.connectionState)
var tools = mcp.tools[item.key]
return h(
'div',
{ key: String(item.key), style: styles.row },
h(
'div',
{ style: styles.rowHead },
h('span', { style: styles.rowTitle }, String(item.name === undefined ? item.key : item.name)),
h(
'div',
{ 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.injectionLabel === undefined ? '—' : item.injectionLabel), tone: 'muted' }),
),
),
h(
'p',
{ 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(
'div',
{ style: styles.actions },
h(Btn, {
label: '健康检查',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('健康检查 ' + String(item.name), 'healthCheck', { connectorId: item.connectorId }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '工具列表',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
loadTools(item)
},
}),
h(Btn, {
label: item.enabled === false ? '启用' : '停用',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction(item.enabled === false ? '启用连接' : '停用连接', 'setEnabled', { key: item.key, enabled: item.enabled === false }).then(function () {
probeMcp()
})
},
}),
h(Btn, {
label: '重连',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('重连', 'reconnect', { key: item.key }).then(function () {
probeMcp()
})
},
}),
mcp.confirm === item.key
? h(Btn, {
label: '确认移除',
variant: 'danger',
disabled: mcp.busy !== '',
onClick: function () {
mcpAction('移除连接', 'disconnect', { key: item.key }).then(function () {
patchMcp({ confirm: null })
probeMcp()
})
},
})
: h(Btn, {
label: '移除连接…',
variant: 'small',
disabled: mcp.busy !== '',
onClick: function () {
patchMcp({ confirm: item.key })
setNotice({ tone: 'warn', text: '再次点击「确认移除」才会断开该连接定义。' })
},
}),
),
tools === undefined
? null
: h(
'div',
{ style: styles.nested },
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 }, '工具可见不等于业务可调用:连接状态与工具缓存分开显示。'),
)
: null,
),
h(
Section,
{
title: 'MCP 市场',
hint: '目录浏览与安装仍由宿主插件负责;本卡只在能确认其公开接口时提供跳转,不以内嵌面板冒充完成。',
},
h('p', { style: styles.hint }, '宿主 MCP 面板地址:' + MCP_PANEL + '(由 dsh-mcp-connector 提供)。目录条目、示例与远端文本都视为不可信内容。'),
),
)
}
return h(
'div',
{ style: styles.root },
header,
tabBar,
noticeBox,
error === null ? null : h(Banner, { tone: 'bad' }, error),
tab === 'connection' ? connectionTab : tab === 'skills' ? skillsTab : mcpTab,
)
}
// A thrown render error must not take the settings page down with it, so the
// card is wrapped in a minimal boundary that renders the message instead.
function CardBoundary(props) {
React.Component.call(this, props)
this.state = { failure: null }
}
CardBoundary.prototype = Object.create(React.Component.prototype)
CardBoundary.prototype.constructor = CardBoundary
CardBoundary.getDerivedStateFromError = function (failure) {
return { failure: failure }
}
CardBoundary.prototype.render = function () {
if (this.state.failure !== null) {
return h(
'div',
{ style: Object.assign({}, styles.root) },
h('div', { style: Object.assign({}, styles.banner, styles.bad) }, '云端记忆设置卡渲染失败:' + messageOf(this.state.failure)),
h('p', { style: styles.hint }, '插件本身仍在运行,可改用 /cloud-memory 页面配置。'),
)
}
return this.props.children
}
function apply(ctx) {
var card = function () {
return h(CardBoundary, null, h(SettingsCard, null))
}
var register = function (seat, options) {
try {
ctx.slots.inject(seat, function () {
return ctx.slots.register(options, card)
})
} catch (failure) {
if (typeof console !== 'undefined') console.warn('[dsh-cloud-memory] slot ' + seat + ' unavailable: ' + messageOf(failure))
}
}
register('settings.section', {
name: 'settings.section',
id: 'cloud-memory',
order: 100,
label: function () {
return '云端记忆'
},
})
register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-cloud-memory' })
}
module.exports = { apply: apply, inject: inject, name: 'dsh-cloud-memory' }
return module.exports
},
})