dsh-brain/preview-import.mjs

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