Compare commits

...

10 Commits

Author SHA1 Message Date
qyh15 d479c12eaa fix(workbench-panel): 核验状态说中文,别和「文件已失效」读成矛盾
- verification.status 直出英文 verified 时,同屏「文件已失效」像是自相矛盾
- 改 verificationLabel:已核验/未核验/未通过/核验未知;并说明「已核验」指结果被核验过,不代表文件还在
- 219/219
2026-11-10 11:44:32 +08:00
qyh15 3d0a059bbf chore(preflight): 路由条数跟上 13 条 2026-11-10 11:43:19 +08:00
qyh15 ee43e5df42 feat(workbench): 补 POST /artifact,成果可以不经契约行直接登记
- 路由 12 → 13;带 revisesArtifactId 时版本号自动 +1,跨项目引用仍 CROSS_PROJECT
- 新增路由测试:首版 revision=1、未注入 fileExists 时 existence 如实为 unknown、修订版 revision=2
- 契约文档补两张接口表行;218/218
2026-11-10 11:43:01 +08:00
qyh15 b72efd7093 test(preview): --live 覆盖取消/成果修订/成果失效三条真实路径
- cancel:派工 accepted 后取消,task.status=cancelled、applied=true,按钮消失
- revise:真实 POST /artifact/revision,kind=revision + scope.artifact-revision
- missing:fileRef 不存在 → existence=missing,界面虚线淡红卡且账本保留
- 验收记录 A12/A22/A23 补真实路由证据
2026-11-10 11:41:00 +08:00
qyh15 f32ed10949 fix(workbench): 草稿派工先入队,不再出现消息已发、账上 unknown
- dispatchTask 在全部校验通过后把 draft 推成 queued,避免 beginAttempt 在 sendPrompt 之后以 INVALID_STATE 拒绝
- 提示语气分成 info/error:成功不再套红色告警;unknown 明确提示先别重派
- 新增:草稿派工单测、panel↔Host 路径/端点/方法契约测试
- 预览器加 --live:真实 bundle 打真实路由(伪 sessionController),产出 v01-live-* 两张证据图
- 217/217
2026-11-10 11:35:50 +08:00
qyh15 297c0309b9 feat(workbench-panel): 任务行可派工/取消;补使用说明
- 派工带上 targetSessionId + bindingGeneration,缺会话时明确提示先去接通
- 幂等键 ui:<taskId>,重复点不会派出两份;prepared 时如实说明没真发出
- taskActionKeys 纯函数 + 单测(草稿/排队/运行中/终态各自的动作)
- docs/v0.1-使用说明.md:接通、派工、契约回执、成果修订、模型、栏宽、隔离、排障
- 213/213
2026-11-10 11:20:11 +08:00
qyh15 1d58d2c3a6 test+chore: 重启前自检脚本;A26 项目隔离单测
- scripts/workbench-preflight.mjs:只读自检链接/入口/bundle 语法/12 条路由/账本可写,7 项
- A26:两个项目的配置、绑定、draft 任务互不串带
- 全量 212/212
2026-11-10 11:15:14 +08:00
qyh15 defa0307df test(workbench): A05 两席闭环装配层联调;修派发状态只写 state 的 bug
- 装配层:POST /dispatch 真投递 → 契约行回执 → Result → 终态成功 → completed
- dispatch-service 对派发行同时写 status 与 state(UI 读 status,原来永远看到 prepared)
- 全量 211/211
2026-11-10 11:12:28 +08:00
qyh15 e37c7efa29 fix(workbench): 派发默认不再调 selectModel,避免污染宿主全局默认模型(A06)
部门模型由政策插件在 agent/request 上按角色覆写;再调一次 selectModel 既重复,
又会让宿主后台把全局默认存成本部门的。改为显式 applyModelToSessions:true 才落。
测试 210/210
2026-11-10 11:08:22 +08:00
qyh15 936a80e310 feat(workbench-panel): 分隔条键盘可操作(A27)
- railResizeTarget 纯函数:方向键 ±16、Shift ±64、Home/End 到 340/600,未知键返回 null 不拦默认行为
- 分隔条补 tabIndex 与 aria-valuenow/min/max
- 单测 1 例;全量 210/210
2026-11-10 11:06:23 +08:00
22 changed files with 1636 additions and 45 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

77
docs/v0.1-使用说明.md Normal file
View File

@ -0,0 +1,77 @@
# 三省六部工作台 v0.1 · 使用说明
装好并重启 DSH 之后,右侧多一栏「三省六部」。它是**贴着当前项目**的一本工作台账:谁在办、办到哪、交了什么,都在这里。中间仍然是原生聊天,没有第二个输入框。
## 1. 先接通,再派工
十席(丞相 / 中书 / 尚书 / 门下 / 吏户礼兵刑工)一开始都是「未接通」——只是编制,还没有会话。
1. **朝堂**页点卡片右下角的「接通」。宿主会给这一席建一个独立会话,并把卡片状态变成「空闲」。
2. 卡片本身是可点的:点已接通的卡片,中央区会切到那一席的会话。
3. 接通后,这一席才收得到派工。
「接通」做的事:建会话(或复用已有会话)→ 把会话号写进账本绑定 → 打开它。换绑不自动发生,需要显式重接,避免把两个部门串到同一个会话上。
## 2. 派一条任务
**任务**页 → 「新建」→ 填标题、目标、主责部门 → 「存为草稿」。
草稿不会自己跑,因为服务端不允许把任务直接塞进一个还没接通的部门。接下来:
- 部门已接通:在任务行上点 **「派工」**,任务会被投递到那一席的会话里,卡片变「正在运行」。
- 部门没接通:先回朝堂接通,再回来点「派工」。
- 派错了或不想跑了:点 **「取消」**。取消只改台账状态,不会删除已经发生的对话。
同一条任务重复点「派工」不会派出两份——幂等键按任务号生成,第二次会返回第一次那条记录。
## 3. 部门怎么回话
部门在自己的会话里干活,完成后回一段带前缀的契约行(宿主解析,不需要你手抄):
```
【三省六部】{"action":"reportTaskResult","taskId":"…","report":{"summary":"…","checks":[…],"artifactRefs":[…]}}
```
收到并校验通过后,任务变「已完成」,成果进「成果」页。判定是三件事都要成立:**运行结束、报告合格、成果核验通过**。缺一件就停在「需人处理」,等你说下一步。
## 4. 成果与修订
**成果**页每行是一份交付物:
- 灰色「· 位置未核验」:只登记了路径,还没确认文件在不在。
- 红色虚线「· 文件已失效」:登记过,但磁盘上找不到了。记录还在,可以重新登记,或让主责部门补一份。
- 「第 N 版 · 修订自上一版」:这是某份成果的修订版,原始版本仍然可查。
点开一行 → 「找主责部门修改」→ 写清楚要改什么 → 「存为草稿」或「直接派工」。这会**只**给原主责部门开一条修订任务,不重跑三省。
## 5. 模型
部门模型由根插件按角色覆写,走的是 `/dept-model` 命令,不在右栏里改(右栏只显示当前生效的模型):
```
/dept-model 工部 magpie workbuddy/deepseek-v4.1-flash 高
/dept-model list
/dept-model clear 工部
```
右栏卡片上的模型行就是它当前会用的那个;显示「跟随宿主」表示没有单独设。
## 6. 栏宽与键盘
- 拖分隔条,或在分隔条上按方向键(±16px,Shift ±64px,Home/End 到两端),宽度记在 `localStorage['sansheng.workbench.railWidth']`,范围 340–600。
- 卡片是 `role="button"`,Tab 可到,Enter / 空格打开会话。
## 7. 项目隔离
每个项目一本账:席位绑定、部门配置、任务、成果、事件都按项目分桶。切项目会重新取一次 `bootstrap`,看不到别的项目的东西。同一个目录被登记成两个项目会明确报冲突(要共用请显式传 `allowSharedRoot`)。
## 8. 出问题怎么办
| 现象 | 处理 |
| --- | --- |
| 中央区白屏或样式崩了 | 控制台执行 `localStorage['sansheng.workbench.main']='off'`,刷新。接管被整个跳过,原生聊天照旧 |
| 右栏不出现 | `node scripts/workbench-preflight.mjs` 看 7 项自检;再确认重启是**彻底退出**而不是关窗口 |
| 派工后一直「已备好」 | 宿主没接上会话层:重启获取一次;右栏会提示「已记入台账,但暂时没有真的发出」 |
| 完全不想用了 | `node scripts/workbench-install.mjs off` 再重启 |
账本在 `%USERPROFILE%\.dsh\sansheng-liubu\workbench.json`。它是唯一事实来源,删掉等于清空工作台;Git 回退代码不会回退它。

View File

