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/
node_modules/
.dsh-test-*/
*.tmp
*.log

View File

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

View File

@ -55,6 +55,7 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
}
async function ensureSeat(projectId, seatId) {
await store.ensureLoaded()
const seat = store.get(projectId).seats[seatId]
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) {
return withLock(projectId, async () => {
await store.ensureLoaded()
const project = store.get(projectId)
if (!project) throw new ProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`)
await store.mutate(s => {

View File

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

View File

@ -9,14 +9,29 @@ export class StoreError extends Error {
}
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() {
let raw
try {
raw = await readFile(this.file, 'utf8')
} 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}`)
}
let parsed
@ -26,6 +41,7 @@ export class SanshengStore {
const valid = validateState(parsed)
if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`)
this.state = valid.state
this._loaded = true
}
snapshot() { return structuredClone(this.state) }
@ -36,6 +52,7 @@ export class SanshengStore {
// 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。
async mutate(fn) {
const run = async () => {
await this.ensureLoaded()
const before = structuredClone(this.state)
try {
const result = await fn(this.state)