build(client): migrate hand-written bundle to tsdown with equivalent output
This commit is contained in:
parent
3703a4458c
commit
dfe31ac3f8
7871
client/index.js
7871
client/index.js
File diff suppressed because it is too large
Load Diff
|
|
@ -38,10 +38,11 @@
|
|||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"build": "tsc -p tsconfig.build.json && tsdown",
|
||||
"build:client": "tsdown",
|
||||
"verify": "node scripts/verify-all.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"prepack": "tsc -p tsconfig.build.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
|
||||
"prepack": "tsc -p tsconfig.build.json && tsdown",
|
||||
"prepublishOnly": "node scripts/pack-guard.mjs",
|
||||
"test": "node scripts/verify-all.mjs"
|
||||
},
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,95 @@
|
|||
// dsh-brain client API helpers.
|
||||
// Adapted from the original hand-written client bundle (dsh-brain).
|
||||
export const API = {
|
||||
status: '/dsh-brain/status',
|
||||
capabilities: '/dsh-brain/capabilities',
|
||||
config: '/dsh-brain/config',
|
||||
login: '/dsh-brain/login',
|
||||
test: '/dsh-brain/test',
|
||||
flush: '/dsh-brain/flush',
|
||||
skills: '/dsh-brain/skills',
|
||||
market: '/dsh-brain/market',
|
||||
sync: '/dsh-brain/sync',
|
||||
clients: '/dsh-brain/clients',
|
||||
migrate: '/dsh-brain/migrate',
|
||||
}
|
||||
|
||||
// ---- MCP bundle (browser bridge) ---------------------------------------
|
||||
// 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.
|
||||
// This bundle owns the tab, the request envelope, the probe timeout and
|
||||
// the host-unavailable state; connections, credentials, tool management
|
||||
// and any cloud-side sync belong to the host dsh-mcp-connector plugin.
|
||||
|
||||
export 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 }
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function postJson(url, payload?) {
|
||||
return request(url, { method: 'POST', body: JSON.stringify(payload === undefined ? {} : payload) })
|
||||
}
|
||||
|
||||
export function messageOf(error) {
|
||||
if (error === null || error === undefined) return '未知错误'
|
||||
if (typeof error === 'string') return error
|
||||
return typeof error.message === 'string' ? error.message : String(error)
|
||||
}
|
||||
|
||||
// One POST to the host MCP bridge. Used by the self-contained MCP panels
|
||||
// below; the dispatcher whitelist lives in dsh-mcp-connector.
|
||||
|
||||
export function statusText(status) {
|
||||
if (status === 404 || status === 405) {
|
||||
return '插件后端还没加载这个接口(HTTP ' + String(status) + '):请完全退出并重启 DSH 后再试。'
|
||||
}
|
||||
return 'HTTP ' + String(status)
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
// ---- settings-ui bundle (configuration surface) ----
|
||||
// pickSettings + the SettingsCard draft/save/login/test/flush logic and the
|
||||
// 连接与上报 tab belong to the settings-ui bundle; the skills/mcp tabs
|
||||
// belong to their own bundles. The card only talks to the public HTTP API —
|
||||
// it never touches SettingsStore/CloudClient/Reporter/SkillSync directly.
|
||||
export 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,
|
||||
activityEnabled: source.activityEnabled === true,
|
||||
memoryEnabled: source.memoryEnabled === true,
|
||||
skillsDir: String(source.skillsDir === undefined ? '' : source.skillsDir),
|
||||
skillsSyncEnabled: source.skillsSyncEnabled === true,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyTokens() {
|
||||
return { activity: '', memory: '', summary: '' }
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
// Host MCP bridge helpers (dsh-mcp-connector public surface).
|
||||
import { messageOf } from './api'
|
||||
export const MCP_BRIDGE = '/mcp-connector/api'
|
||||
export const MCP_PANEL = '/mcp-connector/ui'
|
||||
export const POLL_MS = 10000
|
||||
export const PROBE_TIMEOUT_MS = 5000
|
||||
|
||||
|
||||
export function bridgeCall(method, params) {
|
||||
var controller = typeof AbortController === 'function' ? new AbortController() : null
|
||||
var timer = controller === null ? null : setTimeout(function () { controller.abort() }, 20000)
|
||||
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 } },
|
||||
)
|
||||
}, function (failure) {
|
||||
if (timer !== null) clearTimeout(timer)
|
||||
return { status: 0, body: null, error: messageOf(failure) }
|
||||
})
|
||||
}
|
||||
|
||||
export function bridgeMessage(result) {
|
||||
if (result.body !== null && typeof result.body.message === 'string' && result.body.message !== '') return result.body.message
|
||||
return 'HTTP ' + String(result.status) + (result.error === undefined ? '' : ':' + result.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.
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
// dsh-brain client basic components.
|
||||
import * as React from 'react'
|
||||
import { messageOf } from './api'
|
||||
import { styles } from './styles'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export 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)),
|
||||
)
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
|
||||
export 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),
|
||||
)
|
||||
}
|
||||
|
||||
export function Btn(props) {
|
||||
var base = props.variant === 'primary' ? styles.buttonPrimary : props.variant === 'danger' ? styles.buttonDanger : props.variant === 'small' ? styles.buttonSmall : styles.button
|
||||
var style = props.disabled === true ? Object.assign({}, base, { opacity: 0.45, cursor: 'not-allowed' }) : base
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
style: style,
|
||||
disabled: props.disabled === true,
|
||||
onClick: props.onClick,
|
||||
'aria-label': props.ariaLabel,
|
||||
},
|
||||
props.label,
|
||||
)
|
||||
}
|
||||
|
||||
export function IconBtn(props) {
|
||||
var style = Object.assign({}, styles.iconBtn, props.danger === true ? styles.iconBtnDanger : null, props.disabled === true ? { opacity: 0.45, cursor: 'not-allowed' } : null)
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
style: style,
|
||||
disabled: props.disabled === true,
|
||||
onClick: props.disabled === true ? undefined : props.onClick,
|
||||
'aria-label': props.ariaLabel,
|
||||
title: props.ariaLabel,
|
||||
},
|
||||
props.glyph,
|
||||
)
|
||||
}
|
||||
|
||||
export 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,
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// A real switch, not a checkbox: the tree rows are dense and the state has
|
||||
// to be readable at a glance in both themes.
|
||||
export function Toggle(props) {
|
||||
var on = props.checked === true
|
||||
var disabled = props.disabled === true
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'switch',
|
||||
'aria-checked': on,
|
||||
'aria-label': props.label,
|
||||
title: props.label,
|
||||
disabled: disabled,
|
||||
style: {
|
||||
width: '38px',
|
||||
height: '22px',
|
||||
flex: '0 0 auto',
|
||||
padding: '2px',
|
||||
borderRadius: '999px',
|
||||
border: '1px solid ' + (on ? 'rgba(0,0,0,0.25)' : 'rgba(127,127,127,0.45)'),
|
||||
background: on ? '#3f3f46' : 'rgba(127,127,127,0.28)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: on ? 'flex-end' : 'flex-start',
|
||||
cursor: disabled ? 'not-allowed' : 'pointer',
|
||||
opacity: disabled ? 0.45 : 1,
|
||||
transition: 'background 120ms ease',
|
||||
},
|
||||
onClick: disabled ? undefined : props.onChange,
|
||||
},
|
||||
h('span', {
|
||||
style: {
|
||||
width: '16px',
|
||||
height: '16px',
|
||||
borderRadius: '999px',
|
||||
background: 'rgba(255,255,255,0.96)',
|
||||
boxShadow: '0 1px 2px rgba(0,0,0,0.25)',
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export 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,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
export 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 }, '插件本身仍在运行,可改用 /dsh-brain 页面配置。'),
|
||||
)
|
||||
}
|
||||
return this.props.children
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
// dsh-brain client formatting helpers and label tables.
|
||||
export 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())
|
||||
}
|
||||
|
||||
export function formatIso(value) {
|
||||
if (typeof value !== 'string' || value === '') return '—'
|
||||
var stamp = Date.parse(value)
|
||||
if (!Number.isFinite(stamp)) return value
|
||||
return formatTime(stamp)
|
||||
}
|
||||
|
||||
export 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'
|
||||
}
|
||||
|
||||
export function shortHash(value) {
|
||||
if (typeof value !== 'string' || value === '') return '—'
|
||||
return value.slice(0, 12)
|
||||
}
|
||||
|
||||
export function readStored(key, fallback) {
|
||||
try {
|
||||
var raw = window.localStorage.getItem('dsh-brain:' + key)
|
||||
if (raw === null || raw === '') raw = window.localStorage.getItem('dsh-cloud-memory:' + key)
|
||||
return raw === null || raw === '' ? fallback : raw
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function store(key, value) {
|
||||
try {
|
||||
window.localStorage.setItem('dsh-brain:' + key, String(value))
|
||||
} catch {
|
||||
/* a locked-down window keeps the value in memory only */
|
||||
}
|
||||
}
|
||||
|
||||
export const OUTCOME_LABELS = {
|
||||
recorded: '已上报',
|
||||
duplicate: '重复忽略',
|
||||
failed: '失败',
|
||||
queued: '待重试',
|
||||
skipped: '已跳过',
|
||||
}
|
||||
|
||||
export const OUTCOME_TONES = {
|
||||
recorded: 'ok',
|
||||
duplicate: 'muted',
|
||||
failed: 'bad',
|
||||
queued: 'warn',
|
||||
skipped: 'muted',
|
||||
}
|
||||
|
||||
export const ORIGIN_LABELS = {
|
||||
cloud: '云端下发',
|
||||
uploaded: '本地已上传',
|
||||
local: '本机安装',
|
||||
unknown: '来源未知',
|
||||
}
|
||||
|
||||
export const CHECK_TONES = {
|
||||
ok: 'ok',
|
||||
unconfigured: 'muted',
|
||||
invalid: 'bad',
|
||||
forbidden: 'bad',
|
||||
unreachable: 'bad',
|
||||
error: 'bad',
|
||||
}
|
||||
|
||||
export const CHECK_LABELS = {
|
||||
ok: '可用',
|
||||
unconfigured: '未配置',
|
||||
invalid: '令牌失效',
|
||||
forbidden: '权限不足',
|
||||
unreachable: '不可达',
|
||||
error: '出错',
|
||||
}
|
||||
|
||||
export const MCP_STATE_LABELS = {
|
||||
connected: '已连接',
|
||||
connecting: '连接中',
|
||||
disabled: '已停用',
|
||||
error: '异常',
|
||||
expired: '授权过期',
|
||||
unknown: '未知',
|
||||
needs_auth: '待授权',
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
// dsh-brain client bundle entry — the __ModuleLoader__ module contract.
|
||||
import * as React from 'react'
|
||||
import { messageOf } from './api'
|
||||
import { CardBoundary } from './components'
|
||||
import { SettingsCard } from './SettingsCard'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export const inject = ['slots']
|
||||
|
||||
export function apply(ctx: any): void {
|
||||
const card = function () {
|
||||
return h(CardBoundary as any, null, h(SettingsCard as any, null))
|
||||
}
|
||||
|
||||
const register = function (seat: string, options: any) {
|
||||
try {
|
||||
ctx.slots.inject(seat, function () {
|
||||
return ctx.slots.register(options, card)
|
||||
})
|
||||
} catch (failure) {
|
||||
if (typeof console !== 'undefined') console.warn('[dsh-brain] slot ' + seat + ' unavailable: ' + messageOf(failure))
|
||||
}
|
||||
}
|
||||
|
||||
register('settings.section', {
|
||||
name: 'settings.section',
|
||||
id: 'dsh-brain',
|
||||
order: 100,
|
||||
label: function () {
|
||||
return '云端记忆'
|
||||
},
|
||||
})
|
||||
|
||||
register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-brain' })
|
||||
}
|
||||
|
||||
export const name = 'dsh-brain'
|
||||
|
|
@ -0,0 +1,301 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function ImportSection(props) {
|
||||
var onImported = props && typeof props.onImported === 'function' ? props.onImported : null
|
||||
var tuple = React.useState({ expanded: false, status: 'idle', sources: [], open: {}, busy: '', notice: null, imported: {}, search: '', selection: [], progress: null })
|
||||
var s = tuple[0]
|
||||
var set = tuple[1]
|
||||
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
function load() {
|
||||
patch({ status: 'loading', notice: null })
|
||||
request(API.skills + '/sources', { method: 'GET' }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
patch({ status: 'ready', sources: Array.isArray(res.body.sources) ? res.body.sources : [] })
|
||||
} else patch({ status: 'error', notice: { tone: 'bad', text: bodyError(res, '读取来源失败') } })
|
||||
}, function (error) { patch({ status: 'error', notice: { tone: 'bad', text: messageOf(error) } }) })
|
||||
}
|
||||
function openPanel() {
|
||||
patch({ expanded: true })
|
||||
if (s.status === 'idle' || s.status === 'error') load()
|
||||
}
|
||||
function closePanel() {
|
||||
patch({ expanded: false })
|
||||
}
|
||||
function dshFolders() {
|
||||
var found = {}
|
||||
s.sources.forEach(function (source) {
|
||||
if (!source.writable) return
|
||||
var groups = source.groups || []
|
||||
groups.forEach(function (group) {
|
||||
var skills = group.skills || []
|
||||
skills.forEach(function (skill) { found[skill.folder] = true })
|
||||
})
|
||||
})
|
||||
return found
|
||||
}
|
||||
function toggleSource(sourceId) {
|
||||
var next = Object.assign({}, s.open)
|
||||
var open = s.open[sourceId] !== false
|
||||
next[sourceId] = !open
|
||||
patch({ open: next })
|
||||
}
|
||||
var mine = dshFolders()
|
||||
var others = s.sources.filter(function (source) { return !source.writable })
|
||||
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) {
|
||||
done += 1
|
||||
importedMap[entry.skill.folder] = true
|
||||
} 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()
|
||||
load()
|
||||
})
|
||||
}
|
||||
if (!s.expanded) {
|
||||
return h(
|
||||
'div',
|
||||
{ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' } },
|
||||
h(Btn, {
|
||||
label: '从其他软件导入',
|
||||
ariaLabel: '从其他软件导入',
|
||||
onClick: openPanel,
|
||||
}),
|
||||
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
|
||||
)
|
||||
}
|
||||
function describe(skill) {
|
||||
var text = String(skill.description === undefined || skill.description === null ? '' : skill.description).trim()
|
||||
if (/^[>|][+-]?$/.test(text)) return ''
|
||||
return text
|
||||
}
|
||||
var blocks = others.map(function (source) {
|
||||
var all = skillsOf(source)
|
||||
var visible = matches.filter(function (entry) { return entry.source.id === source.id })
|
||||
var open = s.open[source.id] !== false
|
||||
var selectable = visible.filter(function (entry) { return !importedYet(entry.skill) })
|
||||
return h('div', { key: source.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '8px', minWidth: 0 } },
|
||||
h('span', { style: styles.sourceGlyph }, String(source.label).slice(0, 1)),
|
||||
h('span', { style: styles.sourceTitle }, String(source.label)),
|
||||
h(
|
||||
'span',
|
||||
{ style: styles.hint },
|
||||
source.exists
|
||||
? String(all.length) + ' 个技能' + (needle === '' ? '' : ' · 匹配 ' + String(visible.length)) + ' · 可导入 ' + String(selectable.length)
|
||||
: '未安装',
|
||||
),
|
||||
),
|
||||
source.exists
|
||||
? h('div', { style: styles.actions },
|
||||
h(Btn, {
|
||||
label: '全选本来源(' + String(selectable.length) + ')',
|
||||
ariaLabel: '全选本来源 ' + String(source.label),
|
||||
variant: 'small',
|
||||
disabled: selectable.length === 0 || s.busy !== '',
|
||||
onClick: function () { chooseMany(visible, true) },
|
||||
}),
|
||||
h(Btn, { label: open ? '收起' : '展开', variant: 'small', onClick: function () { toggleSource(source.id) } }),
|
||||
)
|
||||
: 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(
|
||||
Section,
|
||||
{
|
||||
title: '从其他软件导入',
|
||||
hint: '把其他软件技能目录里的技能复制一份到 DSH,原目录不动;同名技能不能重复导入。',
|
||||
aside: h(
|
||||
'div',
|
||||
{ style: styles.actions },
|
||||
h(Btn, { label: '刷新', variant: 'small', onClick: load }),
|
||||
h(Btn, { label: '收起', variant: 'small', onClick: closePanel }),
|
||||
),
|
||||
},
|
||||
s.status === 'loading' ? h('p', { style: styles.hint }, '正在读取来源…')
|
||||
: others.length === 0 ? h('p', { style: styles.hint }, '没有检测到其他软件的技能目录。')
|
||||
: 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),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function MarketSection(props) {
|
||||
var capabilities = props.capabilities || {}
|
||||
var tuple = React.useState({
|
||||
providers: null, provider: '', query: '', entries: [], nextCursor: null, cursor: 0,
|
||||
status: 'idle', error: null, detail: null, plan: null, selected: {}, busy: '', notice: null,
|
||||
})
|
||||
var state = tuple[0]
|
||||
var setState = tuple[1]
|
||||
function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
var available = capabilities.features !== undefined && capabilities.features.skillsMarketplace === true
|
||||
|
||||
React.useEffect(function () {
|
||||
if (available) loadProviders()
|
||||
}, [])
|
||||
|
||||
function loadProviders() {
|
||||
request(API.market + '/providers', { method: 'GET' }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var list = Array.isArray(res.body.providers) ? res.body.providers : []
|
||||
patch({ providers: list, provider: state.provider !== '' ? state.provider : (list.length > 0 ? list[0].id : '') })
|
||||
} else {
|
||||
patch({ error: bodyError(res, '读取市场来源失败') })
|
||||
}
|
||||
}, function (error) { patch({ error: messageOf(error) }) })
|
||||
}
|
||||
function search(append) {
|
||||
if (state.provider === '') return
|
||||
var cursor = append === true ? state.cursor : 0
|
||||
patch({ busy: 'search', error: null, status: 'loading' })
|
||||
var url = API.market + '/search?provider=' + encodeURIComponent(state.provider) + '&q=' + encodeURIComponent(state.query) + '&cursor=' + String(cursor)
|
||||
request(url, { method: 'GET' }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var entries = append === true ? state.entries.concat(res.body.entries || []) : (res.body.entries || [])
|
||||
patch({ entries: entries, nextCursor: res.body.nextCursor === undefined ? null : res.body.nextCursor, cursor: res.body.nextCursor === undefined ? cursor : res.body.nextCursor, status: 'ready', busy: '', detail: null, plan: null })
|
||||
} else {
|
||||
patch({ status: 'error', busy: '', error: bodyError(res, '市场搜索失败') })
|
||||
}
|
||||
}, function (error) { patch({ status: 'error', busy: '', error: messageOf(error) }) })
|
||||
}
|
||||
function openDetail(entry) {
|
||||
patch({ busy: 'detail', detail: null, plan: null, notice: null })
|
||||
postJson(API.market + '/detail', { provider: state.provider, id: entry.id }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) patch({ detail: res.body, busy: '' })
|
||||
else patch({ busy: '', error: bodyError(res, '读取条目详情失败') })
|
||||
}, function (error) { patch({ busy: '', error: messageOf(error) }) })
|
||||
}
|
||||
function makePlan() {
|
||||
if (state.detail === null) return
|
||||
patch({ busy: 'plan', plan: null, notice: null })
|
||||
postJson(API.market + '/plan', { provider: state.provider, id: state.detail.id }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var selected = {}
|
||||
;(res.body.candidates || []).forEach(function (candidate) {
|
||||
if (candidate.conflict !== true && candidate.problem === undefined) selected[candidate.folder] = true
|
||||
})
|
||||
patch({ plan: res.body, selected: selected, busy: '' })
|
||||
} else patch({ busy: '', error: bodyError(res, '无法生成安装计划') })
|
||||
}, function (error) { patch({ busy: '', error: messageOf(error) }) })
|
||||
}
|
||||
function toggleFolder(folder) {
|
||||
var next = Object.assign({}, state.selected)
|
||||
next[folder] = next[folder] !== true
|
||||
patch({ selected: next })
|
||||
}
|
||||
function commitPlan() {
|
||||
if (state.plan === null) return
|
||||
var folders = Object.keys(state.selected).filter(function (folder) { return state.selected[folder] === true })
|
||||
if (folders.length === 0) { patch({ notice: { tone: 'warn', text: '请至少选中一个技能。' } }); return }
|
||||
patch({ busy: 'commit' })
|
||||
postJson(API.market + '/commit', { planId: state.plan.planId, folders: folders }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var skipped = Array.isArray(res.body.skipped) ? res.body.skipped.length : 0
|
||||
patch({ busy: '', plan: null, detail: null, notice: { tone: 'ok', text: '已安装:' + ((res.body.installed || []).join('、') || '无') + (skipped > 0 ? ';跳过 ' + skipped + ' 项' : '') } })
|
||||
if (typeof props.onInstalled === 'function') props.onInstalled()
|
||||
} else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '安装失败') } })
|
||||
}, function (error) { patch({ busy: '', notice: { tone: 'bad', text: messageOf(error) } }) })
|
||||
}
|
||||
|
||||
if (!available) {
|
||||
return h(Section, { title: '技能市场', hint: '本版没有配置经验证的市场来源。' },
|
||||
h('p', { style: styles.hint }, '能力缺口:capabilities.features.skillsMarketplace = false,因此不显示任何搜索框或示例条目。'))
|
||||
}
|
||||
var providerLabel = state.provider
|
||||
if (state.providers !== null) {
|
||||
state.providers.forEach(function (provider) { if (provider.id === state.provider) providerLabel = provider.label })
|
||||
}
|
||||
var resultRows = state.entries.map(function (entry) {
|
||||
return h('div', { key: entry.id, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, entry.name),
|
||||
h('div', { style: styles.pills },
|
||||
entry.version === undefined ? null : h(Pill, { label: '版本', value: String(entry.version), tone: 'muted' }),
|
||||
h(Pill, { label: '技能', value: (entry.skills || []).length, tone: 'muted' }),
|
||||
entry.author === undefined ? null : h(Pill, { label: '作者', value: String(entry.author), tone: 'muted' }),
|
||||
),
|
||||
),
|
||||
h('p', { style: styles.hint }, entry.description === '' ? '(无描述)' : entry.description),
|
||||
h('div', { style: styles.actions }, h(Btn, { label: '查看详情', variant: 'small', disabled: state.busy !== '', onClick: function () { openDetail(entry) } })),
|
||||
)
|
||||
})
|
||||
var detailBox = null
|
||||
if (state.detail !== null) {
|
||||
var details = Array.isArray(state.detail.skillDetails) ? state.detail.skillDetails : []
|
||||
detailBox = h('div', { style: styles.nested },
|
||||
h('p', { style: styles.hint }, '来源:' + String(state.detail.sourceRepo) + ' · ' + (state.detail.description || '')),
|
||||
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
|
||||
details.map(function (skill) {
|
||||
return h('div', { key: skill.folder, style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, skill.name === undefined ? skill.folder : skill.name),
|
||||
h('span', { style: styles.hint }, skill.ok === false ? '(无法读取 SKILL.md)' : String(skill.description || '')),
|
||||
)
|
||||
}),
|
||||
),
|
||||
h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: state.busy === 'plan' ? '拉取中…' : '拉取安装计划', disabled: state.busy !== '', onClick: makePlan })),
|
||||
)
|
||||
}
|
||||
var planBox = null
|
||||
if (state.plan !== null) {
|
||||
var candidates = Array.isArray(state.plan.candidates) ? state.plan.candidates : []
|
||||
planBox = h('div', { style: styles.nested },
|
||||
h('p', { style: styles.hint }, '已固定提交:' + (state.plan.commit === undefined ? '克隆时记录实际提交' : String(state.plan.commit).slice(0, 12)) + ';只安装勾选项,冲突项默认不勾,不执行仓库脚本。'),
|
||||
candidates.length === 0 ? h('p', { style: styles.hint }, '该条目没有可安装的技能。') : null,
|
||||
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '6px' } },
|
||||
candidates.map(function (candidate) {
|
||||
return h('label', { key: candidate.folder, style: styles.checkboxRow },
|
||||
h('input', { type: 'checkbox', checked: state.selected[candidate.folder] === true, disabled: candidate.conflict === true || candidate.problem !== undefined, onChange: function () { toggleFolder(candidate.folder) } }),
|
||||
h('span', null, candidate.folder + ' · ' + String(candidate.files) + ' 个文件 · ' + formatBytes(candidate.bytes) + (candidate.conflict === true ? ' · 已存在,跳过' : '') + (candidate.problem === undefined ? '' : ' · ' + candidate.problem)),
|
||||
)
|
||||
}),
|
||||
),
|
||||
h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: state.busy === 'commit' ? '安装中…' : '安装选中', disabled: state.busy !== '', onClick: commitPlan })),
|
||||
)
|
||||
}
|
||||
return h(Section, { title: '技能市场', hint: '来自经验证的公开市场清单;安装走暂存计划、只装勾选项并固定提交。' },
|
||||
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: '来源', value: String(providerLabel || '未配置'), tone: 'muted' }),
|
||||
state.providers === null ? null : h(Pill, { label: '已接入', value: state.providers.length, tone: 'ok' }),
|
||||
),
|
||||
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: state.query, placeholder: '例如 xlsx / pdf / design', onChange: function (value) { patch({ query: value }) } })),
|
||||
h(Btn, { variant: 'primary', label: state.busy === 'search' ? '搜索中…' : '搜索', disabled: state.busy !== '', onClick: function () { search(false) } }),
|
||||
),
|
||||
state.error === null ? null : h(Banner, { tone: 'bad' }, state.error),
|
||||
state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text),
|
||||
state.status === 'ready' && state.entries.length === 0 ? h('p', { style: styles.hint }, '没有匹配的市场条目。') : null,
|
||||
h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, resultRows),
|
||||
state.nextCursor === null ? null : h('div', { style: styles.actions }, h(Btn, { label: '加载更多', variant: 'small', disabled: state.busy !== '', onClick: function () { search(true) } })),
|
||||
detailBox,
|
||||
planBox,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- P3: interactive sync conflict resolution -------------------------
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
import { bridgeCall, bridgeMessage } from '../bridge'
|
||||
|
||||
export function McpConfigSection(props) {
|
||||
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 s = tuple[0]
|
||||
var set = tuple[1]
|
||||
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
var selected = null
|
||||
for (var i = 0; i < items.length; i += 1) if (items[i].key === s.key) selected = items[i]
|
||||
React.useEffect(function () {
|
||||
bridgeCall('governance', {}).then(function (res) {
|
||||
if (res.body !== null && res.body.ok === true) patch({ gov: res.body.detail })
|
||||
})
|
||||
}, [])
|
||||
function choose(key) {
|
||||
patch({ key: key, json: '', scopePreview: null, policyPreview: null, notice: null })
|
||||
if (key === '') return
|
||||
bridgeCall('editableConnectionConfig', { key: key }).then(function (res) {
|
||||
if (res.body !== null && res.body.ok === true && res.body.detail !== undefined) patch({ json: String(res.body.detail.json === undefined ? '' : res.body.detail.json) })
|
||||
else patch({ json: '', notice: { tone: 'warn', text: bridgeMessage(res) } })
|
||||
})
|
||||
}
|
||||
function save() {
|
||||
if (s.key === '') return
|
||||
patch({ busy: 'save' })
|
||||
bridgeCall('reconfigureConnection', { key: s.key, json: s.json }).then(function (res) {
|
||||
var ok = res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '保存失败:' + bridgeMessage(res) } })
|
||||
if (ok && typeof props.onChanged === 'function') props.onChanged()
|
||||
})
|
||||
}
|
||||
function previewScope() {
|
||||
if (s.key === '') return
|
||||
patch({ busy: 'scope-preview' })
|
||||
var params: any = { key: s.key, targetScope: s.targetScope, mode: 'move' }
|
||||
if (s.targetScope === 'project') params.workspaceId = s.workspaceId
|
||||
bridgeCall('previewConnectionScope', params).then(function (res) {
|
||||
var ok = res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', scopePreview: ok ? res.body.detail : null, notice: ok ? null : { tone: 'bad', text: bridgeMessage(res) } })
|
||||
if (ok && res.body.detail.canApply !== true) patch({ notice: { tone: 'warn', text: bridgeMessage(res) } })
|
||||
})
|
||||
}
|
||||
function applyScope() {
|
||||
if (s.key === '' || s.scopePreview === null) return
|
||||
patch({ busy: 'scope-apply' })
|
||||
var params: any = { key: s.key, targetScope: s.targetScope, mode: 'move', expectedRevision: s.scopePreview.baseRevision }
|
||||
if (s.targetScope === 'project') params.workspaceId = s.workspaceId
|
||||
bridgeCall('applyConnectionScope', params).then(function (res) {
|
||||
var ok = res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '作用域应用失败:' + bridgeMessage(res) }, scopePreview: null })
|
||||
if (ok && typeof props.onChanged === 'function') props.onChanged()
|
||||
})
|
||||
}
|
||||
function previewPolicy(effect) {
|
||||
if (selected === null) return
|
||||
patch({ busy: 'policy-preview' })
|
||||
bridgeCall('previewPolicy', { scope: 'connection', effect: effect, connectorId: selected.connectorId }).then(function (res) {
|
||||
var ok = res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', policyPreview: ok ? res.body.detail : null, notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '策略预览失败:' + bridgeMessage(res) } })
|
||||
})
|
||||
}
|
||||
function applyPolicy() {
|
||||
if (selected === null || s.policyPreview === null) return
|
||||
patch({ busy: 'policy-apply' })
|
||||
bridgeCall('applyPolicy', { scope: 'connection', effect: s.policyPreview.mutation.effect, connectorId: selected.connectorId, expectedRevision: s.policyPreview.baseRevision }).then(function (res) {
|
||||
var ok = res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', policyPreview: null, notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '策略应用失败:' + bridgeMessage(res) } })
|
||||
if (ok) bridgeCall('governance', {}).then(function (g) { if (g.body !== null && g.body.ok === true) patch({ gov: g.body.detail }) })
|
||||
})
|
||||
}
|
||||
var gov = s.gov
|
||||
return h(Section, {
|
||||
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),
|
||||
s.key === '' ? h('p', { style: styles.hint }, '选择一条连接后可编辑配置、调整范围或设置治理策略。') : h('div', { style: styles.nested },
|
||||
h('p', { style: styles.hint }, '可编辑配置(保留标记 <KEEP_EXISTING> 表示保留原密钥):'),
|
||||
h('textarea', { value: s.json, rows: 8, style: Object.assign({}, styles.input, { fontFamily: 'monospace', resize: 'vertical' }), onChange: function (e) { patch({ json: e.target.value }) } }),
|
||||
h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: s.busy === 'save' ? '保存中…' : '保存配置', disabled: s.busy !== '' || s.json === '', onClick: save })),
|
||||
h('p', { style: styles.hint }, '作用域(目标范围 + mode=move,凭据不复制):'),
|
||||
h('div', { style: styles.grid },
|
||||
h('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '目标范围'),
|
||||
h('select', { value: s.targetScope, style: styles.input, onChange: function (e) { patch({ targetScope: e.target.value }) } },
|
||||
h('option', { value: 'global' }, '全局'),
|
||||
h('option', { value: 'project' }, '指定工作区'),
|
||||
),
|
||||
),
|
||||
s.targetScope === 'project' ? h(Field, { label: '工作区 id', value: s.workspaceId, onChange: function (v) { patch({ workspaceId: v }) } }) : null,
|
||||
),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: s.busy === 'scope-preview' ? '预览中…' : '预览作用域', disabled: s.busy !== '', onClick: previewScope }),
|
||||
s.scopePreview === null ? null : h(Btn, { variant: 'primary', label: s.busy === 'scope-apply' ? '应用中…' : '应用作用域(rev ' + String(s.scopePreview.baseRevision) + ')', disabled: s.busy !== '' || s.scopePreview.canApply !== true, onClick: applyScope }),
|
||||
),
|
||||
s.scopePreview === null ? null : h('p', { style: styles.hint }, '影响:' + String(s.scopePreview.impact === undefined ? '' : JSON.stringify(s.scopePreview.impact)) + ';可应用:' + (s.scopePreview.canApply === true ? '是' : '否') + ';凭据复制:否'),
|
||||
h('p', { style: styles.hint }, '治理(当前 connection 级):'),
|
||||
gov === null ? h('p', { style: styles.hint }, '治理文档未读取。') : h('div', { style: styles.pills },
|
||||
h(Pill, { label: 'revision', value: gov.revision, tone: 'muted' }),
|
||||
h(Pill, { label: '规则', value: (gov.rules || []).length, tone: 'muted' }),
|
||||
h(Pill, { label: '优先级', value: String(gov.precedenceLabel || '—'), tone: 'muted' }),
|
||||
),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: '预览 allow', variant: 'small', disabled: s.busy !== '' || selected === null, onClick: function () { previewPolicy('allow') } }),
|
||||
h(Btn, { label: '预览 deny', variant: 'small', disabled: s.busy !== '' || selected === null, onClick: function () { previewPolicy('deny') } }),
|
||||
h(Btn, { label: '预览 inherit', variant: 'small', disabled: s.busy !== '' || selected === null, onClick: function () { previewPolicy('inherit') } }),
|
||||
s.policyPreview === null ? null : h(Btn, { variant: 'primary', label: s.busy === 'policy-apply' ? '应用中…' : '应用策略(rev ' + String(s.policyPreview.baseRevision) + ')', disabled: s.busy !== '', onClick: applyPolicy }),
|
||||
),
|
||||
),
|
||||
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
|
||||
) : null,
|
||||
)
|
||||
}
|
||||
|
||||
export function itemSelect(items, value, onChange) {
|
||||
return h('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '连接'),
|
||||
h('select', { value: value, style: styles.input, onChange: function (e) { onChange(e.target.value) } },
|
||||
h('option', { value: '' }, '选择连接…'),
|
||||
items.map(function (item) { return h('option', { key: item.key, value: item.key }, String(item.name || item.key) + '(' + String(item.transport || '') + ')') }),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- import skills from other tools -------------------------------
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
import { bridgeCall, bridgeMessage } from '../bridge'
|
||||
|
||||
export 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 s = tuple[0]
|
||||
var set = tuple[1]
|
||||
function patch(next) { set(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
function submit() {
|
||||
if (String(s.name).trim() === '') { patch({ notice: { tone: 'warn', text: '请填写连接名称。' } }); return }
|
||||
var params: any = { name: String(s.name).trim(), serverName: String(s.serverName).trim() || undefined, transport: s.transport, authMode: s.authMode }
|
||||
if (s.transport === 'stdio') {
|
||||
if (String(s.command).trim() === '') { patch({ notice: { tone: 'warn', text: 'stdio 连接需要启动命令。' } }); return }
|
||||
params.command = String(s.command).trim()
|
||||
params.args = String(s.args).split(/\s+/).filter(function (x) { return x !== '' })
|
||||
if (String(s.cwd).trim() !== '') params.cwd = String(s.cwd).trim()
|
||||
} else {
|
||||
if (String(s.url).trim() === '') { patch({ notice: { tone: 'warn', text: 'HTTP 连接需要 URL。' } }); return }
|
||||
params.url = String(s.url).trim()
|
||||
if (s.authMode === 'bearer') params.bearerToken = String(s.bearerToken)
|
||||
if (s.authMode === 'api-key') { params.apiKeyHeader = String(s.apiKeyHeader); params.apiKeyValue = String(s.apiKeyValue) }
|
||||
}
|
||||
patch({ busy: 'configure', notice: null })
|
||||
bridgeCall('configure', params).then(function (res) {
|
||||
var ok = res.status === 200 && res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '新增失败:' + bridgeMessage(res) } })
|
||||
if (ok && typeof props.onChanged === 'function') props.onChanged()
|
||||
})
|
||||
}
|
||||
function importJson() {
|
||||
if (String(s.importJson).trim() === '') { patch({ notice: { tone: 'warn', text: '请粘贴 mcpServers JSON。' } }); return }
|
||||
patch({ busy: 'import', notice: null })
|
||||
bridgeCall('importJson', { json: s.importJson }).then(function (res) {
|
||||
var ok = res.status === 200 && res.body !== null && res.body.ok === true
|
||||
patch({ busy: '', notice: ok ? { tone: 'ok', text: bridgeMessage(res) } : { tone: 'bad', text: '导入失败:' + bridgeMessage(res) } })
|
||||
if (ok && typeof props.onChanged === 'function') props.onChanged()
|
||||
})
|
||||
}
|
||||
return h(Section, {
|
||||
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(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('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '传输方式'),
|
||||
h('select', { value: s.transport, style: styles.input, onChange: function (e) { patch({ transport: e.target.value }) } },
|
||||
h('option', { value: 'streamable-http' }, 'Streamable HTTP'),
|
||||
h('option', { value: 'stdio' }, 'stdio(本机进程)'),
|
||||
),
|
||||
),
|
||||
),
|
||||
s.transport === 'stdio'
|
||||
? h('div', { style: styles.grid },
|
||||
h(Field, { label: '启动命令', value: s.command, placeholder: 'npx / uvx / 本机可执行文件', onChange: function (v) { patch({ command: v }) } }),
|
||||
h(Field, { label: '参数(空格分隔)', value: s.args, onChange: function (v) { patch({ args: v }) } }),
|
||||
h(Field, { label: '工作目录(可选)', value: s.cwd, onChange: function (v) { patch({ cwd: v }) } }),
|
||||
)
|
||||
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
|
||||
h(Field, { label: 'URL', value: s.url, placeholder: 'https://…', onChange: function (v) { patch({ url: v }) } }),
|
||||
h('div', { style: styles.grid },
|
||||
h('div', { style: styles.field },
|
||||
h('span', { style: styles.label }, '鉴权'),
|
||||
h('select', { value: s.authMode, style: styles.input, onChange: function (e) { patch({ authMode: e.target.value }) } },
|
||||
h('option', { value: 'none' }, '无'),
|
||||
h('option', { value: 'bearer' }, 'Bearer Token'),
|
||||
h('option', { value: 'api-key' }, 'API Key'),
|
||||
),
|
||||
),
|
||||
s.authMode === 'bearer' ? h(Field, { label: 'Bearer Token', type: 'password', value: s.bearerToken, onChange: function (v) { patch({ bearerToken: v }) } }) : null,
|
||||
s.authMode === 'api-key' ? h(Field, { label: 'API Key 头', value: s.apiKeyHeader, onChange: function (v) { patch({ apiKeyHeader: v }) } }) : null,
|
||||
s.authMode === 'api-key' ? h(Field, { label: 'API Key 值', type: 'password', value: s.apiKeyValue, onChange: function (v) { patch({ apiKeyValue: v }) } }) : null,
|
||||
),
|
||||
),
|
||||
h('div', { style: styles.actions }, h(Btn, { variant: 'primary', label: s.busy === 'configure' ? '保存中…' : '校验并保存连接', disabled: s.busy !== '', onClick: submit })),
|
||||
h('p', { style: styles.hint }, '或粘贴 mcpServers JSON 批量导入:'),
|
||||
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 })),
|
||||
s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text),
|
||||
) : null,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
// dsh-brain client section component.
|
||||
import * as React from 'react'
|
||||
import { API, request, postJson, messageOf, bodyError } from '../api'
|
||||
import { formatTime, formatIso, formatBytes, shortHash, readStored, store, OUTCOME_LABELS, OUTCOME_TONES, ORIGIN_LABELS, CHECK_TONES, CHECK_LABELS, MCP_STATE_LABELS } from '../format'
|
||||
import { styles } from '../styles'
|
||||
import { Pill, Banner, Field, Btn, IconBtn, Switch, Toggle, Section, CardBoundary } from '../components'
|
||||
|
||||
const h = React.createElement
|
||||
|
||||
export function SyncResolveSection(props) {
|
||||
var tuple = React.useState({ status: 'idle', data: null, busy: '', error: null, notice: null, pendingAll: null })
|
||||
var state = tuple[0]
|
||||
var setState = tuple[1]
|
||||
function patch(next) { setState(function (prev) { return Object.assign({}, prev, next) }) }
|
||||
React.useEffect(function () { load() }, [])
|
||||
function load() {
|
||||
patch({ status: 'loading', error: null })
|
||||
request(API.sync + '/status', { method: 'GET' }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) patch({ status: 'ready', data: res.body })
|
||||
else patch({ status: 'error', error: bodyError(res, '读取同步状态失败') })
|
||||
}, function (error) { patch({ status: 'error', error: messageOf(error) }) })
|
||||
}
|
||||
function resolve(name, action, conflictId) {
|
||||
patch({ busy: name + ':' + action, notice: null })
|
||||
postJson(API.sync + '/resolve', { name: name, action: action, conflictId: conflictId }).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) {
|
||||
var stats = state.data === null ? null : state.data.stats
|
||||
patch({ busy: '', data: { stats: stats, conflicts: res.body.conflicts || [] }, notice: { tone: 'ok', text: name + ':' + (res.body.note || '已处理') } })
|
||||
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) } }) })
|
||||
}
|
||||
function runNow() {
|
||||
patch({ busy: 'run' })
|
||||
postJson(API.sync + '/run', {}).then(function (res) {
|
||||
if (res.body !== null && res.body !== undefined && res.body.ok === true) patch({ busy: '', data: { stats: res.body.stats, conflicts: res.body.conflicts || [] }, notice: { tone: 'ok', text: '已执行一次同步。' } })
|
||||
else patch({ busy: '', notice: { tone: 'bad', text: bodyError(res, '同步失败') } })
|
||||
}, 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, conflictIds: conflicts.map(function (item) { return item.conflictId }) }).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 stats = data === null || data === undefined ? null : data.stats
|
||||
var conflicts = data === null || data === undefined || !Array.isArray(data.conflicts) ? [] : data.conflicts
|
||||
var statPills = stats === null ? h('p', { style: styles.hint }, '同步引擎未启用或尚未运行。') : h('div', { style: styles.pills },
|
||||
h(Pill, { label: '运行中', value: stats.running === true ? '是' : '否', tone: stats.running === true ? 'warn' : 'muted' }),
|
||||
h(Pill, { label: '上次运行', value: formatIso(stats.lastRunAt), tone: 'muted' }),
|
||||
h(Pill, { label: '上传', value: (stats.uploaded || []).length, tone: 'muted' }),
|
||||
h(Pill, { label: '下载', value: (stats.downloaded || []).length, tone: 'muted' }),
|
||||
h(Pill, { label: '冲突', value: conflicts.length, tone: conflicts.length > 0 ? 'warn' : 'muted' }),
|
||||
)
|
||||
var conflictRows = conflicts.map(function (conflict) {
|
||||
var local = conflict.local || {}
|
||||
var cloud = conflict.cloud
|
||||
return h('div', { key: conflict.name, style: styles.row },
|
||||
h('div', { style: styles.rowHead },
|
||||
h('span', { style: styles.rowTitle }, conflict.name),
|
||||
h('div', { style: styles.pills },
|
||||
h(Pill, { label: '原因', value: String(conflict.reason), tone: 'warn' }),
|
||||
h(Pill, { label: '本地', value: local.exists === true ? (local.files + ' 文件') : '缺失', tone: local.exists === true ? 'muted' : 'bad' }),
|
||||
h(Pill, { label: '云端', value: cloud === null ? '无' : ('rev ' + String(cloud.revision === undefined ? '?' : cloud.revision)), tone: cloud === null ? 'muted' : 'ok' }),
|
||||
),
|
||||
),
|
||||
h('p', { style: styles.hint }, conflict.note),
|
||||
h('div', { style: styles.actions },
|
||||
h(Btn, { label: '保留本地', variant: 'small', disabled: state.busy !== '' || conflict.canKeepLocal !== true, onClick: function () { resolve(conflict.name, 'keep_local', conflict.conflictId) } }),
|
||||
h(Btn, { label: '采用云端', variant: 'small', disabled: state.busy !== '' || conflict.canTakeCloud !== true, onClick: function () { resolve(conflict.name, 'take_cloud', conflict.conflictId) } }),
|
||||
h(Btn, { label: '手动合并', variant: 'small', disabled: state.busy !== '', onClick: function () { resolve(conflict.name, 'manual', conflict.conflictId) } }),
|
||||
),
|
||||
)
|
||||
})
|
||||
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' } },
|
||||
state.error === null ? null : h(Banner, { tone: 'bad' }, state.error),
|
||||
state.notice === null ? null : h(Banner, { tone: state.notice.tone }, state.notice.text),
|
||||
statPills,
|
||||
batchRow,
|
||||
confirmAllRow,
|
||||
conflicts.length === 0 ? h('p', { style: styles.hint }, '当前没有待处理冲突。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, conflictRows),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- P4: custom connection / edit / scope / policy ---------------------
|
||||
// The MCP marketplace section was removed in 0.9.6: the host's `catalog`
|
||||
// method answers 405 on current dsh-mcp-connector builds, so the card only
|
||||
// rendered an error banner. Discover/install stays in the host's own
|
||||
// plugin market instead of a broken embedded panel.
|
||||
|
||||
|
|
@ -0,0 +1,368 @@
|
|||
// dsh-brain client style objects (inline styles, theme-token friendly).
|
||||
export const styles = {
|
||||
root: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '18px',
|
||||
padding: '4px 2px 20px',
|
||||
fontSize: '13px',
|
||||
lineHeight: 1.55,
|
||||
minWidth: 0,
|
||||
},
|
||||
tabs: {
|
||||
display: 'flex',
|
||||
gap: '4px',
|
||||
padding: '3px',
|
||||
borderRadius: '13px',
|
||||
border: '1px solid rgba(127,127,127,0.22)',
|
||||
background: 'rgba(127,127,127,0.06)',
|
||||
flexWrap: 'wrap',
|
||||
},
|
||||
tab: {
|
||||
flex: '1 1 auto',
|
||||
minWidth: '88px',
|
||||
font: 'inherit',
|
||||
fontSize: '12.5px',
|
||||
padding: '7px 12px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid transparent',
|
||||
background: 'transparent',
|
||||
color: 'inherit',
|
||||
cursor: 'pointer',
|
||||
whiteSpace: 'nowrap',
|
||||
},
|
||||
tabActive: {
|
||||
border: '1px solid rgba(127,127,127,0.30)',
|
||||
background: 'rgba(127,127,127,0.14)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.10)',
|
||||
fontWeight: 600,
|
||||
},
|
||||
section: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '12px',
|
||||
border: '1px solid rgba(127,127,127,0.22)',
|
||||
borderRadius: '16px',
|
||||
padding: '18px 20px',
|
||||
minWidth: 0,
|
||||
},
|
||||
sectionHead: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '10px',
|
||||
flexWrap: 'wrap',
|
||||
},
|
||||
sectionTitle: {
|
||||
margin: 0,
|
||||
fontSize: '13.5px',
|
||||
fontWeight: 650,
|
||||
letterSpacing: '0.02em',
|
||||
},
|
||||
hint: {
|
||||
margin: 0,
|
||||
fontSize: '11.5px',
|
||||
opacity: 0.58,
|
||||
},
|
||||
grid: {
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '12px 18px',
|
||||
},
|
||||
field: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '4px',
|
||||
flex: '1 1 auto',
|
||||
minWidth: '220px',
|
||||
},
|
||||
label: {
|
||||
fontSize: '12px',
|
||||
opacity: 0.75,
|
||||
},
|
||||
input: {
|
||||
font: 'inherit',
|
||||
fontSize: '13px',
|
||||
padding: '8px 11px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid rgba(127,127,127,0.35)',
|
||||
background: 'rgba(127,127,127,0.05)',
|
||||
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: '7px 16px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid rgba(127,127,127,0.4)',
|
||||
background: 'transparent',
|
||||
color: 'inherit',
|
||||
cursor: 'pointer',
|
||||
},
|
||||
buttonPrimary: {
|
||||
font: 'inherit',
|
||||
fontSize: '13px',
|
||||
padding: '7px 18px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid transparent',
|
||||
background: '#3f3f46',
|
||||
boxShadow: '0 2px 6px -2px rgba(0,0,0,0.35)',
|
||||
color: '#ffffff',
|
||||
cursor: 'pointer',
|
||||
fontWeight: 600,
|
||||
},
|
||||
buttonDanger: {
|
||||
font: 'inherit',
|
||||
fontSize: '13px',
|
||||
padding: '7px 16px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid rgba(220,38,38,0.5)',
|
||||
background: 'rgba(220,38,38,0.14)',
|
||||
color: 'inherit',
|
||||
cursor: 'pointer',
|
||||
},
|
||||
buttonSmall: {
|
||||
font: 'inherit',
|
||||
fontSize: '12px',
|
||||
padding: '3px 8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid transparent',
|
||||
background: 'transparent',
|
||||
opacity: 0.85,
|
||||
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%',
|
||||
whiteSpace: 'nowrap',
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
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: '11px',
|
||||
opacity: 0.72,
|
||||
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: {},
|
||||
iconBtn: {
|
||||
width: '28px',
|
||||
height: '28px',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '13px',
|
||||
lineHeight: 1,
|
||||
padding: 0,
|
||||
borderRadius: '8px',
|
||||
border: '1px solid rgba(127,127,127,0.25)',
|
||||
background: 'rgba(127,127,127,0.05)',
|
||||
color: 'inherit',
|
||||
cursor: 'pointer',
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
iconBtnDanger: {
|
||||
border: '1px solid rgba(220,38,38,0.40)',
|
||||
background: 'rgba(220,38,38,0.08)',
|
||||
},
|
||||
statsBar: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap',
|
||||
},
|
||||
stat: {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'baseline',
|
||||
gap: '6px',
|
||||
paddingRight: '18px',
|
||||
marginRight: '18px',
|
||||
borderRight: '1px solid rgba(127,127,127,0.20)',
|
||||
},
|
||||
statLast: {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'baseline',
|
||||
gap: '6px',
|
||||
},
|
||||
statNum: {
|
||||
fontSize: '17px',
|
||||
fontWeight: 700,
|
||||
},
|
||||
banner: {
|
||||
padding: '10px 13px',
|
||||
borderRadius: '11px',
|
||||
border: '1px solid transparent',
|
||||
fontSize: '12.5px',
|
||||
},
|
||||
row: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '6px',
|
||||
border: '1px solid rgba(127,127,127,0.15)',
|
||||
borderRadius: '11px',
|
||||
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(99,102,241,0.6)',
|
||||
background: 'rgba(99,102,241,0.16)',
|
||||
},
|
||||
nested: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '6px',
|
||||
paddingLeft: '10px',
|
||||
borderLeft: '2px solid rgba(127,127,127,0.18)',
|
||||
minWidth: 0,
|
||||
},
|
||||
sourceCard: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '6px',
|
||||
border: '1px solid rgba(127,127,127,0.17)',
|
||||
borderRadius: '14px',
|
||||
padding: '12px 14px',
|
||||
minWidth: 0,
|
||||
},
|
||||
groupRow: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '6px',
|
||||
border: '1px solid transparent',
|
||||
borderRadius: '11px',
|
||||
padding: '7px 9px',
|
||||
background: 'transparent',
|
||||
minWidth: 0,
|
||||
},
|
||||
skillRow: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '8px',
|
||||
padding: '5px 8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid transparent',
|
||||
minWidth: 0,
|
||||
flexWrap: 'nowrap',
|
||||
},
|
||||
clamp1: {
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: '1',
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
clamp2: {
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: '2',
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
sourceGlyph: {
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '6px',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '11px',
|
||||
fontWeight: 700,
|
||||
border: '1px solid rgba(127,127,127,0.22)',
|
||||
background: 'rgba(127,127,127,0.10)',
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
folderGlyph: {
|
||||
fontSize: '12px',
|
||||
opacity: 0.85,
|
||||
flex: '0 0 auto',
|
||||
},
|
||||
sourceTitle: {
|
||||
fontWeight: 600,
|
||||
fontSize: '13px',
|
||||
overflowWrap: 'anywhere',
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": false,
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src-client"]
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import type { UserConfig } from 'tsdown'
|
||||
|
||||
const PLUGIN_ID = 'dsh-brain'
|
||||
|
||||
export default {
|
||||
name: PLUGIN_ID + '/client',
|
||||
entry: { index: 'src-client/index.ts' },
|
||||
outDir: 'client',
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
fixedExtension: false,
|
||||
outExtensions: () => ({ js: '.js' }),
|
||||
dts: false,
|
||||
sourcemap: false,
|
||||
clean: false,
|
||||
deps: { neverBundle: [/^react(?:\/.*)?$/, /^react-dom(?:\/.*)?$/] },
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
plugins: [],
|
||||
outputOptions: {
|
||||
banner: `window.__ModuleLoader__.load({ id: '${PLUGIN_ID}', factory: (require) => {`,
|
||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||
footer: 'return module.exports; } });',
|
||||
},
|
||||
} satisfies UserConfig
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
// U0 client-build verification: the bundled client must keep the
|
||||
// __ModuleLoader__ contract, load like the legacy hand-written file, and
|
||||
// register the same settings seats with the same option shapes.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const React = require('react')
|
||||
|
||||
const results = []
|
||||
function check(name, ok, detail = '') {
|
||||
results.push({ name, ok })
|
||||
console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail === '' ? '' : ' :: ' + detail))
|
||||
}
|
||||
|
||||
const bundle = readFileSync(new URL('./client/index.js', import.meta.url), 'utf8')
|
||||
check('client bundle uses the __ModuleLoader__ contract', bundle.includes('__ModuleLoader__.load'))
|
||||
check('client bundle id stays dsh-brain', /id:\s*['"]dsh-brain['"]/.test(bundle))
|
||||
for (const seat of ['settings.section', 'plugins.bundle.config']) {
|
||||
check('client bundle registers ' + seat, bundle.includes(seat))
|
||||
}
|
||||
for (const label of ['连接与上报', '技能管理', 'MCP 管理']) {
|
||||
check('client bundle keeps tab label ' + label, bundle.includes(label))
|
||||
}
|
||||
check('client bundle is a single file with only react externals', (() => {
|
||||
const requires = [...bundle.matchAll(/require\(\s*['"]([^'"]+)['"]\s*\)/g)].map((match) => match[1])
|
||||
return requires.every((name) => name === 'react' || name === 'react/jsx-runtime')
|
||||
})())
|
||||
|
||||
function loadBundle(file) {
|
||||
const code = readFileSync(file, 'utf8')
|
||||
let definition = null
|
||||
const sandbox = {
|
||||
window: {
|
||||
__ModuleLoader__: {
|
||||
load(value) { definition = value },
|
||||
},
|
||||
localStorage: { getItem: () => null, setItem: () => {} },
|
||||
open: () => undefined,
|
||||
},
|
||||
console,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
fetch: async () => { throw new Error('fetch not available in verification') },
|
||||
AbortController,
|
||||
}
|
||||
sandbox.window.window = sandbox.window
|
||||
sandbox.globalThis = sandbox
|
||||
vm.runInNewContext(code, sandbox, { filename: String(file) })
|
||||
if (definition === null) throw new Error('bundle did not register with __ModuleLoader__: ' + file)
|
||||
return definition.factory((name) => {
|
||||
if (name === 'react') return React
|
||||
if (name === 'react/jsx-runtime') return require('react/jsx-runtime')
|
||||
throw new Error('unexpected require: ' + name)
|
||||
})
|
||||
}
|
||||
|
||||
function registrationShape(file) {
|
||||
const mod = loadBundle(file)
|
||||
const records = []
|
||||
let component = null
|
||||
const ctx = {
|
||||
slots: {
|
||||
inject(seat, callback) {
|
||||
component = null
|
||||
const value = callback()
|
||||
records.push({ seat, value, component })
|
||||
},
|
||||
register(options, registeredComponent) {
|
||||
component = registeredComponent
|
||||
return options
|
||||
},
|
||||
},
|
||||
}
|
||||
mod.apply(ctx)
|
||||
return {
|
||||
name: mod.name,
|
||||
inject: mod.inject,
|
||||
records: records.map((entry) => ({
|
||||
seat: entry.seat,
|
||||
name: entry.value.name,
|
||||
id: entry.value.id,
|
||||
key: entry.value.key,
|
||||
order: entry.value.order,
|
||||
label: typeof entry.value.label === 'function' ? entry.value.label() : undefined,
|
||||
})),
|
||||
components: records.map((entry) => entry.component),
|
||||
}
|
||||
}
|
||||
|
||||
const current = registrationShape('client/index.js')
|
||||
check('apply registers exactly the settings seats', current.records.length === 2)
|
||||
check('settings.section keeps its id/order/label', JSON.stringify(current.records[0]) === JSON.stringify({ seat: 'settings.section', name: 'settings.section', id: 'dsh-brain', key: undefined, order: 100, label: '云端记忆' }))
|
||||
check('plugins.bundle.config keeps its key', JSON.stringify(current.records[1]) === JSON.stringify({ seat: 'plugins.bundle.config', name: 'plugins.bundle.config', id: undefined, key: 'dsh-brain', order: undefined, label: undefined }))
|
||||
check('module exports name dsh-brain', current.name === 'dsh-brain' && Array.isArray(current.inject) && current.inject.includes('slots'))
|
||||
|
||||
// Each registered callback must produce a renderable React element without a DOM.
|
||||
let rendered = 0
|
||||
for (const component of current.components) {
|
||||
const element = typeof component === 'function' ? React.createElement(component) : null
|
||||
if (element !== null && typeof element === 'object' && element.type !== undefined) rendered += 1
|
||||
}
|
||||
check('registered components render without throwing', rendered === current.components.length)
|
||||
|
||||
const legacyFile = new URL('./artifacts/analysis/client-legacy.js', import.meta.url)
|
||||
if (existsSync(legacyFile)) {
|
||||
const legacy = registrationShape(legacyFile)
|
||||
check('migration preserves apply registration shape', JSON.stringify({ name: current.name, inject: current.inject, records: current.records }) === JSON.stringify({ name: legacy.name, inject: legacy.inject, records: legacy.records }), JSON.stringify({ current, legacy }))
|
||||
} else {
|
||||
console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)')
|
||||
}
|
||||
|
||||
console.log('\n' + (results.every((result) => result.ok) ? 'ALL ' + results.length + ' CHECKS PASSED' : results.filter((result) => !result.ok).length + ' FAILED'))
|
||||
process.exit(results.every((result) => result.ok) ? 0 : 1)
|
||||
Loading…
Reference in New Issue