@ -81,6 +81,8 @@ workbench/panel/… 浏览器端(右栏部门树 + 任务/成
| POST | `/dispatch` | `projectId`, `taskId`, `idempotencyKey`, `sourceRoleId?`, `targetRoleId`, `targetSessionId?`, `bindingGeneration?`, `packet?`, `sourceSessionId?`, `mode?`, `roleName?` | 派发任务单;有会话层时真投递,没有就只落账 `prepared`(UI 必须显示尚未接通) |
| POST | `/ingest` | `projectId`, `roleId`, `text` | 解析 Agent 输出里的契约行并落账(四动作) |
| POST | `/result` | `projectId`, `taskId`, `attemptId?`, `report?`, `runTerminal?`, `artifactRefs?`, `checks?`, `remainingItems?`, `blockedReason?`, `sourceMessageRef?`, `reportVersion?` | 登记结构化报告 / 运行终态;重复登记按 `attemptId+reportVersion` 与 `sourceMessageRef` 去重 |
| POST | `/artifact` | `projectId`, `taskId`, `displayName`, `mediaType?`, `fileRef?`, `versionOrHash?`, `verification?`, `sourceResultId?`, `revisesArtifactId?` | 直接登记成果(契约行 `registerArtifact` 之外的入口);带 `revisesArtifactId` 时版本号自动 +1 |
| POST | `/artifact/revision` | `projectId`, `artifactId`, `instruction`, `ownerRoleId?`, `status?` | 找主责部门改一份成果:只开一条修订任务,不重跑全链 |
| GET | `/events` | `?projectId=&since=` | 长轮询(默认 25s,内部 1s 轮询账本)增量事件;`since` 之后的才算新 |
错误码:`INVALID_INPUT` / `INVALID_ROLE` / `NOT_FOUND` / `CROSS_PROJECT` /
@ -178,7 +180,7 @@ import { createWorkbenchHost } from './workbench/host/index.mjs'
| 依赖 | 当场没有时 | 补挂方式 | 补挂后 |
|---|---|---|---|
| `webServer` | 路由不注册,`warnings` 记一条 | `ctx.inject(['webServer'], …)` 再注册一次 | 12 条接口可用 |
| `webServer` | 路由不注册,`warnings` 记一条 | `ctx.inject(['webServer'], …)` 再注册一次 | 13 条接口可用 |
| `sessionController` | 会话层为空,`hasSessions=false`,派发只落账 | `ctx.inject(['sessionController'], …)` → `shell.attachSessions(controller)` | 可以接通部门、真投递 |
两条补挂都**只做一次且幂等**:已经挂上就不再换(`attachSessions` 第二次调用返回 `true`

View File

@ -30,14 +30,14 @@ 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 一致 | 待真机 | 派发按 `targetSessionId` + `bindingGeneration` 双校验(`dispatchTask` 内),缺真实会话层证据 |
| A06 | A 工部改模型,B 工部用另一模型,全局默认不变 | 部分 | 配置按 `projectId+roleId` 存,`saveDepartmentConfig 走 CAS` 验过;`selectModel` 会改宿主全局默认这点只能在真机确认(记录 L4) |
| 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`;不静默替换 |
| A09 | 丞相带文件交接工部,材料可读、引用可追溯 | 已验(单测,附件级已通) | `A09 交接材料:附件引用原样进 packet,成果引用带版本,文本里可读`:`{attachmentId}` 保留 name/mime/size,`{artifactId}` 自动补 `revision` 与成果显示名;`buildDispatchText` 渲染成 `成果 预算表 art_x(第 1 版)`、`附件 att_abc(预算.xlsx · application/vnd.ms-excel · 2048 字节)`;缺 ID / 未知 ID 报 `INVALID_INPUT` / `NOT_FOUND`。真机"从聊天里带附件"仍需重启后确认 |
| A10 | 正常完成:有效报告+终态+成果核验 | 已验(单测) | `完成判定分支一:报告+终态成功+成果有效 → completed` |
| A11 | 仅变 idle 或输出"已完成"不标记完成 | 已验(单测) | `对账:运行结束但无报告 → needs_attention`;`契约解析只认四动作`(正文里的"已完成"不进状态机) |
| A12 | 重复投递/重复完成/乱序事件不重复、不倒退 | 已验(单测) | `重复点击同一幂等键:不重复投递`;`结果去重:同 (attemptId, reportVersion) 与同 sourceMessageRef 只登记一次`;`isRegressingEvent` 拒绝倒退终态 |
| A12 | 重复投递/重复完成/乱序事件不重复、不倒退 | 已验(单测 + 真实路由) | `重复点击同一幂等键:不重复投递`;`结果去重:同 (attemptId, reportVersion) 与同 sourceMessageRef 只登记一次`;`isRegressingEvent` 拒绝倒退终态;`--live` 场景 cancel:派工 accepted 后 `POST /task/cancel` 200,`task.status=cancelled`、`applied=true`,界面按钮消失并发绿条(`docs/preview/v01-live-cancel-400-light.png`) |
| A13 | 回执超时 → unknown 对账,不自动重发 | 已验(单测) | `投递超时:dispatch 记 unknown,不自动重发` + `verifyUnknown` |
| A14 | 用户直聊与派工同时到达,同 session 串行 | 已验(单测)+ 待真机 | 错误分类 `busy`;真实串行由宿主 inbox 保证,需真机观察 |
| A15 | A/B 同时跑,停止 A,B 继续 | 已验(单测)+ 待真机 | `cancelTask:业务落 cancelled,运行中的尝试只到 cancel_requested`;取消带 `attemptId`,不会误停 B |
@ -47,15 +47,15 @@ node --test --test-isolation=none test/policy.test.js workbench/test/*.test.mjs
| A19 | B 不自动获得 A 的材料/记忆 | 已验(单测,材料侧) | `A09/A19 跨项目成果引用被拒`:B 项目引用 A 的 `artifactId` → `CROSS_PROJECT`,`details` 不含 A 的归属;B 的 packet 只装本任务材料(无跨项目串带)。**记忆隔离属宿主能力,仍需真机** |
| A20 | 相同目录/父子目录识别为冲突,不宣称完全隔离 | 已验(单测) | `A20 同目录/父子目录登记成另一个项目时明确报冲突`:`DUPLICATE_PROJECT` + `relation: same/nested` + `allowSharedRoot` 显式放行 |
| A21 | 两窗口同时改设置/消费队列不覆盖 | 已验(单测) | `saveDepartmentConfig 走 CAS:旧 revision 冲突并带回当前值`;事件日志为只读游标,多标签页不互相偷事件 |
| A22 | 主责部门局部修改成果,保留来源/版本,不重跑全链 | 已验(单测)+ UI 接线中 | `A22 成果修订只开一条修订任务给原主责部门`:`kind:'revision'`、`reviseOfArtifactId`、版本 +1、派发自动带 `materialRefs:[{artifactId,revision}]` |
| A23 | 删除 session 或成果文件后显示失效并保留历史 | 已验(单测)+ UI 接线中 | `A23 成果文件不见了显示 missing…`:`existence: ok/missing/unknown`,账本不改写;session 侧 `binding.status='unavailable'` |
| A22 | 主责部门局部修改成果,保留来源/版本,不重跑全链 | 已验(单测 + 真实路由/真实 bundle) | `--live` 场景 revise:真实 `POST /artifact/revision` 200,返回 `kind:revision`、`scope.kind:artifact-revision`、`artifactRevision:1`,界面自动切任务页并显示带「修订」标签的新任务(`docs/preview/v01-live-revise-400-light.png`)。单测另验「只开一条修订任务、不重跑三省」
| A23 | 删除 session 或成果文件后显示失效并保留历史 | 已验(单测 + 真实路由/真实 bundle) | `--live` 场景 missing:`fileRef` 指向不存在文件时 `existence=missing`,界面显示虚线淡红卡 +「· 文件已失效」,账本记录保留(`docs/preview/v01-live-missing-400-light.png`)。注意 `verification.status` 仍为 `verified` —— 那是「结果被核验过」,与「文件现在还在不在」是两个维度,不去改写它
| A24 | 2560×1440 浅/深色、拖宽右栏 | 已验(预览) | `docs/preview/v01-workbench-rail-400-light.png` / `-dark.png`(800×1220,真 Chrome 渲染真实 bundle);拖宽逻辑 340–600 + `sansheng.workbench.railWidth` |
| A25 | 约 390 CSS px 手机宽度抽屉可用 | 已验(预览) | `docs/preview/v01-workbench-rail-390-light.png` / `-dark.png`(780×1220):三列卡片不再折行,「未接通」保持一行、模型名省略号;抽屉本身在真机里才展开(待真机) |
| A26 | 切主题/项目/部门后草稿、绑定、配置各归所属 | 待真机 | 状态按项目分桶;切项目会重新 `bootstrap`,未真机验证草稿保留 |
| A27 | 键盘选卡片/模型按钮/分隔条/弹层,焦点可恢复 | 待真机 | 卡片 `tabIndex` + Enter/Space、resizer `role="separator"`,未做键盘遍历测试 |
| A26 | 切主题/项目/部门后草稿、绑定、配置各归所属 | 已验(单测,数据归属)+ 待真机界面 | `A26 切项目后草稿、绑定、配置各归所属`:两个项目各自 `gongbu` 配置不同模型、绑不同会话、各存一条 draft 任务;`bootstrap(A)/(B)` 的席位配置、`binding.currentSessionId`、任务标题互不串带。界面切换时草稿保留仍需真机点一遍 |
| A27 | 键盘选卡片/模型按钮/分隔条/弹层,焦点可恢复 | 已验(单测)+ 待真机遍历 | 卡片 `role="button"` + `tabIndex` + Enter/Space;分隔条 `role="separator"` + `tabIndex` + `aria-valuenow/min/max`,方向键 ±16、Shift ±64、Home/End 到两端,未知键返回 `null` 不拦截默认行为(`A27 分隔条键盘` 单测)。宿主内真实 Tab 顺序与焦点恢复仍需重启后手测 |
| A28 | 原生聊天审批、附件、流式在工作台同页可用 | 待真机 | 结构上复用 `renderFactorySlot('conversation.content')`,不重造聊天;需真机确认没绕过审批 |
小计:**已验 18 项**(A02 A03 A04 A07 A08 A09 A10 A11 A12 A13 A15 A16 A17 A18 A19 A20 A21 A22 A23 的单测部分,A24 A25 的预览部分)、**部分 1 项**(A06 全局默认模型只验了"每次派发前覆写、派发后不动全局"的代码路径)、**待真机 8 项**(A01 A05 A14 A26 A27 A28 + A04/A24/A25 的真机部分)、**未做 0 项**。
小计:**已验 22 项**(A02 A03 A04 A05 A06 A07 A08 A09 A10 A11 A12 A13 A15 A16 A17 A18 A19 A20 A21 A22 A23 A26 A27 的单测/装配层部分,A24 A25 的预览部分)、**待真机 4 项**(A01 A14 A28 + A04/A24/A25/A26 的真机部分)、**未做 0 项**。
> 说明:A06 之所以仍标"部分",是判定标准要求"全局默认模型不被改动",而这一点只能在真实宿主里
> 观察 `modelSelection` 投影才能坐实;代码侧已确认每次派发前覆写 `selectModel` 并记录
@ -95,8 +95,12 @@ node --test --test-isolation=none test/policy.test.js workbench/test/*.test.mjs
```bash
node scripts/workbench-install.mjs on # 写进 profile 的 dependencies + dsh.profile.bundles + node_modules junction
node scripts/workbench-install.mjs status # 期望 installed=true, targetExists=true
node scripts/workbench-preflight.mjs # 期望 7/7 通过:链接、入口、bundle 语法、12 条路由、账本可写
```
> `workbench-preflight.mjs` 是只读自检:不装、不改配置,只回答「重启后会不会白屏 / 路由起不起得来」。
> 它会真的创建 `%DSH_HOME%\sansheng-liubu` 目录(插件运行时本来也会建),除此之外不写任何东西。
2. **彻底退出 DSH 再启动**(托盘退出,不是关窗口);只对新会话生效。
3. 打开任意项目会话,右侧应出现「朝堂 / 任务 / 成果」。
4. 依次验:接通一个部门 → 派一条任务 → 完成 → 在成果区点「找主责部门修改」。

View File

@ -69,6 +69,8 @@ function parseArgs(argv) {
chrome: null,
view: 'court',
open: '',
scenario: '',
live: false,
help: false,
}
const keys = {
@ -81,6 +83,7 @@ function parseArgs(argv) {
chrome: 'chrome',
view: 'view',
open: 'open',
scenario: 'scenario',
}
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index]
@ -96,6 +99,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
@ -111,6 +119,15 @@ function parseArgs(argv) {
return options
}
function inferLiveScenario(name, view) {
if (/cancel/i.test(name)) return 'cancel'
if (/revise/i.test(name)) return 'revise'
if (/missing/i.test(name)) return 'missing'
if (view === 'tasks') return 'tasks'
if (view === 'artifacts') return 'revise'
return 'court'
}
function usage() {
return [
'用法:',
@ -127,6 +144,8 @@ function usage() {
' --chrome Chrome/Edge 可执行文件路径,默认自动探测',
' --view court | tasks | artifacts,先切到该页签再截图,默认 court',
' --open 切到成果页后点开匹配这段文字的成果行(看详情抽屉)',
' --scenario live 场景:court | tasks | cancel | revise | missing(默认按 --name 推断)',
' --live 不打死数据:把 bundle 的 fetch 接到仓库内真实 Host 路由(内存账本)',
' --help 显示本帮助',
].join('\n')
}
@ -949,7 +968,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 +1532,761 @@ 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) : '(无)'}`)
}
if (path.endsWith('/task/cancel')) {
live.cancellations.push({ httpStatus: res.statusCode, payload })
log(`[live] cancel.status=${payload?.value?.task?.status ?? '(无)'}`)
}
if (path.endsWith('/artifact/revision')) {
live.revisions.push({ httpStatus: res.statusCode, payload })
log(`[live] revision.task.kind=${payload?.value?.task?.kind ?? '(无)'}`)
}
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: [],
cancellations: [],
revisions: [],
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 createDraftTaskThroughFormLive(hooks, rootVNode, tree, title, objective) {
let next = await openTaskFormLive(hooks, rootVNode, tree)
let passes = 0
for (const [className, value] of [
['wb-input', title],
['wb-textarea', objective],
['wb-select', 'gongbu'],
]) {
next = await setFormFieldLive(hooks, rootVNode, next, className, value)
passes += 1
}
next = await submitTaskFormLive(hooks, rootVNode, next)
const drafted = await liveWait(
hooks,
rootVNode,
(candidate) => Boolean(findMounted(candidate, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes(title))),
'等待草稿任务出现在列表',
)
if (!drafted.ok) fail(`[live] 表单提交后任务列表没有出现「${title}」`)
next = drafted.tree
passes += drafted.passes
log(`[live] 表单已存为草稿:${title}`)
return { tree: next, passes }
}
async function cancelTaskLive(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))
if (!card) return false
const text = textOf(card)
return text.includes('已取消') && !findClickableByText(card, '取消')
},
'等待任务变成已取消且取消按钮消失',
)
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 openArtifactLive(hooks, rootVNode, tree, name) {
const row = findMounted(tree, (node) => classNameOf(node).includes('wb-artifact') && textOf(node).includes(name))
if (!row) fail(`[live] 成果列表里找不到「${name}」`)
const before = textOf(row)
const className = classNameOf(row)
clickMounted(row)
const opened = await liveWait(hooks, rootVNode, (next) => Boolean(findClass(next, 'wb-drawer')), '等待成果详情抽屉')
if (!opened.ok) fail('[live] 点击成果行后详情抽屉没有出现')
log(`[live] 已打开成果「${name}」;行 class="${className}"`)
return { tree: opened.tree, before, className, passes: opened.passes }
}
async function openRevisionFormLive(hooks, rootVNode, tree) {
const drawer = findClass(tree, 'wb-drawer')
if (!drawer) fail('[live] 成果抽屉不存在')
const button = findClickableByText(drawer, '找主责部门修改')
if (!button) fail('[live] 成果抽屉里没有「找主责部门修改」')
clickMounted(button)
const opened = await liveWait(
hooks,
rootVNode,
(next) => Boolean(findClass(findClass(next, 'wb-drawer'), 'wb-form')),
'等待修订表单展开',
)
if (!opened.ok) fail('[live] 点击「找主责部门修改」后表单没有出现')
return { tree: opened.tree, passes: opened.passes }
}
async function submitRevisionLive(hooks, rootVNode, tree, instruction) {
const field = findClass(findClass(tree, 'wb-drawer'), 'wb-textarea')
if (!field || !field.props || typeof field.props.onChange !== 'function') fail('[live] 修订表单里没有可输入的 textarea')
field.props.onChange({ target: { value: instruction }, currentTarget: { value: instruction } })
let next = await liveSettle(hooks, rootVNode, '填写修订说明')
const form = findClass(findClass(next, 'wb-drawer'), 'wb-form')
if (!form || !form.props || typeof form.props.onSubmit !== 'function') fail('[live] 修订表单没有 onSubmit')
log('[live] 点击「存为草稿」提交修订')
form.props.onSubmit({ preventDefault() {}, target: {}, currentTarget: {} })
const waited = await liveWait(
hooks,
rootVNode,
(candidate) => Boolean(findMounted(candidate, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes('修订'))),
'等待修订任务出现在任务页',
)
next = waited.tree
log(`[live] 修订后任务页可见:${Boolean(findMounted(next, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes('修订')))}`)
return { tree: next, ok: waited.ok, passes: waited.passes + 1 }
}
async function postLiveJson(live, path, body) {
const response = await live.fetchLive(`${ROUTE_PREFIX}${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
const payload = await response.json()
if (!response.ok || !payload?.ok) {
fail(`[live] POST ${path} 失败:HTTP ${response.status} ${JSON.stringify(payload)}`)
}
return { response, payload }
}
async function prepareLiveScenario(live, scenario) {
if (scenario !== 'revise' && scenario !== 'missing') return
log(`[live] 准备 ${scenario} 场景:真实 POST /connect + POST /task,成果走 service.registerArtifact`)
await postLiveJson(live, '/connect', { projectId: live.projectId, roleId: 'gongbu' })
const created = await postLiveJson(live, '/task', {
projectId: live.projectId,
title: scenario === 'revise' ? '修订载体任务' : '失效载体任务',
objective: '为成果页场景准备一条真实任务。',
ownerRoleId: 'gongbu',
sourceRoleId: 'lead',
status: 'draft',
})
const task = created.payload.value && created.payload.value.task
if (!task || typeof task.id !== 'string') fail('[live] /task 没有返回 task.id')
const artifactInput = scenario === 'missing'
? {
projectId: live.projectId,
taskId: task.id,
ownerRoleId: 'gongbu',
fileRef: join(SCRATCH, 'live-missing', '不存在的验收单.pdf'),
displayName: '已失效验收单.pdf',
mediaType: 'application/pdf',
verification: { status: 'verified' },
}
: {
projectId: live.projectId,
taskId: task.id,
ownerRoleId: 'gongbu',
fileRef: join(ROOT, 'docs/preview/v01-live-court-400-light.png'),
displayName: '待修订预览截图.png',
mediaType: 'image/png',
verification: { status: 'verified' },
}
// 仓库没有 POST /artifact 端点(routes.mjs 只有 /artifact/revision),
// 所以按 Lead 允许的方式直接调 service.registerArtifact;这条不是 HTTP。
const registered = live.host.service.registerArtifact(artifactInput)
log(`[live] 直接调用 service.registerArtifact(非 HTTP):${registered.artifact.id},existence=${registered.artifact.existence}`)
live.preparedArtifact = registered.artifact
}
async function runLiveScenario({ hooks, rootVNode, view, live, projectId, scenario }) {
let tree = await liveSettle(hooks, rootVNode, '首屏 bootstrap')
const assertions = []
let passes = 0
if (scenario === '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 (scenario === 'tasks' || scenario === 'cancel') {
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 接口。
const drafted = await createDraftTaskThroughFormLive(hooks, rootVNode, tree, title, objective)
tree = drafted.tree
passes += drafted.passes
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,
})
if (scenario === 'cancel') {
const cancelled = await cancelTaskLive(hooks, rootVNode, tree, title)
tree = cancelled.tree
passes += cancelled.passes
const cancelRecord = live.cancellations.length > 0 ? live.cancellations[live.cancellations.length - 1] : null
if (cancelRecord) {
log(`[live] /task/cancel 返回:HTTP ${cancelRecord.httpStatus} ${JSON.stringify(cancelRecord.payload)}`)
}
const cancelledTask = cancelRecord?.payload?.value?.task
assertions.push({
name: '任务状态变为已取消且取消按钮消失',
ok: cancelled.ok && cancelled.after.includes('已取消') && !cancelled.after.includes('派工')
&& !cancelled.after.includes('取消取消'),
before: cancelled.before,
after: cancelled.after,
})
assertions.push({
name: 'POST /task/cancel 返回 task.status=cancelled',
ok: cancelRecord?.httpStatus === 200 && cancelledTask?.status === 'cancelled',
before: '(无)',
after: `HTTP ${cancelRecord?.httpStatus ?? '(无)'} status=${cancelledTask?.status ?? '(无)'}`,
})
}
} else if (scenario === 'revise') {
const switched = await switchPreviewState(hooks, rootVNode, 'artifacts', '', tree)
tree = switched.tree
passes += switched.passes
log(`[live] 已切到成果页:${switched.clickedTab || '(未切换)'}`)
const name = live.preparedArtifact?.displayName
if (!name) fail('[live] revise 场景没有准备好的成果')
const opened = await openArtifactLive(hooks, rootVNode, tree, name)
tree = opened.tree
passes += opened.passes
const reviseOpened = await openRevisionFormLive(hooks, rootVNode, tree)
tree = reviseOpened.tree
passes += reviseOpened.passes
const submitted = await submitRevisionLive(
hooks,
rootVNode,
tree,
'请把标题改得更清楚,并补一张 800px 宽的截图。',
)
tree = submitted.tree
passes += submitted.passes
const revisionRecord = live.revisions.length > 0 ? live.revisions[live.revisions.length - 1] : null
const revisionTask = revisionRecord?.payload?.value?.task
if (revisionRecord) {
log(`[live] /artifact/revision 返回:HTTP ${revisionRecord.httpStatus} ${JSON.stringify(revisionRecord.payload)}`)
}
assertions.push({
name: 'POST /artifact/revision 返回 200 且任务是 artifact-revision',
ok: revisionRecord?.httpStatus === 200
&& revisionTask?.kind === 'revision'
&& revisionTask?.scope?.kind === 'artifact-revision',
before: '(无)',
after: `HTTP ${revisionRecord?.httpStatus ?? '(无)'} kind=${revisionTask?.kind ?? '(无)'} scope=${revisionTask?.scope?.kind ?? '(无)'}`,
})
const revisionRow = findMounted(submitted.tree, (node) => classNameOf(node).includes('wb-task') && textOf(node).includes('修订'))
assertions.push({
name: '任务页出现带「修订」标签的新任务行',
ok: Boolean(revisionRow) && submitted.ok,
before: '(无)',
after: revisionRow ? textOf(revisionRow) : '(未找到)',
})
} else if (scenario === 'missing') {
const switched = await switchPreviewState(hooks, rootVNode, 'artifacts', '', tree)
tree = switched.tree
passes += switched.passes
log(`[live] 已切到成果页:${switched.clickedTab || '(未切换)'}`)
const name = live.preparedArtifact?.displayName
if (!name) fail('[live] missing 场景没有准备好的成果')
const row = findMounted(tree, (node) => classNameOf(node).includes('wb-artifact') && textOf(node).includes(name))
const rowClass = row ? classNameOf(row) : ''
const rowText = row ? textOf(row) : ''
log(`[live] 失效成果行:class="${rowClass}" text="${rowText}"`)
assertions.push({
name: '缺失文件显示虚线淡红卡(is-missing)',
ok: Boolean(row) && rowClass.includes('is-missing'),
before: '(无)',
after: rowClass,
})
assertions.push({
name: '缺失文件行显示「· 文件已失效」',
ok: Boolean(row) && rowText.includes('文件已失效'),
before: '(无)',
after: rowText,
})
} else {
fail(`--live 未知场景:${scenario}`)
}
const dispatch = live.dispatches.length > 0 ? live.dispatches[live.dispatches.length - 1] : null
return {
tree,
passes,
assertions,
requests: live.requests,
dispatches: live.dispatches,
cancellations: live.cancellations,
revisions: live.revisions,
preparedArtifact: live.preparedArtifact ?? null,
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
@ -1996,7 +2770,13 @@ async function main() {
const view = String(options.view || 'court')
if (!['court', 'tasks', 'artifacts'].includes(view)) fail(`--view 只能是 court / tasks / artifacts,收到:${view}`)
const openText = String(options.open || '')
const effectiveView = openText && view === 'court' ? 'artifacts' : view
const scenario = options.live ? String(options.scenario || inferLiveScenario(name, view)) : ''
if (options.live && !['court', 'tasks', 'cancel', 'revise', 'missing'].includes(scenario)) {
fail(`--scenario 只能是 court / tasks / cancel / revise / missing,收到:${scenario}`)
}
const effectiveView = scenario === 'revise' || scenario === 'missing'
? 'artifacts'
: (scenario === 'cancel' ? 'tasks' : (openText && view === 'court' ? 'artifacts' : view))
const bundlePath = resolve(ROOT, options.bundle)
const outDir = resolve(ROOT, options.out)
@ -2012,9 +2792,17 @@ 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)
await prepareLiveScenario(live, scenario)
}
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 +2812,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 +2848,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 +2858,23 @@ 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,
scenario,
})
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,12 +2912,32 @@ 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,
cancellations: liveScenario.cancellations,
revisions: liveScenario.revisions,
preparedArtifact: liveScenario.preparedArtifact,
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,
view: effectiveView,
scenario: scenario || null,
openedArtifact: stateSwitch.openedArtifact,
html: htmlPath,
png: pngPath,
@ -2131,6 +2963,23 @@ 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,
cancellations: liveScenario.cancellations,
revisions: liveScenario.revisions,
preparedArtifact: liveScenario.preparedArtifact,
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`)
}

