fix(host): apply 同步返回 + 状态惰性加载(真实宿主里修复 cordis Invalid effect)

This commit is contained in:
qyh15 2026-11-14 23:36:01 +08:00
parent 2bbafe7ab1
commit 98a8645fdd
5 changed files with 32 additions and 10 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
ds-bot/ ds-bot/
node_modules/ node_modules/
.dsh-test-*/
*.tmp *.tmp
*.log *.log

View File

@ -10,16 +10,14 @@ import { ROUTE } from './src/host/constants.js'
export const name = 'sansheng' export const name = 'sansheng'
export const inject = ['workspaceRegistry', 'sessionController', 'agents', 'llm', 'systemPrompt', 'connection'] export const inject = ['workspaceRegistry', 'sessionController', 'agents', 'llm', 'systemPrompt', 'connection']
export async function apply(ctx, config = {}) { export function apply(ctx, config = {}) {
const store = new SanshengStore( const store = new SanshengStore(
typeof config.statePath === 'string' && config.statePath !== '' ? config.statePath : sanshengStatePath(config.home), typeof config.statePath === 'string' && config.statePath !== '' ? config.statePath : sanshengStatePath(config.home),
) )
try { // apply 必须同步返回(cordis 把异步/非函数返回值当非法 effect);状态在首次请求时惰性读入。
await store.load() void store.ensureLoaded().catch(error => {
} catch (error) {
// 状态损坏不能静默丢弃;记录后仍允许插件加载,但后续操作会因空状态而需重新启用。
console.warn(`sansheng: ${error?.message ?? error}`) console.warn(`sansheng: ${error?.message ?? error}`)
} })
const host = { const host = {
workspaceRegistry: ctx.workspaceRegistry, workspaceRegistry: ctx.workspaceRegistry,
@ -45,6 +43,4 @@ export async function apply(ctx, config = {}) {
return new Response(JSON.stringify(result), { status: 200, headers: { 'content-type': 'application/json' } }) return new Response(JSON.stringify(result), { status: 200, headers: { 'content-type': 'application/json' } })
}, },
}), 'sansheng: api route') }), 'sansheng: api route')
return service
} }

View File

@ -55,6 +55,7 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
} }
async function ensureSeat(projectId, seatId) { async function ensureSeat(projectId, seatId) {
await store.ensureLoaded()
const seat = store.get(projectId).seats[seatId] const seat = store.get(projectId).seats[seatId]
if (seat.status === 'bound' && seat.sessionId) return { ok: true, skipped: true } if (seat.status === 'bound' && seat.sessionId) return { ok: true, skipped: true }
@ -103,6 +104,7 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
async function enable(projectId) { async function enable(projectId) {
return withLock(projectId, async () => { return withLock(projectId, async () => {
await store.ensureLoaded()
const project = store.get(projectId) const project = store.get(projectId)
if (!project) throw new ProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`) if (!project) throw new ProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`)
await store.mutate(s => { await store.mutate(s => {

View File

@ -77,6 +77,7 @@ export class SanshengService {
} }
async list() { async list() {
await this.store.ensureLoaded()
return { return {
projects: [...this.store.list()] projects: [...this.store.list()]
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) .sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
@ -85,6 +86,7 @@ export class SanshengService {
} }
async open({ workspaceId, name, path } = {}) { async open({ workspaceId, name, path } = {}) {
await this.store.ensureLoaded()
if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path') if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path')
const registry = this.host.workspaceRegistry const registry = this.host.workspaceRegistry
let ws let ws
@ -108,18 +110,21 @@ export class SanshengService {
} }
async project(projectId) { async project(projectId) {
await this.store.ensureLoaded()
const p = this.store.get(projectId) const p = this.store.get(projectId)
if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
return projectView(p) return projectView(p)
} }
async enable(projectId) { async enable(projectId) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
await this.provisioner.enable(projectId) await this.provisioner.enable(projectId)
return this.project(projectId) return this.project(projectId)
} }
async configure(projectId, seatId, { model, instructions } = {}) { async configure(projectId, seatId, { model, instructions } = {}) {
await this.store.ensureLoaded()
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`) if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`)
const project = this.store.get(projectId) const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
@ -147,6 +152,7 @@ export class SanshengService {
} }
async models() { async models() {
await this.store.ensureLoaded()
const catalog = await this.host.sessionController.modelCatalog() const catalog = await this.host.sessionController.modelCatalog()
return normalizeCatalog(catalog) return normalizeCatalog(catalog)
} }

View File

@ -9,14 +9,29 @@ export class StoreError extends Error {
} }
export class SanshengStore { export class SanshengStore {
constructor(file) { this.file = file; this.state = emptyState(); this._queue = Promise.resolve() } constructor(file) {
this.file = file
this.state = emptyState()
this._queue = Promise.resolve()
this._loaded = false
this._loadPromise = null
}
// 惰性加载:插件 apply 必须同步返回,真实 HTTP 请求到达时再确保状态已读入。
ensureLoaded() {
if (this._loaded) return Promise.resolve()
if (!this._loadPromise) {
this._loadPromise = this.load().catch(error => { this._loadPromise = null; throw error })
}
return this._loadPromise
}
async load() { async load() {
let raw let raw
try { try {
raw = await readFile(this.file, 'utf8') raw = await readFile(this.file, 'utf8')
} catch (error) { } catch (error) {
if (error?.code === 'ENOENT') { this.state = emptyState(); return } if (error?.code === 'ENOENT') { this.state = emptyState(); this._loaded = true; return }
throw new StoreError('sansheng/state-corrupt', `无法读取状态文件:${error?.message ?? error}`) throw new StoreError('sansheng/state-corrupt', `无法读取状态文件:${error?.message ?? error}`)
} }
let parsed let parsed
@ -26,6 +41,7 @@ export class SanshengStore {
const valid = validateState(parsed) const valid = validateState(parsed)
if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`) if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`)
this.state = valid.state this.state = valid.state
this._loaded = true
} }
snapshot() { return structuredClone(this.state) } snapshot() { return structuredClone(this.state) }
@ -36,6 +52,7 @@ export class SanshengStore {
// 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。 // 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。
async mutate(fn) { async mutate(fn) {
const run = async () => { const run = async () => {
await this.ensureLoaded()
const before = structuredClone(this.state) const before = structuredClone(this.state)
try { try {
const result = await fn(this.state) const result = await fn(this.state)