dsh-brain/preview-mcp.mjs

345 lines
14 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.

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