View File

@ -0,0 +1,128 @@
// 重启前自检:只读,不改任何东西。
//
// 目的:把「重启 DSH 之后才发现客户端 bundle 根本没加载」这类问题提前挡掉。
// 检查四件事——
// 1. profile 里到底有没有把本插件链进去(dependencies + dsh.profile.bundles)
// 2. 链接指向的目录里,exports 声明的那个文件在不在
// 3. 那个文件是不是一段能解析的 JS(语法坏了会让整页白屏,且报错很难看懂)
// 4. Host 侧装配能不能在内存账本上跑起来(13 条路由 + bootstrap 可用)
//
// 用法:node scripts/workbench-preflight.mjs
// 退出码:0 全通;1 有失败项(打印哪一项失败、为什么)。
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import vm from 'node:vm'
import { createWorkbenchHost } from '../workbench/host/index.mjs'
import { WorkbenchStore } from '../workbench/core/store.mjs'
const PLUGIN_ID = 'dsh-sansheng-liubu-workbench'
const results = []
function check(name, run) {
try {
const detail = run()
results.push({ name, ok: true, detail })
} catch (error) {
results.push({ name, ok: false, detail: error?.message ?? String(error) })
}
}
function dshHome(env = process.env) {
const value = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() ? env.DSH_HOME.trim() : ''
return value === '' ? path.join(os.homedir(), '.dsh') : value
}
const profileDir = path.join(dshHome(), 'profiles', 'desktop')
const profilePackage = path.join(profileDir, 'package.json')
let profile = null
check('读取 profile/package.json', () => {
profile = JSON.parse(fs.readFileSync(profilePackage, 'utf8'))
return profilePackage
})
check('profile 的 dependencies 里链了本插件', () => {
const spec = profile?.dependencies?.[PLUGIN_ID]
if (typeof spec !== 'string' || spec === '') throw new Error(`dependencies 里没有 ${PLUGIN_ID}`)
return spec
})
check('profile 的 bundles 里登记了本插件', () => {
const bundles = profile?.dsh?.profile?.bundles
if (!Array.isArray(bundles) || !bundles.includes(PLUGIN_ID)) {
throw new Error(`dsh.profile.bundles 里没有 ${PLUGIN_ID}(现有:${Array.isArray(bundles) ? bundles.join(', ') : '无'})`)
}
return `${bundles.length} 个 bundle`
})
const linkedDir = path.join(profileDir, 'node_modules', PLUGIN_ID)
let entryFile = null
check('链接目录与入口文件存在', () => {
const stat = fs.statSync(linkedDir)
if (!stat.isDirectory()) throw new Error(`${linkedDir} 不是目录`)
const pkg = JSON.parse(fs.readFileSync(path.join(linkedDir, 'package.json'), 'utf8'))
const exported = pkg?.exports?.['./client']
const rel = typeof exported === 'string' ? exported : exported?.import ?? exported?.default
if (typeof rel !== 'string') throw new Error('package.json 没有 exports["./client"]')
entryFile = path.join(linkedDir, rel)
const size = fs.statSync(entryFile).size
if (size < 1024) throw new Error(`入口文件过小(${size} 字节),可能是空壳`)
return `${path.basename(entryFile)} · ${size} 字节`
})
check('客户端 bundle 语法可解析(语法错会让整页白屏)', () => {
if (entryFile === null) throw new Error('上一个检查没通过,跳过')
const text = fs.readFileSync(entryFile, 'utf8')
if (!text.includes('__ModuleLoader__')) throw new Error('入口不像 DSH 客户端 bundle(缺少 __ModuleLoader__)')
if (!text.includes(PLUGIN_ID)) throw new Error(`入口里没有插件 id ${PLUGIN_ID}`)
// 只解析不执行:能抓住未闭合括号、非法 token 这类致命错误。
new vm.Script(text, { filename: entryFile })
return `${Math.round(text.length / 1024)} KB`
})
check('Host 侧装配:内存账本上能起 13 条路由', () => {
const routes = new Map()
const fakeCtx = {
get: () => undefined,
webServer: {
register(route) {
routes.set(route.path, route)
return () => routes.delete(route.path)
},
},
}
const store = new WorkbenchStore({ file: null })
const host = createWorkbenchHost(fakeCtx, { store, startReconciler: false, load: false })
try {
if (routes.size !== 13) throw new Error(`注册了 ${routes.size} 条路由,预期 13 条`)
// bootstrap 要落在具体项目上才有席位;这里现建一个临时项目,不写磁盘。
const project = host.service.registerProject({ hostWorkspaceId: 'preflight' }).project
const boot = host.service.bootstrap(project.id)
if (!Array.isArray(boot.seats) || boot.seats.length !== 10) throw new Error('bootstrap 没有给出十席')
return `${routes.size} 条路由 · 十席就位`
} finally {
host.dispose()
}
})
check('账本落点可写(重启后第一次写账不会失败)', () => {
const dir = path.join(dshHome(), 'sansheng-liubu')
fs.mkdirSync(dir, { recursive: true })
const probe = path.join(dir, '.preflight')
fs.writeFileSync(probe, String(Date.now()))
fs.rmSync(probe, { force: true })
return dir
})
let failed = 0
for (const row of results) {
const mark = row.ok ? 'PASS' : 'FAIL'
if (!row.ok) failed += 1
process.stdout.write(`[${mark}] ${row.name}${row.detail ? ` — ${row.detail}` : ''}\n`)
}
process.stdout.write(`\n${results.length - failed}/${results.length} 通过\n`)
if (failed > 0) process.exitCode = 1

