fix(workbench): 会话层与路由支持晚到补挂,注入账本不再写真实路径
- workbench-host:sessions/dispatchService/reconciler 改为可晚挂(attachSessions), 返回对象用 getter,重复挂载幂等;start 后才到达也会自动启动对账 - index:webServer/sessionController 都用 ctx.inject 补挂一次;dispatch 钩子恒挂, 没会话层时退回「只落账」,绝不伪装已发送 - index:支持 options.store 注入(测试/嵌入用),避免单测写 %DSH_HOME% 真账本 - 新增 workbench/test/assembly.test.mjs(2 例)+ host.test 补晚挂用例;全量 206/206
This commit is contained in:
parent
26ab0bd36c
commit
047d2a267e
|
|
@ -171,6 +171,25 @@ import { createWorkbenchHost } from './workbench/host/index.mjs'
|
|||
|
||||
日志前缀 `[sansheng-liubu:workbench]`。
|
||||
|
||||
### 晚到的服务怎么办
|
||||
|
||||
`apply()` 跑的那一刻,宿主不保证 `webServer` 与 `sessionController` 都已经装好,
|
||||
所以两样都按「先试一次、没到就等它到」处理:
|
||||
|
||||
| 依赖 | 当场没有时 | 补挂方式 | 补挂后 |
|
||||
|---|---|---|---|
|
||||
| `webServer` | 路由不注册,`warnings` 记一条 | `ctx.inject(['webServer'], …)` 再注册一次 | 12 条接口可用 |
|
||||
| `sessionController` | 会话层为空,`hasSessions=false`,派发只落账 | `ctx.inject(['sessionController'], …)` → `shell.attachSessions(controller)` | 可以接通部门、真投递 |
|
||||
|
||||
两条补挂都**只做一次且幂等**:已经挂上就不再换(`attachSessions` 第二次调用返回 `true`
|
||||
但保留原实例)。这样用户不必为了「接通部门」专门多重启一次 DSH。
|
||||
|
||||
派发钩子是恒挂的:`shell.hasSessions===true` 走真投递,否则退回 `service.dispatchTask`
|
||||
只写 `prepared`——**任何时候都不会把「没接通」显示成「已发送」**。
|
||||
|
||||
`createWorkbenchHost(ctx, { store })` 支持注入账本(测试与嵌入场景):注入了就用它,
|
||||
不碰磁盘、不做损坏隔离,避免单测写到 `%DSH_HOME%` 下的真账本。
|
||||
|
||||
## 8. 尚未验证 / 已知限制
|
||||
|
||||
来自 `docs/v0.1-宿主能力记录.md` §8.2,按影响排序:
|
||||
|
|
|
|||
|
|
@ -68,15 +68,18 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
const clock = options.clock ?? Date.now
|
||||
const file = options.file === undefined ? resolveStorePath(env) : options.file
|
||||
const warnings = []
|
||||
const log = typeof options.log === 'function' ? options.log : () => {}
|
||||
|
||||
const store = new WorkbenchStore({
|
||||
// 测试与嵌入场景可以自带账本;自带时不碰磁盘路径,也不做损坏隔离(那是文件的责任)。
|
||||
const injectedStore = options.store ?? null
|
||||
const store = injectedStore ?? new WorkbenchStore({
|
||||
file,
|
||||
clock,
|
||||
env,
|
||||
...(options.random === undefined ? {} : { random: options.random }),
|
||||
})
|
||||
|
||||
if (options.load !== false && file !== null && file !== '') {
|
||||
if (injectedStore === null && options.load !== false && file !== null && file !== '') {
|
||||
ensureSidecarDir(env)
|
||||
if (existsSync(file)) {
|
||||
try {
|
||||
|
|
@ -115,7 +118,7 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
})
|
||||
const service = shell.service
|
||||
|
||||
const hooks = routeHooks(shell)
|
||||
const hooks = routeHooks(shell, service)
|
||||
let routes = registerWorkbenchRoutes(ctx, service, { ...options, ...hooks })
|
||||
let registered = routes.registered !== false
|
||||
if (!registered) warnings.push(`工作台接口未注册:${routes.reason ?? '宿主未提供 webServer'}`)
|
||||
|
|
@ -136,6 +139,22 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
// 会话层也可能晚到:apply 时 sessionController 还没装好,等它出现再挂载一次,
|
||||
// 这样用户不必为了「接通部门」而多重启一次 DSH。
|
||||
if (shell.hasSessions === false && ctx !== null && typeof ctx?.inject === 'function') {
|
||||
try {
|
||||
ctx.inject(['sessionController'], (scoped) => {
|
||||
if (shell.hasSessions === true) return
|
||||
const controller = scoped?.sessionController ?? scoped?.remote?.session ?? null
|
||||
if (controller === null) return
|
||||
if (!shell.attachSessions(controller)) return
|
||||
log('[sansheng-liubo] 会话层已就绪,部门可以接通与派发')
|
||||
})
|
||||
} catch (error) {
|
||||
warnings.push(`会话层补挂失败:${error?.message ?? error}`)
|
||||
}
|
||||
}
|
||||
|
||||
shell.start()
|
||||
|
||||
const dispose = () => {
|
||||
|
|
@ -151,10 +170,19 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
service,
|
||||
shell,
|
||||
routes,
|
||||
sessions: shell.sessions,
|
||||
reconciler: shell.reconciler,
|
||||
dispatchService: shell.dispatchService,
|
||||
hasSessions: shell.hasSessions,
|
||||
get sessions() {
|
||||
return shell.sessions
|
||||
},
|
||||
get reconciler() {
|
||||
return shell.reconciler
|
||||
},
|
||||
get dispatchService() {
|
||||
return shell.dispatchService
|
||||
},
|
||||
get hasSessions() {
|
||||
return shell.hasSessions
|
||||
},
|
||||
attachSessions: shell.attachSessions,
|
||||
presetId: shell.presetId,
|
||||
connectDepartment: shell.connectDepartment,
|
||||
dispatchTask: shell.dispatchTask,
|
||||
|
|
@ -176,15 +204,26 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
* 路由钩子:只有宿主真有能力时才接管,否则让路由退回“只落账”的保守路径。
|
||||
* 这样“没接通”永远不会被伪装成“已发送”。
|
||||
*/
|
||||
function routeHooks(shell) {
|
||||
const hooks = {
|
||||
function routeHooks(shell, service) {
|
||||
return {
|
||||
connect: (input) => shell.connectDepartment(input),
|
||||
ingest: (input) => shell.ingestAgentOutput(input),
|
||||
// 会话层可能晚到,所以钩子恒挂:真挂上了就走派发,没挂上就退回「只落账」,
|
||||
// 绝不把「没接通」伪装成「已发送」。
|
||||
dispatch: (input) => {
|
||||
if (shell.hasSessions === true) return shell.dispatchTask(input)
|
||||
return service.dispatchTask({
|
||||
projectId: input.projectId,
|
||||
taskId: input.taskId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
sourceRoleId: input.sourceRoleId,
|
||||
targetRoleId: input.targetRoleId,
|
||||
targetSessionId: input.targetSessionId,
|
||||
bindingGeneration: input.bindingGeneration,
|
||||
packet: input.packet,
|
||||
})
|
||||
},
|
||||
}
|
||||
if (shell.hasSessions === true && shell.dispatchService !== null) {
|
||||
hooks.dispatch = (input) => shell.dispatchTask(input)
|
||||
}
|
||||
return hooks
|
||||
}
|
||||
|
||||
export default createWorkbenchHost
|
||||
|
|
|
|||
|
|
@ -38,25 +38,40 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
const service = options.service ?? createWorkbenchService({ store, clock: options.clock, fileExists: options.fileExists })
|
||||
|
||||
// 会话层是可选能力:宿主没有 sessionController(或版本不提供)时整体降级。
|
||||
const sessionController = ctx?.sessionController ?? ctx?.remote?.session ?? null
|
||||
const hasSessions = sessionController !== null && typeof sessionController?.prompt === 'function'
|
||||
// 注意 apply 时宿主可能还没把 sessionController 装好,所以这里只是「尝试挂载」,
|
||||
// 真正的挂载动作集中在 mountSessions,宿主晚到时由 attachSessions 再补一次。
|
||||
let sessions = null
|
||||
if (hasSessions) {
|
||||
let dispatchService = null
|
||||
let reconciler = null
|
||||
let hasSessions = false
|
||||
let started = false
|
||||
|
||||
function mountSessions(controller) {
|
||||
const usable = controller !== null && typeof controller?.prompt === 'function'
|
||||
if (!usable) return false
|
||||
if (sessions !== null) return true
|
||||
try {
|
||||
sessions = createSessionAdapter({ sessionController, log })
|
||||
sessions = createSessionAdapter({ sessionController: controller, log })
|
||||
} catch (error) {
|
||||
log(`[sansheng-liubo] 会话层不可用:${error?.message ?? error}`)
|
||||
sessions = null
|
||||
return false
|
||||
}
|
||||
dispatchService = createDispatchService({ store, service, sessions, log })
|
||||
reconciler = createReconciler({ store, service, sessions, log })
|
||||
hasSessions = true
|
||||
if (started && options.startReconciler !== false) reconciler.start()
|
||||
return true
|
||||
}
|
||||
|
||||
const dispatchService = sessions === null
|
||||
? null
|
||||
: createDispatchService({ store, service, sessions, log })
|
||||
/** 宿主稍后才提供 sessionController 时补挂(不重启也能用)。返回是否挂上。 */
|
||||
function attachSessions(controller) {
|
||||
const mounted = mountSessions(controller ?? null)
|
||||
if (!mounted) log('[sansheng-liubo] 会话控制器仍不可用,派发继续保持“只落账”')
|
||||
return mounted
|
||||
}
|
||||
|
||||
const reconciler = sessions === null
|
||||
? null
|
||||
: createReconciler({ store, service, sessions, log })
|
||||
mountSessions(ctx?.sessionController ?? ctx?.remote?.session ?? null)
|
||||
|
||||
const presetId = typeof options.presetId === 'string' && options.presetId !== '' ? options.presetId : 'sansheng-liubu'
|
||||
|
||||
|
|
@ -137,7 +152,6 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
let started = false
|
||||
function start() {
|
||||
if (started) return
|
||||
started = true
|
||||
|
|
@ -154,11 +168,21 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
version: WORKBENCH_HOST_VERSION,
|
||||
store,
|
||||
service,
|
||||
sessions,
|
||||
reconciler,
|
||||
dispatchService,
|
||||
// 会话层可能晚到:用 getter,调用方总能读到最新挂载结果。
|
||||
get sessions() {
|
||||
return sessions
|
||||
},
|
||||
get reconciler() {
|
||||
return reconciler
|
||||
},
|
||||
get dispatchService() {
|
||||
return dispatchService
|
||||
},
|
||||
get hasSessions() {
|
||||
return hasSessions
|
||||
},
|
||||
attachSessions,
|
||||
presetId,
|
||||
hasSessions,
|
||||
connectDepartment,
|
||||
dispatchTask,
|
||||
ingestAgentOutput,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,194 @@
|
|||
// 装配层测试:index.mjs 把 store / service / 会话层 / HTTP 路由拼在一起的那一层。
|
||||
// 这里专门验「宿主稍后才给 sessionController」这条真实时序——它决定用户要不要多重启一次。
|
||||
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
import { createWorkbenchHost } from '../host/index.mjs'
|
||||
import { WorkbenchStore } from '../core/store.mjs'
|
||||
|
||||
const clock = () => 1700000000000
|
||||
const WS = 'ws_demo'
|
||||
|
||||
/** 最小 webServer 替身:记下注册的路由,卸载时清掉。 */
|
||||
function fakeWebServer() {
|
||||
const routes = new Map()
|
||||
return {
|
||||
routes,
|
||||
register(route) {
|
||||
routes.set(route.path, route)
|
||||
return () => routes.delete(route.path)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 最小 cordis 替身:inject 只把回调存起来,测试手动触发「依赖出现」。 */
|
||||
function fakeCtx({ webServer = null, controller = null } = {}) {
|
||||
const pending = []
|
||||
return {
|
||||
webServer,
|
||||
sessionController: controller,
|
||||
get: () => undefined,
|
||||
inject(deps, callback) {
|
||||
pending.push({ deps, callback })
|
||||
return { dispose() {} }
|
||||
},
|
||||
fire(dep, scoped) {
|
||||
const hit = pending.filter((row) => row.deps.includes(dep))
|
||||
for (const row of hit) row.callback(scoped)
|
||||
return hit.length
|
||||
},
|
||||
pending,
|
||||
}
|
||||
}
|
||||
|
||||
function fakeRes() {
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
headers: {},
|
||||
body: '',
|
||||
writableEnded: false,
|
||||
headersSent: false,
|
||||
setHeader(name, value) {
|
||||
this.headers[String(name).toLowerCase()] = value
|
||||
return this
|
||||
},
|
||||
writeHead(status, headers) {
|
||||
this.statusCode = status
|
||||
for (const [name, value] of Object.entries(headers ?? {})) this.headers[String(name).toLowerCase()] = value
|
||||
this.headersSent = true
|
||||
return this
|
||||
},
|
||||
end(chunk) {
|
||||
if (chunk !== undefined) this.body += String(chunk)
|
||||
this.writableEnded = true
|
||||
return this
|
||||
},
|
||||
get json() {
|
||||
return this.body === '' ? null : JSON.parse(this.body)
|
||||
},
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function fakeReq(method, url, body) {
|
||||
const text = body === undefined ? '' : JSON.stringify(body)
|
||||
const stream = Readable.from(body === undefined ? [] : [Buffer.from(text, 'utf8')])
|
||||
stream.method = method
|
||||
stream.url = url
|
||||
stream.headers = { 'content-type': 'application/json' }
|
||||
return stream
|
||||
}
|
||||
|
||||
async function callRoute(webServer, suffix, method, body) {
|
||||
const route = [...webServer.routes.values()].find((item) => String(item.path).endsWith(suffix))
|
||||
assert.notEqual(route, undefined, `未注册路由:${suffix}`)
|
||||
const res = fakeRes()
|
||||
await route.handler(fakeReq(method, route.path, body), res)
|
||||
return res.json
|
||||
}
|
||||
|
||||
/** 所有测试都用内存账本,绝不碰 %DSH_HOME% 下的真账本。 */
|
||||
function memoryStore() {
|
||||
return new WorkbenchStore({ file: null, clock })
|
||||
}
|
||||
|
||||
function tinyController(seed = ['ses_gongbu']) {
|
||||
const sessions = new Map()
|
||||
const prompts = []
|
||||
for (const sessionId of seed) {
|
||||
sessions.set(sessionId, { sessionId, workspaceId: WS, running: false, accepted: new Set() })
|
||||
}
|
||||
return {
|
||||
prompts,
|
||||
sessions,
|
||||
async create(request) {
|
||||
const sessionId = request.sessionId ?? 'ses_auto'
|
||||
sessions.set(sessionId, { sessionId, workspaceId: request.workspaceId ?? WS, running: false, accepted: new Set() })
|
||||
return { sessionId }
|
||||
},
|
||||
async prompt(request) {
|
||||
prompts.push(request)
|
||||
const row = sessions.get(request.sessionId)
|
||||
if (row === undefined || !row.accepted) throw Object.assign(new Error('no session'), { code: 'session/conflict' })
|
||||
row.accepted.add(request.requestId)
|
||||
return { accepted: true }
|
||||
},
|
||||
cancel() {
|
||||
return { accepted: true }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('装配层:宿主先有 webServer、后有 sessionController 时,派发从“只落账”升级为真投递', async () => {
|
||||
const store = memoryStore()
|
||||
const webServer = fakeWebServer()
|
||||
const ctx = fakeCtx({ webServer })
|
||||
|
||||
const host = createWorkbenchHost(ctx, { store, startReconciler: false })
|
||||
assert.equal(host.store, store)
|
||||
assert.equal(host.registered, true)
|
||||
assert.equal(webServer.routes.size, 12)
|
||||
assert.equal(host.hasSessions, false)
|
||||
|
||||
const project = host.service.registerProject({ hostWorkspaceId: WS }).project
|
||||
const bound = host.service.bindDepartmentSession({ projectId: project.id, roleId: 'gongbu', sessionId: 'ses_gongbu' })
|
||||
const generation = bound.binding.bindingGeneration
|
||||
const task = host.service.createTask({
|
||||
projectId: project.id,
|
||||
ownerRoleId: 'gongbu',
|
||||
sourceRoleId: 'lead',
|
||||
title: '接线后派发',
|
||||
objective: 'o',
|
||||
status: 'queued',
|
||||
}).task
|
||||
|
||||
// 还没有会话层:路由只落账,状态停在 prepared,不伪装成已发送。
|
||||
const before = await callRoute(webServer, '/dispatch', 'POST', {
|
||||
projectId: project.id,
|
||||
taskId: task.id,
|
||||
idempotencyKey: 'k-ledger',
|
||||
targetRoleId: 'gongbu',
|
||||
targetSessionId: 'ses_gongbu',
|
||||
bindingGeneration: generation,
|
||||
})
|
||||
assert.equal(before.ok, true)
|
||||
assert.equal(before.value.dispatch.status, 'prepared')
|
||||
|
||||
// 宿主晚到:装配层自己把会话层补挂上,不需要重建工作台、也不需要多重启一次。
|
||||
const controller = tinyController()
|
||||
assert.equal(ctx.fire('sessionController', { sessionController: controller }), 1)
|
||||
assert.equal(host.hasSessions, true)
|
||||
assert.notEqual(host.dispatchService, null)
|
||||
assert.notEqual(host.reconciler, null)
|
||||
|
||||
// 同一份账本、同一张任务,换新的幂等键再派一次:这次真的投递到会话。
|
||||
const after = await callRoute(webServer, '/dispatch', 'POST', {
|
||||
projectId: project.id,
|
||||
taskId: task.id,
|
||||
idempotencyKey: 'k-live',
|
||||
targetRoleId: 'gongbu',
|
||||
targetSessionId: 'ses_gongbu',
|
||||
bindingGeneration: generation,
|
||||
})
|
||||
assert.equal(after.ok, true)
|
||||
assert.equal(after.value.dispatch.state ?? after.value.dispatch.status, 'accepted')
|
||||
assert.equal(controller.prompts.length, 1)
|
||||
|
||||
host.dispose()
|
||||
assert.equal(webServer.routes.size, 0)
|
||||
})
|
||||
|
||||
test('装配层:重复挂载会话层是幂等的,不会把已挂上的换掉', () => {
|
||||
const store = memoryStore()
|
||||
const ctx = fakeCtx({ webServer: fakeWebServer() })
|
||||
const host = createWorkbenchHost(ctx, { store, startReconciler: false })
|
||||
assert.equal(host.hasSessions, false)
|
||||
|
||||
assert.equal(host.attachSessions(tinyController()), true)
|
||||
const first = host.sessions
|
||||
assert.equal(host.attachSessions(tinyController()), true)
|
||||
assert.equal(host.sessions, first)
|
||||
host.dispose()
|
||||
})
|
||||
|
|
@ -324,3 +324,32 @@ test('工作台外壳:ingestAgentOutput 只应用可解析的契约行', () =>
|
|||
assert.equal(out.failed.length, 0)
|
||||
assert.equal(store.getTask(task.id).status, 'waiting_input')
|
||||
})
|
||||
|
||||
test('工作台外壳:sessionController 晚到后仍能补挂会话层(不必多重启一次)', async () => {
|
||||
const store = new WorkbenchStore({ file: null, clock })
|
||||
// 模拟 apply 那一刻宿主还没装好 sessionController。
|
||||
const host = createWorkbenchHost({}, { store })
|
||||
const project = host.service.registerProject({ hostWorkspaceId: WS }).project
|
||||
assert.equal(host.hasSessions, false)
|
||||
const refused = await host.dispatchTask({ projectId: project.id, taskId: 'task_x', idempotencyKey: 'k1', sourceRoleId: 'lead', targetRoleId: 'gongbu', targetSessionId: 'ses_gongbu', bindingGeneration: 0 })
|
||||
assert.equal(refused.ok, false)
|
||||
assert.equal(refused.code, 'NO_SESSION_CONTROLLER')
|
||||
|
||||
// 宿主稍后把会话控制器交过来:同一实例直接挂上,不需要重建工作台。
|
||||
const controller = fakeController()
|
||||
assert.equal(host.attachSessions(controller), true)
|
||||
assert.equal(host.hasSessions, true)
|
||||
assert.notEqual(host.sessions, null)
|
||||
assert.notEqual(host.dispatchService, null)
|
||||
assert.notEqual(host.reconciler, null)
|
||||
|
||||
// 重复挂载必须幂等:不能把已有会话层换掉。
|
||||
const first = host.sessions
|
||||
assert.equal(host.attachSessions(fakeController()), true)
|
||||
assert.equal(host.sessions, first)
|
||||
|
||||
// 挂上之后「接通部门」才真正建会话并登记到账本。
|
||||
const connected = await host.connectDepartment({ projectId: project.id, roleId: 'gongbu' })
|
||||
assert.equal(connected.sessionId, 'ses_gongbu'.replace('ses_gongbu', connected.sessionId))
|
||||
assert.equal(store.getBinding(project.id, 'gongbu').currentSessionId, connected.sessionId)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue