diff --git a/docs/preview/v01-live-court-400-light.png b/docs/preview/v01-live-court-400-light.png new file mode 100644 index 0000000..027f485 Binary files /dev/null and b/docs/preview/v01-live-court-400-light.png differ diff --git a/docs/preview/v01-live-tasks-400-light.png b/docs/preview/v01-live-tasks-400-light.png new file mode 100644 index 0000000..adfb92b Binary files /dev/null and b/docs/preview/v01-live-tasks-400-light.png differ diff --git a/docs/v0.1-验收记录.md b/docs/v0.1-验收记录.md index 8c28234..05cf691 100644 --- a/docs/v0.1-验收记录.md +++ b/docs/v0.1-验收记录.md @@ -30,7 +30,7 @@ node --test --test-isolation=none test/policy.test.js workbench/test/*.test.mjs | A02 | 切 A/B、重命名/移动项目不换 session | 已验(单测) | `registerProject 同一工作区只建一个项目`;绑定只用 `hostWorkspaceId` 与 `bindingGeneration`,名称变更不触碰绑定 | | A03 | 点分组节点不创建项目或十席会话 | 已验(单测) | `layoutGroups renders three tiers without inventing parent links`;`initial seats describe configuration rows without creating sessions` | | A04 | 双击首次启动同部门只建一个 session | 已验(单测)+ 待真机 | `会话适配:缺 sessionId 时按 workspace 建会话且不重复建`;`绑定:同一会话被别处持有 → SESSION_CONFLICT`。真机二次点击要复验(U4) | -| A05 | 十席分别发短消息,输入/历史/实际 session 一致 | 已验(装配层闭环 + 界面派工入口) | `A05 两席闭环`:经 HTTP 路由 `POST /dispatch` 真的把任务单投进工部会话(`controller.prompts[0].content[0].text` 含任务标题),派发按 `targetSessionId` + `bindingGeneration` 双校验;工部用契约行回执 → `Result` 落账 → 终态成功 + 成果核验 → 任务 `completed`。十席各自 session 的输入/历史一致性仍需真机逐个看。界面任务行已加「派工 / 取消」(`taskActionKeys` 单测 + tasks 页预览截图),派工同样带 sessionId + bindingGeneration | +| A05 | 十席分别发短消息,输入/历史/实际 session 一致 | 已验(真实 bundle + 真实路由,伪宿主会话) | `--live` 模式把**真实 panel bundle** 打到**真实 Host 路由**上:新建任务存草稿 → 点「派工」→ `POST /dispatch` 200 且 `dispatch.status=accepted`,任务行变「工部 · 执行中」,伪 controller 收到 743 字符任务单(`docs/preview/v01-live-tasks-400-light.png`)。装配层测试另有完整闭环(契约回执 → Result → completed)。真宿主的十席输入/历史一致性仍需重启后逐个看 | | A06 | A 工部改模型,B 工部用另一模型,全局默认不变 | 已验(单测)+ 待真机 | 配置按 `projectId+roleId` 存、`saveDepartmentConfig` CAS;**派发时默认不再调 `selectModel`**(部门模型由政策插件在 `agent/request` 上按角色覆写,再调一次会让宿主把全局默认存成本部门的),模型快照仍记在 `attempt.effectiveConfigSnapshot`。真机待看 `modelSelection` 投影 | | A07 | 运行中改模型,本次仍用原模型 | 已验(单测) | `首次派发:固定模型快照 → prompt 用 attemptId 作幂等键`:`effectiveConfigSnapshot` 在派发时冻结 | | A08 | 模型不支持旧 effort / 目录失效,校验错误可见 | 已验(单测) | `会话适配:prompt 必须带 requestId,错误分类可区分可重试与必失败` 覆盖 `model_unavailable`;不静默替换 | diff --git a/scripts/preview-workbench.mjs b/scripts/preview-workbench.mjs index 11f2338..8c33667 100644 --- a/scripts/preview-workbench.mjs +++ b/scripts/preview-workbench.mjs @@ -69,6 +69,7 @@ function parseArgs(argv) { chrome: null, view: 'court', open: '', + live: false, help: false, } const keys = { @@ -96,6 +97,11 @@ function parseArgs(argv) { options.help = true continue } + if (rawKey === 'live') { + if (eq !== -1 && body.slice(eq + 1) === 'false') options.live = false + else options.live = true + continue + } const field = keys[rawKey] if (!field) fail(`无法识别的参数:--${rawKey}`) let value @@ -127,6 +133,7 @@ function usage() { ' --chrome Chrome/Edge 可执行文件路径,默认自动探测', ' --view court | tasks | artifacts,先切到该页签再截图,默认 court', ' --open 切到成果页后点开匹配这段文字的成果行(看详情抽屉)', + ' --live 不打死数据:把 bundle 的 fetch 接到仓库内真实 Host 路由(内存账本)', ' --help 显示本帮助', ].join('\n') } @@ -949,7 +956,7 @@ function loadBundle(sourcePath, hooks, options) { const { React } = hooks const env = createBrowserEnv({ theme: options.theme, - fetchStub: createFetchStub(options.theme, (path, method) => { + fetchStub: options.fetchStub || createFetchStub(options.theme, (path, method) => { log(`fetch 未命中固定数据:${method} ${path}(返回空对象/数组占位)`) }), }) @@ -1513,6 +1520,521 @@ function createDemoContext() { // #region 选择要渲染的组件 +/* #region 真实 Host 模式(--live) + 与打桩模式共用同一套 vm/hooks/序列化/截图;区别只在于 fetch: + 这里把 bundle 的 fetch 桥到 workbench/host 真正注册的路由,账本用内存 store, + 绝不碰 %USERPROFILE%\.dsh\sansheng-liubu\workbench.json。 */ + +function createLiveSessionController(onPrompt) { + let next = 1 + const sessions = new Map() + const calls = { create: [], prompt: [], inspect: [], selectModel: [], cancel: [] } + const controller = { + calls, + sessions, + async create(request = {}) { + calls.create.push(request) + const existing = [...sessions.values()].find( + (row) => row.workspaceId === (request.workspaceId ?? null) && request.sessionId === undefined, + ) + if (existing !== undefined) return { sessionId: existing.sessionId, agentPreset: existing.agentPreset ?? null } + const sessionId = request.sessionId ?? `sess_live_${next++}` + sessions.set(sessionId, { + sessionId, + workspaceId: request.workspaceId ?? null, + agentPreset: request.agentPreset ?? null, + running: false, + accepted: new Set(), + }) + return { sessionId, agentPreset: request.agentPreset ?? null } + }, + async inspect(sessionId) { + calls.inspect.push(sessionId) + const row = sessions.get(sessionId) + if (row === undefined) throw Object.assign(new Error('not found'), { code: 'session/not-found' }) + return { sessionId, attached: true } + }, + async prompt(request) { + calls.prompt.push(request) + const row = sessions.get(request.sessionId) + if (row === undefined) throw Object.assign(new Error('no session'), { code: 'session/conflict' }) + const text = request?.content?.[0]?.text ?? '' + if (typeof onPrompt === 'function') onPrompt({ sessionId: request.sessionId, requestId: request.requestId, text }) + if (row.accepted.has(request.requestId)) return { accepted: true } + row.accepted.add(request.requestId) + row.running = true + return { accepted: true } + }, + cancel(request) { + calls.cancel.push(request) + const row = sessions.get(request?.sessionId) + if (row !== undefined) row.running = false + return { accepted: true } + }, + async selectModel(request) { + calls.selectModel.push(request) + return { selected: { provider: request?.provider ?? null, model: request?.model ?? null } } + }, + async list() { + return { + items: [...sessions.values()].map((row) => ({ + sessionId: row.sessionId, + running: row.running, + agentAvailable: true, + updatedAt: '', + blank: false, + })), + } + }, + } + return controller +} + +/** 把标准 fetch 调用桥到 workbench/host 注册的 route handler。 */ +function createLiveFetch(handlers, live) { + return async function liveFetch(input, init = {}) { + const raw = typeof input === 'string' + ? input + : input && typeof input.url === 'string' + ? input.url + : String(input) + const url = new URL(raw, 'http://preview.local') + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase() + const path = url.pathname + const handler = handlers.get(path) + const bodyText = init && init.body !== undefined && init.body !== null + ? (typeof init.body === 'string' ? init.body : JSON.stringify(init.body)) + : '' + + if (typeof handler !== 'function') { + const entry = { method, path, query: url.search, status: 404, note: '未注册路由' } + live.requests.push(entry) + log(`[live] ${method} ${path} → 404(未注册路由)`) + return makeResponse(404, { ok: false, error: { code: 'NOT_FOUND', message: `未注册路由:${path}` } }) + } + + const req = { + method, + url: `${path}${url.search}`, + headers: Object.assign({}, init && init.headers), + async *[Symbol.asyncIterator]() { + if (bodyText !== '') yield Buffer.from(bodyText, 'utf8') + }, + } + const headers = {} + let body = '' + const res = { + statusCode: 200, + headers, + headersSent: false, + writableEnded: false, + destroyed: false, + setHeader(name, value) { headers[String(name).toLowerCase()] = value }, + getHeader(name) { return headers[String(name).toLowerCase()] }, + writeHead(status, extra) { + this.statusCode = status + if (extra && typeof extra === 'object') { + for (const [key, value] of Object.entries(extra)) headers[String(key).toLowerCase()] = value + } + this.headersSent = true + return this + }, + write(chunk) { body += chunk === undefined ? '' : String(chunk); return true }, + end(chunk) { + if (chunk !== undefined && chunk !== null) body += String(chunk) + this.writableEnded = true + }, + on() {}, once() {}, off() {}, emit() {}, removeListener() {}, + } + + let failure = null + try { + await handler(req, res) + } catch (error) { + failure = error + if (!res.writableEnded) { + res.writeHead(500, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ ok: false, error: { code: 'LIVE_BRIDGE_CRASH', message: String(error?.message ?? error) } })) + } + } + + let payload = {} + try { payload = body === '' ? {} : JSON.parse(body) } catch { payload = { raw: body } } + const entry = { method, path, query: url.search, status: res.statusCode } + live.requests.push(entry) + log(`[live] ${method} ${path}${url.search} → ${res.statusCode}`) + if (failure) log(`[live] handler 抛错:${failure?.stack ?? failure}`) + + if (path.endsWith('/dispatch')) { + const record = payload && payload.value ? payload.value.dispatch : null + live.dispatches.push({ + status: record ? (record.status || record.state || null) : null, + httpStatus: res.statusCode, + payload, + }) + log(`[live] dispatch.status=${record ? (record.status || record.state) : '(无)'}`) + } + + return { + ok: res.statusCode >= 200 && res.statusCode < 300, + status: res.statusCode, + statusText: res.statusCode === 200 ? 'OK' : 'Error', + headers: { get: (name) => headers[String(name).toLowerCase()] ?? null }, + json: async () => JSON.parse(JSON.stringify(payload)), + text: async () => body, + } + } +} + +async function setupLiveHost() { + const hostModule = await import(pathToFileURL(join(ROOT, 'workbench/host/index.mjs')).href) + const storeModule = await import(pathToFileURL(join(ROOT, 'workbench/core/store.mjs')).href) + const clock = () => Date.now() + const store = new storeModule.WorkbenchStore({ + file: null, + clock, + env: { DSH_HOME: join(SCRATCH, 'live-home') }, + }) + const live = { + requests: [], + dispatches: [], + prompts: [], + projectId: null, + controller: null, + } + const controller = createLiveSessionController((entry) => { + live.prompts.push(entry) + log(`[live] 伪 sessionController 收到 prompt(${entry.text.length} 字符):${entry.text.slice(0, 80).replace(/\\s+/g, ' ')}…`) + }) + live.controller = controller + + const handlers = new Map() + const webServer = { + register(registration = {}) { + const path = registration.path + if (typeof path !== 'string' || typeof registration.handler !== 'function') { + throw new Error('webServer.register 需要 path 与 handler') + } + handlers.set(path, registration.handler) + return () => { handlers.delete(path) } + }, + } + + const ctx = { + webServer, + // 故意先不给 sessionController:让 Host 走 ctx.inject(['sessionController']) 的晚挂路径。 + inject(deps, callback) { + const scoped = { webServer, sessionController: controller } + try { + callback(scoped) + } catch (error) { + log(`[live] ctx.inject 回调失败:${error?.message ?? error}`) + } + return () => {} + }, + uiWorkspace: { + currentWorkspaceId: 'ws_demo', + openSession(sessionId) { log(`[live] openSession(${sessionId})(替身,仅记录)`) }, + selection: { + getSnapshot: () => ({ workspaceId: 'ws_demo' }), + set(value) { log(`[live] uiWorkspace.selection.set(${JSON.stringify(value)})`) }, + }, + }, + } + + const host = hostModule.createWorkbenchHost(ctx, { + store, + clock, + load: false, + startReconciler: false, + longPollMs: 0, + pollIntervalMs: 10, + log: (message) => log(`[host] ${message}`), + }) + if (host.registered === false) fail(`真实 Host 路由未注册:${host.warning || '未知原因'}`) + if (host.hasSessions !== true) fail('真实 Host 没有挂上伪 sessionController(inject 晚挂失败)') + + live.host = host + live.routes = host.routes + live.fetchLive = createLiveFetch(handlers, live) + log(`[live] Host 就绪:账本 file=${String(store.file)},路由 ${host.routes.paths?.length ?? handlers.size} 条,hasSessions=${host.hasSessions}`) + return live +} + +async function registerLiveProject(live) { + const response = await live.fetchLive(`${ROUTE_PREFIX}/project`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + hostWorkspaceId: 'ws_demo', + displayNameCache: '演示项目', + canonicalRoot: 'C:\\\\demo', + }), + }) + const payload = await response.json() + const project = payload && payload.value && payload.value.project + if (!response.ok || !project || typeof project.id !== 'string') { + fail(`通过真实 POST /project 注册项目失败(HTTP ${response.status}):${JSON.stringify(payload)}`) + } + live.projectId = project.id + log(`[live] 已通过真实 /project 注册项目:${project.id}`) + return project.id +} + +function createLiveUiContext() { + return { + uiWorkspace: { + currentWorkspaceId: 'ws_demo', + openSession(sessionId) { log(`[live] bundle 请求打开会话 ${sessionId}`) }, + selection: { + getSnapshot: () => ({ workspaceId: 'ws_demo' }), + set(value) { log(`[live] selection.set(${JSON.stringify(value)})`) }, + }, + }, + } +} + +function findAllMounted(node, predicate, out = []) { + if (!node) return out + if (predicate(node)) out.push(node) + if (node.fragment) { + for (const child of node.children) findAllMounted(child, predicate, out) + } else if (Array.isArray(node.children)) { + for (const child of node.children) findAllMounted(child, predicate, out) + } + return out +} + +function textOf(node) { + return mountedText(node).replace(/\\s+/g, ' ').trim() +} + +function findClass(node, className) { + return findMounted(node, (child) => classNameOf(child).includes(className)) +} + +function findSeatCard(tree, roleName) { + return findMounted(tree, (node) => { + if (!classNameOf(node).includes('wb-card')) return false + const text = textOf(node) + return text.includes(roleName) + }) +} + +function findClickableByText(node, needle) { + return findMounted(node, (child) => { + if (child.type !== 'button') return false + return textOf(child).includes(needle) + }) +} + +async function liveSettle(hooks, rootVNode, label) { + const result = await settle(hooks, rootVNode, 4000) + log(`[live] ${label}:${result.settled ? '稳定' : '未稳定'},${result.passes} 轮,${result.elapsedMs}ms`) + return result.tree +} + +async function liveWait(hooks, rootVNode, predicate, label, budgetMs = 4000) { + const started = Date.now() + let tree = null + let passes = 0 + while (Date.now() - started < budgetMs) { + const result = await settle(hooks, rootVNode, 1000) + tree = result.tree + passes += result.passes + if (predicate(tree)) { + log(`[live] ${label}:满足(${Date.now() - started}ms,${passes} 轮)`) + return { tree, passes, ok: true } + } + await new Promise((resolveWait) => setTimeout(resolveWait, 30)) + } + log(`[live] ${label}:超时未满足(${budgetMs}ms)`) + return { tree, passes, ok: false } +} + +async function connectSeatLive(hooks, rootVNode, tree, roleName) { + const card = findSeatCard(tree, roleName) + if (!card) fail(`[live] 在朝堂里找不到「${roleName}」卡片`) + const before = textOf(card) + const button = findMounted(card, (node) => classNameOf(node).includes('wb-connect')) + if (!button) fail(`[live]「${roleName}」卡片没有「接通」按钮:${before}`) + log(`[live] 点击「${roleName} · 接通」;点击前:${before}`) + if (!clickMounted(button)) fail(`[live]「${roleName} · 接通」的 onClick 不可调用`) + const waited = await liveWait( + hooks, + rootVNode, + (nextTree) => { + const nextCard = findSeatCard(nextTree, roleName) + return Boolean(nextCard) && !textOf(nextCard).includes('未接通') && !classNameOf(nextCard).includes('is-pending') + }, + `等待「${roleName}」接通`, + ) + const afterCard = findSeatCard(waited.tree, roleName) + const after = afterCard ? textOf(afterCard) : '(卡片消失)' + log(`[live]「${roleName}」点击后:${after}`) + return { tree: waited.tree, before, after, ok: waited.ok, passes: waited.passes } +} + +async function openTaskFormLive(hooks, rootVNode, tree) { + const newButton = findClickableByText(tree, '新建') + if (!newButton) fail('[live] 任务页找不到「新建」按钮') + clickMounted(newButton) + const opened = await liveWait(hooks, rootVNode, (next) => Boolean(findClass(next, 'wb-form')), '等待任务表单展开') + if (!opened.ok) fail('[live] 点击「新建」后表单没有出现') + return opened.tree +} + +async function setFormFieldLive(hooks, rootVNode, tree, className, value) { + const form = findClass(tree, 'wb-form') + if (!form) fail(`[live] 找不到任务表单(设置 ${className} 时)`) + const field = findClass(form, className) + if (!field || !field.props || typeof field.props.onChange !== 'function') { + fail(`[live] 任务表单里找不到可输入的 .${className}`) + } + field.props.onChange({ target: { value }, currentTarget: { value } }) + return liveSettle(hooks, rootVNode, `填写 ${className}=${value}`) +} + +async function submitTaskFormLive(hooks, rootVNode, tree) { + const form = findClass(tree, 'wb-form') + if (!form || !form.props || typeof form.props.onSubmit !== 'function') fail('[live] 任务表单没有 onSubmit') + form.props.onSubmit({ preventDefault() {}, target: {}, currentTarget: {} }) + return liveSettle(hooks, rootVNode, '提交任务草稿') +} + +async function dispatchTaskLive(hooks, rootVNode, tree, title) { + const taskCard = findMounted(tree, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes(title)) + if (!taskCard) fail(`[live] 任务列表里找不到「${title}」`) + const before = textOf(taskCard) + const button = findClickableByText(taskCard, '派工') + if (!button) fail(`[live]「${title}」没有「派工」按钮:${before}`) + log(`[live] 点击「派工」;点击前:${before}`) + clickMounted(button) + const waited = await liveWait( + hooks, + rootVNode, + (next) => { + const card = findMounted(next, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes(title)) + const text = card ? textOf(card) : '' + return Boolean(card) && !text.includes('排队') && !text.includes('草稿') && (text.includes('执行中') || text.includes('正在运行')) + }, + '等待任务进入运行态', + ) + const afterCard = findMounted(waited.tree, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes(title)) + const after = afterCard ? textOf(afterCard) : '(任务消失)' + log(`[live]「派工」后:${after}`) + return { tree: waited.tree, before, after, ok: waited.ok, passes: waited.passes } +} + +async function runLiveScenario({ hooks, rootVNode, view, live, projectId }) { + let tree = await liveSettle(hooks, rootVNode, '首屏 bootstrap') + const assertions = [] + let passes = 0 + + if (view === 'court') { + const connected = await connectSeatLive(hooks, rootVNode, tree, '丞相') + tree = connected.tree + passes += connected.passes + assertions.push({ + name: '丞相接通后从「未接通」变「空闲」', + ok: connected.ok && connected.after.includes('空闲'), + before: connected.before, + after: connected.after, + }) + const courtNotice = findMounted(connected.tree, (node) => classNameOf(node).includes('wb-alert')) + const courtNoticeClass = courtNotice ? classNameOf(courtNotice) : '' + const courtNoticeText = courtNotice ? textOf(courtNotice) : '' + log(`[live] 接通提示:class="${courtNoticeClass}" text="${courtNoticeText}"`) + assertions.push({ + name: '接通成功提示为绿色信息条(is-info)', + ok: courtNoticeClass.includes('is-info') && courtNoticeText.includes('已接通'), + before: '(无)', + after: courtNoticeText, + }) + } else if (view === 'tasks') { + const connected = await connectSeatLive(hooks, rootVNode, tree, '工部') + tree = connected.tree + passes += connected.passes + assertions.push({ + name: '工部接通', + ok: connected.ok, + before: connected.before, + after: connected.after, + }) + + const switched = await switchPreviewState(hooks, rootVNode, 'tasks', '', tree) + tree = switched.tree + passes += switched.passes + log(`[live] 已切到任务页:${switched.clickedTab || '(未切换)'}`) + + const title = '实机验证:预览器直连 Host' + const objective = '确认 --live 模式能把任务单真正送进工部会话。' + // 真实路径:新建 → 存为草稿 → 任务行点「派工」,不经过 queued 接口。 + tree = await openTaskFormLive(hooks, rootVNode, tree) + const fields = [ + ['wb-input', title], + ['wb-textarea', objective], + ['wb-select', 'gongbu'], + ] + for (const [className, value] of fields) { + tree = await setFormFieldLive(hooks, rootVNode, tree, className, value) + } + tree = await submitTaskFormLive(hooks, rootVNode, tree) + const drafted = await liveWait( + hooks, + rootVNode, + (next) => Boolean(findMounted(next, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes(title))), + '等待草稿任务出现在列表', + ) + if (!drafted.ok) fail(`[live] 表单提交后任务列表没有出现「${title}」`) + tree = drafted.tree + passes += drafted.passes + log(`[live] 表单已存为草稿:${title}`) + + const dispatched = await dispatchTaskLive(hooks, rootVNode, tree, title) + const dispatchRecord = live.dispatches.length > 0 ? live.dispatches[live.dispatches.length - 1] : null + if (dispatchRecord) { + log(`[live] /dispatch 返回:HTTP ${dispatchRecord.httpStatus} ${JSON.stringify(dispatchRecord.payload)}`) + } + tree = dispatched.tree + passes += dispatched.passes + assertions.push({ + name: '派工后任务离开排队态、进入执行中', + ok: dispatched.ok && !dispatched.after.includes('排队') && !dispatched.after.includes('草稿') + && (dispatched.after.includes('执行中') || dispatched.after.includes('正在运行')), + before: dispatched.before, + after: dispatched.after, + }) + const noticeNode = findMounted(dispatched.tree, (node) => classNameOf(node).includes('wb-alert')) + const noticeClass = noticeNode ? classNameOf(noticeNode) : '' + const noticeText = noticeNode ? textOf(noticeNode) : '' + log(`[live] 派工提示:class="${noticeClass}" text="${noticeText}"`) + assertions.push({ + name: '派工成功提示为绿色信息条(is-info)', + ok: noticeClass.includes('is-info') && noticeText.includes('已派出'), + before: '(无)', + after: noticeText, + }) + } else { + fail(`--live 目前只编排 court / tasks 两个场景,收到:${view}`) + } + + const dispatch = live.dispatches.length > 0 ? live.dispatches[live.dispatches.length - 1] : null + return { + tree, + passes, + assertions, + requests: live.requests, + dispatches: live.dispatches, + dispatchStatus: dispatch ? dispatch.status : null, + prompts: live.prompts, + projectId, + controllerCalls: live.controller.calls, + } +} + +/* #endregion */ + function pickComponent(exports) { const keys = Object.keys(exports || {}) const preview = exports && exports.__preview @@ -2012,9 +2534,16 @@ async function main() { const profileDir = join(SCRATCH, 'chrome-profile') ensureDir(profileDir) + let live = null + if (options.live) { + log('模式:--live(真实 Host 路由,内存账本,不使用固定数据)') + live = await setupLiveHost() + await registerLiveProject(live) + } + log(`加载 bundle:${bundlePath}`) const hooks = createHooks() - const loaded = loadBundle(bundlePath, hooks, { theme }) + const loaded = loadBundle(bundlePath, hooks, { theme, fetchStub: live ? live.fetchLive : null }) log(`bundle 导出键:${Object.keys(loaded.exports).join(', ') || '(空)'}`) log(`捕获 CSS:${loaded.css.length} 字符`) @@ -2024,8 +2553,16 @@ async function main() { let component = picked.component let props = { ...picked.props } let placeholder = false + let entryMode = picked.mode - if (typeof component !== 'function') { + if (live && typeof loaded.exports.WorkbenchRail === 'function') { + // 真实 Host 模式下用 rail 本体(WorkbenchPanel 会丢掉 projectId 并走工作区推导, + // 这里已经有真实注册出来的项目号,直接喂给它)。 + component = loaded.exports.WorkbenchRail + props = { ctx: createLiveUiContext(), projectId: live.projectId, compact: true } + entryMode = 'exports.WorkbenchRail(live)' + log(`渲染入口改为 exports.WorkbenchRail(projectId=${live.projectId})`) + } else if (typeof component !== 'function') { placeholder = true const keyList = (picked.keys || Object.keys(loaded.exports)).join(', ') || '(空)' log(`没有找到面板组件,退化为占位 div。bundle 导出键:${keyList}`) @@ -2052,8 +2589,8 @@ async function main() { } } - if (props.projectId === undefined) props.projectId = 'prj_demo1' - if (props.sessionId === undefined) props.sessionId = LEAD_SESSION + if (!live && props.projectId === undefined) props.projectId = 'prj_demo1' + if (!live && props.sessionId === undefined) props.sessionId = LEAD_SESSION if (props.compact === undefined) props.compact = true const rootVNode = hooks.React.createElement(component, props) @@ -2062,7 +2599,22 @@ async function main() { let tree = settleResult.tree let stateSwitch = { clickedTab: null, openedArtifact: null } - if (effectiveView !== 'court' || openText) { + let liveScenario = null + if (live) { + liveScenario = await runLiveScenario({ + hooks, + rootVNode, + view: effectiveView, + live, + projectId: live.projectId, + }) + tree = liveScenario.tree + settleResult.passes += liveScenario.passes + for (const assertion of liveScenario.assertions) { + log(`[live] 断言「${assertion.name}」:${assertion.ok ? '通过' : '未通过'};after=${assertion.after}`) + } + log(`[live] 请求 ${liveScenario.requests.length} 次;dispatch.status=${liveScenario.dispatchStatus ?? '(无)'};prompt ${liveScenario.prompts.length} 条`) + } else if (effectiveView !== 'court' || openText) { const switched = await switchPreviewState(hooks, rootVNode, effectiveView, openText, tree) tree = switched.tree stateSwitch = { clickedTab: switched.clickedTab, openedArtifact: switched.openedArtifact } @@ -2100,8 +2652,24 @@ async function main() { bundle: bundlePath, bundleBase: options.bundle, bundleBytes: statSync(bundlePath).size, - entry: picked.mode, + entry: entryMode, placeholder, + live: liveScenario + ? { + projectId: liveScenario.projectId, + requests: liveScenario.requests, + dispatches: liveScenario.dispatches, + dispatchStatus: liveScenario.dispatchStatus, + prompts: liveScenario.prompts.map((entry) => ({ + sessionId: entry.sessionId, + requestId: entry.requestId, + text: entry.text.slice(0, 200), + chars: entry.text.length, + })), + assertions: liveScenario.assertions, + controllerCalls: liveScenario.controllerCalls, + } + : null, theme, width, scale, @@ -2131,6 +2699,20 @@ async function main() { : null, scriptLines: sourceLines, } + if (liveScenario) { + const liveLogPath = join(SCRATCH, `${name}-${width}-${theme}-live.json`) + writeFileSync(liveLogPath, JSON.stringify({ + bundle: bundlePath, + projectId: liveScenario.projectId, + requests: liveScenario.requests, + dispatches: liveScenario.dispatches, + dispatchStatus: liveScenario.dispatchStatus, + prompts: liveScenario.prompts, + assertions: liveScenario.assertions, + controllerCalls: liveScenario.controllerCalls, + }, null, 2), 'utf8') + log(`[live] 请求/派发/prompt 日志:${liveLogPath}`) + } process.stdout.write(`PREVIEW_RESULT ${JSON.stringify(report)}\n`) } diff --git a/workbench/host/service.mjs b/workbench/host/service.mjs index 8756c39..1aca849 100644 --- a/workbench/host/service.mjs +++ b/workbench/host/service.mjs @@ -618,7 +618,7 @@ export function createWorkbenchService(options = {}) { */ const dispatchTask = guard((input = {}) => { const project = projectIdOf(input) - const task = requireTask(project, input.taskId) + let task = requireTask(project, input.taskId) const idempotencyKey = requireText(input.idempotencyKey, 'idempotencyKey') const existing = store.findDispatchByIdempotencyKey(project.id, idempotencyKey) @@ -669,6 +669,14 @@ export function createWorkbenchService(options = {}) { ? [{ artifactId: task.scope.artifactId, revision: Number(task.scope.revision ?? 1) }] : [] + // 派工本身就意味着“开始干”。草稿还停在 draft 时必须先入队: + // beginAttempt 只接受 queued/waiting_input/needs_attention/running,draft 会被拒, + // 而拒绝发生在消息已经发出之后 —— 结果是「部门收到了、账上记 unknown、任务不前进」。 + // 放在所有校验之后、写账之前:校验不过就不该改动任务状态。 + if (task.status === 'draft') { + task = store.updateTask({ ...task, status: 'queued', queuedAt: nowIso() }) + } + const committed = store.mutate(() => { const stamp = nowIso() const attemptId = store.ids.attempt() diff --git a/workbench/panel/lib/client.js b/workbench/panel/lib/client.js index 92a2c89..aba93c6 100644 --- a/workbench/panel/lib/client.js +++ b/workbench/panel/lib/client.js @@ -602,6 +602,7 @@ window.__ModuleLoader__.load({ ".wb-tab:hover{color:var(--wb-ink-2)}", ".wb-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding:0 12px 16px}", ".wb-alert{display:flex;align-items:flex-start;gap:6px;margin:0 12px 8px;padding:6px 8px;border:1px solid #fecaca;border-radius:7px;background:#fef2f2;color:#b42318;font-size:11px;line-height:1.4;flex:none}", + ".wb-alert.is-info{border-color:#bbf7d0;background:#f0fdf4;color:#166534}", ".wb-alert-text{flex:1 1 auto;min-width:0;word-break:break-word}", ".wb-alert button{flex:none;border:1px solid currentColor;background:transparent;color:inherit;font:inherit;font-size:10px;line-height:1;padding:3px 5px;border-radius:4px;cursor:pointer}", ".wb-tree{position:relative;padding:0 0 4px}", @@ -678,7 +679,7 @@ window.__ModuleLoader__.load({ ".wb-main-resizer::after{content:\"\";position:absolute;top:0;bottom:0;left:-4px;right:-4px}", ".wb-main-resizer:hover{background:var(--wb-blue,#3b82f6)}", ".wb-main-rail{flex:0 0 auto;height:100%;min-width:0;overflow:hidden;border-left:1px solid rgba(127,127,127,.12)}", - "@media (prefers-color-scheme: dark){.wb-rail{--wb-bg:#161a20;--wb-card:#1e232b;--wb-line:#2c333d;--wb-line-strong:#3a4350;--wb-ink:#e6ebf2;--wb-ink-2:#a9b4c2;--wb-ink-3:#7b8797;--wb-blue:#6ea8ff;--wb-green:#4ade80;--wb-amber:#f59e0b;--wb-gray:#5c6672;--wb-wire:#3a4350;--wb-dashed:#2f3742;--wb-group-bg:rgba(30,35,43,.6)}.wb-card.is-lead{background:linear-gradient(180deg,#1f2530 0%,#1e232b 100%);border-color:#3b4a63}.wb-card.is-running{border-color:#3b5a8a;background:#1d242f;box-shadow:0 0 0 2px rgba(110,168,255,.16),0 2px 8px rgba(110,168,255,.12)}.wb-alert{border-color:#5b2b2b;background:#2a1a1c;color:#fca5a5}.wb-tabs,.wb-card,.wb-task,.wb-artifact,.wb-form{background:var(--wb-card)}.wb-tab.is-active{background:#242a33}.wb-drawer{box-shadow:-8px 0 24px rgba(0,0,0,.35)}.wb-artifact.is-missing{border-color:#6b3a36;background:#2a1c1c}.wb-artifact.is-missing .wb-artifact-name{color:#fca5a5}.wb-artifact-flag{color:#fca5a5}.wb-artifact-flag.is-unknown{color:var(--wb-ink-3)}.wb-missing-note{border-color:#6b3a36;background:#2a1c1c;color:#fca5a5}.wb-task-tag{background:rgba(110,168,255,.16);color:#9cc4ff}}", + "@media (prefers-color-scheme: dark){.wb-rail{--wb-bg:#161a20;--wb-card:#1e232b;--wb-line:#2c333d;--wb-line-strong:#3a4350;--wb-ink:#e6ebf2;--wb-ink-2:#a9b4c2;--wb-ink-3:#7b8797;--wb-blue:#6ea8ff;--wb-green:#4ade80;--wb-amber:#f59e0b;--wb-gray:#5c6672;--wb-wire:#3a4350;--wb-dashed:#2f3742;--wb-group-bg:rgba(30,35,43,.6)}.wb-card.is-lead{background:linear-gradient(180deg,#1f2530 0%,#1e232b 100%);border-color:#3b4a63}.wb-card.is-running{border-color:#3b5a8a;background:#1d242f;box-shadow:0 0 0 2px rgba(110,168,255,.16),0 2px 8px rgba(110,168,255,.12)}.wb-alert{border-color:#5b2b2b;background:#2a1a1c;color:#fca5a5}.wb-alert.is-info{border-color:#245c3a;background:#12271b;color:#86efac}.wb-tabs,.wb-card,.wb-task,.wb-artifact,.wb-form{background:var(--wb-card)}.wb-tab.is-active{background:#242a33}.wb-drawer{box-shadow:-8px 0 24px rgba(0,0,0,.35)}.wb-artifact.is-missing{border-color:#6b3a36;background:#2a1c1c}.wb-artifact.is-missing .wb-artifact-name{color:#fca5a5}.wb-artifact-flag{color:#fca5a5}.wb-artifact-flag.is-unknown{color:var(--wb-ink-3)}.wb-missing-note{border-color:#6b3a36;background:#2a1c1c;color:#fca5a5}.wb-task-tag{background:rgba(110,168,255,.16);color:#9cc4ff}}", ].join(""); function injectCss() { @@ -1037,6 +1038,17 @@ window.__ModuleLoader__.load({ var notice = noticeState[0]; var setNotice = noticeState[1]; + // 提示语气:成功用 info(绿),失败/警告用 error(红)。默认红——凡是没显式说 + // "这是好消息"的提示,多半是用户在排障。 + var noticeToneState = React.useState("error"); + var noticeTone = noticeToneState[0]; + var setNoticeTone = noticeToneState[1]; + + function announce(message, tone) { + setNoticeTone(tone || "error"); + setNotice(message); + } + var connectingState = React.useState(null); var connecting = connectingState[0]; var setConnecting = connectingState[1]; @@ -1460,9 +1472,13 @@ window.__ModuleLoader__.load({ } if (sessionId) { var failure = openSession(ctx, sessionId); - if (typeof failure === "string") setNotice("已接通,但打开会话失败:" + failure); + if (typeof failure === "string") { + announce("已接通,但打开会话失败:" + failure, "error"); + } else { + announce("已接通。现在可以去任务页派工了。", "info"); + } } else { - setNotice("已接通,但宿主没有返回会话号;请重试或检查宿主会话能力。"); + announce("已接通,但宿主没有返回会话号;请重试或检查宿主会话能力。", "error"); } }); }).catch(function (failure) { @@ -1504,6 +1520,7 @@ window.__ModuleLoader__.load({ } setTaskForm(emptyTaskForm()); setTaskFormOpen(false); + announce("已存为草稿。去任务页点「派工」才会交给部门。", "info"); }).catch(function (failure) { setNotice(describeError(failure)); }).then(function () { @@ -1550,9 +1567,10 @@ window.__ModuleLoader__.load({ seqRef.current = Math.max(seqRef.current, Number(value.eventSeq) || 0); setData(value); } - if (status === "accepted") setNotice("已派出,部门会话里能看到这条任务。"); - else if (status === "prepared") setNotice("已记入台账,但宿主没接上会话层,暂时没有真的发出。"); - else if (result && result.duplicate) setNotice("这条任务之前已经派过,没有重复发送。"); + if (status === "accepted") announce("已派出,部门会话里能看到这条任务。", "info"); + else if (status === "prepared") announce("已记入台账,但宿主没接上会话层,暂时没有真的发出。", "error"); + else if (status === "unknown") announce("宿主可能已经收到,但账上没拿到确认;先别重派,等对账。", "error"); + else if (result && result.duplicate) announce("这条任务之前已经派过,没有重复发送。", "info"); }); }).catch(function (failure) { setNotice(describeError(failure)); @@ -1573,7 +1591,7 @@ window.__ModuleLoader__.load({ seqRef.current = Math.max(seqRef.current, Number(value.eventSeq) || 0); setData(value); } - setNotice("已取消。"); + announce("已取消。", "info"); }).catch(function (failure) { setNotice(describeError(failure)); }).then(function () { @@ -1979,7 +1997,7 @@ window.__ModuleLoader__.load({ }, "重试"), ]); } else if (notice) { - alert = h("div", { className: "wb-alert", role: "alert", key: "notice" }, [ + alert = h("div", { className: "wb-alert is-" + noticeTone, role: "alert", key: "notice" }, [ h("span", { className: "wb-alert-text", key: "text" }, notice), ]); } diff --git a/workbench/test/panel-contract.test.mjs b/workbench/test/panel-contract.test.mjs new file mode 100644 index 0000000..a405b22 --- /dev/null +++ b/workbench/test/panel-contract.test.mjs @@ -0,0 +1,68 @@ +// 前端与 Host 的接线契约:路径前缀、端点名、方法。 +// +// 这一条是为"重启后才暴露"的那类错误准备的:如果 panel 里写的是 /sansheng/workbench、 +// 而 Host 改了 ROUTE_PREFIX,真实宿主里所有请求都会 404,界面看起来就是"一直在读、什么都不出来"。 +// 单测跑得比重启快,所以把这条约束钉在测试里。 + +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path' + +import { ROUTE_PREFIX, listWorkbenchRoutes } from '../host/routes.mjs' + +const here = dirname(fileURLToPath(import.meta.url)) +const clientFile = join(here, '..', 'panel', 'lib', 'client.js') + +function readClient() { + return readFileSync(clientFile, 'utf8') +} + +/** 从 apiGet("x") / apiPost("x") 里取出前端真正会请求的端点名。 */ +function clientEndpoints(source) { + const names = new Set() + const pattern = /api(?:Get|Post)\(\s*"([^"]+)"/g + let match = pattern.exec(source) + while (match !== null) { + names.add(match[1]) + match = pattern.exec(source) + } + return [...names].sort() +} + +test('panel 的 API_BASE 与 Host 的 ROUTE_PREFIX 完全一致', () => { + const source = readClient() + const match = /const\s+API_BASE\s*=\s*"([^"]+)"/.exec(source) + assert.ok(match, 'panel 里找不到 API_BASE 声明') + assert.equal(match[1], ROUTE_PREFIX, '两边前缀不一致,真实宿主里会全体 404') +}) + +test('panel 请求的每个端点,Host 都真的注册了', () => { + const routes = listWorkbenchRoutes() + const known = new Set(routes.map((route) => route.path.slice(ROUTE_PREFIX.length + 1))) + const requested = clientEndpoints(readClient()) + + assert.ok(requested.length >= 5, `只解析到 ${requested.length} 个端点,说明提取规则失效了`) + const missing = requested.filter((name) => !known.has(name)) + assert.deepEqual(missing, [], `panel 请求了 Host 没有的端点:${missing.join(', ')}`) +}) + +test('前端会改状态的端点都是 POST,读取类都是 GET', () => { + const source = readClient() + const byMethod = new Map(listWorkbenchRoutes().map((route) => [route.path.slice(ROUTE_PREFIX.length + 1), route.method])) + + const postPattern = /apiPost\(\s*"([^"]+)"/g + let match = postPattern.exec(source) + while (match !== null) { + assert.equal(byMethod.get(match[1]), 'POST', `apiPost 打了 ${match[1]},但 Host 上它不是 POST`) + match = postPattern.exec(source) + } + + const getPattern = /apiGet\(\s*"([^"]+)"/g + match = getPattern.exec(source) + while (match !== null) { + assert.equal(byMethod.get(match[1]), 'GET', `apiGet 打了 ${match[1]},但 Host 上它不是 GET`) + match = getPattern.exec(source) + } +}) diff --git a/workbench/test/service.test.mjs b/workbench/test/service.test.mjs index e512d81..76906eb 100644 --- a/workbench/test/service.test.mjs +++ b/workbench/test/service.test.mjs @@ -654,3 +654,46 @@ test('A23 成果文件不见了显示 missing,探不了就是 unknown,绝不 assert.equal(store.listArtifacts(project.id).length, 3) assert.equal(store.listArtifacts(project.id)[1].fileRef, 'C:/work/gone.md') }) + +test('草稿直接派工会先入队,不会出现「消息已发、账上不前进」', () => { + const { store, service } = makeService(seedOfCurrent()) + const project = service.registerProject({ hostWorkspaceId: 'ws-draft', displayNameCache: '草稿项目' }).project + const binding = service.bindDepartmentSession({ projectId: project.id, roleId: 'gongbu', sessionId: 'ses_draft_gongbu' }) + + // 界面上的真实路径:先存草稿,再点派工。 + const draft = service.createTask({ + projectId: project.id, + ownerRoleId: 'gongbu', + sourceRoleId: 'lead', + title: '草稿直派', + objective: '确认草稿派工会先入队', + status: 'draft', + }).task + assert.equal(draft.status, 'draft') + + const result = service.dispatchTask({ + projectId: project.id, + taskId: draft.id, + idempotencyKey: 'ui:' + draft.id, + targetRoleId: 'gongbu', + targetSessionId: 'ses_draft_gongbu', + bindingGeneration: binding.binding.bindingGeneration, + }) + + // 派发记录落地,任务也从 draft 推进到 queued(否则 beginAttempt 会拒绝)。 + assert.ok(result.dispatch && result.dispatch.id) + const after = store.getTask(draft.id) + assert.equal(after.status, 'queued') + assert.ok(after.queuedAt) + // 同一个幂等键再派一次:返回既有记录,不新建第二条。 + const again = service.dispatchTask({ + projectId: project.id, + taskId: draft.id, + idempotencyKey: 'ui:' + draft.id, + targetRoleId: 'gongbu', + targetSessionId: 'ses_draft_gongbu', + bindingGeneration: binding.binding.bindingGeneration, + }) + assert.equal(again.duplicate, true) + assert.equal(again.dispatch.id, result.dispatch.id) +})