316 lines
19 KiB
JavaScript
316 lines
19 KiB
JavaScript
// Client-build verification.
|
|
// U0: the bundled client keeps the __ModuleLoader__ contract, loads like the
|
|
// legacy hand-written file, and registers the same settings seats.
|
|
// U1: the Brain panel registers on both native seats (main + sidebar.panellist)
|
|
// and degrades silently when a seat is missing.
|
|
import { once } from 'node:events'
|
|
import { existsSync, readFileSync } from 'node:fs'
|
|
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
|
|
import { createServer } from 'node:http'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import { createRequire } from 'node:module'
|
|
import vm from 'node:vm'
|
|
import { Context, Service } from '@deepseek-ai/cordis'
|
|
|
|
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))
|
|
const cssModuleIds = [...bundle.matchAll(/^\s*\/\/ \S*?dsh-brain-css:(\S+)$/gm)].map((match) => match[1])
|
|
check('client CSS module comments use portable repository paths',
|
|
cssModuleIds.length === 2
|
|
&& cssModuleIds.includes('src-client/panel/BrainPanel.module.css.mjs')
|
|
&& cssModuleIds.includes('src-client/sidebar/ProjectMemory.module.css.mjs'))
|
|
for (const seat of ['settings.section', 'plugins.bundle.config', 'sidebar.panellist']) {
|
|
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 keeps the panel semantic anchor', bundle.includes('data-dsh-panel-entry') && bundle.includes('data-dsh-plugin'))
|
|
check('Brain bundles its own project memory tab', bundle.includes('dsh-brain:memory'))
|
|
// Memory reads moved to the Mnemon bridge (single source of truth); the local
|
|
// forget path stays for the future write round. Departments are unchanged.
|
|
for (const apiPath of ['/dsh-brain/mnemon/runtime', '/dsh-brain/mnemon/list', '/dsh-brain/mnemon/status', '/dsh-brain/mnemon/documents', '/dsh-brain/local-memory/forget', '/dsh-brain/departments/list', '/dsh-brain/departments/create', '/dsh-brain/departments/update', '/dsh-brain/departments/disable', '/dsh-brain/departments/checkpoint', '/dsh-brain/departments/recall']) {
|
|
check('client bundle consumes ' + apiPath, bundle.includes(apiPath))
|
|
}
|
|
for (const label of ['记忆条目', '部门列表', '部门召回', '数据已变化,请刷新']) {
|
|
check('client bundle keeps U2 surface ' + label, bundle.includes(label))
|
|
}
|
|
check('single Brain browser factory uses only host browser externals', (() => {
|
|
const requires = [...bundle.matchAll(/require\(\s*['"]([^'"]+)['"]\s*\)/g)].map((match) => match[1])
|
|
const externals = new Set(['react', 'react/jsx-runtime', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'])
|
|
return bundle.match(/__ModuleLoader__\.load\(/g)?.length === 1 && requires.every(name => externals.has(name))
|
|
})())
|
|
|
|
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')
|
|
if (name === 'react-dom') return { createPortal: value => value }
|
|
if (name === '@deepseek-ai/dsh-client-ui-primitives') return new Proxy({}, { get: () => () => null })
|
|
throw new Error('unexpected require: ' + name)
|
|
})
|
|
}
|
|
|
|
function exercise(file) {
|
|
const mod = loadBundle(file)
|
|
const registrations = []
|
|
const ctx = {
|
|
slots: {
|
|
inject(seat, callback) { callback() },
|
|
register(options, component) {
|
|
registrations.push({ seat: options.name, options, component })
|
|
return () => {}
|
|
},
|
|
},
|
|
effect(setup) {
|
|
const dispose = typeof setup === 'function' ? setup() : undefined
|
|
return typeof dispose === 'function' ? dispose : () => {}
|
|
},
|
|
}
|
|
mod.apply(ctx)
|
|
return { name: mod.name, inject: mod.inject, registrations }
|
|
}
|
|
|
|
function shapeOf(entry) {
|
|
return {
|
|
seat: entry.seat,
|
|
name: entry.options.name,
|
|
id: entry.options.id,
|
|
key: entry.options.key,
|
|
order: entry.options.order,
|
|
label: typeof entry.options.label === 'function' ? entry.options.label() : undefined,
|
|
inject: typeof entry.options.inject === 'function' ? 'function' : undefined,
|
|
}
|
|
}
|
|
|
|
const current = exercise('client/index.js')
|
|
const seats = current.registrations.map((entry) => entry.seat)
|
|
check('apply registers settings + panel seats', ['settings.section', 'plugins.bundle.config', 'main', 'sidebar.panellist'].every((seat) => seats.includes(seat)), JSON.stringify(seats))
|
|
const bySeat = Object.fromEntries(current.registrations.map((entry) => [entry.seat, entry]))
|
|
check('settings.section keeps its id/order/label', JSON.stringify(shapeOf(bySeat['settings.section'])) === JSON.stringify({ seat: 'settings.section', name: 'settings.section', id: 'dsh-brain', key: undefined, order: 100, label: '云端记忆', inject: undefined }))
|
|
check('plugins.bundle.config keeps its key', JSON.stringify(shapeOf(bySeat['plugins.bundle.config'])) === JSON.stringify({ seat: 'plugins.bundle.config', name: 'plugins.bundle.config', id: undefined, key: 'dsh-brain', order: undefined, label: undefined, inject: undefined }))
|
|
check('main panel uses the dsh-brain panel key', bySeat['main'] !== undefined && bySeat['main'].options.key === 'dsh-brain')
|
|
check('sidebar panellist row uses id dsh-brain at order 30 with Brain label', bySeat['sidebar.panellist'] !== undefined && bySeat['sidebar.panellist'].options.id === 'dsh-brain' && bySeat['sidebar.panellist'].options.order === 30 && bySeat['sidebar.panellist'].options.label() === 'Brain')
|
|
check('module exports name dsh-brain', current.name === 'dsh-brain' && Array.isArray(current.inject) && current.inject.includes('slots'))
|
|
|
|
let rendered = 0
|
|
for (const entry of current.registrations) {
|
|
const element = typeof entry.component === 'function' ? React.createElement(entry.component) : null
|
|
if (element !== null && typeof element === 'object' && element.type !== undefined) rendered += 1
|
|
}
|
|
check('registered components render without throwing', rendered === current.registrations.length)
|
|
|
|
let silentThrew = false
|
|
try {
|
|
const mod = loadBundle('client/index.js')
|
|
mod.apply({ slots: { inject() {}, register() { throw new Error('must not register') } }, effect(setup) { if (typeof setup === 'function') setup() } })
|
|
} catch { silentThrew = true }
|
|
check('missing panel seats degrade silently', !silentThrew)
|
|
|
|
let rejectThrew = false
|
|
try {
|
|
const mod = loadBundle('client/index.js')
|
|
mod.apply({ slots: { inject() { throw new Error('seat unavailable') }, register() { return () => {} } }, effect(setup) { if (typeof setup === 'function') setup() } })
|
|
} catch { rejectThrew = true }
|
|
check('rejecting panel seats degrade without throwing', !rejectThrew)
|
|
|
|
const standaloneTab = { id: 'dsh-mnemon:memory' }
|
|
const sidebarTabs = new Map([[standaloneTab.id, standaloneTab]])
|
|
const sidebarEffects = []
|
|
let betterSidebar
|
|
let notifyServiceChange
|
|
loadBundle('client/index.js').apply({
|
|
slots: { inject() {} },
|
|
get: (name) => name === 'betterSidebar' ? betterSidebar : undefined,
|
|
on(event, listener) {
|
|
if (event === 'internal/service') notifyServiceChange = listener
|
|
return () => { if (notifyServiceChange === listener) notifyServiceChange = undefined }
|
|
},
|
|
effect(setup) { sidebarEffects.push(setup()) },
|
|
})
|
|
check('project tab waits for the optional better sidebar service', sidebarTabs.size === 1 && typeof notifyServiceChange === 'function')
|
|
betterSidebar = {
|
|
registerTab(tab) {
|
|
if (sidebarTabs.has(tab.id)) throw new Error('duplicate sidebar tab ' + tab.id)
|
|
sidebarTabs.set(tab.id, tab)
|
|
return () => sidebarTabs.delete(tab.id)
|
|
},
|
|
}
|
|
notifyServiceChange?.('betterSidebar')
|
|
notifyServiceChange?.('betterSidebar')
|
|
const projectTab = sidebarTabs.get('dsh-brain:memory')
|
|
check('Brain registers one project tab alongside standalone Mnemon', sidebarTabs.size === 2 && projectTab?.title() === '项目记忆' && sidebarTabs.get(standaloneTab.id) === standaloneTab)
|
|
const initialProject = projectTab?.component({ visible: true, scope: { sessionId: 's1' } })
|
|
const updatedProject = projectTab?.component({ visible: true, scope: { sessionId: 's1', cwd: 'C:/worktree' } })
|
|
check('project tab resolves the session without an initial directory hint and remounts when the hint changes',
|
|
initialProject?.props.sessionId === 's1' && updatedProject?.props.sessionId === 's1' && initialProject.key !== updatedProject.key)
|
|
for (const dispose of sidebarEffects) dispose?.()
|
|
check('Brain teardown removes its project tab and service listener', sidebarTabs.size === 1 && sidebarTabs.get(standaloneTab.id) === standaloneTab && notifyServiceChange === undefined)
|
|
|
|
// The shipped Cordis lifecycle drives delayed dependencies and teardown. Slot
|
|
// and connection fixtures expose only the host faces this client consumes.
|
|
const browser = new Context()
|
|
const entries = new Map()
|
|
const listeners = new Map()
|
|
const slotList = name => entries.get(name) ?? []
|
|
const publishSlot = (name, rows) => {
|
|
entries.set(name, rows)
|
|
for (const listener of [...(listeners.get(name) ?? [])]) listener()
|
|
}
|
|
class VerificationSlots extends Service {
|
|
constructor(ctx) { super(ctx, 'slots') }
|
|
inject(name, setup) { return this.ctx.effect(setup, "slot: " + name) }
|
|
register(options, component) {
|
|
const entry = { options, component, inject: options.inject }
|
|
publishSlot(options.name, [...slotList(options.name), entry])
|
|
return () => publishSlot(options.name, slotList(options.name).filter(row => row !== entry))
|
|
}
|
|
entries(name) { return slotList(name) }
|
|
entriesOfSlot(name) { return slotList(name) }
|
|
subscribe(name, listener) {
|
|
if (!listeners.has(name)) listeners.set(name, new Set())
|
|
listeners.get(name).add(listener)
|
|
return () => listeners.get(name).delete(listener)
|
|
}
|
|
}
|
|
const rpcCalls = []
|
|
const observable = value => ({ getSnapshot: () => value, subscribe: () => () => {} })
|
|
const disposers = []
|
|
const locale = {
|
|
...observable({ active: 'zh' }),
|
|
bind: () => key => key,
|
|
register(namespace) {
|
|
disposers.push('register:' + namespace)
|
|
return () => disposers.push('dispose:' + namespace)
|
|
},
|
|
}
|
|
const connection = { isLoopback: true, rpc: { async call(channel, endpoint, payload) {
|
|
rpcCalls.push({ channel, endpoint, payload })
|
|
return { ok: true, value: { status: 'ready', value: { tabEnabled: true, displayMode: 'sidebar', sidebar: false }, writable: true, mode: 'host' } }
|
|
} } }
|
|
const willSettle = () => new Promise(resolve => setImmediate(resolve))
|
|
const slotService = new VerificationSlots(browser)
|
|
const mod = loadBundle('client/index.js')
|
|
const applied = browser.plugin(mod)
|
|
await applied
|
|
check('Brain loads before optional workbench host services arrive', slotList('main').some(row => row.options.key === 'dsh-brain') && slotList('settings.section').length === 1)
|
|
for (const [name, service] of Object.entries({
|
|
connection, locale,
|
|
sessions: { list: observable({ byId: {} }) },
|
|
workspaces: { list: observable({ items: [] }) },
|
|
uiSession: { adapter: { current: observable({}) } },
|
|
layout: { selectPanel() {} },
|
|
})) browser.reflect.provide(name, service)
|
|
await willSettle()
|
|
check('embedded Mnemon mounts the sidebar workbench with Brain settings intact', slotList('shell.overlay').some(row => row.options.id === 'mnemon') && slotList('settings.section').some(row => row.options.id === 'dsh-brain:mnemon') && slotList('settings.section').some(row => row.options.id === 'dsh-brain'))
|
|
const sources = slotList('mnemon.source.page').map(row => row.options.id)
|
|
check('embedded Mnemon installs all four vendored source page families', ['runtime', 'documents', 'memory-spaces', 'skills'].every(name => sources.some(id => id?.startsWith(name + '/'))), JSON.stringify(sources))
|
|
check('component settings use Brain bundle and hosted row IDs', slotList('plugins.row.config').some(row => row.options.key === 'dsh-brain#dsh-brain-mnemon-strategy-general') && slotList('plugins.row.config').some(row => row.options.key === 'dsh-brain#dsh-brain-mnemon-source-runtime'))
|
|
check('embedded client issues vendor settings RPCs for core, interactions and skills', ['mnemon', 'mnemon-ui', 'mnemon-skills'].every(namespace => rpcCalls.some(call => call.channel === '/dsh-brain-mnemon-settings' && call.endpoint === 'get' && call.payload.namespace === namespace)))
|
|
const stopStandalone = slotService.register({ name: 'plugins.bundle.config', key: 'dsh-mnemon' }, () => null)
|
|
await willSettle()
|
|
check('standalone detection disposes Mnemon and preserves Brain', !slotList('settings.section').some(row => row.options.id === 'dsh-brain:mnemon') && slotList('mnemon.source.page').length === 0 && slotList('main').some(row => row.options.key === 'dsh-brain'))
|
|
stopStandalone()
|
|
await willSettle()
|
|
check('embedded Mnemon returns when standalone is removed', slotList('settings.section').some(row => row.options.id === 'dsh-brain:mnemon'))
|
|
await applied.dispose()
|
|
check('browser teardown releases workbench locale and standalone listener', disposers.join(',') === 'register:dsh-brain-mnemon,dispose:dsh-brain-mnemon,register:dsh-brain-mnemon,dispose:dsh-brain-mnemon' && listeners.get('plugins.bundle.config')?.size === 0)
|
|
|
|
const legacyFile = new URL('./artifacts/analysis/client-legacy.js', import.meta.url)
|
|
if (existsSync(legacyFile)) {
|
|
const legacy = exercise(legacyFile)
|
|
const pickSettingsSeats = (value) => value.registrations.filter((entry) => entry.seat === 'settings.section' || entry.seat === 'plugins.bundle.config').map(shapeOf).sort((left, right) => left.seat.localeCompare(right.seat))
|
|
check('migration preserves settings registration shape', JSON.stringify(pickSettingsSeats(current)) === JSON.stringify(pickSettingsSeats(legacy)), JSON.stringify({ current: pickSettingsSeats(current), legacy: pickSettingsSeats(legacy) }))
|
|
} else {
|
|
console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)')
|
|
}
|
|
|
|
// The global panel must pass an explicit scope to both management tabs.
|
|
const layout = readFileSync(new URL('./src-client/panel/BrainPanel.tsx', import.meta.url), 'utf8')
|
|
const patch = readFileSync(new URL('./cordis.patch.yml', import.meta.url), 'utf8')
|
|
check('global panel binds both tabs to global data',
|
|
layout.includes("h(MemoryTab, { scope: 'global' })") && layout.includes("h(DepartmentTab, { scope: 'global' })"))
|
|
check('the UI loader row mounts at the package root for browser discovery',
|
|
/id: dsh-brain-ui\r?\n(?: *#[^\r\n]*\r?\n)* *name: dsh-brain\r?\n *config:\r?\n *entry: ui(?:\r?\n|$)/.test(patch))
|
|
check('settings section mounts the full plugin config form',
|
|
bySeat['settings.section']?.component === bySeat['plugins.bundle.config']?.component && typeof bySeat['settings.section']?.component === 'function')
|
|
|
|
const root = await mkdtemp(join(tmpdir(), 'brain-ui-workspace-'))
|
|
try {
|
|
const [projectA, projectB] = [join(root, 'project a'), join(root, 'project b')]
|
|
await Promise.all([mkdir(projectA), mkdir(projectB)])
|
|
const { LocalMemoryManager, projectBrainRoot } = await import('./lib/local-memory/index.js')
|
|
const { createCoreRoutes, ROUTES } = await import('./lib/routes.js')
|
|
const localMemory = new LocalMemoryManager({ cwd: () => projectA, globalRoot: join(root, 'global') })
|
|
const a = await localMemory.withWorkspace(projectA, () => localMemory.remember({ scope: 'project', content: 'workspace A sample' }))
|
|
const b = await localMemory.withWorkspace(projectB, () => localMemory.remember({ scope: 'project', content: 'workspace B sample' }))
|
|
const documentB = await localMemory.addDocument({ title: 'Workspace B document', content: 'workspace B sample document' }, projectB)
|
|
const route = createCoreRoutes({ localMemory }).find((entry) => entry.path === ROUTES.localMemory)
|
|
const server = createServer((req, res) => {
|
|
void route.handler(req, res).catch(() => { res.statusCode = 500; res.end() })
|
|
})
|
|
server.listen(0, '127.0.0.1')
|
|
try {
|
|
await once(server, 'listening')
|
|
const origin = 'http://127.0.0.1:' + server.address().port
|
|
const base = origin + ROUTES.localMemory
|
|
const workspace = '?workspace=' + encodeURIComponent(projectB)
|
|
const getJson = async (suffix) => {
|
|
const response = await fetch(base + suffix)
|
|
if (!response.ok) throw new Error(suffix + ': HTTP ' + response.status)
|
|
return response.json()
|
|
}
|
|
const [defaultPage, scopedPage, status, documents] = await Promise.all([
|
|
getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace + '&scope=project'),
|
|
])
|
|
check('omitting workspace still lists the default project', defaultPage.total === 1 && defaultPage.items[0]?.id === a.record.id)
|
|
check('workspace query lists only the selected project fixture', scopedPage.total === 1 && scopedPage.items[0]?.id === b.record.id)
|
|
check('status and documents read the selected project', status.projectRoot === projectBrainRoot(projectB) && documents.documents[0]?.id === documentB.id)
|
|
const invalidDocuments = await Promise.all([
|
|
fetch(base + '/documents?scope=project'), fetch(base + '/documents' + workspace + '&scope=global'),
|
|
])
|
|
check('explicit document scope requires a project workspace', invalidDocuments.every(({ status }) => status === 400))
|
|
const forget = await fetch(base + '/forget', {
|
|
method: 'POST', headers: { origin, 'content-type': 'application/json' },
|
|
body: JSON.stringify({ id: b.record.id, expectedRevision: b.record.revision, workspace: projectB }),
|
|
})
|
|
check('forget uses the target workspace and preserves the default project', forget.ok && (await getJson('/memories' + workspace)).total === 0 && (await getJson('/memories')).items[0]?.id === a.record.id)
|
|
} finally {
|
|
await new Promise((resolve) => server.close(resolve))
|
|
}
|
|
} finally {
|
|
await rm(root, { recursive: true, force: true })
|
|
}
|
|
|
|
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)
|