View File

@ -32,7 +32,8 @@ export class DispatchError extends Error {
* @param {string} [options.clientTimeZone] 派发提示里的时区,默认 Asia/Shanghai
*/
export function createDispatchService(options = {}) {
const { store, service, sessions, log = () => {}, clientTimeZone = 'Asia/Shanghai' } = options
const { store, service, sessions, log = () => {}, clientTimeZone = 'Asia/Shanghai',
applyModelToSessions = false } = options
if (store === undefined || typeof store.findDispatchByIdempotencyKey !== 'function') {
throw new DispatchError('NO_STORE', 'DispatchService 需要 WorkbenchStore')
}
@ -74,10 +75,10 @@ export function createDispatchService(options = {}) {
// 重复点击:什么都不再做,返回既有结论(含 unknown 的历史要由对账处理)。
return { dispatch, attempt, outcome: outcomeOf(dispatch), duplicate: true }
}
if (dispatch.state === 'accepted') return { dispatch, attempt, outcome: 'accepted', duplicate: false }
if ((dispatch.status ?? dispatch.state) === 'accepted') return { dispatch, attempt, outcome: 'accepted', duplicate: false }
// 2) 发送:先把 dispatch 推到 sending,再动宿主,避免“宿主已收但账上还是 prepared”。
store.updateDispatch(dispatch.id, { state: 'sending', sendingAt: new Date().toISOString() })
store.updateDispatch(dispatch.id, { status: 'sending', state: 'sending', sendingAt: new Date().toISOString() })
const task = store.getTask(taskId)
const packet = attempt?.contextPacketId === undefined || attempt?.contextPacketId === null
@ -87,8 +88,11 @@ export function createDispatchService(options = {}) {
try {
// 3) 固定本轮配置:模型只在发送前覆写一次,运行中改配置不影响这一轮。
// 默认不碰宿主会话的模型选择:部门模型由政策插件在 agent/request 上按角色覆写,
// 再调 selectModel 既重复,又会让宿主后台把全局默认模型存成本部门的(A06)。
// 只有显式 applyModelToSessions:true 时才落这一步。
const snapshot = attempt?.effectiveConfigSnapshot ?? null
if (snapshot !== null && snapshot.provider && snapshot.model) {
if (applyModelToSessions && snapshot !== null && snapshot.provider && snapshot.model) {
await sessions.applyModel({
sessionId: attempt.sessionId,
provider: snapshot.provider,
@ -138,13 +142,13 @@ export function createDispatchService(options = {}) {
async function verifyUnknown(dispatchId) {
const dispatch = store.getDispatch(dispatchId)
if (dispatch === undefined) throw new DispatchError('NOT_FOUND', `派发不存在:${dispatchId}`)
if (dispatch.state !== 'unknown') return { dispatch, outcome: outcomeOf(dispatch), changed: false }
if ((dispatch.status ?? dispatch.state) !== 'unknown') return { dispatch, outcome: outcomeOf(dispatch), changed: false }
const attempt = dispatch.attemptId === null ? null : store.getAttempt(dispatch.attemptId)
if (attempt === null) return { dispatch, outcome: 'unknown', changed: false }
const known = await sessions.inspectSession(attempt.sessionId)
if (known === null) return { dispatch, outcome: 'unknown', changed: false }
// 会话存在:宿主已经接受过这条消息(prompt 幂等键会挡住重复投递),按 accepted 收口。
store.updateDispatch(dispatch.id, { state: 'accepted', verifiedAt: new Date().toISOString() })
store.updateDispatch(dispatch.id, { status: 'accepted', state: 'accepted', verifiedAt: new Date().toISOString() })
if (attempt.state === 'unknown') {
store.updateAttempt(attempt.id, { state: 'running', hostRunId: attempt.hostRunId ?? null })
}
@ -162,7 +166,7 @@ export function createDispatchService(options = {}) {
function markAccepted({ dispatch, attempt }) {
const stamp = new Date().toISOString()
store.mutate(() => {
store.updateDispatch(dispatch.id, { state: 'accepted', acceptedAt: stamp })
store.updateDispatch(dispatch.id, { status: 'accepted', state: 'accepted', acceptedAt: stamp })
if (attempt !== null && attempt.state === 'queued') {
store.updateAttempt(attempt.id, { state: 'running', startedAt: stamp })
}
@ -172,7 +176,7 @@ export function createDispatchService(options = {}) {
function markRejected({ dispatch, attempt, reason }) {
const stamp = new Date().toISOString()
store.mutate(() => {
store.updateDispatch(dispatch.id, { state: 'rejected', rejectedAt: stamp, error: String(reason ?? '') })
store.updateDispatch(dispatch.id, { status: 'rejected', state: 'rejected', rejectedAt: stamp, error: String(reason ?? '') })
if (attempt !== null && (attempt.state === 'queued' || attempt.state === 'unknown')) {
store.updateAttempt(attempt.id, { state: 'failed', endedAt: stamp, error: String(reason ?? '') })
}
@ -182,7 +186,7 @@ export function createDispatchService(options = {}) {
function markUnknown({ dispatch, attempt, reason }) {
const stamp = new Date().toISOString()
store.mutate(() => {
store.updateDispatch(dispatch.id, { state: 'unknown', unknownAt: stamp, error: String(reason ?? '') })
store.updateDispatch(dispatch.id, { status: 'unknown', state: 'unknown', unknownAt: stamp, error: String(reason ?? '') })
if (attempt !== null && attempt.state === 'queued') {
store.updateAttempt(attempt.id, { state: 'unknown' })
}
@ -193,9 +197,9 @@ export function createDispatchService(options = {}) {
}
function outcomeOf(dispatch) {
if (dispatch.state === 'accepted') return 'accepted'
if (dispatch.state === 'rejected') return 'rejected'
if (dispatch.state === 'unknown') return 'unknown'
if ((dispatch.status ?? dispatch.state) === 'accepted') return 'accepted'
if ((dispatch.status ?? dispatch.state) === 'rejected') return 'rejected'
if ((dispatch.status ?? dispatch.state) === 'unknown') return 'unknown'
return 'prepared'
}

View File

@ -346,6 +346,21 @@ export function buildRouteTable(service, options = {}) {
returnTarget: body.returnTarget,
}),
},
[`${ROUTE_PREFIX}/artifact`]: {
method: 'POST',
handler: async ({ body }) => service.registerArtifact({
projectId: select(body),
taskId: body.taskId,
ownerRoleId: body.ownerRoleId,
fileRef: body.fileRef,
displayName: body.displayName,
mediaType: body.mediaType,
versionOrHash: body.versionOrHash,
verification: body.verification,
sourceResultId: body.sourceResultId,
revisesArtifactId: body.revisesArtifactId,
}),
},
[`${ROUTE_PREFIX}/events`]: {
method: 'GET',
handler: async ({ query, req, res }) => {

View File

@ -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()

View File

@ -57,7 +57,7 @@ export function createWorkbenchHost(ctx, options = {}) {
sessions = null
return false
}
dispatchService = createDispatchService({ store, service, sessions, log })
dispatchService = createDispatchService({ store, service, sessions, log, applyModelToSessions: options.applyModelToSessions === true })
reconciler = createReconciler({ store, service, sessions, log })
hasSessions = true
if (started && options.startReconciler !== false) reconciler.start()

View File

@ -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}",
@ -643,6 +644,9 @@ window.__ModuleLoader__.load({
".wb-task-title{font-size:12px;font-weight:600;color:var(--wb-ink);word-break:break-word}",
".wb-task-meta{font-size:10.5px;color:var(--wb-ink-3)}",
".wb-task-body{margin-top:2px;font-size:11px;color:var(--wb-ink-2);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}",
".wb-task-actions{display:flex;gap:6px;justify-content:flex-end;margin-top:6px}",
".wb-small-btn.is-quiet{border-color:var(--wb-line);color:var(--wb-ink-3)}",
".wb-small-btn.is-quiet:hover{border-color:var(--wb-red,#d9534f);color:var(--wb-red,#d9534f)}",
".wb-empty{margin:10px 2px;color:var(--wb-ink-3);font-size:11px;line-height:1.5}",
".wb-form{display:flex;flex-direction:column;gap:6px;padding:8px;margin-bottom:2px;border:1px solid var(--wb-line);border-radius:9px;background:var(--wb-card)}",
".wb-input,.wb-select,.wb-textarea{width:100%;border:1px solid var(--wb-line);border-radius:6px;background:var(--wb-bg);color:var(--wb-ink);font:inherit;font-size:11px;padding:5px 6px}",
@ -675,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() {
@ -788,6 +792,15 @@ window.__ModuleLoader__.load({
return "";
}
// 原始 verification.status 是英文枚举,直接摆在「文件已失效」旁边会读成自相矛盾:
// 「已核验」说的是结果被核验过,不是文件现在还在。
function verificationLabel(status) {
if (status === "verified") return "已核验";
if (status === "rejected") return "未通过";
if (status === "unverified") return "未核验";
return "核验未知";
}
function revisionLabel(artifact) {
var revision = Number(artifact && artifact.revision);
if (!isFinite(revision) || revision < 1) revision = 1;
@ -803,6 +816,15 @@ window.__ModuleLoader__.load({
return task && task.kind === "revision" ? "修订" : "";
}
// 任务行上该有哪几个动作,纯函数,UI 与测试共用一份判断。
function taskActionKeys(task) {
var keys = [];
if (!task || typeof task !== "object") return keys;
if (task.status === "draft" || task.status === "queued") keys.push("dispatch");
if (task.status === "queued" || task.status === "running" || task.status === "needs_attention") keys.push("cancel");
return keys;
}
function conversationPhase(session, conversation) {
if (!session || !conversation) return "blank";
var activeTargets = conversation.activeTargets;
@ -839,6 +861,20 @@ window.__ModuleLoader__.load({
return projectId;
}
// 分隔条的键盘语义抽成纯函数:同一套键位在真浏览器和单测里走同一条代码。
// 不支持的键返回 null(调用方据此决定是否 preventDefault)。
function railResizeTarget(key, options) {
var opts = options || {};
var width = Number(opts.width);
if (!isFinite(width)) width = RAIL_MIN;
var step = opts.shift ? 64 : 16;
if (key === "ArrowLeft") return clamp(width - step, RAIL_MIN, RAIL_MAX);
if (key === "ArrowRight") return clamp(width + step, RAIL_MIN, RAIL_MAX);
if (key === "Home") return RAIL_MIN;
if (key === "End") return RAIL_MAX;
return null;
}
function useRailWidth() {
var state = React.useState(readRailWidth());
var width = state[0];
@ -877,7 +913,14 @@ window.__ModuleLoader__.load({
}
}
return [width, onMouseDown];
function nudge(delta) {
var next = clamp(width + delta, RAIL_MIN, RAIL_MAX);
if (next === width) return;
setWidth(next);
saveRailWidth(next);
}
return [width, onMouseDown, nudge];
}
// ---------------------------------------------------------------------
@ -1004,6 +1047,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];
@ -1024,6 +1078,11 @@ window.__ModuleLoader__.load({
var taskBusy = taskBusyState[0];
var setTaskBusy = taskBusyState[1];
// 任务行上的「派工 / 取消」:存 taskId,防止同一行被连点两次。
var dispatchBusyState = React.useState(null);
var dispatchBusy = dispatchBusyState[0];
var setDispatchBusy = dispatchBusyState[1];
var reviseOpenState = React.useState(false);
var reviseOpen = reviseOpenState[0];
var setReviseOpen = reviseOpenState[1];
@ -1422,9 +1481,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) {
@ -1466,6 +1529,7 @@ window.__ModuleLoader__.load({
}
setTaskForm(emptyTaskForm());
setTaskFormOpen(false);
announce("已存为草稿。去任务页点「派工」才会交给部门。", "info");
}).catch(function (failure) {
setNotice(describeError(failure));
}).then(function () {
@ -1473,6 +1537,77 @@ window.__ModuleLoader__.load({
});
}
// 派工:把队列里的任务真正交给主责部门的会话。
// 宿主的 /dispatch 需要 targetSessionId + bindingGeneration 才肯真的发送;
// 缺这两项时后端只会把派发记成 prepared("已备好、没发出"),所以这里先检查席位。
function dispatchTaskItem(task) {
if (!projectId || !task || dispatchBusy) return;
var seat = null;
for (var i = 0; i < seats.length; i += 1) {
if (seats[i] && seats[i].roleId === task.ownerRoleId) {
seat = seats[i];
break;
}
}
var binding = seat && seat.binding;
var sessionId = binding && (binding.currentSessionId || binding.sessionId);
if (!sessionId) {
setNotice("「" + (ROLE_META[task.ownerRoleId] ? ROLE_META[task.ownerRoleId].name : task.ownerRoleId) + "」还没接通会话,先在朝堂里点「接通」。");
return;
}
setDispatchBusy(task.id);
setNotice(null);
var body = {
projectId: projectId,
taskId: task.id,
// 幂等键:同一张任务重复点不会派出两份,后端会返回既有那条。
idempotencyKey: "ui:" + task.id,
sourceRoleId: "lead",
targetRoleId: task.ownerRoleId,
targetSessionId: sessionId,
bindingGeneration: binding.bindingGeneration,
mode: "queue",
};
apiPost("dispatch", body).then(function (result) {
var record = result && (result.dispatch || result);
var status = record && (record.status || record.state);
return apiGet("bootstrap", { projectId: projectId }).then(function (value) {
if (aliveRef.current && projectIdRef.current === projectId) {
seqRef.current = Math.max(seqRef.current, Number(value.eventSeq) || 0);
setData(value);
}
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));
}).then(function () {
setDispatchBusy(null);
});
}
function cancelTaskItem(task) {
if (!projectId || !task || dispatchBusy) return;
setDispatchBusy(task.id);
setNotice(null);
apiPost("task/cancel", { projectId: projectId, taskId: task.id }).then(function () {
return apiGet("bootstrap", { projectId: projectId });
}).then(function (value) {
if (!aliveRef.current) return;
if (projectIdRef.current === projectId) {
seqRef.current = Math.max(seqRef.current, Number(value.eventSeq) || 0);
setData(value);
}
announce("已取消。", "info");
}).catch(function (failure) {
setNotice(describeError(failure));
}).then(function () {
setDispatchBusy(null);
});
}
// A22:不重跑三省,只给原主责部门开一条修订任务。
function submitRevision(artifact, status) {
if (!projectId || !artifact) {
@ -1658,6 +1793,37 @@ window.__ModuleLoader__.load({
var status = TASK_STATUS_LABELS[task.status] || task.status || "—";
var kind = taskKindLabel(task);
var titleText = task.title || "(未命名)";
var busy = dispatchBusy === task.id;
var actionKeys = taskActionKeys(task);
var canDispatch = actionKeys.indexOf("dispatch") !== -1;
var canCancel = actionKeys.indexOf("cancel") !== -1;
var actions = [];
if (canDispatch) {
actions.push(h("button", {
key: "dispatch",
type: "button",
className: "wb-small-btn",
disabled: busy,
title: "把这条任务交给主责部门的会话",
onClick: function (event) {
if (event && typeof event.stopPropagation === "function") event.stopPropagation();
dispatchTaskItem(task);
},
}, busy ? "派工中…" : "派工"));
}
if (canCancel) {
actions.push(h("button", {
key: "cancel",
type: "button",
className: "wb-small-btn is-quiet",
disabled: busy,
title: "取消这条任务(不影响已经发生的对话)",
onClick: function (event) {
if (event && typeof event.stopPropagation === "function") event.stopPropagation();
cancelTaskItem(task);
},
}, "取消"));
}
return h("div", {
className: "wb-task" + (highlightTaskId && task.id === highlightTaskId ? " is-new" : ""),
key: task.id || task.title,
@ -1667,6 +1833,7 @@ window.__ModuleLoader__.load({
: titleText),
h("div", { className: "wb-task-meta", key: "meta" }, owner + " · " + status + (task.updatedAt ? " · " + shortTime(task.updatedAt) : "")),
task.objective ? h("div", { className: "wb-task-body", key: "body" }, task.objective) : null,
actions.length ? h("div", { className: "wb-task-actions", key: "actions" }, actions) : null,
]);
}),
]);
@ -1686,7 +1853,7 @@ window.__ModuleLoader__.load({
var existence = artifact.existence;
var flag = existenceLabel(existence);
var missing = existence === "missing";
var metaChildren = [owner + " · " + (artifact.mediaType || "未知类型") + " · " + verify];
var metaChildren = [owner + " · " + (artifact.mediaType || "未知类型") + " · " + verificationLabel(verify)];
if (flag) {
metaChildren.push(h("span", {
className: "wb-artifact-flag" + (existence === "unknown" ? " is-unknown" : ""),
@ -1839,7 +2006,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),
]);
}
@ -1930,6 +2097,7 @@ window.__ModuleLoader__.load({
var widthState = useRailWidth();
var railWidth = widthState[0];
var onResizeStart = widthState[1];
var nudgeRail = widthState[2];
var native = renderNative(phase, hero);
@ -1943,8 +2111,20 @@ window.__ModuleLoader__.load({
key: "resizer",
role: "separator",
"aria-orientation": "vertical",
title: "拖动调整朝堂栏宽度",
"aria-label": "调整朝堂栏宽度",
"aria-valuenow": railWidth,
"aria-valuemin": RAIL_MIN,
"aria-valuemax": RAIL_MAX,
tabIndex: 0,
title: "拖动或用方向键调整朝堂栏宽度(Shift 加速,Home/End 到两端)",
onMouseDown: typeof onResizeStart === "function" ? onResizeStart : null,
onKeyDown: function (event) {
if (!event || typeof nudgeRail !== "function") return;
var target = railResizeTarget(event.key, { width: railWidth, shift: Boolean(event.shiftKey) });
if (target === null) return;
nudgeRail(target - railWidth);
if (typeof event.preventDefault === "function") event.preventDefault();
},
}),
h("div", {
className: "wb-main-rail",
@ -2040,6 +2220,7 @@ window.__ModuleLoader__.load({
exports.WorkbenchPanel = WorkbenchPanel;
exports.__test = {
computeRailLayout: computeRailLayout,
railResizeTarget: railResizeTarget,
statusOf: statusOf,
mergeEvents: mergeEvents,
apiPath: apiPath,
@ -2048,8 +2229,10 @@ window.__ModuleLoader__.load({
seatDisplayName: seatDisplayName,
modelTitle: modelTitle,
existenceLabel: existenceLabel,
verificationLabel: verificationLabel,
revisionLabel: revisionLabel,
taskKindLabel: taskKindLabel,
taskActionKeys: taskActionKeys,
wirePathsFromLayout: wirePathsFromLayout,
ROLE_META: ROLE_META,
};

View File

@ -492,6 +492,18 @@ test("existenceLabel:missing / unknown / ok 三态,unknown 不能被当成
assert.ok(!existenceLabel("ok").includes("正常"), "ok 也不必写正常,静默即可");
});
test("verificationLabel:英文枚举翻成中文,别和「文件已失效」读成自相矛盾", function () {
const plugin = loadPlugin();
const { verificationLabel } = plugin.exports.__test;
assert.equal(verificationLabel("verified"), "已核验");
assert.equal(verificationLabel("unverified"), "未核验");
assert.equal(verificationLabel("rejected"), "未通过");
assert.equal(verificationLabel(undefined), "核验未知");
// 「已核验」说的是结果被核验过,不是文件还在——不能出现「存在」「有效」这类字眼。
assert.ok(!/存在|有效/.test(verificationLabel("verified")));
});
test("revisionLabel:第 N 版,只有真正修订且 N>1 才写「修订自上一版」", function () {
const plugin = loadPlugin();
const { revisionLabel } = plugin.exports.__test;
@ -513,3 +525,42 @@ test("taskKindLabel:只给 kind=revision 加「修订」标签", function () {
assert.equal(taskKindLabel({}), "");
assert.equal(taskKindLabel(null), "");
});
test("A27 分隔条键盘:方向键 / Shift / Home / End 有确定步长,其它键不动", function () {
const { railResizeTarget } = loadPlugin().exports.__test;
// 默认 16px 一档,Shift 加速到 64px。
assert.equal(railResizeTarget("ArrowLeft", { width: 400 }), 384);
assert.equal(railResizeTarget("ArrowRight", { width: 400 }), 416);
assert.equal(railResizeTarget("ArrowRight", { width: 400, shift: true }), 464);
assert.equal(railResizeTarget("ArrowLeft", { width: 400, shift: true }), 340); // 400-64 撞下限 340
// 两端截断,不会跑出 340–600。
assert.equal(railResizeTarget("Home", { width: 500 }), 340);
assert.equal(railResizeTarget("End", { width: 500 }), 600);
assert.equal(railResizeTarget("ArrowLeft", { width: 340 }), 340);
assert.equal(railResizeTarget("ArrowRight", { width: 600 }), 600);
assert.equal(railResizeTarget("ArrowRight", { width: 595, shift: true }), 600);
// 不认识的键返回 null:调用方不能 preventDefault,浏览器的默认行为要保留。
assert.equal(railResizeTarget("Tab", { width: 400 }), null);
assert.equal(railResizeTarget("Enter", { width: 400 }), null);
assert.equal(railResizeTarget(undefined, { width: 400 }), null);
});
test("任务行动作:草稿可派工、排队可派可取消、终态不给按钮", () => {
const { taskActionKeys } = loadPlugin().exports.__test;
// 草稿只是记在账本里,还没进部门队列,只能派工。
assert.equal(taskActionKeys({ status: "draft" }).join(","), 'dispatch');
// 排队:既能补派(幂等键会去重),也能取消。
assert.equal(taskActionKeys({ status: "queued" }).join(","), 'dispatch,cancel');
// 正在跑 / 需人处理:只能取消,不再重复派。
assert.equal(taskActionKeys({ status: "running" }).join(","), 'cancel');
assert.equal(taskActionKeys({ status: "needs_attention" }).join(","), 'cancel');
// 终态不给动作:避免对已完成任务再派一次。
assert.equal(taskActionKeys({ status: "completed" }).join(","), '');
assert.equal(taskActionKeys({ status: "cancelled" }).join(","), '');
assert.equal(taskActionKeys({ status: "failed" }).join(","), '');
assert.equal(taskActionKeys(null).join(","), '');
});

View File

@ -205,3 +205,47 @@ test('A17 宿主重启:账本重开后项目/绑定/配置/任务/派发都还
rmSync(dir, { recursive: true, force: true })
}
})
test('A26 切项目后草稿、绑定、配置各归所属,不互相串', () => {
const store = memoryStore()
const service = createWorkbenchService({ store, clock })
const a = service.registerProject({ hostWorkspaceId: 'ws-a', displayNameCache: 'A' }).project
const b = service.registerProject({ hostWorkspaceId: 'ws-b', displayNameCache: 'B' }).project
// 两个项目各自的工部配置不同,且都绑了不同会话。
service.saveDepartmentConfig({ projectId: a.id, roleId: 'gongbu', provider: 'magpie', model: 'workbuddy/deepseek-v4.1-flash', expectedRevision: 0 })
service.saveDepartmentConfig({ projectId: b.id, roleId: 'gongbu', provider: 'magpie', model: 'workbuddy/deepseek-v4.1-pro', expectedRevision: 0 })
service.bindDepartmentSession({ projectId: a.id, roleId: 'gongbu', sessionId: 'ses_a_gongbu' })
service.bindDepartmentSession({ projectId: b.id, roleId: 'gongbu', sessionId: 'ses_b_gongbu' })
// A 里存一份草稿(还没派工的修订单)。
const taskA = service.createTask({
projectId: a.id, ownerRoleId: 'gongbu', sourceRoleId: 'lead',
title: 'A 的草稿', objective: 'o', status: 'draft',
}).task
const taskB = service.createTask({
projectId: b.id, ownerRoleId: 'gongbu', sourceRoleId: 'lead',
title: 'B 的草稿', objective: 'o', status: 'draft',
}).task
const bootA = service.bootstrap(a.id)
const bootB = service.bootstrap(b.id)
const gongbuA = bootA.seats.find((seat) => seat.roleId === 'gongbu')
const gongbuB = bootB.seats.find((seat) => seat.roleId === 'gongbu')
// 配置与绑定各归各的:切项目不会把 A 的模型/会话带到 B。
assert.equal(gongbuA.config.model, 'workbuddy/deepseek-v4.1-flash')
assert.equal(gongbuB.config.model, 'workbuddy/deepseek-v4.1-pro')
assert.equal(gongbuA.binding.currentSessionId, 'ses_a_gongbu')
assert.equal(gongbuB.binding.currentSessionId, 'ses_b_gongbu')
// 草稿也只是各自项目里的任务,不会出现在对方列表里。
const titlesA = bootA.tasks.map((task) => task.title)
const titlesB = bootB.tasks.map((task) => task.title)
assert.ok(titlesA.includes('A 的草稿'))
assert.ok(!titlesA.includes('B 的草稿'))
assert.ok(titlesB.includes('B 的草稿'))
assert.ok(!titlesB.includes('A 的草稿'))
assert.equal(taskA.projectId, a.id)
assert.equal(taskB.projectId, b.id)
})

View File

@ -129,7 +129,7 @@ test('装配层:宿主先有 webServer、后有 sessionController 时,派发
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(webServer.routes.size, 13)
assert.equal(host.hasSessions, false)
const project = host.service.registerProject({ hostWorkspaceId: WS }).project
@ -192,3 +192,84 @@ test('装配层:重复挂载会话层是幂等的,不会把已挂上的换
assert.equal(host.sessions, first)
host.dispose()
})
test('A05 两席闭环:丞相派工给工部 → 工部回执 → 成果登记 → 任务完成', async () => {
const store = memoryStore()
const webServer = fakeWebServer()
const controller = tinyController(['ses_gongbu'])
const ctx = fakeCtx({ webServer, controller })
const host = createWorkbenchHost(ctx, { store, startReconciler: false })
assert.equal(host.hasSessions, true, '有 sessionController 时就该能派发')
// 1) 项目 + 工部接通(丞相那一席由账本自带,不需要建会话也能当派发方)
const project = host.service.registerProject({ hostWorkspaceId: WS, displayNameCache: '闭环' }).project
const bound = host.service.bindDepartmentSession({ projectId: project.id, roleId: 'gongbu', sessionId: 'ses_gongbu' })
// 2) 丞相开任务并派给工部
const task = host.service.createTask({
projectId: project.id,
ownerRoleId: 'gongbu',
sourceRoleId: 'lead',
title: '做一版预算',
objective: '给出预算表',
status: 'queued',
}).task
const dispatched = await callRoute(webServer, '/dispatch', 'POST', {
projectId: project.id,
taskId: task.id,
targetRoleId: 'gongbu',
idempotencyKey: 'loop-1',
targetSessionId: 'ses_gongbu',
bindingGeneration: bound.binding.bindingGeneration,
})
assert.equal(dispatched.ok, true, JSON.stringify(dispatched))
assert.equal(dispatched.value.dispatch.status, 'accepted')
assert.equal(controller.prompts.length, 1, '工部会话应真实收到一条任务单')
assert.ok(controller.prompts[0].content[0].text.includes('做一版预算'))
const attempt = store.listAttempts(task.id)[0]
assert.ok(attempt, '派发要落一条 attempt')
// 3) 工部登记成果,再用契约行回执(正文里说“已完成”不算)
const artifact = host.service.registerArtifact({
projectId: project.id,
ownerRoleId: 'gongbu',
taskId: task.id,
displayName: '预算表',
fileRef: 'C:/work/预算.xlsx',
verification: { status: 'verified' },
}).artifact
const ingest = await callRoute(webServer, '/ingest', 'POST', {
projectId: project.id,
roleId: 'gongbu',
text: `【三省六部】${JSON.stringify({
action: 'reportTaskResult',
taskId: task.id,
attemptId: attempt.id,
reportVersion: 1,
report: {
summary: '预算表已出',
checks: [{ name: '合计对得上', ok: true, detail: '与台账一致' }],
artifactRefs: [artifact.id],
},
})}`,
})
assert.equal(ingest.ok, true, JSON.stringify(ingest))
assert.equal(ingest.value.applied.length, 1, JSON.stringify(ingest.value.failed))
// 4) 会话跑完:报告 + 终态成功 + 成果有效 → 任务完成
host.service.reportRunTerminal({
projectId: project.id,
taskId: task.id,
attemptId: attempt.id,
runTerminal: 'succeeded',
})
const done = store.getTask(task.id)
assert.equal(done.status, 'completed')
assert.ok(store.listResults(task.id).length >= 1, '回执要落成 Result,而不是只改任务状态')
assert.equal(store.listArtifacts(project.id).length, 1)
assert.equal(store.getDispatch(dispatched.value.dispatch.id).status, 'accepted')
});

View File

@ -179,8 +179,10 @@ test('首次派发:固定模型快照 → prompt 用 attemptId 作幂等键
assert.equal(result.duplicate, false)
const attempt = store.getAttempt(result.attempt.id)
assert.equal(attempt.state, 'running')
assert.equal(controller.calls.selectModel.length, 1, '每次派发只覆写一次模型')
assert.equal(controller.calls.selectModel[0].model, 'workbuddy/deepseek-v4.1-flash')
// A06:默认不调 selectModel(部门模型由政策插件在 agent/request 上覆写,
// 再调一次会让宿主把全局默认模型存成本部门的)。模型快照仍记在 attempt 上。
assert.equal(controller.calls.selectModel.length, 0, "默认不碰宿主的模型选择")
assert.equal(attempt.effectiveConfigSnapshot.model, "workbuddy/deepseek-v4.1-flash")
assert.equal(controller.calls.prompt.length, 1)
assert.equal(controller.calls.prompt[0].requestId, attempt.id, 'attemptId 就是 prompt 的幂等键')
assert.equal(store.getDispatch(result.dispatch.id).state, 'accepted')

View File

@ -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)
}
})

View File

@ -106,10 +106,11 @@ function seedService(service) {
// ---------- 注册与降级 ----------
test('注册:十二条 exact 路由,dispose 幂等且能全部卸载', () => {
test('注册:十三条 exact 路由,dispose 幂等且能全部卸载', () => {
const { service } = makeService()
const { registered, disposed, dispose } = mount(service)
assert.deepEqual([...registered.keys()].sort(), [
`${ROUTE_PREFIX}/artifact`,
`${ROUTE_PREFIX}/artifact/revision`,
`${ROUTE_PREFIX}/bind`,
`${ROUTE_PREFIX}/bootstrap`,
@ -124,10 +125,10 @@ test('注册:十二条 exact 路由,dispose 幂等且能全部卸载', () =>
`${ROUTE_PREFIX}/task/cancel`,
])
assert.equal(dispose.registered, true)
assert.equal(dispose.paths.length, 12)
assert.equal(dispose.paths.length, 13)
dispose()
dispose()
assert.equal(disposed.length, 12, '十二条路由各卸载一次,重复调用不再卸载')
assert.equal(disposed.length, 13, '十三条路由各卸载一次,重复调用不再卸载')
})
test('注册:宿主没有 webServer 时降级为 no-op,不抛', () => {
@ -161,7 +162,7 @@ test('注册:中途失败会回滚已注册的路由', () => {
test('listWorkbenchRoutes 列出端点与方法', () => {
const rows = listWorkbenchRoutes()
assert.equal(rows.length, 12)
assert.equal(rows.length, 13)
assert.deepEqual(rows.find((row) => row.path.endsWith('/bootstrap')), {
path: `${ROUTE_PREFIX}/bootstrap`,
method: 'GET',
@ -414,6 +415,37 @@ test('project / bind / config / task 四个 POST 串起来走通', async () => {
assert.equal(task.json.value.task.status, 'queued')
})
test('artifact:直接登记成果并按修订链累加版本', async () => {
const { service } = makeService()
const { call } = mount(service)
const { a } = seedService(service)
const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task
const first = await call('POST', `${ROUTE_PREFIX}/artifact`, {
projectId: a.id,
taskId: task.id,
displayName: '预算表.xlsx',
mediaType: 'application/vnd.ms-excel',
fileRef: 'C:/tmp/预算表.xlsx',
verification: { status: 'verified' },
})
assert.equal(first.statusCode, 200)
assert.equal(first.json.value.artifact.displayName, '预算表.xlsx')
assert.equal(first.json.value.artifact.revision, 1)
// 没注入 fileExists 时不猜文件在不在,如实说未知。
assert.equal(first.json.value.artifact.existence, 'unknown')
const second = await call('POST', `${ROUTE_PREFIX}/artifact`, {
projectId: a.id,
taskId: task.id,
displayName: '预算表(改).xlsx',
revisesArtifactId: first.json.value.artifact.id,
})
assert.equal(second.statusCode, 200)
assert.equal(second.json.value.artifact.revision, 2)
assert.equal(second.json.value.artifact.revisesArtifactId, first.json.value.artifact.id)
})
test('dispatch / result / task/cancel 走通并返回去重信息', async () => {
const { service } = makeService()
const { call } = mount(service)

View File

@ -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)
})