diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index ff8166c..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,200 +0,0 @@ -# Changelog - -> 版本号以 `package.json` 为准(当前 0.9.2)。更早的 0.6.x 条目沿用旧编号,保留作历史。 - -## 0.9.2 — 模型设置这次真的会落到部门身上 - -- 面板原来从 `ctx.remote.commands` 取指令接口,新宿主把服务挂成 `remote.commands`(要写进 inject,用 `ctx.get` 取),所以一直报「没有直接执行指令的接口」;现在按官方挂法取,并在 inject 里声明 `remote.session` / `remote.subagents` / `remote.commands`。 -- 宿主返回的是 `{ ok, value: { commandId, result } }`,面板现在先解包再判断 `result.kind`,同步兼容旧的裸返回。 -- 保存失败时也会把 busy 放掉:以前宿主一拒绝,两个下拉框就永久变灰点不动。 -- 测试 55 项(新增「指令接口挂在 `ctx.get` 上也能静默执行」)。 - -## 0.9.1 — 三省与六部之间真的空开了 - -- 上一版只加了三省、六部**组内**卡片的间距;「三省」整组到「六部」整组之间还是贴着的。 -- 这次给六部这块加 `margin-top: 16px`,任何侧栏宽度下都留出空隙,不再靠那条细连接线撑门面。 -## 0.9.0 — 你也可以直接给部门派活,模型不再绕丞相 - -- 席位详情里新增「直接派活」:写清要办的事,点「派给礼部」,消息直接进该部门自己的会话——丞相收不到、也不参与。丞相照旧可以自己派活,两条路互不干扰。 -- 派活走宿主 `subagents.prompt`(`{ requestId, parentSessionId, childSessionId, mode: "continuable", delivery: "queue" }`),每次带独立 requestId;宿主拒绝时把原因原样显示。 -- 改模型不再借丞相的会话:先在部门自己的会话里执行 `/dept-model`,那个会话冷着就退到任一已登记会话——指令只写全局路由表,依然不产生对话消息、不唤醒模型。 -- 测试新增 4 项(派活投递、非子会话报错、模型优先用部门会话、失败回退且不发消息),全量 54 项通过。 -## 0.8.0 — 换完即存,不再惊动智能体 - -- 模型和推理等级改成**选完就保存**,去掉「保存模型设置」按钮;脚注直接显示「自动保存 · 当前:…」。 -- 保存改走宿主 `commands/execute` 直接执行 `/dept-model`:不投递提示词、不在对话里留消息、不触发模型轮次,丞相不会因此进入大段推理。 -- 宿主没有这个接口或指令尚未加载时,只在前端报错(「宿主没有执行这条指令」),不会退化成一条普通消息发给智能体。 -- 测试新增两项:确认改模型时**不**调用 `session.prompt`、以及缺接口时的报错;全量 50 项通过。 -## 0.7.2 — 三省与六部之间松一点 - -- 三省(`.sl-grid-3`)与六部(`.sl-grid-6`)的卡片间距从 8–10px 统一到 12px,三个容器断点(含 ≤620px 的两列布局)一起调,窄侧栏下也不再挤在一起。 -## 0.7.1 — 十个席位都有模型设置,没召见的也能先选好 - -- 面板「模型设置」原来只在 `seat.present` 时渲染,没召见的部门连入口都没有。现在绑定的是席位本身:未召见的部门也能选模型,保存时同样下发 `/dept-model <角色> [推理等级]`,并注明「召见后生效」。 -- 未召见的席位读清单时不再传会话 id:直接读全局清单,当前值取面板里固定过的那条;保存后脚注写「该部门还没召见;保存后在召见时生效」。 -- 顺带修掉一个由缺席席位暴露的 bug:`activeSeat` 在 `activeChildId` 为空时会撞上「没有会话 id 的缺席席位」(`undefined === undefined`),把标题写成「正在与吏部对话」。现在只有存在子会话时才去找席位。 -- 预览脚本新增 `--absent=<角色,...>`,可以直接截「未召见的部门」这一态;演示数据补上全局清单的 `default` 字段,缺席席位才有默认可选模型。 -- 测试新增「还没召见的部门也能先选好模型,保存走 /dept-model」;`node --test` 49 项全过。 - -## 0.7.0 — 每个部门可以单独固定模型 - -- 部门是子会话(`origin: "subagent"`),宿主的 `session.selectModel` 对它们一律拒绝(`session/agent-busy`,建议走 subagent delivery),所以「在这里选好就生效」原来根本做不到。现在面板改为下发 `/dept-model <部门> [推理等级]` 指令,由模式插件按角色把模型写进运行时路由表并落盘 `routes.json`,`agent/request` 钩子在下一轮开工时生效。 -- 模式插件新增 `parseDeptModelCommand` / `describeDeptRoutes` / `readStoredRoutes` / `writeStoredRoutes`:支持 set、`list`、`clear [部门]`,未知部门与参数不足各自给出可读原因;路由文件按 `DSH_HOME`(缺省 `~/.dsh`)下的 `sansheng-liubu/routes.json` 读写,读不到就当没固定过。 -- 面板「模型设置」对部门显示「按部门固定」,选好保存即固定,脚注显示「该部门固定使用此模型」;每个部门的固定值用 `localStorage` 记在面板侧(`sansheng-liubu.route.<角色>`),用于显示当前模型。 -- 预览脚本新增 `--seat=<角色>`,可以直接截某个部门的详情;演示数据补了 `localStorage` 与部门子会话地址,工部示例固定为 DeepSeek V4。 -- 测试:客户端新增「改模型改由丞相会话下发 /dept-model」「固定路由从面板记录读出来当当前模型」两项;策略侧新增指令解析与路由文件往返用例。`node --test` 48 项全过。 - -## 0.6.0 — 模型选择真的能用了 - -- 部门设置里的模型清单原来靠 `modelDirectories.directoryFor(sessionId)` 取该会话的目录,而这个方法只认「本页登记过的会话」,于是每个还没在面板里打开过的部门都读不到模型。现在清单改从宿主的全局目录 `modelDirectories.catalog` 读(`catalog.load()` 一份,所有部门共用),不再依赖会话登记。 -- 保存模型改成真正的 RPC:有 `ModelDirectory` 时走 `directory.select(...)`,没有时直接 `remote.session.selectModel({ sessionId, provider, model, reasoningEffort })`。**没在本页打开过的部门也能改模型**,保存后立即生效。 -- 「当前模型」读不到该部门自己的选择时,退回全局默认并标明「跟随默认」,不再冒充成别人的选择;界面脚注会说明「该部门会话未在本页打开,选好保存后直接生效」。 -- 错误分级:服务缺失 →「当前宿主没有全局模型清单(modelDirectories.catalog)」;清单读取失败 →「读取模型清单失败:<原文>」;6 秒超时 →「读取模型清单超时(显示已知缓存)」;宿主拒绝保存 → 「:」。 -- 测试从 4 项模型用例重写为 6 项:服务缺失、清单来自全局且不依赖登记、未登记时保存走 RPC、宿主拒绝原文、清单读取失败保留缓存、正常路径;`node --test` 客户端 35 项全过。 - -## 0.5.7 — 模型目录读不到时说清是哪一步断了 - -- 部门设置里的「当前宿主未提供模型目录」不再是一句万能提示。原来 `modelDirectoryOf` 把三种情况都吞成 `undefined`:取不到 `modelDirectories` 服务、`directoryFor` 方法不存在、`directoryFor(sessionId)` 抛异常。现在分别返回 `{ service: false }`、`{ error }`、`{ directory }`。 -- 宿主的 `ModelDirectoryResolver.directoryFor` 在该会话没登记时抛 `ui-model-selection: session "" resolved no scope / no binding`。这种情况不再报「宿主未提供模型目录」,而是**借另一个已登记会话的目录把全局模型清单列出来**:列表照常可选看,`current` 留空不冒充别人的选择,保存按钮禁用并写明「进入该部门会话后才能改模型」。其它异常(服务崩溃、超时、快照读取失败)原样带出原文,同时用 `[三省六部]` 前缀在控制台留下会话 id 与原始错误。 -- 新增 `sessionsOtherThan`(最近活跃会话 → 任意已登记会话)做兜底;`loadCatalog` 的投影收敛成一个 `project()`,成功/超时/兜底三条路径共用,`unresolved` 随结果返回给界面。 -- 新增 4 项测试:服务缺失、会话未登记时兜底且不冒充当前选择(含 `selectModel` 拒绝)、其它异常原样带出、正常路径。`node --test` 43 项、`node --check`、`git diff --check`、`check-install` 全过。 - -## 0.5.6 — 左栏那一行改名「上朝」并置顶 - -- 按用户要求把左侧栏导航行的标签从「三省六部」改成「上朝」,`order` 从 10 改为 −100,排在「插件」以外所有插件行之前(`插件` 恒列首行,是宿主写死的)。 -- 只改呈现,不动行为:点击仍然是停靠右侧栏的 `main` 重定向桩。 -- 39 项测试(含新增的「标签是上朝、order 为负」断言)、`node --check`、`git diff --check`、`check-install` 全过。 - -## 0.5.5 — 左栏只留一处入口 - -- 撤掉 0.5.3 的左侧栏底部入口(`sidebar.footer.action`)与它的 `SanshengRailAction` 组件、8 条 `.sl-rail-*` 样式(`.sl-rail-mark` 保留,重定向桩还在用)。0.5.4 之后左栏同时有导航行和底部一行,是同一功能的两个入口,按用户要求收敛成一个。 -- 左栏现在只有「插件 / 定时任务 / 任务看板 / MCP 连接器」那一列里的「三省六部」一行;会话头部的「三省」开关仍是另一处入口(两处都只做停靠,不是两套面板)。 -- 删掉 2 条只服务于底部入口的测试,槽位断言回到五个;39 项测试、`node --check`、`git diff --check`、`check-install` 全过。 - -## 0.5.4 — 入口搬进左侧栏导航列 - -- 用户要的不是底部那一条,而是「插件 / 定时任务 / 任务看板 / MCP 连接器」那一列;那一列只认 `sidebar.panellist`,于是注册一行导航:`id: sansheng-liubu`、`order: 10`、`label: 三省六部`,图标是插件画的 18px 细线「三」字样标(`SanshengNavGlyph`,激活时线宽 1.6)。 -- 那一列的点击行为由宿主写死为 `selectPanel(id)`,一定要 `main` 槽,所以同时注册 `main`(`key: sansheng-liubu`)作为**重定向桩**:`SanshengDockRedirect` 挂载后立刻调 `dockToSidebarTab(host)`,停靠右侧栏、清掉旧提示、`selectPanel(null)` 退回原会话;没有会话时只在页面中央写明原因(`.sl-dock-stub`)。它不渲染朝堂、不承载聊天,这是对 0.5.0「两个槽一律不注册」的收敛式修订。 -- 底部入口(`sidebar.footer.action`)保留:两处入口等价,共用同一条提示存储。 -- 新增 2 条测试:导航行与 `main` 桩的注册(含 `label()` 与 `key`)、`dockToSidebarTab` 成功/失败两条路径(失败时不得 `selectPanel`)。另修了断言写法:`h("svg", props, [children])` 在测试替身里是单层嵌套,要先 `.flat()`。 -- 41 项测试、`node --check`、`git diff --check`、`check-install` 全部通过。 - -## 0.5.3 — 左侧栏也有三省六部入口 - -- 在左侧栏底部(`sidebar.footer.action`,`id: sansheng-liubu:rail`)加了一个常驻入口:只做「把朝堂停靠到当前会话的右侧栏」,与会话头开关共用同一条提示存储,不切整页面板、不新增聊天存储。 -- 折叠侧栏时只剩「三省」字标;展开时补上「三省六部 / 收起朝堂」文字,失败原因显示在文字下方(`role="status"`,最多两行,完整文本在 `title` 里),字标转红作为折叠状态下的可见信号。 -- 不再用 `sidebar.panellist`:那个槽的点击会走 `selectPanel` 去要 `main` 槽,而 0.5.0 起不再注册 `main`,点进去只会得到空面板。 -- 修掉会话头开关的一个连带问题:失败时原来会回退到 `host.togglePanel()`,同样指向不存在的整页面板;现在只写提示。 -- 新增 3 条测试:左栏入口的注册与两种宽度下的渲染、无会话时的可见原因、以及「失败时不得 `selectPanel` 到无 `main` 槽的面板」。 -- 39 项测试、`node --check`、`git diff --check`、`check-install` 全部通过。 - -## 0.5.2 — 断点跟随侧栏容器,窄栏不再挤压状态说明 - -- 响应式断点从浏览器视口改为面板容器:`.sl-root` 声明 `container-type:inline-size;container-name:slpanel`,11 处 `@media (max-width: …)` 全部换成 `@container slpanel (max-width: …)`。真实宿主窗口最大化时侧栏仍只有 371px,旧的视口断点一个都不会触发,等于窄栏样式从来没生效过。 -- 删掉 `.sl-compact .sl-grid-3,.sl-compact .sl-grid-6` 的强制两列:它优先级高于容器断点,会把单列规则压死。现在列数完全由容器宽度决定。 -- 单列阈值落在 330px 容器宽(约 348px 侧栏):360px 及以上保持两列,320px 降为单列。 -- 部门配置里的「最近活动」独占一行、最多两行后省略,不再和状态文字挤在同一行被裁断;`panel/lib/client.js:891` 的 `shortText(…, 46)` 保持不变。 -- `scripts/preview.mjs` 新增 `--viewport=<像素>`:窗口可比侧栏宽,用来复现「大窗口 + 窄侧栏」的真实宿主形态;新增 371px、320px 两张入库预览图。 -- 新增两条回归测试:禁止视口 `@media` 断点且必须保留容器断点;`.sl-detail-status small` 必须独占一行且不得 `white-space:nowrap`。 -- 36 项测试、`node --check`、`git diff --check`、`check-install` 全部通过。 - -## 0.5.1 — 清掉侧栏化残留,会话头开关不再静默 - -- 删除侧栏化后不再渲染的旧样式:独立聊天栏、整页面板壳、`sl-left-nav`、`sl-task-jump` 等 46 个类共约 117 行规则;CSS 由 374 行收到 257 行。 -- 删除无调用点的 `SanshengPinRow`、`DockButton`,以及已经没有外部消费方的 `SidebarIcon` 导出;`panel/lib/client.js` 由 1890 行收到 1758 行。 -- 会话头部开关在拿不到会话、或宿主没有右侧栏服务时,把失败原因直接显示在开关旁(`role="status"`,完整文本放在 `title`),不再静默回退成整页面板。 -- 新增两条回归测试:开关失败提示的渲染与清除;`className` 里出现的每个 `sl-*` 类都必须有对应 CSS 规则,防止样式与组件再次脱节。 -- 去掉 `sl-side-pane`、`sl-control-model`、`sl-control-effort` 三个「有类名、无规则」的幽灵类名。 -- 34 项测试、`node --check`、`git diff --check`、`check-install` 全部通过。 - -## 0.5.0 — 收进右侧栏,聊天回归 DSH 原生 - -- 移除整页「三省六部」面板、丞相主对话摘要卡和第二套聊天入口;聊天统一使用 DSH 原生输入框与消息流。 -- 朝堂编制与任务流转收进会话右侧栏:顶部「朝堂 / 任务」页签、四张统计卡、组织图与选中部门配置在同一侧栏内滚动。 -- 在原生输入框输入 `@` 选择部门后进入其子会话;右侧栏自动选中对应部门,返回丞相时恢复丞相选中。 -- 移除 `main`、`sidebar.panellist` 和 `sidebar.panellist.actions` 注册,只在会话头部与右侧栏注入入口,不再占用工作区主视图。 -- 侧栏顶部改为紧凑状态行:协作状态、`输入 @ 选择部门` 提示与子会话返回按钮;统计卡可点击切换朝堂/任务。 -- 移除 Agent 预设编辑与重复「下旨」输入;部门设置只保留固定职责、模型/推理等级和会话入口。 -- 策略插件与面板版本推进到 0.5.0;侧栏结构、槽位注册、@ 导航和自动选中均有回归测试。 - -## 0.4.2 — 原生 @ 部门成员 - -- 在 DSH 原生会话输入框注册 `@` 来源,候选为已建立的九个子 Agent 会话;主对话仍使用宿主原有输入框,不新增第二套聊天。 -- 选择 `@中书省`、`@工部` 等部门后进入该成员的现有子会话,随后直接在原生输入框发送任务;不会把消息静默转发或改写接收人。 -- 进入子会话时右侧朝堂图自动选中对应部门,部门配置同步切换;返回丞相主会话时恢复选中丞相,不再出现“人在工部、面板还选着丞相”的错位。 -- 面板主对话区提示改为「输入 @ 可直接找部门成员」;未设官、没有会话的部门不出现在候选中。 -- 新增 @ 候选与会话导航回归测试;32 项策略和客户端测试通过。 - -## 0.4.1 — 重设计朝堂面板 - -- 按 DSH 原生主题变量重构面板:品牌与朝班状态头、丞相主对话卡、独立任务流转区、右侧统计与部门配置。 -- 部门改为边界清楚的实体卡片:蓝灰描边、字徽、名称与中文状态;选中态使用蓝边、浅蓝底和勾选标记。 -- 朝堂图固定为「丞相 → 三省 → 六部」:丞相连接三省,尚书省连接整个六部分组;六部两排三列,明确同属一级。 -- 左侧增加「主对话 / 任务流转」切换;点击「在办任务」统计卡或对话区入口,可直接切到任务流转。 -- 点击「在朝成员」统计卡进入全宽朝堂编制:收起左栏与统计,组织图和部门配置铺满面板;顶栏或地图头部均可返回协作台。 -- 设置区移除 Agent 预设输入与重复的「下旨」文本框,只保留固定职责、模型/推理等级和「与某部对话」。 -- 新增子 Agent 会话入口:选中部门后直接打开其 DSH 子会话;顶部可返回丞相主会话,不再另造聊天存储。 -- 统计保持两列两行;右侧栏、窄屏和紧凑侧栏分别减少列数,卡片状态行不再塞入任务计数。 -- 修复空闲状态显示为英文 `idle` 的问题;深色与明亮模式共用结构,颜色均由 DSH 主题变量派生。 -- 策略插件与面板版本推进到 0.4.1;当时 31 项策略和客户端测试通过。 - -## 0.4.0 — 补齐六部 - -- 角色由七席扩为十席:丞相 + 三省 + 吏、户、礼、兵、刑、工六部;新增 `COURT_ROLES` 作为唯一编制来源。 -- 新增 `libu`(吏部)、`hubu`(户部)、`xingbu`(刑部)角色提示词;`libu` 由「礼部」改为「吏部」,礼部改用 `lipu`,避免与吏部拼音重名。 -- 按职责重划写入边界:吏部/户部只有 write、edit;礼部、刑部另有命令行;兵部另含远程与 MCP 通道;工部独有 Image-gen 生图。 -- 尚书省提示词改为按吏户礼兵刑工分工、只召集真正用到的部门;丞相提示词同步十席组织。 -- 面板朝堂图改为「丞相 → 三省 → 六部」三排结构,六部同排直隶尚书省;座位计数与测试同步到十席。 -- 版本推进:策略插件 0.4.0,面板 0.4.0。 - -## 0.3.7 — 上朝改为手动启用 - -- 包自带的 `cordis.patch.yml` 改为空层(`[]`):装包不再往模式选择器里注册「上朝」,也不再能成为新会话的默认模式。 -- 新增 `preset.patch.yml`:想上朝时把它的 `- insert:` 段合并进 profile 的 `cordis.patch.yml`,重启后才会出现该选项。 -- 新增 `scripts/mode.mjs`(`npm run mode -- on|off|status`):带标记地写入/撤回那段 insert,可逆且幂等,不会替你选中模式。 -- `scripts/check-install.mjs` 改为校验「装包不等于开模式」:包内 patch 必须不含预设行,`preset.patch.yml` 必须能复现同一 preset id,并报告当前是否已启用。 -- README 补「启用方式」与 Git 回滚,删除已失效的 backup 目录回滚说明。 - -## 0.6.2 — 默认进入丞相 - -- 将尚未加入 Agent Team 的新会话主 Agent 直接映射为丞相(Lead)。 -- 使用“上朝”模式后可立即与丞相对话,不再需要手动切换默认 Agent。 -- 已加入团队的中书、门下、尚书、工部、礼部和兵部角色映射保持不变。 - -## 0.6.1 — 交由 dsh-image-gen 执行 - -- 上朝不再重复注册 `generate_image`,避免与 `dsh-image-gen` 工具冲突。 -- 工部获准使用 Image-gen 的 `generate_image`、`generate_images` 和 `edit_image`。 -- Provider、凭据、模型、计费与图片保存全部交由 Image-gen 管理。 -- 上朝仅保留角色职责、任务准奏和工具权限边界。 - -## 0.6.0 — 普通百炼生图 - -- 工部恢复 `generate_image`,使用普通百炼 `/images/generations` 接口。 -- 通过 DSH 凭据服务读取 `BAILIAN_API_KEY`,源码不保存密钥。 -- 默认 dry-run,真实调用必须显式 `live=true`。 -- 固定三模型白名单,无其他图片渠道 fallback。 -- 保留其他图片生成和编辑工具的拒绝策略。 - -## 0.5.1 — 移除上朝生图能力 - -- 删除 `generate_image` 工具注册、请求构造、参数矩阵、付费开关及网络调用实现。 -- 删除 `sansheng-liubu:imagegen` 提示词块和相关可选能力探测。 -- 工部恢复为识图、OCR、截图与视觉分析,不提供生图或图片编辑。 -- 策略明确拒绝所有图片生成和编辑工具。 -- 保留工具审核开放制、执行部门文件工具、管理型工具审批与审计逻辑。 -- 删除生图使用文档;mode id 和 preset id 保持不变。 - -## 0.5.0 — 工具审核开放、六部配笔与千问生图 - -### 变更范围 - -- 将管理型工具的一刀切禁令改为审发分离:丞相可调用并记录审计日志;部门须持门下省准奏记录;兵部负责装配、发放、回收、登记和销账,只发不批。 -- 兵部、礼部、工部获得 `read`、`write`、`edit`、`bash`、`grep`、`glob` 等执行工具;中书、门下、尚书维持只读工具集。 -- 该版本曾向工部加入可选生图能力,已在 0.5.1 移除。 - -### 历史缺陷防复发 - -- `sansheng-liubu:role` 使用共享安装引用计数保护,不重复注册。 -- 未引入 `sanshengLiubuGeneration` preset service;模式沿用 agent 原生 scope。 -- preset 只保留 `sansheng-liubu-policy` 单一引用,未接入 v2、v3 或 v031 陈旧链。 diff --git a/README.md b/README.md index 5356cb5..09653f9 100644 --- a/README.md +++ b/README.md @@ -1,80 +1,51 @@ -# 「上朝」DSH 多 Agent 模式 +# 三省六部 -> **2026-11-10:规划从头开始。** 唯一开发方案为 [基于 DS Bot 的三层开发与自我迭代方案](docs/DSBot-三省六部开发方案.md):基于 Fei2411/DS-Bot 的 DSH 插件,直接复用 better-sidebar、better-workspace-group,首版只做丞相、尚书、工部。旧方案、TODO 和预览图已清理。当前仍是规划阶段;下文仅记录保留的旧运行代码及其用法,不作为新开发需求或已完成的证据。 +> 2026-11-10 收敛:只保留两个子包——`sansheng/`(治理插件)与 `ds-bot/`(团队底座)。 +> 旧方案(「上朝」preset、右侧十席面板、独立工作台 v0.1)已删除,历史仍在 Git 里(`git log --all`)。 -面向 DeepSeek Harness Web GUI 的 Agent Preset,mode id 保持 `sansheng-liubu`。 +## 结构 -**本插件默认不开启。** 装上它不会往 DSH 的模式选择器里塞「上朝」,也不会成为新会话的默认模式。只有你按下面步骤显式启用、并在新建会话时主动选中「上朝」,这套流程才开始运行。 +| 目录 | 包名 | 作用 | +|---|---|---| +| `sansheng/` | `dsh-sansheng-sansheng` | 在 DS Bot 团队上补三角色(丞相 / 尚书 / 工部)绑定、状态、目标门禁与审查记录 | +| `ds-bot/` | `ds-bot` | 长驻 Bot 团队、Bot 间消息与群聊(Fei2411/DS-Bot 的 vendored 副本,本地改动见 `ds-bot/PATCHES.md`) | +| `docs/` | — | [DSBot 开发方案](docs/DSBot-三省六部开发方案.md) 与 P0 / P1 证据 | -启用之后,尚未加入 Agent Team 的默认主 Agent 会自动担任丞相(Lead),你可以直接与丞相对话,其余部门由丞相按流程创建。 +根目录 `package.json` 只是工作区清单(`workspaces: sansheng, ds-bot`),本身不是 DSH 插件,也不进 `dsh.profile.bundles`。 -## 启用方式(选了才生效) +## 装进 DSH -```powershell -node scripts/mode.mjs status # 现在开没开 -node scripts/mode.mjs on # 让「上朝」出现在模式选择器里 -node scripts/mode.mjs off # 彻底移除这个选项 +两个子包都以 `link:` 依赖挂进 `~/.dsh/profiles/desktop`,并写进 `dsh.profile.bundles`: + +```json +"ds-bot": "link:C:/Users/qyh15/三省六部/ds-bot", +"dsh-sansheng-sansheng": "link:C:/Users/qyh15/三省六部/sansheng" ``` -`on` 只是把 [preset.patch.yml](preset.patch.yml) 里那段 insert 写入 `~/.dsh/profiles/desktop/cordis.patch.yml`(带标记,可原样撤回),**不会**替你选中它。执行后彻底重启 DSH,新建会话时在模式选择器里主动选「上朝」,这套流程才启动;不选就一直是普通模式。 +```json +"bundles": [ ..., "dsh-sansheng-sansheng", "ds-bot" ] +``` -`off` 把那段 insert 整段删掉,文件回到原样;已存在的会话仍保留它自己的模式记录,不会被切成别的模式。 - -包自带的 [cordis.patch.yml](cordis.patch.yml) 是空层(`[]`),这是刻意的——装包本身不产生任何行为。想手工合并也可以,规则同上:顶层保持数组,删掉 `[]` 再接那段 insert。 - -若重启后模式选择器里看不到「上朝」,把 `dsh-sansheng-liubu-mode` 也加进 `~/.dsh/profiles/desktop/package.json` 的 `dsh.profile.bundles` 再重启——预设按包名解析那支策略插件,个别部署要求它显式列出。这条不影响「默认关闭」:加进 bundles 只是让插件可加载,策略仍只在会话 preset 为 `sansheng-liubu` 时才生效。 - -## 部门职责 - -- `lead`(丞相):统筹、决策、组队与管理型工具;调用须留痕。 -- `zhongshu`(中书省):调查与规划,只读。 -- `menxia`(门下省):准奏、封驳、验收与查账,只读。 -- `shangshu`(尚书省):任务依赖和分工调度,只读。 -- `libu`(吏部):Agent 与技能维护、成员编制与角色配置;只动技能、角色与配置文档,不开命令行。 -- `hubu`(户部):数据、表格与计算;依据真实数据给出可复算的结论,不补造数据。 -- `lipu`(礼部):文档、汇报、文案润色与可视化产出。 -- `bingbu`(兵部):环境运行、调试与部署,以及工具装配、发放、回收、登记、销账;只发不批。 -- `xingbu`(刑部):按风险开展的专项测试与独立验证;只跑不部署,不替代门下审议。 -- `gongbu`(工部/图像司):编码与工程实现;识图、OCR、截图与视觉分析;通过 `dsh-image-gen` 执行生图、批量生图和图片编辑。 - -执行部门常备 `read`、`write`、`edit`、`bash`、`grep`、`glob` 等工具;规划/审议部门保持只读。 - -## Image-gen 接管 - -上朝插件不再自行注册图片工具或读取图片 Provider 凭据,而是复用已安装的 `dsh-image-gen`: - -- `generate_image`:单张生图; -- `generate_images`:批量生图; -- `edit_image`:参考图与连续编辑。 - -三项工具只允许工部在已准奏且处于执行中的任务里调用。Provider、模型、API Key、Base URL、订阅登录、计费和结果保存均由 Image-gen 配置管理。`image_generate` 与 `codex_image_generate` 继续被上朝策略拒绝。 - -请在“插件 → 已安装 → dsh-image-gen”中配置并测试 Provider。修改插件配置或本模式后需彻底重启 DSH。 - -## 工具审核则例 - -1. 部门申请工具须写明用途、范围、期限;门下准奏后由兵部发放,限期使用,到期回收销账。 -2. 只读工具由门下专决;写入须注明 writeScopes;涉费、删除、全局配置须人工签字。 -3. `task_board_*`、`automation_*` 归丞相执掌并留痕;部门调用管理型工具须持门下准奏记录。 -4. 门下验收查账;越界者下次从严;工具不得转借。 +改完 profile 必须彻底重启 DSH 才生效。 ## 验证 -```powershell -node --check index.js -node --test --test-isolation=none test/policy.test.js panel/test/client.test.js -node scripts/check-install.mjs +```sh +node --test --test-isolation=none sansheng/test/*.test.js # 或在 sansheng/ 里 npm test +node --check sansheng/index.js ``` -`check-install.mjs` 会确认三件事:包自带 patch 是空层(不注册预设)、`preset.patch.yml` 能复现出同一个 preset id、以及你的 profile 当前到底有没有启用「上朝」(输出里的 `modeEnabled`)。 +Node >= 22。 -## 回滚 +## 历史 -版本历史统一走 Git,不建备份目录、不留时间戳副本: +- 第一代(11-07 ~ 11-09):`dsh-sansheng-liubu-mode`(上朝 Agent Preset)+ `dsh-sansheng-liubu-panel`(右侧十席面板)。 +- 第二代(11-10 上午):`dsh-sansheng-liubu-workbench`(自建数据层 / Host 服务 / HTTP / 前端的独立工作台 v0.1),同日 12:19 被 DS Bot 方案取代。 +- 当前(11-10 起):`ds-bot` + `sansheng`。 -```powershell -git log --oneline # 找目标提交 -git revert # 或 git reset --hard +删除的内容都能从 Git 取回,例如: + +```sh +git log --all --oneline -- panel +git show :panel/lib/client.js ``` - -回滚后重启 DSH。mode id 与 preset id 不变。 diff --git a/cordis.patch.yml b/cordis.patch.yml deleted file mode 100644 index e8329eb..0000000 --- a/cordis.patch.yml +++ /dev/null @@ -1,8 +0,0 @@ -# 三省六部模式:默认不注册任何东西。 -# -# 装上本包不会往 DSH 的模式选择器里塞「上朝」,也不会成为新会话的默认模式—— -# 想上朝时,把 preset.patch.yml 里的 insert 合并进 -# ~/.dsh/profiles/desktop/cordis.patch.yml -# 再彻底重启 DSH,新会话才能在模式选择器里看到并选择「上朝」。 -# 想退出:删掉那段 insert,重启即可;已存在的会话仍保留它自己的模式记录。 -[] diff --git a/vendor/ds-bot/LICENSE b/ds-bot/LICENSE similarity index 100% rename from vendor/ds-bot/LICENSE rename to ds-bot/LICENSE diff --git a/vendor/ds-bot/NOTICE b/ds-bot/NOTICE similarity index 100% rename from vendor/ds-bot/NOTICE rename to ds-bot/NOTICE diff --git a/vendor/ds-bot/PATCHES.md b/ds-bot/PATCHES.md similarity index 100% rename from vendor/ds-bot/PATCHES.md rename to ds-bot/PATCHES.md diff --git a/vendor/ds-bot/README.md b/ds-bot/README.md similarity index 100% rename from vendor/ds-bot/README.md rename to ds-bot/README.md diff --git a/vendor/ds-bot/client.js b/ds-bot/client.js similarity index 100% rename from vendor/ds-bot/client.js rename to ds-bot/client.js diff --git a/vendor/ds-bot/cordis.patch.yml b/ds-bot/cordis.patch.yml similarity index 100% rename from vendor/ds-bot/cordis.patch.yml rename to ds-bot/cordis.patch.yml diff --git a/vendor/ds-bot/index.js b/ds-bot/index.js similarity index 100% rename from vendor/ds-bot/index.js rename to ds-bot/index.js diff --git a/vendor/ds-bot/office.js b/ds-bot/office.js similarity index 100% rename from vendor/ds-bot/office.js rename to ds-bot/office.js diff --git a/vendor/ds-bot/package.json b/ds-bot/package.json similarity index 100% rename from vendor/ds-bot/package.json rename to ds-bot/package.json diff --git a/vendor/ds-bot/pnpm-lock.yaml b/ds-bot/pnpm-lock.yaml similarity index 100% rename from vendor/ds-bot/pnpm-lock.yaml rename to ds-bot/pnpm-lock.yaml diff --git a/vendor/ds-bot/src/host/agents.js b/ds-bot/src/host/agents.js similarity index 100% rename from vendor/ds-bot/src/host/agents.js rename to ds-bot/src/host/agents.js diff --git a/vendor/ds-bot/src/host/approvals.js b/ds-bot/src/host/approvals.js similarity index 100% rename from vendor/ds-bot/src/host/approvals.js rename to ds-bot/src/host/approvals.js diff --git a/vendor/ds-bot/src/host/avatar-library.js b/ds-bot/src/host/avatar-library.js similarity index 100% rename from vendor/ds-bot/src/host/avatar-library.js rename to ds-bot/src/host/avatar-library.js diff --git a/vendor/ds-bot/src/host/avatar.js b/ds-bot/src/host/avatar.js similarity index 100% rename from vendor/ds-bot/src/host/avatar.js rename to ds-bot/src/host/avatar.js diff --git a/vendor/ds-bot/src/host/browser-plugins.js b/ds-bot/src/host/browser-plugins.js similarity index 100% rename from vendor/ds-bot/src/host/browser-plugins.js rename to ds-bot/src/host/browser-plugins.js diff --git a/vendor/ds-bot/src/host/browser.js b/ds-bot/src/host/browser.js similarity index 100% rename from vendor/ds-bot/src/host/browser.js rename to ds-bot/src/host/browser.js diff --git a/vendor/ds-bot/src/host/browser/gate.js b/ds-bot/src/host/browser/gate.js similarity index 100% rename from vendor/ds-bot/src/host/browser/gate.js rename to ds-bot/src/host/browser/gate.js diff --git a/vendor/ds-bot/src/host/browser/loop.js b/ds-bot/src/host/browser/loop.js similarity index 100% rename from vendor/ds-bot/src/host/browser/loop.js rename to ds-bot/src/host/browser/loop.js diff --git a/vendor/ds-bot/src/host/browser/mount.js b/ds-bot/src/host/browser/mount.js similarity index 100% rename from vendor/ds-bot/src/host/browser/mount.js rename to ds-bot/src/host/browser/mount.js diff --git a/vendor/ds-bot/src/host/browser/refs.js b/ds-bot/src/host/browser/refs.js similarity index 100% rename from vendor/ds-bot/src/host/browser/refs.js rename to ds-bot/src/host/browser/refs.js diff --git a/vendor/ds-bot/src/host/browser/script-child.js b/ds-bot/src/host/browser/script-child.js similarity index 100% rename from vendor/ds-bot/src/host/browser/script-child.js rename to ds-bot/src/host/browser/script-child.js diff --git a/vendor/ds-bot/src/host/browser/script-runner.js b/ds-bot/src/host/browser/script-runner.js similarity index 100% rename from vendor/ds-bot/src/host/browser/script-runner.js rename to ds-bot/src/host/browser/script-runner.js diff --git a/vendor/ds-bot/src/host/browser/script.js b/ds-bot/src/host/browser/script.js similarity index 100% rename from vendor/ds-bot/src/host/browser/script.js rename to ds-bot/src/host/browser/script.js diff --git a/vendor/ds-bot/src/host/browser/session-model.js b/ds-bot/src/host/browser/session-model.js similarity index 100% rename from vendor/ds-bot/src/host/browser/session-model.js rename to ds-bot/src/host/browser/session-model.js diff --git a/vendor/ds-bot/src/host/browser/session.js b/ds-bot/src/host/browser/session.js similarity index 100% rename from vendor/ds-bot/src/host/browser/session.js rename to ds-bot/src/host/browser/session.js diff --git a/vendor/ds-bot/src/host/browser/task.js b/ds-bot/src/host/browser/task.js similarity index 100% rename from vendor/ds-bot/src/host/browser/task.js rename to ds-bot/src/host/browser/task.js diff --git a/vendor/ds-bot/src/host/btw.js b/ds-bot/src/host/btw.js similarity index 100% rename from vendor/ds-bot/src/host/btw.js rename to ds-bot/src/host/btw.js diff --git a/vendor/ds-bot/src/host/capabilities.js b/ds-bot/src/host/capabilities.js similarity index 100% rename from vendor/ds-bot/src/host/capabilities.js rename to ds-bot/src/host/capabilities.js diff --git a/vendor/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js similarity index 100% rename from vendor/ds-bot/src/host/channel.js rename to ds-bot/src/host/channel.js diff --git a/vendor/ds-bot/src/host/chat-index.js b/ds-bot/src/host/chat-index.js similarity index 100% rename from vendor/ds-bot/src/host/chat-index.js rename to ds-bot/src/host/chat-index.js diff --git a/vendor/ds-bot/src/host/computer/catalog.js b/ds-bot/src/host/computer/catalog.js similarity index 100% rename from vendor/ds-bot/src/host/computer/catalog.js rename to ds-bot/src/host/computer/catalog.js diff --git a/vendor/ds-bot/src/host/computer/index.js b/ds-bot/src/host/computer/index.js similarity index 100% rename from vendor/ds-bot/src/host/computer/index.js rename to ds-bot/src/host/computer/index.js diff --git a/vendor/ds-bot/src/host/computer/leases.js b/ds-bot/src/host/computer/leases.js similarity index 100% rename from vendor/ds-bot/src/host/computer/leases.js rename to ds-bot/src/host/computer/leases.js diff --git a/vendor/ds-bot/src/host/computer/mac-helper.js b/ds-bot/src/host/computer/mac-helper.js similarity index 100% rename from vendor/ds-bot/src/host/computer/mac-helper.js rename to ds-bot/src/host/computer/mac-helper.js diff --git a/vendor/ds-bot/src/host/connectors/catalog.js b/ds-bot/src/host/connectors/catalog.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/catalog.js rename to ds-bot/src/host/connectors/catalog.js diff --git a/vendor/ds-bot/src/host/connectors/gateway.js b/ds-bot/src/host/connectors/gateway.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/gateway.js rename to ds-bot/src/host/connectors/gateway.js diff --git a/vendor/ds-bot/src/host/connectors/index.js b/ds-bot/src/host/connectors/index.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/index.js rename to ds-bot/src/host/connectors/index.js diff --git a/vendor/ds-bot/src/host/connectors/mail/index.js b/ds-bot/src/host/connectors/mail/index.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/mail/index.js rename to ds-bot/src/host/connectors/mail/index.js diff --git a/vendor/ds-bot/src/host/connectors/mail/presets.js b/ds-bot/src/host/connectors/mail/presets.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/mail/presets.js rename to ds-bot/src/host/connectors/mail/presets.js diff --git a/vendor/ds-bot/src/host/connectors/mail/transport.js b/ds-bot/src/host/connectors/mail/transport.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/mail/transport.js rename to ds-bot/src/host/connectors/mail/transport.js diff --git a/vendor/ds-bot/src/host/connectors/oauth.js b/ds-bot/src/host/connectors/oauth.js similarity index 100% rename from vendor/ds-bot/src/host/connectors/oauth.js rename to ds-bot/src/host/connectors/oauth.js diff --git a/vendor/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js similarity index 100% rename from vendor/ds-bot/src/host/constants.js rename to ds-bot/src/host/constants.js diff --git a/vendor/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js similarity index 100% rename from vendor/ds-bot/src/host/delivery.js rename to ds-bot/src/host/delivery.js diff --git a/vendor/ds-bot/src/host/diagnostics.js b/ds-bot/src/host/diagnostics.js similarity index 100% rename from vendor/ds-bot/src/host/diagnostics.js rename to ds-bot/src/host/diagnostics.js diff --git a/vendor/ds-bot/src/host/dsh-update.js b/ds-bot/src/host/dsh-update.js similarity index 100% rename from vendor/ds-bot/src/host/dsh-update.js rename to ds-bot/src/host/dsh-update.js diff --git a/vendor/ds-bot/src/host/feed.js b/ds-bot/src/host/feed.js similarity index 100% rename from vendor/ds-bot/src/host/feed.js rename to ds-bot/src/host/feed.js diff --git a/vendor/ds-bot/src/host/files.js b/ds-bot/src/host/files.js similarity index 100% rename from vendor/ds-bot/src/host/files.js rename to ds-bot/src/host/files.js diff --git a/vendor/ds-bot/src/host/folders.js b/ds-bot/src/host/folders.js similarity index 100% rename from vendor/ds-bot/src/host/folders.js rename to ds-bot/src/host/folders.js diff --git a/vendor/ds-bot/src/host/goal-skills.js b/ds-bot/src/host/goal-skills.js similarity index 100% rename from vendor/ds-bot/src/host/goal-skills.js rename to ds-bot/src/host/goal-skills.js diff --git a/vendor/ds-bot/src/host/goals.js b/ds-bot/src/host/goals.js similarity index 100% rename from vendor/ds-bot/src/host/goals.js rename to ds-bot/src/host/goals.js diff --git a/vendor/ds-bot/src/host/group-log.js b/ds-bot/src/host/group-log.js similarity index 100% rename from vendor/ds-bot/src/host/group-log.js rename to ds-bot/src/host/group-log.js diff --git a/vendor/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.js similarity index 100% rename from vendor/ds-bot/src/host/groups.js rename to ds-bot/src/host/groups.js diff --git a/vendor/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.js similarity index 100% rename from vendor/ds-bot/src/host/handoffs.js rename to ds-bot/src/host/handoffs.js diff --git a/vendor/ds-bot/src/host/home-lock.js b/ds-bot/src/host/home-lock.js similarity index 100% rename from vendor/ds-bot/src/host/home-lock.js rename to ds-bot/src/host/home-lock.js diff --git a/vendor/ds-bot/src/host/im/format.js b/ds-bot/src/host/im/format.js similarity index 100% rename from vendor/ds-bot/src/host/im/format.js rename to ds-bot/src/host/im/format.js diff --git a/vendor/ds-bot/src/host/im/index.js b/ds-bot/src/host/im/index.js similarity index 100% rename from vendor/ds-bot/src/host/im/index.js rename to ds-bot/src/host/im/index.js diff --git a/vendor/ds-bot/src/host/im/platforms/dingtalk.js b/ds-bot/src/host/im/platforms/dingtalk.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/dingtalk.js rename to ds-bot/src/host/im/platforms/dingtalk.js diff --git a/vendor/ds-bot/src/host/im/platforms/discord.js b/ds-bot/src/host/im/platforms/discord.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/discord.js rename to ds-bot/src/host/im/platforms/discord.js diff --git a/vendor/ds-bot/src/host/im/platforms/feishu.js b/ds-bot/src/host/im/platforms/feishu.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/feishu.js rename to ds-bot/src/host/im/platforms/feishu.js diff --git a/vendor/ds-bot/src/host/im/platforms/index.js b/ds-bot/src/host/im/platforms/index.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/index.js rename to ds-bot/src/host/im/platforms/index.js diff --git a/vendor/ds-bot/src/host/im/platforms/qq.js b/ds-bot/src/host/im/platforms/qq.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/qq.js rename to ds-bot/src/host/im/platforms/qq.js diff --git a/vendor/ds-bot/src/host/im/platforms/retry.js b/ds-bot/src/host/im/platforms/retry.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/retry.js rename to ds-bot/src/host/im/platforms/retry.js diff --git a/vendor/ds-bot/src/host/im/platforms/slack.js b/ds-bot/src/host/im/platforms/slack.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/slack.js rename to ds-bot/src/host/im/platforms/slack.js diff --git a/vendor/ds-bot/src/host/im/platforms/telegram.js b/ds-bot/src/host/im/platforms/telegram.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/telegram.js rename to ds-bot/src/host/im/platforms/telegram.js diff --git a/vendor/ds-bot/src/host/im/platforms/wecom.js b/ds-bot/src/host/im/platforms/wecom.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/wecom.js rename to ds-bot/src/host/im/platforms/wecom.js diff --git a/vendor/ds-bot/src/host/im/platforms/weixin.js b/ds-bot/src/host/im/platforms/weixin.js similarity index 100% rename from vendor/ds-bot/src/host/im/platforms/weixin.js rename to ds-bot/src/host/im/platforms/weixin.js diff --git a/vendor/ds-bot/src/host/images.js b/ds-bot/src/host/images.js similarity index 100% rename from vendor/ds-bot/src/host/images.js rename to ds-bot/src/host/images.js diff --git a/vendor/ds-bot/src/host/learning.js b/ds-bot/src/host/learning.js similarity index 100% rename from vendor/ds-bot/src/host/learning.js rename to ds-bot/src/host/learning.js diff --git a/vendor/ds-bot/src/host/legacy.mjs b/ds-bot/src/host/legacy.mjs similarity index 100% rename from vendor/ds-bot/src/host/legacy.mjs rename to ds-bot/src/host/legacy.mjs diff --git a/vendor/ds-bot/src/host/links.js b/ds-bot/src/host/links.js similarity index 100% rename from vendor/ds-bot/src/host/links.js rename to ds-bot/src/host/links.js diff --git a/vendor/ds-bot/src/host/local-agents/acp.js b/ds-bot/src/host/local-agents/acp.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/acp.js rename to ds-bot/src/host/local-agents/acp.js diff --git a/vendor/ds-bot/src/host/local-agents/adapter.js b/ds-bot/src/host/local-agents/adapter.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/adapter.js rename to ds-bot/src/host/local-agents/adapter.js diff --git a/vendor/ds-bot/src/host/local-agents/claude.js b/ds-bot/src/host/local-agents/claude.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/claude.js rename to ds-bot/src/host/local-agents/claude.js diff --git a/vendor/ds-bot/src/host/local-agents/codex.js b/ds-bot/src/host/local-agents/codex.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/codex.js rename to ds-bot/src/host/local-agents/codex.js diff --git a/vendor/ds-bot/src/host/local-agents/discover.js b/ds-bot/src/host/local-agents/discover.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/discover.js rename to ds-bot/src/host/local-agents/discover.js diff --git a/vendor/ds-bot/src/host/local-agents/engines.js b/ds-bot/src/host/local-agents/engines.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/engines.js rename to ds-bot/src/host/local-agents/engines.js diff --git a/vendor/ds-bot/src/host/local-agents/index.js b/ds-bot/src/host/local-agents/index.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/index.js rename to ds-bot/src/host/local-agents/index.js diff --git a/vendor/ds-bot/src/host/local-agents/jsonrpc.js b/ds-bot/src/host/local-agents/jsonrpc.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/jsonrpc.js rename to ds-bot/src/host/local-agents/jsonrpc.js diff --git a/vendor/ds-bot/src/host/local-agents/mcp.js b/ds-bot/src/host/local-agents/mcp.js similarity index 100% rename from vendor/ds-bot/src/host/local-agents/mcp.js rename to ds-bot/src/host/local-agents/mcp.js diff --git a/vendor/ds-bot/src/host/memory-copy.js b/ds-bot/src/host/memory-copy.js similarity index 100% rename from vendor/ds-bot/src/host/memory-copy.js rename to ds-bot/src/host/memory-copy.js diff --git a/vendor/ds-bot/src/host/memory-entries.js b/ds-bot/src/host/memory-entries.js similarity index 100% rename from vendor/ds-bot/src/host/memory-entries.js rename to ds-bot/src/host/memory-entries.js diff --git a/vendor/ds-bot/src/host/memory-pending.js b/ds-bot/src/host/memory-pending.js similarity index 100% rename from vendor/ds-bot/src/host/memory-pending.js rename to ds-bot/src/host/memory-pending.js diff --git a/vendor/ds-bot/src/host/memory-review.js b/ds-bot/src/host/memory-review.js similarity index 100% rename from vendor/ds-bot/src/host/memory-review.js rename to ds-bot/src/host/memory-review.js diff --git a/vendor/ds-bot/src/host/memory-search.js b/ds-bot/src/host/memory-search.js similarity index 100% rename from vendor/ds-bot/src/host/memory-search.js rename to ds-bot/src/host/memory-search.js diff --git a/vendor/ds-bot/src/host/memory-tidy.js b/ds-bot/src/host/memory-tidy.js similarity index 100% rename from vendor/ds-bot/src/host/memory-tidy.js rename to ds-bot/src/host/memory-tidy.js diff --git a/vendor/ds-bot/src/host/memory.js b/ds-bot/src/host/memory.js similarity index 100% rename from vendor/ds-bot/src/host/memory.js rename to ds-bot/src/host/memory.js diff --git a/vendor/ds-bot/src/host/models.js b/ds-bot/src/host/models.js similarity index 100% rename from vendor/ds-bot/src/host/models.js rename to ds-bot/src/host/models.js diff --git a/vendor/ds-bot/src/host/office-skills.js b/ds-bot/src/host/office-skills.js similarity index 100% rename from vendor/ds-bot/src/host/office-skills.js rename to ds-bot/src/host/office-skills.js diff --git a/vendor/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js similarity index 100% rename from vendor/ds-bot/src/host/parts.js rename to ds-bot/src/host/parts.js diff --git a/vendor/ds-bot/src/host/permissions.js b/ds-bot/src/host/permissions.js similarity index 100% rename from vendor/ds-bot/src/host/permissions.js rename to ds-bot/src/host/permissions.js diff --git a/vendor/ds-bot/src/host/privacy.js b/ds-bot/src/host/privacy.js similarity index 100% rename from vendor/ds-bot/src/host/privacy.js rename to ds-bot/src/host/privacy.js diff --git a/vendor/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.js similarity index 100% rename from vendor/ds-bot/src/host/prompt.js rename to ds-bot/src/host/prompt.js diff --git a/vendor/ds-bot/src/host/providers.js b/ds-bot/src/host/providers.js similarity index 100% rename from vendor/ds-bot/src/host/providers.js rename to ds-bot/src/host/providers.js diff --git a/vendor/ds-bot/src/host/requests.js b/ds-bot/src/host/requests.js similarity index 100% rename from vendor/ds-bot/src/host/requests.js rename to ds-bot/src/host/requests.js diff --git a/vendor/ds-bot/src/host/resume.js b/ds-bot/src/host/resume.js similarity index 100% rename from vendor/ds-bot/src/host/resume.js rename to ds-bot/src/host/resume.js diff --git a/vendor/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js similarity index 100% rename from vendor/ds-bot/src/host/roster.js rename to ds-bot/src/host/roster.js diff --git a/vendor/ds-bot/src/host/schedules.js b/ds-bot/src/host/schedules.js similarity index 100% rename from vendor/ds-bot/src/host/schedules.js rename to ds-bot/src/host/schedules.js diff --git a/vendor/ds-bot/src/host/secrets.js b/ds-bot/src/host/secrets.js similarity index 100% rename from vendor/ds-bot/src/host/secrets.js rename to ds-bot/src/host/secrets.js diff --git a/vendor/ds-bot/src/host/side.js b/ds-bot/src/host/side.js similarity index 100% rename from vendor/ds-bot/src/host/side.js rename to ds-bot/src/host/side.js diff --git a/vendor/ds-bot/src/host/skills/goal-grill/SKILL.md b/ds-bot/src/host/skills/goal-grill/SKILL.md similarity index 100% rename from vendor/ds-bot/src/host/skills/goal-grill/SKILL.md rename to ds-bot/src/host/skills/goal-grill/SKILL.md diff --git a/vendor/ds-bot/src/host/steer.js b/ds-bot/src/host/steer.js similarity index 100% rename from vendor/ds-bot/src/host/steer.js rename to ds-bot/src/host/steer.js diff --git a/vendor/ds-bot/src/host/steward.js b/ds-bot/src/host/steward.js similarity index 100% rename from vendor/ds-bot/src/host/steward.js rename to ds-bot/src/host/steward.js diff --git a/vendor/ds-bot/src/host/store.js b/ds-bot/src/host/store.js similarity index 100% rename from vendor/ds-bot/src/host/store.js rename to ds-bot/src/host/store.js diff --git a/vendor/ds-bot/src/host/text.js b/ds-bot/src/host/text.js similarity index 100% rename from vendor/ds-bot/src/host/text.js rename to ds-bot/src/host/text.js diff --git a/vendor/ds-bot/src/host/thinking.js b/ds-bot/src/host/thinking.js similarity index 100% rename from vendor/ds-bot/src/host/thinking.js rename to ds-bot/src/host/thinking.js diff --git a/vendor/ds-bot/src/host/time-context.js b/ds-bot/src/host/time-context.js similarity index 100% rename from vendor/ds-bot/src/host/time-context.js rename to ds-bot/src/host/time-context.js diff --git a/vendor/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js similarity index 100% rename from vendor/ds-bot/src/host/tools.js rename to ds-bot/src/host/tools.js diff --git a/vendor/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js similarity index 100% rename from vendor/ds-bot/src/host/turns.js rename to ds-bot/src/host/turns.js diff --git a/vendor/ds-bot/src/host/update.js b/ds-bot/src/host/update.js similarity index 100% rename from vendor/ds-bot/src/host/update.js rename to ds-bot/src/host/update.js diff --git a/vendor/ds-bot/src/host/usage.js b/ds-bot/src/host/usage.js similarity index 100% rename from vendor/ds-bot/src/host/usage.js rename to ds-bot/src/host/usage.js diff --git a/vendor/ds-bot/src/office/check.js b/ds-bot/src/office/check.js similarity index 100% rename from vendor/ds-bot/src/office/check.js rename to ds-bot/src/office/check.js diff --git a/vendor/ds-bot/src/office/cli.js b/ds-bot/src/office/cli.js similarity index 100% rename from vendor/ds-bot/src/office/cli.js rename to ds-bot/src/office/cli.js diff --git a/vendor/ds-bot/src/office/docx.js b/ds-bot/src/office/docx.js similarity index 100% rename from vendor/ds-bot/src/office/docx.js rename to ds-bot/src/office/docx.js diff --git a/vendor/ds-bot/src/office/package.js b/ds-bot/src/office/package.js similarity index 100% rename from vendor/ds-bot/src/office/package.js rename to ds-bot/src/office/package.js diff --git a/vendor/ds-bot/src/office/png.js b/ds-bot/src/office/png.js similarity index 100% rename from vendor/ds-bot/src/office/png.js rename to ds-bot/src/office/png.js diff --git a/vendor/ds-bot/src/office/pptx.js b/ds-bot/src/office/pptx.js similarity index 100% rename from vendor/ds-bot/src/office/pptx.js rename to ds-bot/src/office/pptx.js diff --git a/vendor/ds-bot/src/office/skills/office-tools/SKILL.md b/ds-bot/src/office/skills/office-tools/SKILL.md similarity index 100% rename from vendor/ds-bot/src/office/skills/office-tools/SKILL.md rename to ds-bot/src/office/skills/office-tools/SKILL.md diff --git a/vendor/ds-bot/src/office/skills/office/SKILL.md b/ds-bot/src/office/skills/office/SKILL.md similarity index 100% rename from vendor/ds-bot/src/office/skills/office/SKILL.md rename to ds-bot/src/office/skills/office/SKILL.md diff --git a/vendor/ds-bot/src/office/xlsx.js b/ds-bot/src/office/xlsx.js similarity index 100% rename from vendor/ds-bot/src/office/xlsx.js rename to ds-bot/src/office/xlsx.js diff --git a/vendor/ds-bot/src/office/xml.js b/ds-bot/src/office/xml.js similarity index 100% rename from vendor/ds-bot/src/office/xml.js rename to ds-bot/src/office/xml.js diff --git a/vendor/ds-bot/src/office/zip.js b/ds-bot/src/office/zip.js similarity index 100% rename from vendor/ds-bot/src/office/zip.js rename to ds-bot/src/office/zip.js diff --git a/vendor/ds-bot/src/shared/group-replies.js b/ds-bot/src/shared/group-replies.js similarity index 100% rename from vendor/ds-bot/src/shared/group-replies.js rename to ds-bot/src/shared/group-replies.js diff --git a/vendor/ds-bot/src/shared/im-platforms.js b/ds-bot/src/shared/im-platforms.js similarity index 100% rename from vendor/ds-bot/src/shared/im-platforms.js rename to ds-bot/src/shared/im-platforms.js diff --git a/vendor/ds-bot/src/shared/mentions.js b/ds-bot/src/shared/mentions.js similarity index 100% rename from vendor/ds-bot/src/shared/mentions.js rename to ds-bot/src/shared/mentions.js diff --git a/vendor/ds-bot/web-search.js b/ds-bot/web-search.js similarity index 100% rename from vendor/ds-bot/web-search.js rename to ds-bot/web-search.js diff --git a/icon.svg b/icon.svg deleted file mode 100644 index 2131061..0000000 --- a/icon.svg +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/index.js b/index.js deleted file mode 100644 index 132f2b6..0000000 --- a/index.js +++ /dev/null @@ -1,455 +0,0 @@ -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createWorkbenchHost, resolveStorePath } from './workbench/host/index.mjs' - -const PRESET_ID = 'sansheng-liubu' -export const POLICY_VERSION = '0.4.0' - -/** - * 默认不强制任何 provider/model:宿主未必注册了这些适配器,强行指定会让整轮请求 - * 以 NO_ADAPTER 失败(例如 "no adapter registered for provider xiaomi")。 - * 角色模型改由面板里的「联动模型」按当前宿主目录选择,或在 preset 配置里显式给 routes。 - */ -export const DEFAULT_ROUTES = Object.freeze({}) - -/** 三省六部:丞相 1 + 三省 3 + 六部 6 = 10 席;六部为吏、户、礼、兵、刑、工。 */ -export const COURT_ROLES = Object.freeze([ - 'lead', 'zhongshu', 'menxia', 'shangshu', - 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu', -]) -const KNOWN_ROLES = new Set(['zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) -const READ_ONLY_ROLES = new Set(['lead', 'zhongshu', 'menxia', 'shangshu', 'minister']) -const EXECUTION_ROLES = new Set(['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) -const IMAGE_TOOLS = new Set(['generate_image', 'generate_images', 'edit_image']) -const FORBIDDEN_IMAGE_TOOLS = new Set(['image_generate', 'codex_image_generate']) -export const READ_ONLY_TOOLSET = Object.freeze(['read', 'grep', 'glob']) -export const EXECUTION_TOOLSET = Object.freeze(['read', 'write', 'edit', 'bash', 'pwsh', 'grep', 'glob']) - -const MANAGEMENT_TOOL_PREFIXES = Object.freeze(['task_board_', 'automation_']) -const OTHER_MANAGEMENT_TOOLS = new Set(['create_skill', 'plugin_manager']) -const HUMAN_SIGNATURE_TOOLS = new Set([ - 'create_skill', 'plugin_manager', 'remote_ssh_delete', 'automation_delete', -]) -const MUTATING_TOOLS = new Set([ - 'write', 'edit', 'pwsh', 'bash', - 'remote_ssh_write', 'remote_ssh_mkdir', 'remote_ssh_exec', - 'ws_mcp_call', ...IMAGE_TOOLS, -]) - -/** - * 六部各自可改什么,按职责划线,不互相借用: - * - 吏部:技能与角色文件(.md/.json/.yml 等),不开命令行,避免改代码或环境。 - * - 户部:数据文件(xlsx/csv/parquet 等);重算与渲染交 Office/Univer 工具,故不开命令行。 - * - 礼部:文档、汇报与截图等材料产出。 - * - 兵部:跑命令、定位问题,另含远程与 MCP 通道。 - * - 刑部:测试与专项验证,只跑不部署;远程命令会绕过风险分级,因此不给。 - * - 工部:代码实现,含 Image-gen 生图。 - */ -const ROLE_ALLOWED_MUTATIONS = Object.freeze({ - libu: new Set(['write', 'edit']), - hubu: new Set(['write', 'edit']), - lipu: new Set(['write', 'edit', 'pwsh', 'bash']), - bingbu: new Set([ - 'write', 'edit', 'pwsh', 'bash', - 'remote_ssh_write', 'remote_ssh_mkdir', 'remote_ssh_exec', 'ws_mcp_call', - ]), - xingbu: new Set(['write', 'edit', 'pwsh', 'bash']), - gongbu: new Set(['write', 'edit', 'pwsh', 'bash', ...IMAGE_TOOLS]), -}) - -const TOOL_GOVERNANCE = `## 工具开放审核则例 -一、凡部门需用工具,须奏明用途、范围、期限,经门下省审核,准奏后由兵部发放,限期使用,到期收回销账。 -二、只读之具,门下可专决;改易文件者,须注明写入范围;涉费、删除、全局配置者,须人工签字。 -三、兵部掌武库:工具装配、发放、回收、登记,只发不批;管理型工具(task_board_*、automation_*)与付费开关归丞相执掌,用时留痕;执行部门常备文件读写、命令行、测试之具。 -四、门下验收查账,越界者下次从严;所授之具不得转借。` - -const LEAD_PROMPT = `# 三省六部模式:丞相 - -你是本会话的丞相,也是 Agent Team Lead。你直接面向用户,负责定策、组队、监督制度执行与最终回奏;不要亲自修改文件。 - -## 固定组织(三省六部十席) -- zhongshu(中书省):调查现状、澄清需求、起草方案,只读。 -- menxia(门下省):独立审议、准奏或封驳,并在执行后验收,只读。 -- shangshu(尚书省):把批准方案转成任务依赖、按吏户礼兵刑工六部分工,只读。 -- libu(吏部):Agent 与技能维护,只动技能、角色与配置文档。 -- hubu(户部):数据、表格与计算,负责真实数据与可复算的结论。 -- lipu(礼部):文档、汇报与可视化产出。 -- bingbu(兵部):环境运行、调试与部署,掌工具装配、发放、回收、登记与销账,只发不批。 -- xingbu(刑部):按风险做专项测试与独立验证,只跑不部署。 -- gongbu(工部):编码与工程实现,负责落盘改动、构建与安装脚本。 - -## 强制流程 -1. 对实质性任务,先创建 zhongshu、menxia、shangshu;成员名必须完全使用上述英文 id。 -2. 在共享任务板建立“中书拟案”→“门下审议”→“尚书派工”→执行任务→“尚书合成”→“门下审核”的依赖链。 -3. 中书提交可执行方案和验收标准;门下只能输出准奏或封驳,封驳必须给出阻塞问题;审议默认一轮。 -4. 门下准奏前不得进入执行。准奏后先向用户回奏「方案 + 审议结论 + 拟派分工」,取得用户明确确认(“准奏”“开始”“可以”等)后,才让尚书派工;六部成员(libu、hubu、lipu、bingbu、xingbu、gongbu)只有 Lead 能创建,且只召集本任务真正用到的部门,不得为凑齐六部而拆分。 -5. 每个执行部门必须先领取自己的 in_progress 任务;写入范围写进 writeScopes,依赖必须全部完成;执行完先自检再上缴。 -6. 六部完成后由尚书合成一份整体结果,再交门下按验收标准审核;审核失败时,执行部门修复一次,再次失败则如实报告并请求用户决定。 -7. 回复用户前必须等待所有必需成员完成,最终使用“丞相回奏”格式汇总方案、审议、执行、验证和风险;若只有部分成果通过,必须附「部分 → 主责部门」清单,写清哪一部门未交付及原因。 - -${TOOL_GOVERNANCE} - -禁止调用 GPT 模型或 codex_image_generate。` - -const ROLE_PROMPTS = Object.freeze({ - zhongshu: `# 中书省职责 -你负责调查、规划和任务拆解。只读,不得修改文件或运行有副作用的命令。先读取实际项目与约束,再产出:目标、非目标、任务 DAG、writeScopes、风险和验收标准。将结果发送给丞相与门下省。收到封驳后只针对阻塞问题修订。\n\n${TOOL_GOVERNANCE}`, - menxia: `# 门下省职责 -你是独立审核者,只读,不得替中书改方案或替执行部门实施。审议必须给出 verdict=approve|reject、blockingIssues、risks、acceptanceCriteria。存在阻塞问题必须封驳;准奏时完成“门下审议”任务。执行后查验工具发放、使用、回收与销账记录,并依据验收标准检查证据;验收对象是尚书合成的整体结果,六部须先自检再上缴。\n\n${TOOL_GOVERNANCE}`, - shangshu: `# 尚书省职责 -你只负责调度设计,不直接写文件,也不能创建 teammate。把门下批准的方案转成共享任务、依赖、负责人建议和互不重叠的 writeScopes;按吏户礼兵刑工的职责分工,通知丞相创建本任务真正需要的六部成员。跟踪状态、汇总异常,并在所需部门完成或部分完成后合成一份整体结果(含未完成项与主责部门)交门下审核。只调用必要的部门:一个部门能完成的不要拆给多个部门,同类小任务合并派工。\n\n${TOOL_GOVERNANCE}`, - libu: `# 吏部职责 -你负责 Agent 与技能维护:技能设计与评估、角色配置与成员编制文档。可用的写入工具限于此范围,不写业务代码、不跑命令行、不改数据。仅当新增或实质改进技能时才安排评测,普通配置修改不启动多代理基准测试;不擅自更换模型或扩大权限。实施前领取自己的任务并确认 blocker 已完成,仅改声明的 writeScopes,完成后提交改动清单与自检结果。\n\n常备工具:write、edit、read、grep、glob。\n\n${TOOL_GOVERNANCE}`, - hubu: `# 户部职责 -你负责数据与计算:表格、数据文件、统计与可复算的结论。可用的写入工具只用于数据文件;读取、重算与渲染交宿主提供的 Office / Univer 工具,不跑命令行。依据实际数据选择统计方法,不把表格操作等同于统计验证,不补造数据;无法核实时如实标注未核实。实施前领取自己的任务并确认 blocker 已完成,完成后提交数据来源、口径与复算方式。\n\n常备工具:write、edit、read、grep、glob。\n\n${TOOL_GOVERNANCE}`, - lipu: `# 礼部职责 -你负责文档、汇报、文案润色与可视化产出,包括 README、变更记录与演示材料。实施前领取自己的任务并确认所有 blocker 已完成;仅修改声明的 writeScopes。完成后向丞相和门下提交成稿与自检结果。\n\n常备工具:${EXECUTION_TOOLSET.join('、')}。\n\n${TOOL_GOVERNANCE}`, - bingbu: `# 兵部职责 -你负责环境运行、调试与部署,并掌武库:工具装配、发放、回收、登记、销账,只发不批。实施前读取任务、领取任务并确认所有 blocker 已完成;仅修改声明的 writeScopes。先复现再定位,运行适用命令与测试,报告复现步骤、根因、修复文件、测试结果、工具台账和剩余风险。部署发布须在授权范围内。\n\n常备工具:${EXECUTION_TOOLSET.join('、')}。\n\n${TOOL_GOVERNANCE}`, - xingbu: `# 刑部职责 -你负责按风险开展的专项测试与独立验证,不承担门下成品审议,也不部署。采用复现定位与有效测试设计:给出问题位置、证据与影响,不越权修改他部成果;修复由主责部门完成。不是每项任务都必经你手,只在风险需要时受派。实施前领取自己的任务并确认 blocker 已完成;仅修改声明的 writeScopes(测试代码与报告)。\n\n常备工具:${EXECUTION_TOOLSET.join('、')}。\n\n${TOOL_GOVERNANCE}`, - gongbu: `# 工部职责 -你负责代码实现、构建、安装脚本与文件落地。实施前领取自己的任务并确认所有 blocker 已完成;仅修改声明的 writeScopes。先读后改,改完运行适用的构建或测试命令,报告修改文件、执行结果和剩余风险。\n\n常备工具:${EXECUTION_TOOLSET.join('、')}。\n\n${TOOL_GOVERNANCE}`, - minister: `# 执行成员职责 -你是三省六部团队中的临时成员。服从丞相调度,先领取任务并尊重依赖与 writeScopes;不要绕过门下审核。\n\n${TOOL_GOVERNANCE}`, -}) - -export function roleFromMembership(membership) { - // A normal newly-created preset session has no Agent Team membership yet. - // Treat that primary/default agent as the Chancellor so users converse with - // the Lead immediately, before the Chancellor creates the remaining court. - if (!membership) return 'lead' - if (membership.role === 'lead') return 'lead' - const name = String(membership.name || '').trim().toLowerCase() - return KNOWN_ROLES.has(name) ? name : 'minister' -} - -export function routeForRole(role, routes = DEFAULT_ROUTES) { - if (!routes) return undefined - return routes[role] ?? routes.minister -} - -export function toolsetForRole(role) { - return EXECUTION_ROLES.has(role) ? [...EXECUTION_TOOLSET] : [...READ_ONLY_TOOLSET] -} - -function hasExecutableAssignment(role, tasks) { - const byId = new Map(tasks.map(task => [task.id, task])) - return tasks.some(task => task.status === 'in_progress' && task.ownerName === role && - (task.blockedBy ?? []).every(id => byId.get(id)?.status === 'completed')) -} - -function managementApproval(role, toolName, tasks, now = Date.now()) { - return tasks.find(task => { - const approval = task?.approval - if (task.status !== 'in_progress' || task.ownerName !== role || !approval) return false - if (approval.reviewer !== 'menxia' || approval.verdict !== 'approve') return false - if (!approval.purpose || !approval.scope || !approval.expiresAt) return false - if (Date.parse(approval.expiresAt) <= now) return false - return Array.isArray(approval.tools) && approval.tools.some(entry => entry === toolName || - (entry.endsWith('*') && toolName.startsWith(entry.slice(0, -1)))) - }) -} - -function isManagementTool(toolName) { - return OTHER_MANAGEMENT_TOOLS.has(toolName) || MANAGEMENT_TOOL_PREFIXES.some(prefix => toolName.startsWith(prefix)) -} - -export function evaluateToolPolicy(role, toolName, tasks = [], options = {}) { - const audit = typeof options.audit === 'function' ? options.audit : () => {} - if (FORBIDDEN_IMAGE_TOOLS.has(toolName)) return `上朝模式只允许使用 Image-gen 工具,不得调用 ${toolName}。` - const destructiveBoardAction = toolName === 'task_board_manage' && options.args?.action === 'delete' - if ((HUMAN_SIGNATURE_TOOLS.has(toolName) || destructiveBoardAction) && options.humanSigned !== true) { - return `${toolName} 涉及删除或全局配置,须先取得人工签字。` - } - if (isManagementTool(toolName)) { - if (role === 'lead') { - audit({ action: 'management-tool', role, toolName, decision: 'allow', authority: 'chancellor' }) - return undefined - } - const approval = managementApproval(role, toolName, tasks, options.now) - if (!approval) return `${role} 调用管理型工具 ${toolName} 前须提交用途、范围、期限,并取得门下省准奏记录。` - audit({ action: 'management-tool', role, toolName, decision: 'allow', approvalId: approval.id }) - return undefined - } - if (!MUTATING_TOOLS.has(toolName)) return undefined - if (READ_ONLY_ROLES.has(role)) return `${role} 是只读规划、审核或调度角色,不得调用写入型工具 ${toolName}。` - if (!EXECUTION_ROLES.has(role)) return `${role} 不是获准的执行部门,不能调用 ${toolName}。` - if (!ROLE_ALLOWED_MUTATIONS[role]?.has(toolName)) return `${toolName} 不属于 ${role} 的职责范围。` - if (!hasExecutableAssignment(role, tasks)) return `${role} 尚未准奏:请先领取一个 in_progress 且所有 blocker 已完成的共享任务。` - return undefined -} - -function rolePrompt(role) { return role === 'lead' ? LEAD_PROMPT : ROLE_PROMPTS[role] ?? ROLE_PROMPTS.minister } - -function normalizeRoutes(routes = {}) { - const merged = { ...DEFAULT_ROUTES } - for (const [role, route] of Object.entries(routes)) { - if (!route || typeof route !== 'object') continue - if (typeof route.provider !== 'string' || typeof route.model !== 'string') continue - merged[role] = { provider: route.provider, model: route.model, - ...(typeof route.reasoningEffort === 'string' ? { reasoningEffort: route.reasoningEffort } : {}) } - } - return merged -} - -/** - * 面板上的「部门模型」走这条指令:宿主的 session.selectModel 会拒绝子会话 - * (`session.header.origin === "subagent"` → session/agent-busy),所以部门模型 - * 只能由本插件在 agent/request 时改,面板则用 /dept-model 把选择下发过来。 - */ -export const DEPT_MODEL_COMMAND = 'dept-model' -export const DEPT_MODEL_USAGE = '<部门> [推理等级] | list | clear [部门]' - -export function routesFilePath(env = process.env) { - const home = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() ? env.DSH_HOME.trim() : path.join(os.homedir(), '.dsh') - return path.join(home, 'sansheng-liubu', 'routes.json') -} - -export function readStoredRoutes(file) { - try { - const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) - return normalizeRoutes(parsed && typeof parsed === 'object' ? parsed : {}) - } catch (error) { return {} } -} - -export function writeStoredRoutes(file, routes) { - try { - fs.mkdirSync(path.dirname(file), { recursive: true }) - fs.writeFileSync(file, JSON.stringify(routes, null, 2) + '\n', 'utf8') - return true - } catch (error) { return false } -} - -export function parseDeptModelCommand(rawInput) { - const tokens = String(rawInput === undefined || rawInput === null ? '' : rawInput).trim().split(/\s+/).filter(Boolean) - if (tokens.length === 0 || tokens[0].toLowerCase() === 'list') return { action: 'list' } - const head = tokens[0].toLowerCase() - if (head === 'clear' || head === 'reset') { - const role = (tokens[1] || '').toLowerCase() - if (role && !COURT_ROLES.includes(role)) return { action: 'error', reason: `未知部门:${tokens[1]}` } - return { action: 'clear', role: role || undefined } - } - if (!COURT_ROLES.includes(head)) return { action: 'error', reason: `未知部门:${tokens[0]}(可用:${COURT_ROLES.join('、')})` } - if (tokens.length < 3) return { action: 'error', reason: `用法:/${DEPT_MODEL_COMMAND} ${DEPT_MODEL_USAGE}` } - const reasoningEffort = tokens[3] - return { - action: 'set', - role: head, - route: { provider: tokens[1], model: tokens[2], ...(reasoningEffort ? { reasoningEffort } : {}) }, - } -} - -export function describeDeptRoutes(routes = {}) { - const entries = Object.entries(routes).filter(([, route]) => route && route.provider && route.model) - if (entries.length === 0) return `十席目前都跟随宿主默认模型;用 /${DEPT_MODEL_COMMAND} ${DEPT_MODEL_USAGE} 逐个固定。` - return '部门固定模型:' + entries - .map(([role, route]) => `${role}=${route.provider}/${route.model}${route.reasoningEffort ? '·' + route.reasoningEffort : ''}`) - .join(';') -} - -function registerDeptModelCommand(ctx, handler) { - if (!ctx.commands || typeof ctx.commands.register !== 'function') return () => {} - try { - const dispose = ctx.effect(function* () { - yield ctx.commands.register({ - name: DEPT_MODEL_COMMAND, - description: '固定某个部门的模型(面板「模型设置」用)', - input: { hint: DEPT_MODEL_USAGE }, - handler: invocation => handler(invocation && invocation.rawInput), - }) - }, `sansheng-liubu: /${DEPT_MODEL_COMMAND}`) - return typeof dispose === 'function' ? dispose : () => {} - } catch (error) { - ctx.logger?.warn?.(`[sansheng-liubu] 注册 /${DEPT_MODEL_COMMAND} 失败:${error && error.message ? error.message : error}`) - return () => {} - } -} - -const INSTALLATIONS = globalThis[Symbol.for('dsh.sansheng-liubu.installations')] ??= - new WeakMap() - -/** - * 工作台是“整台机器一份”,不是“每个 agent 一份”:同一份账本只能有一个写者。 - * 但本插件的 apply 可能被多次调用(每个组合了「上朝」预设的 agent 各一次), - * 所以按账本路径引用计数:最后一个卸载时才真的 dispose,中途不重复建 store。 - */ -const WORKBENCH = globalThis[Symbol.for('dsh.sansheng-liubu.workbench')] ??= new Map() - -/** - * 只有真的跑在宿主里才建工作台:单测用 mock ctx 调 apply() 时不该往 - * %DSH_HOME% 写账本、也不该起对账计时器。cordis 的 Context 一定有 get()。 - */ -function hostSurfaceAvailable(ctx) { - if (!ctx) return false - if (typeof ctx.get === 'function') return true - return Boolean(ctx.webServer || ctx.sessionController || ctx.remote) -} - -function acquireWorkbench(ctx, presetId, log) { - if (!hostSurfaceAvailable(ctx)) return null - let file = null - try { - file = resolveStorePath(process.env) - } catch { - // 拿不到路径就退回内存账本,不能因为一个路径算不出来就让政策插件加载失败。 - file = null - } - const key = file ?? '(memory)' - const existing = WORKBENCH.get(key) - if (existing) { - existing.refs += 1 - return existing - } - const entry = { refs: 1, host: null, key } - try { - // 挂在 root 上:工作台属于整个应用,不该随某个 agent 的销毁一起消失。 - entry.host = createWorkbenchHost(ctx?.root ?? ctx, { presetId }) - for (const warning of entry.host.warnings ?? []) log?.(warning) - log?.(`账本 ${entry.host.file};接口${entry.host.registered ? '已注册' : '未注册'};` - + `会话层${entry.host.hasSessions ? '可用' : '不可用(派发只落账)'}`) - } catch (error) { - log?.(`工作台启动失败:${error?.message ?? error}`) - entry.host = null - } - WORKBENCH.set(key, entry) - return entry -} - -function releaseWorkbench(entry) { - if (!entry || entry !== WORKBENCH.get(entry.key)) return - entry.refs -= 1 - if (entry.refs > 0) return - WORKBENCH.delete(entry.key) - try { - entry.host?.dispose?.() - } catch { - // 卸载失败不影响插件卸载;下次启动仍会从同一个账本继续。 - } -} - -export const name = 'sansheng-liubu-mode' -export const inject = ['agents', 'agentTeams', 'agentPresets', 'systemPrompt', 'tools', 'commands'] - -export function apply(ctx, config = {}) { - const presetId = typeof config.presetId === 'string' ? config.presetId : PRESET_ID - const routeFile = routesFilePath() - const routes = normalizeRoutes({ ...readStoredRoutes(routeFile), ...(config.routes || {}) }) - const owned = new Map() - const audit = entry => ctx.logger?.info?.(`[sansheng-liubu:audit] ${JSON.stringify({ at: new Date().toISOString(), ...entry })}`) - - // 工作台:账本 + 部门会话 + HTTP 接口。整体失败只记日志,不能让政策插件加载不了—— - // 「上朝」的 prompt/工具策略是刚需,工作台是增量能力。 - const logWorkbench = message => { - try { - ctx.logger?.info?.(`[sansheng-liubu:workbench] ${message}`) - } catch { - /* 日志失败不影响业务 */ - } - } - const workbench = acquireWorkbench(ctx, presetId, logWorkbench) - - const persist = () => { - if (writeStoredRoutes(routeFile, routes)) return - ctx.logger?.warn?.(`[sansheng-liubu] 路由表写入失败:${routeFile}`) - } - - const runDeptModel = rawInput => { - const parsed = parseDeptModelCommand(rawInput) - if (parsed.action === 'error') return { kind: 'error', text: parsed.reason } - if (parsed.action === 'list') return { kind: 'success', text: describeDeptRoutes(routes) } - if (parsed.action === 'clear') { - if (parsed.role) delete routes[parsed.role] - else for (const role of Object.keys(routes)) delete routes[role] - persist() - return { - kind: 'success', - text: parsed.role ? `${parsed.role} 已恢复跟随宿主默认模型。` : '十席都已恢复跟随宿主默认模型。', - } - } - routes[parsed.role] = parsed.route - persist() - const effort = parsed.route.reasoningEffort ? `(推理等级 ${parsed.route.reasoningEffort})` : '' - return { - kind: 'success', - text: `${parsed.role} 已固定为 ${parsed.route.provider}/${parsed.route.model}${effort},该部门下一轮开工即生效。`, - } - } - const disposeCommand = registerDeptModelCommand(ctx, runDeptModel) - - const uninstall = agent => { - const release = owned.get(agent) - if (!release) return - owned.delete(agent) - release() - } - - const install = agent => { - if (owned.has(agent)) return - if (ctx.agentPresets.composedPreset(agent.ctx) !== presetId) return - const membership = ctx.agentTeams.tryMembership(agent) - const role = roleFromMembership(membership) - if (!role) return - - const existing = INSTALLATIONS.get(agent) - if (existing) { - existing.refs += 1 - owned.set(agent, () => { - existing.refs -= 1 - if (existing.refs === 0) { existing.dispose(); INSTALLATIONS.delete(agent) } - }) - return - } - - const scoped = agent.ctx - const dispose = scoped.effect(() => { - const disposers = [] - try { - disposers.push(scoped.systemPrompt.section({ - name: 'sansheng-liubu:role', - order: scoped.systemPrompt.getSectionOrder('TEAM_POLICY') + 1, - text: rolePrompt(role), - })) - disposers.push(scoped.on('agent/request', async (_payload, next) => { - const resolved = await next() - const route = routeForRole(role, routes) - if (!route) return resolved - const { reasoningEffort: _oldEffort, ...base } = resolved - return { ...base, provider: route.provider, model: route.model, - ...(route.reasoningEffort ? { reasoningEffort: route.reasoningEffort } : {}) } - }, { prepend: true })) - disposers.push(scoped.tools.guard(execution => { - const tasks = ctx.agentTeams.listTasks(agent) - return evaluateToolPolicy(role, execution.name, tasks, { - audit, - humanSigned: execution?.approval?.humanSigned === true || execution?.humanSigned === true, - args: execution?.args, - }) - })) - } catch (error) { - for (const cleanup of disposers.reverse()) cleanup() - throw error - } - return () => { for (const cleanup of disposers.reverse()) cleanup() } - }) - const shared = { refs: 1, dispose } - INSTALLATIONS.set(agent, shared) - owned.set(agent, () => { - shared.refs -= 1 - if (shared.refs === 0) { shared.dispose(); INSTALLATIONS.delete(agent) } - }) - } - - for (const agent of ctx.agents.list()) install(agent) - const disposeCreated = ctx.on('agent/created', ({ agent }) => install(agent)) - const disposeDisposed = ctx.on('agent/disposed', ({ agent }) => uninstall(agent)) - - return () => { - disposeCommand() - disposeCreated() - disposeDisposed() - for (const agent of [...owned.keys()]) uninstall(agent) - releaseWorkbench(workbench) - } -} diff --git a/locale/en.json b/locale/en.json deleted file mode 100644 index 3717007..0000000 --- a/locale/en.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Imperial Court", - "description": "A Chancellor-led multi-agent mode for planning, review, dispatch, visual work, writing, and coding." - } -} diff --git a/locale/zh.json b/locale/zh.json deleted file mode 100644 index f88f078..0000000 --- a/locale/zh.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "上朝", - "description": "丞相统筹的多 Agent 协作模式,提供规划、审核、调度、图像、写作和代码能力。" - } -} diff --git a/package.json b/package.json index 891f3be..a4686de 100644 --- a/package.json +++ b/package.json @@ -1,41 +1,14 @@ { - "name": "dsh-sansheng-liubu-mode", - "version": "0.9.2", + "name": "sansheng-liubu", + "version": "0.2.0", "private": true, - "description": "上朝:丞相统筹的三省六部多 Agent 模式", "type": "module", - "main": "./index.js", - "exports": { - ".": "./index.js", - "./package.json": "./package.json", - "./locale/*.json": "./locale/*.json" - }, - "files": [ - "index.js", - "cordis.patch.yml", - "preset.patch.yml", - "icon.svg", - "locale/*.json", - "README.md", - "CHANGELOG.md", - "panel/**", - "panel/test", - "scripts", - "locale" + "description": "三省六部:基于 DS Bot 的丞相 / 尚书 / 工部三角色开发工作台", + "workspaces": [ + "sansheng", + "ds-bot" ], - "icon": "./icon.svg", - "dsh": { - "manifestVersion": 1, - "bundle": { - "patch": "./cordis.patch.yml" - } - }, "scripts": { - "test": "node --test --test-isolation=none test/policy.test.js panel/test/client.test.js", - "check:install": "node scripts/check-install.mjs", - "mode": "node scripts/mode.mjs", - "preview": "node scripts/preview.mjs", - "test:sansheng": "node --test --test-isolation=none sansheng/test/*.test.js" - }, - "license": "MIT" + "test": "node --test --test-isolation=none sansheng/test/*.test.js" + } } diff --git a/panel/README.md b/panel/README.md deleted file mode 100644 index 6a34123..0000000 --- a/panel/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# dsh-sansheng-liubu-panel - -三省六部 Agent Team 的 DSH Web 客户端面板。它是独立插件包,避免与 `dsh-sansheng-liubu-mode` 的预设宿主插件重复加载。 - -## 功能 - -- 在会话头部显示当前团队成员数。 -- 朝堂编制与任务流转收进会话右侧栏,用「朝堂 / 任务」页签切换;不再占用工作区主视图。 -- 右侧栏顶部提供协作状态、`输入 @ 选择部门` 提示和子会话返回按钮;四个统计卡固定在侧栏内,可点击切换朝堂或任务。 -- 朝堂图按丞相、三省、六部分层展示;选中部门后在侧栏下方配置模型、推理等级或进入其会话。 -- 在 DSH 原生会话输入框输入 `@`,可直接选择已设官的部门并进入其子会话发送任务;不另造聊天框,也不会静默改写接收人。 -- 进入部门子会话后侧栏自动选中对应部门;返回丞相主会话时恢复丞相选中。 -- 复用 DSH 主题变量,支持明亮、深色和窄侧栏布局。 - -面板只读 `agentTeam` 投影并复用现有 `uiWorkspace.openSession`,不创建 Agent、不调用工具、不改变权限边界。 - -## 安装 - -在 DSH profile 的 `package.json` 中加入: - -```json -"dependencies": { - "dsh-sansheng-liubu-panel": "link:C:/Users/qyh15/三省六部/panel" -}, -"dsh": { - "profile": { - "bundles": ["dsh-sansheng-liubu-panel"] - } -} -``` - -安装后需要重启 DSH Host,再刷新 Web 页面。客户端 bundle 会在页面启动时由 `dsh-client-modules` 组合;只刷新页面不会让 Host 重新扫描新插件。 - -## 验证 - -```bash -node --test --test-isolation=none panel/test/client.test.js -node ../scripts/check-install.mjs -``` diff --git a/panel/cordis.patch.yml b/panel/cordis.patch.yml deleted file mode 100644 index fb6d3eb..0000000 --- a/panel/cordis.patch.yml +++ /dev/null @@ -1,4 +0,0 @@ -# 三省六部 Agent 面板:只加载 Web 客户端 bundle,不参与 Agent 策略。 -- insert: - - id: sansheng-agent-panel - name: dsh-sansheng-liubu-panel diff --git a/panel/index.js b/panel/index.js deleted file mode 100644 index 56ab657..0000000 --- a/panel/index.js +++ /dev/null @@ -1,32 +0,0 @@ -// 三省六部:Host 侧桥接。 -// -// 浏览器不能直接创建 Agent(Agent Teams 只有 Lead 通过模型工具才能组建), -// 所以“组建朝班”走一条受控路径:面板把请求写进当前会话的草稿并通知用户发送, -// 或者(在有该能力时)直接投递一条预置指令给丞相会话。 -// -// 这里同时导出可测试的纯函数,供 panel/test 直接调用,不依赖 cordis 运行时。 - -export const PRESET_ID = 'sansheng-liubu' - -/** 组建朝班的指令:丞相据此创建三省,再由尚书创建六部。 */ -export function formationPrompt(roles = ['zhongshu', 'menxia', 'shangshu']) { - const names = roles.join('、') - return [ - '【上朝】请按三省六部流程组建朝班:', - `1. 立即创建 ${names} 三个部门成员(spawn_teammate),角色名必须与上述名称完全一致。`, - '2. 在共享任务板上建立:中书拟案 → 门下审议 → 尚书派工 的任务链,写清各自的 writeScopes。', - '3. 门下准奏后,由尚书按职责分派:吏部(Agent 与技能维护)、户部(数据与计算)、礼部(内容与呈现)、兵部(环境运行与部署)、刑部(按风险专项测试)、工部(开发实现);只召集本任务真正用到的部门,角色名为 libu/hubu/lipu/bingbu/xingbu/gongbu。', - '4. 每个阶段完成后向我汇报,得到我确认再进入下一阶段。', - ].join('\n') -} - -/** 下旨文本:面板里选部门 + 输入指令时使用。 */ -export function decreePrompt(role, text) { - const body = String(text ?? '').trim() - if (body === '') return '' - return `【丞相下旨 · ${role}】\n${body}` -} - -export function apply() { - // 面板完全在浏览器侧运行;Host 侧不需要注册服务,保留空实现让 Loader 能正常加载。 -} diff --git a/panel/lib/client.js b/panel/lib/client.js deleted file mode 100644 index ebd170f..0000000 --- a/panel/lib/client.js +++ /dev/null @@ -1,2107 +0,0 @@ -window.__ModuleLoader__.load({ - id: "dsh-sansheng-liubu-panel", - factory: (require) => { - var module = { exports: {} }; - var exports = module.exports; - Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); - - const React = require("react"); - const h = React.createElement; - - // #region 常量与纯函数(与 lib/model.js 保持一致,客户端 bundle 需自包含) - const PANEL_ID = "sansheng-liubu"; - const SANSENG_TAB_ID = PANEL_ID + "-tab"; - const SANSENG_TAB_KIND = "sansheng"; - - const ROLE_IDS = ["lead", "zhongshu", "menxia", "shangshu", "libu", "hubu", "lipu", "bingbu", "xingbu", "gongbu"]; - const ROLE_LABELS = { - lead: "丞相", - zhongshu: "中书省", - menxia: "门下省", - shangshu: "尚书省", - libu: "吏部", - hubu: "户部", - lipu: "礼部", - bingbu: "兵部", - xingbu: "刑部", - gongbu: "工部", - }; - const ROLE_MARKS = { - lead: "丞", - zhongshu: "中", - menxia: "门", - shangshu: "尚", - libu: "吏", - hubu: "户", - lipu: "礼", - bingbu: "兵", - xingbu: "刑", - gongbu: "工", - }; - const ROLE_DUTIES = { - lead: "统筹全局、向用户汇报、最终交付", - zhongshu: "拟案规划,拆解任务与验收标准", - menxia: "审议准奏与交付验收,可否决", - shangshu: "派工调度,合成各部门成果", - libu: "Agent 与技能维护、成员编制", - hubu: "数据、表格与计算,可复算结论", - lipu: "文档、汇报与可视化产出", - bingbu: "环境运行、调试与部署,掌武库", - xingbu: "按风险的专项测试与独立验证", - gongbu: "编码与工程实现", - }; - const ROW_OF = { - lead: 0, zhongshu: 1, shangshu: 1, menxia: 1, - libu: 2, hubu: 2, lipu: 2, bingbu: 2, xingbu: 2, gongbu: 2, - }; - const COLUMN_OF = { - zhongshu: 0, shangshu: 1, menxia: 2, - libu: 0, hubu: 1, lipu: 2, bingbu: 3, xingbu: 4, gongbu: 5, - }; - const STATUS_LABELS = { - running: "运行中", - idle: "空闲", - inactive: "空闲", - provisioning: "创建中", - failed: "失败", - absent: "未设官", - }; - const TASK_LABELS = { pending: "待办", in_progress: "执行中", completed: "已完成" }; - const EFFORT_LABELS = { minimal: "极低", low: "低", medium: "中", high: "高", max: "最高", xhigh: "极高" }; - - function roleLabel(role) { - return ROLE_LABELS[role] || "成员"; - } - - function roleMark(role) { - return ROLE_MARKS[role] || "员"; - } - - function modelLabel(model) { - if (typeof model === "string") return model; - if (!model || typeof model !== "object") return ""; - if (typeof model.name === "string") return model.name; - if (typeof model.model === "string") return model.model; - if (typeof model.id === "string") return model.id; - return ""; - } - - function effortLabel(effort) { - if (typeof effort !== "string") return ""; - return EFFORT_LABELS[effort] || effort; - } - - function shortText(value, limit) { - const text = String(value === undefined || value === null ? "" : value).replace(/\s+/g, " ").trim(); - const max = limit || 120; - return text.length <= max ? text : text.slice(0, max - 1) + "…"; - } - - function arrangeRoster(team) { - const members = Array.isArray(team && team.members) ? team.members : []; - const byRole = new Map(); - for (const member of members) { - if (member && typeof member.name === "string") byRole.set(member.name, member); - } - return ROLE_IDS.map((role) => { - const member = byRole.get(role); - return { - role, - label: ROLE_LABELS[role], - mark: ROLE_MARKS[role], - duty: ROLE_DUTIES[role], - row: ROW_OF[role], - column: COLUMN_OF[role], - id: member && member.id, - member, - present: member !== undefined, - }; - }); - } - - /** 朝堂总览四数:在朝、运行中、在办、已完成;图与侧栏统计共用同一份投影。 */ - function courtStats(seats, buckets, isRunning) { - let present = 0; - let runningCount = 0; - for (const entry of Array.isArray(seats) ? seats : []) { - if (!entry.present) continue; - present += 1; - if (isRunning(entry) === true) runningCount += 1; - } - return [ - { key: "members", label: "在朝成员", value: present, mark: "员" }, - { key: "running", label: "正在运行", value: runningCount, mark: "运" }, - { key: "pending", label: "在办任务", value: (buckets && buckets.in_progress ? buckets.in_progress.length : 0) + (buckets && buckets.pending ? buckets.pending.length : 0), mark: "办" }, - { key: "done", label: "已完成", value: (buckets && buckets.completed ? buckets.completed.length : 0), mark: "成" }, - ]; - } - - /** 当前正在查看的子会话对应哪一席;找不到时保持现有选择。 */ - function childRoleOf(seats, childSessionId) { - if (!childSessionId) return undefined; - const match = (Array.isArray(seats) ? seats : []).find((seat) => seat && seat.id === childSessionId); - return match ? match.role : undefined; - } - - /** 原生输入框里的 @ 候选:只列有会话的部门;丞相主会话由当前输入框承载。 */ - function seatMentionOptions(seats) { - return (Array.isArray(seats) ? seats : []) - .filter((seat) => seat && seat.role !== "lead" && typeof seat.id === "string" && seat.id.length > 0) - .map((seat) => ({ - name: seat.label, - value: seat.id, - label: seat.label, - description: seat.duty + " · 选择后进入该部门会话", - })); - } - - function memberStatus(member, running, summaryRunning) { - if (member === undefined || member === null) return "absent"; - if (member.phase === "failed") return "failed"; - if (member.phase === "provisioning") return "provisioning"; - return running === true || summaryRunning === true ? "running" : "idle"; - } - - function bucketsOf(tasks) { - const buckets = { pending: [], in_progress: [], completed: [] }; - for (const task of Array.isArray(tasks) ? tasks : []) { - const key = task && task.status; - if (key === "pending" || key === "in_progress" || key === "completed") buckets[key].push(task); - else buckets.pending.push(task); - } - return buckets; - } - - /** 归属某部门的任务;ownerName 可能是角色 id 也可能是中文名。 */ - function tasksOfRole(tasks, role) { - const list = Array.isArray(tasks) ? tasks : Array.isArray(tasks && tasks.tasks) ? tasks.tasks : []; - return list.filter((task) => task && (task.ownerName === role || task.ownerName === roleLabel(role))); - } - - function statusSummary(seat, team, running, summaryRunning) { - const status = memberStatus(seat && seat.member, running, summaryRunning); - const owned = seat ? tasksOfRole(team, seat.role) : []; - const buckets = bucketsOf(owned); - return { - status, - statusLabel: STATUS_LABELS[status] || status, - owned, - runningCount: buckets.in_progress.length, - pendingCount: buckets.pending.length, - completedCount: buckets.completed.length, - }; - } - - function modelOptions(catalog) { - const options = []; - const groups = Array.isArray(catalog && catalog.groups) ? catalog.groups : []; - for (const group of groups) { - const provider = group && (group.id || group.provider); - const models = Array.isArray(group && group.models) ? group.models : []; - for (const model of models) { - if (!provider || !model || !model.id) continue; - const efforts = Array.isArray(model.reasoning && model.reasoning.efforts) - ? model.reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name || effortLabel(effort.id) })) - : []; - options.push({ - provider, - model: model.id, - rowId: provider + "/" + model.id, - label: model.name || model.id, - efforts, - defaultEffort: model.reasoning && model.reasoning.defaultEffort, - }); - } - } - return options; - } - - function findModelOption(options, current) { - if (!current || !current.provider || !current.model) return undefined; - return options.find((option) => option.provider === current.provider && option.model === current.model); - } - - /** 部门模型指令:宿主拒绝给子会话直接改模型,改由丞相会话下发到模式插件。 */ - const DEPT_MODEL_COMMAND = "dept-model"; - - function seatRouteKey(role) { - return "sansheng-liubu.route." + role; - } - - /** 面板记住每个部门的固定模型(宿主插件另存一份在 routes.json)。 */ - function readSeatRoute(role) { - try { - const store = globalThis.localStorage; - if (!store || typeof store.getItem !== "function") return undefined; - const raw = store.getItem(seatRouteKey(role)); - if (!raw) return undefined; - const parsed = JSON.parse(raw); - if (!parsed || typeof parsed.provider !== "string" || typeof parsed.model !== "string") return undefined; - return { - provider: parsed.provider, - model: parsed.model, - ...(typeof parsed.reasoningEffort === "string" && parsed.reasoningEffort ? { reasoningEffort: parsed.reasoningEffort } : {}), - }; - } catch (error) { return undefined; } - } - - function writeSeatRoute(role, route) { - try { - const store = globalThis.localStorage; - if (store && typeof store.setItem === "function") store.setItem(seatRouteKey(role), JSON.stringify(route)); - } catch (error) { /* 记不住就只影响下次刷新,不报错 */ } - } - - function modelSwitchPlan(current, next, addressesSubagent) { - if (!next || !next.provider || !next.model) return { ok: false, reason: "未选择模型" }; - const effort = next.reasoningEffort === undefined ? undefined : next.reasoningEffort; - if (current && current.provider === next.provider && current.model === next.model && (current.reasoningEffort || undefined) === effort) { - return { ok: false, reason: "与当前设置相同" }; - } - const payload = { provider: next.provider, model: next.model }; - if (effort !== undefined) payload.reasoningEffort = effort; - // 部门是子会话:宿主不给它们单独改模型,改走模式插件的 /dept-model 路由。 - return { ok: true, payload, via: addressesSubagent === true ? "command" : "session" }; - } - - function decreeText(role, text, team) { - const body = String(text === undefined || text === null ? "" : text).trim(); - if (body === "") return ""; - const active = (Array.isArray(team && team.tasks) ? team.tasks : []) - .filter((task) => task && task.status === "in_progress") - .map((task) => task.subject || task.title || task.id) - .filter(Boolean); - const context = active.length > 0 ? "\n(当前在办:" + active.join(";") + ")" : ""; - return "【丞相下旨 · " + roleLabel(role) + "】\n" + body + context; - } - - /** 从 TextBlock 数组里拼出纯文本(Chat 的 content/root 结构在不同节点上略有差异)。 */ - function textOfBlocks(blocks) { - if (!Array.isArray(blocks)) return ""; - return blocks - .filter((block) => block && (block.kind === "text" || block.type === "text")) - .map((block) => block.text) - .filter((text) => typeof text === "string") - .join("\n") - .trim(); - } - - /** 按 anchorSeq 排序后取最近一条用户输入与最近一条助手文本。 */ - function lastExchange(nodes) { - const list = (Array.isArray(nodes) ? nodes : []).filter(Boolean); - const ordered = list.slice().sort((left, right) => { - const a = Number(left.anchorSeq ?? 0); - const b = Number(right.anchorSeq ?? 0); - return a === b ? 0 : a < b ? -1 : 1; - }); - let lastUser = ""; - let lastAssistant = ""; - for (const node of ordered) { - const data = node.data || {}; - if (node.kind === "user") { - const text = textOfBlocks(data.content); - if (text !== "") lastUser = shortText(text, 180); - } else if (node.kind === "assistant" || node.kind === "assistant-step") { - const text = textOfBlocks(data.blocks) || textOfBlocks(data.root && data.root.blocks) || (typeof data.root === "string" ? data.root : ""); - if (text !== "") lastAssistant = shortText(text, 220); - } - } - return { lastUser, lastAssistant }; - } - // #endregion - - /** 由 apply() 建立,向 main 槽条目传递 uiWorkspace(root 槽拿不到会话级服务)。 */ - let WorkspaceContext = null; - - // #region 样式 - const css = ` -.sl-toggle{appearance:none;border:0;background:0 0;color:var(--dsw-alias-label-tertiary,#8a8f98);font:inherit;font-size:12px;display:inline-flex;align-items:center;gap:6px;padding:3px 7px;border-radius:6px;cursor:pointer;min-height:28px} -.sl-toggle:hover,.sl-toggle:focus-visible{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))} -.sl-toggle.active{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.12))} -.sl-toggle-mark{font-size:10px;letter-spacing:.06em;padding:1px 4px;border-radius:4px;border:1px solid currentColor;opacity:.8} -.sl-toggle-wrap{display:inline-flex;align-items:center;gap:6px;min-width:0} -.sl-toggle-notice{max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;line-height:16px;color:var(--dsw-alias-state-error-primary,#dc2626)} -.sl-rail-mark{flex:none;font-size:10px;letter-spacing:.06em;padding:1px 4px;border-radius:4px;border:1px solid currentColor;opacity:.85} -.sl-dock-stub{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:10px;padding:24px;color:var(--dsw-alias-label-secondary,#5b616b);font-size:13px;line-height:20px;text-align:center} -.sl-dock-stub-text{max-width:min(460px,80%);overflow-wrap:anywhere} -.sl-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-size:13px;line-height:20px} -.sl-crash{display:flex;flex-direction:column;gap:8px;margin:24px;padding:18px 20px;border:1px solid #e5484d;border-radius:10px;background:#fff5f5;color:#8b1a1d;font-size:13px;line-height:20px;white-space:normal} -.sl-crash strong{font-size:14px} -.sl-crash pre{margin:0;padding:10px 12px;border-radius:6px;background:rgba(127,127,127,.08);font-size:12px;line-height:18px;white-space:pre-wrap;word-break:break-all;overflow:auto;max-height:240px} -.sl-crash p{margin:0;color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:12px} -.sl-btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:12px;padding:3px 10px;border-radius:7px;cursor:pointer} -.sl-btn:hover{background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12))} -.sl-btn[disabled]{opacity:.5;cursor:default} -.sl-btn.primary{background:var(--dsw-alias-state-business-primary,#3b82f6);border-color:transparent;color:#fff} -.sl-body{flex:1;min-height:0;display:flex} -.sl-right{width:392px;min-width:300px;max-width:46%;display:flex;flex-direction:column;min-height:0;overflow-y:auto} -@container slpanel (max-width:980px){.sl-body{flex-direction:column}.sl-right{width:auto;max-width:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14))}} -.sl-map{padding:12px 16px 16px;flex:none} -.sl-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;padding:14px 16px 0;flex:none} -.sl-stat{display:flex;align-items:center;gap:7px;padding:8px 9px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05));min-width:0} -.sl-stat-mark{flex:none;width:20px;height:20px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-stat-running .sl-stat-mark{background:color-mix(in srgb,#22c55e 18%,transparent);color:#16a34a} -.sl-stat-done .sl-stat-mark{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 16%,transparent);color:var(--dsw-alias-state-business-primary,#3b82f6)} -.sl-stat-body{display:flex;flex-direction:column;min-width:0;line-height:1.15} -.sl-stat-body b{font-size:17px;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:.01em} -.sl-stat-body small{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -@container slpanel (max-width:980px){.sl-stats{padding:12px 14px 0}} -.sl-node{position:relative;display:flex;flex-direction:column;gap:2px;padding:8px 9px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05));cursor:pointer;text-align:left;color:inherit;font:inherit;min-width:0;transition:border-color .12s,box-shadow .12s,transform .12s} -.sl-node:hover{transform:translateY(-1px);border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.4))} -.sl-node[aria-selected="true"]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 55%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 28%,transparent)} -.sl-node.is-absent{opacity:.62;border-style:dashed} -.sl-node-top{display:flex;align-items:center;gap:6px;min-width:0} -.sl-mark{flex:none;width:20px;height:20px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-node[aria-selected="true"] .sl-mark{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 18%,transparent);color:var(--dsw-alias-state-business-primary,#3b82f6)} -.sl-name{font-weight:600;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -.sl-dot{width:6px;height:6px;border-radius:50%;flex:none;background:var(--dsw-alias-label-tertiary,#9ca3af)} -.sl-dot.running{background:#22c55e;box-shadow:0 0 0 2px color-mix(in srgb,#22c55e 20%,transparent)} -.sl-dot.warning{background:#f59e0b} -.sl-dot.error{background:#ef4444} -.sl-dot.absent{background:transparent;border:1px solid var(--dsw-alias-label-tertiary,#9ca3af)} -.sl-detail{flex:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));padding:12px 16px 16px;display:flex;flex-direction:column;gap:8px} -.sl-detail-head{display:flex;align-items:center;gap:8px} -.sl-detail-head strong{font-size:13px} -.sl-detail-head small{color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:11px} -.sl-hint{color:var(--dsw-alias-label-tertiary,#8a8f98);font-size:11px;line-height:17px} -.sl-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px;line-height:17px} -.sl-ok{color:#15803d;font-size:11px;line-height:17px} -.sl-section-title{display:flex;align-items:center;gap:8px;padding:10px 16px 4px;font-size:11px;font-weight:600;letter-spacing:.04em;color:var(--dsw-alias-label-tertiary,#8a8f98);text-transform:uppercase} -.sl-section-title span{margin-left:auto;font-weight:500;text-transform:none;letter-spacing:0} -.sl-tash{list-style:none;margin:0;padding:0 16px 10px;display:flex;flex-direction:column;gap:4px} -.sl-tash li{display:flex;align-items:center;gap:6px;font-size:11px;line-height:17px;color:var(--dsw-alias-label-secondary,#5b616b);min-width:0} -.sl-tash li b{font-weight:500;color:var(--dsw-alias-label-primary,#1f2329);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;flex:1} -.sl-tash li em{font-style:normal;color:var(--dsw-alias-label-tertiary,#8a8f98);flex:none} -.sl-tab-title{display:flex;align-items:center;gap:6px;min-width:0} -.sl-tab-mark{width:18px;height:18px;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;font-size:9px;font-weight:600;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5b616b)} - -/* 2026 court workspace: quiet DSH surfaces, clear hierarchy, one blue accent. */ -.sl-root{container-type:inline-size;container-name:slpanel;--sl-accent:var(--dsw-alias-state-business-primary,#4d6bfe);--sl-card:var(--dsw-alias-bg-layer-1,#fff);--sl-page:var(--dsw-alias-bg-layer-2,#f5f6f8);--sl-line:var(--dsw-alias-border-l1,rgba(127,127,127,.14));background:var(--sl-page);font-size:13px} -.sl-section-kicker{font-size:9px;line-height:14px;letter-spacing:.13em;color:var(--dsw-alias-label-tertiary,#8a8f98);font-weight:600} -.sl-state-dot{width:6px;height:6px;border-radius:50%;background:#22c55e;box-shadow:0 0 0 3px color-mix(in srgb,#22c55e 12%,transparent)} -.sl-body{display:grid;grid-template-columns:minmax(0,1fr) 440px;gap:16px;padding:16px;overflow:hidden;background:var(--sl-page)} -.sl-right{width:auto;min-width:0;max-width:none;gap:12px;padding:0;overflow-y:auto;overflow-x:hidden;border:0} -.sl-task-panel,.sl-map,.sl-detail{background:var(--sl-card);border:1px solid var(--sl-line);border-radius:14px;box-shadow:0 1px 2px rgba(15,23,42,.025)} -.sl-btn{min-height:32px;padding:5px 13px;border-radius:8px;border-color:var(--sl-line);background:var(--sl-card);font-weight:500} -.sl-btn.primary{background:var(--sl-accent);box-shadow:0 3px 8px color-mix(in srgb,var(--sl-accent) 16%,transparent)} -.sl-btn.primary:hover{background:color-mix(in srgb,var(--sl-accent) 88%,#172554)} -.sl-task-panel{flex:1;min-height:180px;padding:16px 18px} -.sl-section-title{padding:0 0 12px;gap:12px} -.sl-section-heading{display:flex;flex-direction:column} -.sl-section-heading h2,.sl-map-head h2{margin:0;font-size:14px;line-height:20px;font-weight:600} -.sl-section-title .sl-section-count{margin-left:auto;padding:3px 8px;border-radius:6px;background:var(--sl-page);font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-tash{padding:0;gap:6px} -.sl-tash li{padding:10px 11px;border:1px solid transparent;border-radius:9px;background:var(--sl-page);gap:10px} -.sl-tash li:hover{border-color:color-mix(in srgb,var(--sl-accent) 20%,transparent)} -.sl-task-state{width:18px;display:flex;justify-content:center;flex:none} -.sl-task-copy{display:flex;flex-direction:column;min-width:0;flex:1} -.sl-task-copy small{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-tash li .sl-task-owner{padding:2px 7px;border-radius:5px;background:var(--sl-card);color:var(--dsw-alias-label-secondary,#5b616b);font-size:10px} -.sl-task-empty{min-height:108px;display:flex;align-items:center;justify-content:center;gap:12px;border:1px dashed var(--sl-line);border-radius:10px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-empty-mark{width:30px;height:30px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:color-mix(in srgb,#22c55e 9%,transparent);color:#16a34a} -.sl-task-empty strong{font-size:12px;font-weight:500;color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-task-empty p{margin:2px 0 0;font-size:10px} -.sl-stats{grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;padding:0} -.sl-stat{position:relative;display:block;padding:12px 11px 11px;border-radius:12px;background:var(--sl-card);border-color:var(--sl-line);box-shadow:0 1px 2px rgba(15,23,42,.025)} -.sl-stat-mark{position:absolute;right:9px;top:9px;width:20px;height:20px;background:var(--sl-page);font-size:10px} -.sl-stat-body{gap:1px} -.sl-stat-body b{font-size:22px;line-height:27px;letter-spacing:-.02em} -.sl-stat-body small{font-size:10px} -.sl-stat-members .sl-stat-mark{background:color-mix(in srgb,var(--sl-accent) 10%,transparent);color:var(--sl-accent)} -.sl-stat-pending .sl-stat-mark{background:color-mix(in srgb,#f59e0b 12%,transparent);color:#d97706} -.sl-map{padding:14px;border-radius:14px} -.sl-map-head{display:flex;align-items:flex-end;justify-content:space-between;gap:10px;margin-bottom:12px} -.sl-map-head>span{font-size:9px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-tier-label{display:flex;align-items:center;justify-content:space-between;margin:0 1px 6px;font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-tier-label small{font-size:9px} -.sl-node:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 65%,transparent);outline-offset:2px} -.sl-node{border-color:var(--sl-line);border-radius:10px;background:var(--sl-card);box-shadow:none;transition:border-color .15s,box-shadow .15s,transform .15s,background .15s} -.sl-node:hover{transform:translateY(-1px);border-color:color-mix(in srgb,var(--sl-accent) 35%,transparent);box-shadow:0 4px 12px rgba(15,23,42,.05)} -.sl-node[aria-selected="true"]{border-color:color-mix(in srgb,var(--sl-accent) 55%,transparent);background:color-mix(in srgb,var(--sl-accent) 4%,var(--sl-card));box-shadow:0 0 0 2px color-mix(in srgb,var(--sl-accent) 9%,transparent)} -.sl-node.is-absent{opacity:.55;background:var(--sl-page)} -.sl-node-top{gap:6px} -.sl-mark{background:var(--sl-page);color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-node[aria-selected="true"] .sl-mark{background:color-mix(in srgb,var(--sl-accent) 12%,transparent);color:var(--sl-accent)} -.sl-name{font-size:11px} -.sl-detail{border:1px solid var(--sl-line);border-radius:14px;padding:15px;gap:11px;margin-bottom:2px} -.sl-detail-head{gap:10px;padding-bottom:10px;border-bottom:1px solid var(--sl-line)} -.sl-detail-mark{width:34px;height:34px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--sl-accent) 10%,transparent);color:var(--sl-accent);font-size:14px;font-weight:650;flex:none} -.sl-detail-title{display:flex;flex-direction:column;min-width:0} -.sl-detail-head strong{font-size:13px;line-height:19px} -.sl-detail-head small{font-size:10px;line-height:15px} -.sl-detail-head .sl-btn{font-size:10px;min-height:28px;padding:3px 8px} -.sl-hint{font-size:10px;line-height:16px} -.sl-root ::-webkit-scrollbar{width:6px;height:6px} -.sl-root ::-webkit-scrollbar-thumb{background:var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:10px} -.sl-root ::-webkit-scrollbar-track{background:transparent} -@container slpanel (max-width:1180px){.sl-body{grid-template-columns:minmax(0,1fr) 400px;gap:12px;padding:12px}} -@container slpanel (max-width:980px){.sl-body{display:flex;flex-direction:column;overflow-y:auto}.sl-right{width:auto;max-width:none;overflow:visible;border:0}.sl-task-panel{min-height:150px}.sl-stats{padding:0}.sl-detail{margin-bottom:0}} -@container slpanel (max-width:620px){.sl-body{padding:9px;gap:10px}.sl-task-panel,.sl-map,.sl-detail{border-radius:11px}.sl-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.sl-map-head>span{display:none}} - -.sl-compact{padding:0} -.sl-compact .sl-body{display:flex;flex-direction:column;padding:0;gap:0;overflow:hidden} -.sl-compact .sl-right{width:auto;max-width:none;min-width:0;border-top:0;flex:1;overflow-y:auto} -.sl-compact .sl-stats{grid-template-columns:repeat(2,minmax(0,1fr))} - -/* 2026-11 redesign: department cards are the primary surface. */ -.sl-root{--sl-node-border:color-mix(in srgb,var(--sl-accent) 17%,var(--sl-line));--sl-soft-accent:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-card))} -.sl-stats{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px} -.sl-stat{display:flex;align-items:center;gap:8px;min-height:68px;padding:11px 12px} -.sl-stat-mark{position:static;inset:auto;margin-left:auto;width:26px;height:26px;border-radius:8px;font-size:11px} -.sl-stat-body b{font-size:24px;line-height:29px} -.sl-stat-body small{font-size:10px;line-height:15px} -.sl-map{padding:15px 14px 14px} -.sl-map-head{align-items:center;margin-bottom:8px} -.sl-map-head .sl-section-kicker{display:block;margin-bottom:1px} -.sl-map-head>span{white-space:nowrap} -.sl-tier{margin-top:8px} -.sl-grid{display:grid;gap:10px;min-width:0} -.sl-grid-1{grid-template-columns:minmax(0,1fr)} -.sl-grid-1 .sl-node{width:min(232px,100%);margin:0 auto} -.sl-grid-3,.sl-grid-6{grid-template-columns:repeat(3,minmax(0,1fr));gap:12px} -.sl-connector-tri{position:relative;height:19px;margin:0 4px} -.sl-connector-tri:before{content:"";position:absolute;left:16.667%;right:16.667%;top:7px;height:1px;background:color-mix(in srgb,var(--sl-accent) 22%,var(--sl-line))} -.sl-connector-tri:after{content:"";position:absolute;left:50%;top:0;width:1px;height:8px;background:color-mix(in srgb,var(--sl-accent) 22%,var(--sl-line))} -.sl-connector-tri span{position:absolute;top:7px;bottom:0;width:1px;background:color-mix(in srgb,var(--sl-accent) 22%,var(--sl-line))} -.sl-connector-tri span:nth-child(1){left:16.667%} -.sl-connector-tri span:nth-child(2){left:50%} -.sl-connector-tri span:nth-child(3){left:83.333%} -.sl-stem{width:1px;height:15px;margin:0 auto;background:color-mix(in srgb,var(--sl-accent) 22%,var(--sl-line))} -.sl-ministry-group{margin-top:16px;padding:10px;border:1px solid color-mix(in srgb,var(--sl-accent) 11%,var(--sl-line));border-radius:14px;background:color-mix(in srgb,var(--sl-accent) 3%,var(--sl-page))} -.sl-group-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin:0 2px 9px} -.sl-group-title{display:block;font-size:11px;line-height:16px;font-weight:600;color:var(--dsw-alias-label-primary,#1f2329)} -.sl-group-head small{display:block;margin-top:1px;font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-group-count{flex:none;padding:2px 7px;border-radius:5px;background:var(--sl-card);border:1px solid var(--sl-line);font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-ministry-group .sl-node{background:var(--sl-card)} -.sl-node{min-height:80px;align-items:stretch;justify-content:center;gap:7px;padding:11px 11px 10px;border:1px solid var(--sl-node-border);border-radius:12px;background:var(--sl-card);box-shadow:0 1px 2px rgba(15,23,42,.035)} -.sl-node:hover{transform:translateY(-1px);border-color:color-mix(in srgb,var(--sl-accent) 42%,var(--sl-line));box-shadow:0 6px 18px rgba(15,23,42,.07)} -.sl-node:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 68%,transparent);outline-offset:2px} -.sl-node[aria-pressed="true"],.sl-node.is-selected{border-color:var(--sl-accent);background:var(--sl-soft-accent);box-shadow:inset 0 0 0 1px var(--sl-accent),0 6px 18px color-mix(in srgb,var(--sl-accent) 12%,transparent)} -.sl-node.is-absent{border-style:dashed;background:var(--sl-page);opacity:.64} -.sl-node.status-failed{border-color:color-mix(in srgb,#ef4444 38%,var(--sl-line))} -.sl-node-check{position:absolute;right:7px;top:7px;width:17px;height:17px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:var(--sl-accent);color:#fff;font-size:10px;line-height:17px;font-weight:700} -.sl-node-top{gap:7px;padding-right:12px} -.sl-mark{flex:none;width:28px;height:28px;border-radius:8px;background:color-mix(in srgb,var(--sl-accent) 8%,var(--sl-page));color:color-mix(in srgb,var(--sl-accent) 76%,#1f2329);font-size:12px;font-weight:650} -.sl-node[aria-pressed="true"] .sl-mark{background:var(--sl-accent);color:#fff} -.sl-name{font-size:13px;line-height:19px;font-weight:650;letter-spacing:.01em} -.sl-node-status{display:flex;align-items:center;gap:5px;min-width:0;padding-left:35px;font-size:10px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-detail{padding:15px;gap:12px} -.sl-detail-head{padding-bottom:11px} -.sl-detail-title{flex:1} -.sl-detail-head strong{font-size:15px;line-height:21px} -.sl-detail-title small{display:block;margin-top:1px;line-height:15px} -.sl-detail-chip{flex:none;padding:2px 7px;border-radius:5px;background:var(--sl-page);border:1px solid var(--sl-line);font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-detail-status{display:flex;align-items:center;flex-wrap:wrap;gap:6px;min-width:0;padding:0 1px;font-size:10px;line-height:16px;color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-detail-status small{flex:1 1 100%;margin:0;min-width:0;overflow:hidden;color:var(--dsw-alias-label-tertiary,#8a8f98);display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;white-space:normal;overflow-wrap:anywhere} -.sl-setting-block{display:flex;flex-direction:column;gap:9px;padding:11px;border:1px solid var(--sl-line);border-radius:11px;background:var(--sl-page)} -.sl-setting-head{display:flex;align-items:center;justify-content:space-between;gap:8px} -.sl-setting-head h3{margin:0;font-size:12px;line-height:18px;font-weight:600} -.sl-setting-head small{font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-model-grid{display:grid;grid-template-columns:minmax(0,1fr) 104px;gap:8px} -.sl-control{display:flex;flex-direction:column;gap:5px;min-width:0} -.sl-control>span{font-size:9px;line-height:14px;font-weight:500;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-control select{width:100%;min-width:0;min-height:34px;padding:6px 8px;border:1px solid var(--sl-line);border-radius:8px;background:var(--sl-card);color:inherit;font:inherit;font-size:11px;outline:none} -.sl-control select:focus-visible{border-color:color-mix(in srgb,var(--sl-accent) 55%,transparent);box-shadow:0 0 0 2px color-mix(in srgb,var(--sl-accent) 8%,transparent)} -.sl-control select:disabled{opacity:.58} -.sl-model-foot{display:flex;align-items:center;gap:8px;min-width:0} -.sl-model-foot .sl-btn{flex:none;min-height:30px;font-size:10px;padding:4px 9px} -.sl-model-foot small{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-model-foot small.is-dirty{color:#b45309} -.sl-link-button{appearance:none;align-self:flex-start;border:0;background:none;padding:0;color:var(--sl-accent);font:inherit;font-size:10px;line-height:16px;cursor:pointer} -.sl-conversation-block{display:flex;flex-direction:column;gap:7px} -.sl-delegate-block{display:flex;flex-direction:column;gap:8px;padding-top:2px} -.sl-delegate-block textarea{width:100%;box-sizing:border-box;resize:vertical;min-height:54px;border:1px solid var(--sl-line);border-radius:9px;background:var(--sl-card);color:inherit;font:inherit;font-size:11px;line-height:17px;padding:7px 9px} -.sl-delegate-block textarea::placeholder{color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-conversation-action{width:100%;min-height:40px;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:0 13px;border:1px solid transparent;border-radius:10px;background:var(--sl-accent);color:#fff;font:inherit;font-size:12px;line-height:18px;font-weight:600;cursor:pointer;box-shadow:0 4px 12px color-mix(in srgb,var(--sl-accent) 18%,transparent)} -.sl-conversation-action:hover{background:color-mix(in srgb,var(--sl-accent) 88%,#172554)} -.sl-conversation-action:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 60%,transparent);outline-offset:2px} -.sl-conversation-action:disabled{background:var(--sl-page);color:var(--dsw-alias-label-tertiary,#8a8f98);border-color:var(--sl-line);box-shadow:none;cursor:default} -.sl-conversation-arrow{font-size:13px;opacity:.82} -.sl-conversation-hint{margin:0;font-size:10px;line-height:16px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-advanced{border-top:1px solid var(--sl-line);padding-top:9px} -.sl-advanced summary{display:flex;align-items:center;justify-content:space-between;list-style:none;cursor:pointer;font-size:10px;line-height:16px;font-weight:500;color:var(--dsw-alias-label-secondary,#5b616b)} -.sl-advanced summary::-webkit-details-marker{display:none} -.sl-advanced summary:after{content:"+";font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-advanced[open] summary:after{content:"−"} -.sl-advanced-list{margin:8px 0 0;display:grid;gap:5px;font-size:9px;line-height:15px} -.sl-advanced-list div{display:flex;gap:8px;min-width:0} -.sl-advanced-list dt{flex:none;width:58px;color:var(--dsw-alias-label-tertiary,#8a8f98)} -.sl-advanced-list dd{margin:0;min-width:0;word-break:break-all;color:var(--dsw-alias-label-secondary,#5b616b)} -@container slpanel (max-width:1180px){.sl-grid-6{gap:12px}.sl-node{min-height:76px;padding:10px}} -@container slpanel (max-width:980px){.sl-grid-3,.sl-grid-6{grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}} -@container slpanel (max-width:620px){.sl-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.sl-grid-3,.sl-grid-6{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.sl-connector-tri,.sl-stem{display:none}.sl-grid-1 .sl-node{width:100%}.sl-map{padding:13px 11px}.sl-detail{padding:13px}.sl-model-grid{grid-template-columns:minmax(0,1fr) 94px}} -@container slpanel (max-width:330px){.sl-grid-3,.sl-grid-6{grid-template-columns:1fr}} -.sl-compact .sl-stats{grid-template-columns:repeat(2,minmax(0,1fr))} -.sl-compact .sl-connector-tri,.sl-compact .sl-stem{display:none} -.sl-compact .sl-grid-1 .sl-node{width:100%} -button.sl-stat{appearance:none;width:100%;border:1px solid var(--sl-line);color:inherit;font:inherit;text-align:left;cursor:pointer} -.sl-stat-pending:hover{border-color:color-mix(in srgb,var(--sl-accent) 34%,var(--sl-line));background:color-mix(in srgb,var(--sl-accent) 3%,var(--sl-card))} -.sl-stat-pending:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 60%,transparent);outline-offset:2px} -button.sl-stat-members:hover{border-color:color-mix(in srgb,var(--sl-accent) 34%,var(--sl-line));background:color-mix(in srgb,var(--sl-accent) 3%,var(--sl-card))} -button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 60%,transparent);outline-offset:2px} -.sl-body.is-court{grid-template-columns:minmax(0,1fr)} -.sl-body.is-court .sl-right{width:100%;max-width:1100px;margin:0 auto} -.sl-body.is-court .sl-stats{display:none} -.sl-body.is-court .sl-map{padding:20px 18px 18px} -.sl-body.is-court .sl-detail{padding:18px} -.sl-map-meta{display:flex;align-items:center;gap:9px;flex:none} -.sl-map-meta>span{font-size:9px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap} -@container slpanel (max-width:980px){.sl-body.is-court .sl-right{max-width:none}.sl-body.is-court .sl-map{padding:15px 13px}} - -/* 右侧栏形态:聊天留给 DSH 原生会话,面板只承载朝堂与任务。 */ -.sl-sidebar{background:transparent} -.sl-side-meta{display:flex;align-items:center;gap:7px;flex:none;min-width:0;padding:11px 3px 8px} -.sl-side-state{display:inline-flex;align-items:center;gap:6px;flex:none;padding:2px 7px;border:1px solid var(--sl-line);border-radius:999px;background:var(--sl-card);font-size:10px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap} -.sl-side-state.is-child{color:var(--sl-accent);border-color:color-mix(in srgb,var(--sl-accent) 22%,transparent);background:color-mix(in srgb,var(--sl-accent) 7%,transparent)} -.sl-side-state .sl-state-dot{width:6px;height:6px;border-radius:50%;background:#21a36a;box-shadow:0 0 0 3px color-mix(in srgb,#21a36a 12%,transparent)} -.sl-side-state.is-child .sl-state-dot{background:var(--sl-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--sl-accent) 12%,transparent)} -.sl-side-hint{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:right;font-size:9px;line-height:14px;color:var(--dsw-alias-label-caption,#9aa0a6)} -.sl-side-return{appearance:none;flex:none;padding:3px 7px;border:1px solid var(--sl-line);border-radius:6px;background:var(--sl-card);color:var(--sl-accent);font:inherit;font-size:9px;line-height:14px;cursor:pointer} -.sl-side-return:hover{background:color-mix(in srgb,var(--sl-accent) 7%,var(--sl-card))} -.sl-side-return:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 55%,transparent);outline-offset:1px} -.sl-body-sidebar{display:flex;min-height:0;padding:0 2px 10px;overflow:hidden;background:transparent} -.sl-body-sidebar .sl-right{flex:1;width:auto;min-width:0;max-width:none;gap:10px;padding:0 1px 0 0;overflow-y:auto;overflow-x:hidden} -.sl-side-tabs{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:3px;flex:none;padding:3px;border:1px solid var(--sl-line);border-radius:10px;background:color-mix(in srgb,var(--sl-card) 94%,transparent);box-shadow:0 2px 8px rgba(15,23,42,.04);backdrop-filter:blur(8px)} -.sl-side-tab{appearance:none;flex:1;display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:30px;padding:4px 10px;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary,#5b616b);font:inherit;font-size:11px;line-height:16px;font-weight:500;cursor:pointer} -.sl-side-tab:hover{background:var(--sl-page);color:var(--dsw-alias-label-primary,#1f2329)} -.sl-side-tab.is-active{background:var(--sl-soft-accent,color-mix(in srgb,var(--sl-accent) 9%,var(--sl-card)));color:var(--sl-accent);font-weight:600;box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--sl-accent) 16%,transparent)} -.sl-side-tab:focus-visible{outline:2px solid color-mix(in srgb,var(--sl-accent) 60%,transparent);outline-offset:1px} -.sl-side-tab-count{min-width:17px;padding:0 5px;border-radius:5px;background:color-mix(in srgb,var(--sl-accent) 9%,var(--sl-page));color:var(--sl-accent);font-size:9px;line-height:15px;text-align:center;font-variant-numeric:tabular-nums} -.sl-sidebar .sl-stats{grid-template-columns:repeat(2,minmax(0,1fr));padding:0;gap:8px} -.sl-sidebar .sl-stat{padding:9px 10px;border-radius:11px;background:var(--sl-card);box-shadow:0 1px 2px rgba(15,23,42,.02)} -.sl-sidebar .sl-stat-body b{font-size:18px} -.sl-side-court{display:flex;flex-direction:column;gap:10px;min-width:0} -.sl-sidebar .sl-map{padding:14px 13px 15px;border-radius:14px} -.sl-sidebar .sl-detail{padding:14px;border-radius:14px;gap:10px} -.sl-sidebar .sl-conversation-action{min-height:36px} -.sl-side-tasks{flex:none;min-height:0;padding:15px 14px;border-radius:14px} -.sl-sidebar .sl-task-panel .sl-section-title{padding-bottom:10px} -@container slpanel (max-width:420px){.sl-sidebar .sl-map{padding:12px 10px}.sl-sidebar .sl-detail{padding:12px}.sl-side-tabs{position:static}} -`; - const cssId = "dsh-sansheng-liubu-panel/panel.css"; - if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(cssId) + "]") === null) { - const tag = document.createElement("style"); - tag.dataset.plugin = "dsh-sansheng-liubu-panel"; - tag.dataset.pluginCss = cssId; - tag.textContent = css; - document.head.appendChild(tag); - } - // #endregion - - // #region 小部件 - function Dot(props) { - const status = props.status || "inactive"; - const tone = status === "running" ? "running" : status === "failed" ? "error" : status === "provisioning" ? "warning" : status === "absent" ? "absent" : ""; - return h("span", { className: "sl-dot" + (tone ? " " + tone : ""), "aria-hidden": "true" }); - } - - function SeatCard(props) { - const { seat, selected, onSelect, status } = props; - const cls = ["sl-node", "status-" + status]; - if (!seat.present) cls.push("is-absent"); - if (selected) cls.push("is-selected"); - return h("button", { - type: "button", - className: cls.join(" "), - "aria-pressed": selected ? "true" : "false", - "aria-label": seat.label + "," + (STATUS_LABELS[status] || status), - "data-role": seat.role, - title: seat.duty, - onClick: () => onSelect(seat.role), - children: [ - selected ? h("span", { className: "sl-node-check", "aria-hidden": "true", children: "✓" }) : null, - h("span", { className: "sl-node-top" }, [ - h("span", { className: "sl-mark", "aria-hidden": "true", children: seat.mark }), - h("span", { className: "sl-name", children: seat.label }), - ]), - h("span", { className: "sl-node-status" }, [ - h(Dot, { status }), - h("span", { children: STATUS_LABELS[status] || status }), - ]), - ], - }); - } - // #endregion - - // #region 主面板 - function SanshengPanel(props) { - const host = props.host; - const tabSessionId = props.sessionId; - const compact = props.compact === true; - // 直接订阅宿主服务层 store,不调用 slot 注入的会话级 hook(root 级 main 槽下不可用)。 - const sessions = useStoreSnapshot(host.sessionsStore, EMPTY_SESSIONS) || EMPTY_SESSIONS; - const statuses = useStoreSnapshot(host.statusStore, undefined); - const activePanelId = useStoreSnapshot(host.panelStore, {}).activePanelId; - const projections = sessions.projectionsBySession || {}; - - // main 面板是 root 级槽:拿不到会话级 props,用户正在看哪个会话只能从 - // uiWorkspace 的选中记录(持久化在 dsh.sessions.current)读。 - const selection = useWorkspaceSelection(); - const pickedId = host.getSelectedSession ? host.getSelectedSession() : undefined; - const focusedSessionId = tabSessionId || pickedId || selection.sessionId; - const activeAddress = selection.subagentAddress || (focusedSessionId ? subagentAddressOf(sessions, focusedSessionId) : undefined); - const leadSessionId = (activeAddress && activeAddress.parentSessionId) || focusedSessionId; - const team = leadSessionId && projections[leadSessionId] - ? projections[leadSessionId].values.agentTeam - : undefined; - const seats = React.useMemo(() => arrangeRoster(team), [team]); - const buckets = React.useMemo(() => bucketsOf(team && team.tasks), [team]); - - const [selectedRole, setSelectedRole] = React.useState("lead"); - const [sidebarView, setSidebarView] = React.useState("court"); - const seat = seats.find((entry) => entry.role === selectedRole) || seats[0]; - - const runningOf = (id) => { - if (!id) return undefined; - const fromStatus = statuses && typeof statuses.get === "function" ? statuses.get(id) : undefined; - if (fromStatus && typeof fromStatus.running === "boolean") return fromStatus.running; - const fromList = sessions.byId[id]; - return fromList ? fromList.running : undefined; - }; - - const seatState = (entry) => { - const status = memberStatus(entry.member, runningOf(entry.id), undefined); - const owned = tasksOfRole(team, entry.role); - const ownBuckets = bucketsOf(owned); - const running = status === "running"; - const recent = entry.id ? host.recentText(entry.id) : ""; - const model = entry.id ? host.memberModel(entry.id) : ""; - const lastText = recent ? recent : (owned.length > 0 ? owned[owned.length - 1].subject || "" : ""); - return { - status, - counts: { - runningCount: ownBuckets.in_progress.length, - pendingCount: ownBuckets.pending.length, - completedCount: ownBuckets.completed.length, - }, - lastText: shortText(lastText, 40), - model, - running, - }; - }; - - const stats = React.useMemo( - () => courtStats(seats, buckets, (entry) => memberStatus(entry.member, runningOf(entry.id), undefined) === "running"), - [seats, buckets, sessions, statuses], - ); - - const openTaskCount = buckets.in_progress.length + buckets.pending.length; - const showTasks = () => setSidebarView("tasks"); - const showCourt = () => setSidebarView("court"); - const seatInfo = seat ? seatState(seat) : { status: "absent", counts: {}, lastText: "", model: "" }; - - // —— 图下配置区 —— - const [catalog, setCatalog] = React.useState({ status: "idle", options: [], error: null, current: undefined, subagent: false }); - const [draftModel, setDraftModel] = React.useState(""); - const [draftEffort, setDraftEffort] = React.useState(""); - const [notice, setNotice] = React.useState(null); - const [busy, setBusy] = React.useState(false); - const [catalogRetry, setCatalogRetry] = React.useState(0); - const [delegationText, setDelegationText] = React.useState(""); - const [delegating, setDelegating] = React.useState(false); - - const targetId = seat && seat.id ? seat.id : seat && seat.role === "lead" ? leadSessionId : undefined; - - React.useEffect(() => { - if (catalog.status === "loading") return undefined; - if (!targetId && !(seat && seat.role)) { setCatalog({ status: "idle", options: [], error: null, current: undefined, subagent: false }); return undefined; } - let alive = true; - setCatalog((prev) => ({ ...prev, status: "loading", error: null })); - host.loadCatalog(targetId, seat && seat.role).then((result) => { - if (!alive) return; - setCatalog({ status: "ready", options: result.options, current: result.current, error: result.error, subagent: result.subagent, fixed: result.fixed === true, unresolved: result.unresolved === true, inherited: result.inherited === true }); - setDraftModel(result.current ? result.current.provider + "/" + result.current.model : ""); - setDraftEffort((result.current && result.current.reasoningEffort) || ""); - }, (error) => { - if (alive) setCatalog({ status: "error", options: [], error: String(error && error.message || error), current: undefined, subagent: false }); - }); - return () => { alive = false; }; - }, [targetId, seat && seat.role, catalogRetry]); - - const presetForSeat = seat && seat.id && sessions.byId[seat.id] && sessions.byId[seat.id].projectionValues - ? sessions.byId[seat.id].projectionValues.agentPreset - : undefined; - - const chosenOption = catalog.options.find((option) => option.rowId === draftModel); - const currentModelValue = catalog.current ? catalog.current.provider + "/" + catalog.current.model : ""; - const currentEffortValue = (catalog.current && catalog.current.reasoningEffort) || ""; - const modelDirty = draftModel !== currentModelValue || draftEffort !== currentEffortValue; - - const applySelection = (option, effort) => { - if (!option || !seat) return; - const plan = modelSwitchPlan(catalog.current, { - provider: option.provider, - model: option.model, - reasoningEffort: effort || undefined, - }, catalog.subagent || !seat.id); - if (!plan.ok) return; - setBusy(true); - setNotice(null); - const request = plan.via === "command" - ? host.routeModel(seat.role, plan.payload, seat.id) - : host.selectModel(seat.id, plan.payload); - const finish = (result) => { - setBusy(false); - if (result && result.ok) { - if (plan.via === "command") writeSeatRoute(seat.role, plan.payload); - setCatalog((prev) => ({ ...prev, current: plan.payload, fixed: plan.via === "command" ? true : prev.fixed })); - } else { - setNotice({ kind: "error", text: (result && result.error) || "宿主没有接受这次选择" }); - } - }; - request.then(finish, (error) => finish({ ok: false, error: String((error && error.message) || error) })); - }; - const activeChildId = activeAddress && activeAddress.childSessionId - ? activeAddress.childSessionId - : focusedSessionId !== leadSessionId ? focusedSessionId : undefined; - const activeSeat = activeChildId ? seats.find((entry) => entry.id === activeChildId) : undefined; - const previousChildRef = React.useRef(null); - React.useEffect(() => { - const previousChild = previousChildRef.current; - previousChildRef.current = activeChildId || null; - if (activeChildId) { - const role = childRoleOf(seats, activeChildId); - if (role) setSelectedRole(role); - return; - } - if (previousChild) setSelectedRole("lead"); - }, [activeChildId, seats]); - const onTargetConversation = Boolean(targetId && focusedSessionId === targetId); - const conversationLabel = seat && seat.role === "lead" - ? "返回丞相主会话" - : "与" + (seat ? seat.label : "该部门") + "对话"; - const conversationHint = seat && seat.role === "lead" - ? "回到统一受理需求的主会话;部门对话不会自动转呈丞相。" - : "进入该部门自己的 DSH 会话;消息不会自动同步给丞相。"; - - const sendDelegation = () => { - const body = delegationText.trim(); - if (body === "" || !seat || !seat.id) return; - setDelegating(true); - setNotice(null); - host.dispatchToSeat(seat.id, body).then((result) => { - setDelegating(false); - if (result.ok) { setDelegationText(""); setNotice({ kind: "ok", text: "已派给" + seat.label }); } - else setNotice({ kind: "error", text: result.error }); - }); - }; - - const openSeatConversation = () => { - if (!targetId) { - setNotice({ kind: "error", text: "该部门还没有可进入的会话,请先让丞相组建朝班。" }); - return; - } - if (!host.openSession(targetId)) { - setNotice({ kind: "error", text: "打开部门会话失败,请稍后重试。" }); - } - }; - - const returnToLead = () => { - const target = leadSessionId || (seat && seat.role === "lead" ? seat.id : undefined); - if (!target || !host.openSession(target)) { - setNotice({ kind: "error", text: "还没有丞相主会话,请先打开主对话。" }); - } - }; - - const seatOf = (role) => seats.find((entry) => entry.role === role); - const renderSeat = (role) => { - const entry = seatOf(role); - if (!entry) return null; - const info = seatState(entry); - return h(SeatCard, { - key: entry.role, - seat: entry, - selected: entry.role === selectedRole, - status: info.status, - onSelect: (nextRole) => { setSelectedRole(nextRole); setNotice(null); }, - }); - }; - - return h("div", { className: (compact ? "sl-root sl-compact " : "sl-root ") + "sl-sidebar", "data-sansheng-panel": "true", "data-sansheng-compact": compact ? "1" : "0", "data-sansheng-sidebar": "1" }, [ - h("div", { className: "sl-side-meta" }, [ - h("span", { className: "sl-side-state" + (activeChildId ? " is-child" : "") }, [ - h("span", { className: "sl-state-dot", "aria-hidden": "true" }), - team === undefined - ? "等待组建朝班" - : activeSeat - ? "正在与" + activeSeat.label + "对话" - : "朝班协作中", - ]), - h("span", { className: "sl-side-hint", children: "输入 @ 选择部门" }), - activeChildId - ? h("button", { - type: "button", - className: "sl-side-return", - onClick: returnToLead, - children: "返回丞相", - }) - : null, - ]), - h("div", { className: "sl-body sl-body-sidebar" }, [ - h("div", { className: "sl-right" }, [ - h("div", { className: "sl-side-tabs", role: "tablist", "aria-label": "朝堂视图" }, [ - h("button", { - type: "button", - role: "tab", - className: "sl-side-tab" + (sidebarView === "court" ? " is-active" : ""), - "aria-selected": sidebarView === "court", - "data-side-tab": "court", - onClick: showCourt, - children: "朝堂", - }), - h("button", { - type: "button", - role: "tab", - className: "sl-side-tab" + (sidebarView === "tasks" ? " is-active" : ""), - "aria-selected": sidebarView === "tasks", - "data-side-tab": "tasks", - onClick: showTasks, - children: ["任务", h("span", { className: "sl-side-tab-count", children: openTaskCount })], - }), - ]), - h("div", { className: "sl-stats", "data-sansheng-stats": "1" }, stats.map((stat) => - h(stat.key === "pending" || stat.key === "members" ? "button" : "div", { - key: stat.key, - type: stat.key === "pending" || stat.key === "members" ? "button" : undefined, - onClick: stat.key === "pending" ? showTasks : stat.key === "members" ? showCourt : undefined, - title: stat.key === "pending" ? "查看任务流转" : stat.key === "members" ? "查看朝堂编制" : undefined, - className: "sl-stat sl-stat-" + stat.key, - }, [ - h("span", { className: "sl-stat-mark", "aria-hidden": "true", children: stat.mark }), - h("span", { className: "sl-stat-body" }, [ - h("b", { children: String(stat.value).padStart(2, "0") }), - h("small", { children: stat.label }), - ]), - ]))), - sidebarView === "court" - ? h("div", { className: "sl-side-court" }, [ - h("div", { className: "sl-map" }, [ - h("div", { className: "sl-map-head" }, [ - h("div", {}, [ - h("span", { className: "sl-section-kicker", children: "组织编制" }), - h("h2", { children: "朝堂编制" }), - ]), - h("div", { className: "sl-map-meta" }, [ - h("span", { children: "十席 · 按需召集" }), - ]), - ]), - h("div", { className: "sl-tier" }, [ - h("div", { className: "sl-tier-label" }, [ - h("span", { children: "丞相" }), - h("small", { children: "统筹 · 分派 · 交付" }), - ]), - h("div", { className: "sl-grid sl-grid-1", "data-tier": "lead" }, renderSeat("lead")), - ]), - h("div", { className: "sl-connector-tri", "aria-hidden": "true" }, [ - h("span", { key: "zhongshu" }), - h("span", { key: "shangshu" }), - h("span", { key: "menxia" }), - ]), - h("div", { className: "sl-tier" }, [ - h("div", { className: "sl-tier-label" }, [ - h("span", { children: "三省" }), - h("small", { children: "拟案 · 执行 · 审议" }), - ]), - h("div", { className: "sl-grid sl-grid-3", "data-tier": "provinces" }, [ - renderSeat("zhongshu"), - renderSeat("shangshu"), - renderSeat("menxia"), - ]), - ]), - h("div", { className: "sl-stem", "aria-hidden": "true" }), - h("section", { className: "sl-ministry-group", "data-ministry-group": "1" }, [ - h("div", { className: "sl-group-head" }, [ - h("div", {}, [ - h("span", { className: "sl-group-title", children: "六部 · 尚书省调度" }), - h("small", { children: "两排同属一级,按需召集" }), - ]), - h("span", { className: "sl-group-count", children: "6 席" }), - ]), - h("div", { className: "sl-grid sl-grid-6", "data-tier": "ministries" }, [ - renderSeat("libu"), - renderSeat("hubu"), - renderSeat("lipu"), - renderSeat("bingbu"), - renderSeat("xingbu"), - renderSeat("gongbu"), - ]), - ]), - ]), - h("section", { className: "sl-detail", "data-selected-role": seat ? seat.role : "none" }, [ - h("div", { className: "sl-detail-head" }, [ - h("span", { className: "sl-detail-mark", "aria-hidden": "true", children: seat ? seat.mark : "员" }), - h("div", { className: "sl-detail-title" }, [ - h("strong", { children: seat ? seat.label : "成员" }), - h("small", { children: seat ? seat.duty : "" }), - ]), - h("span", { className: "sl-detail-chip", children: "固定职责" }), - ]), - h("div", { className: "sl-detail-status" }, [ - h(Dot, { status: seatInfo.status }), - h("span", { children: STATUS_LABELS[seatInfo.status] || seatInfo.status }), - seatInfo.lastText ? h("small", { children: shortText(seatInfo.lastText, 46) }) : null, - ]), - seat && !seat.present ? h("div", { className: "sl-hint", children: "该部门尚未设立。让丞相按流程组建后再进入会话。" }) : null, - seat ? h("div", { className: "sl-setting-block" }, [ - h("div", { className: "sl-setting-head" }, [ - h("h3", { children: "模型设置" }), - h("small", { children: catalog.subagent ? (seat.present ? "按部门固定" : "召见后生效") : "只影响该部门" }), - ]), - catalog.subagent ? h("div", { className: "sl-hint", children: seat.present ? "部门是子会话,宿主不允许事后单独改;这里选好后由模式把它固定下来,下一轮开工即用。" : "该部门还没召见。这里选好的模型由模式记下来,召见时直接按它开工。" }) : null, - h(React.Fragment, null, [ - h("div", { className: "sl-model-grid" }, [ - h("label", { className: "sl-control" }, [ - h("span", { children: "模型" }), - h("select", { - value: draftModel, - disabled: catalog.status === "loading" || busy, - "aria-label": "部门模型", - onChange: (event) => { - const value = event.target.value; - const option = catalog.options.find((entry) => entry.rowId === value); - const effort = option && option.defaultEffort ? option.defaultEffort : ""; - setDraftModel(value); - setDraftEffort(effort); - applySelection(option, effort); - }, - children: [ - h("option", { value: "", children: catalog.status === "loading" ? "读取中…" : "选择模型" }), - ...catalog.options.map((option) => h("option", { key: option.rowId, value: option.rowId, children: option.label })), - ], - }), - ]), - h("label", { className: "sl-control" }, [ - h("span", { children: "推理等级" }), - h("select", { - value: draftEffort, - disabled: catalog.status === "loading" || busy || !chosenOption, - "aria-label": "部门推理等级", - onChange: (event) => { - const value = event.target.value; - setDraftEffort(value); - applySelection(chosenOption, value); - }, - children: [ - h("option", { value: "", children: "默认" }), - ...(chosenOption ? chosenOption.efforts : []).map((effort) => h("option", { key: effort.id, value: effort.id, children: effort.name })), - ], - }), - ]), - ]), - h("div", { className: "sl-model-foot" }, [ - h("small", { - className: notice && notice.kind === "error" ? "is-dirty" : "", - children: busy || modelDirty - ? "自动保存中…" - : notice && notice.kind === "error" - ? "保存失败,换一次再试" - : catalog.fixed - ? "自动保存 · 该部门固定使用此模型" - : !seat.present - ? "自动保存 · 召见时按此模型开工" - : catalog.inherited - ? "自动保存 · 当前跟随默认(" + modelLabel(catalog.current) + ")" - : "自动保存 · 当前:" + (catalog.current ? modelLabel(catalog.current) : "未设置"), - }), - ]), - ]), - catalog.error ? h("div", { className: "sl-error", children: catalog.error }) : null, - catalog.error ? h("button", { - type: "button", - className: "sl-link-button", - onClick: () => setCatalogRetry((value) => value + 1), - children: "重试读取模型", - }) : null, - ]) : null, - h("div", { className: "sl-conversation-block" }, [ - h("button", { - type: "button", - className: "sl-conversation-action", - disabled: !targetId || onTargetConversation, - "data-conversation-target": seat ? seat.role : "", - onClick: openSeatConversation, - children: [ - h("span", { children: onTargetConversation ? (seat && seat.role === "lead" ? "正在丞相主会话" : "正在此部门会话") : conversationLabel }), - h("span", { className: "sl-conversation-arrow", "aria-hidden": "true", children: "↗" }), - ], - }), - h("p", { className: "sl-conversation-hint", children: onTargetConversation ? "你当前就在这个会话中。" : conversationHint }), - seat && seat.id && seat.role !== "lead" ? h("div", { className: "sl-delegate-block" }, [ - h("label", { className: "sl-control" }, [ - h("span", { children: "直接派活" }), - h("textarea", { - rows: 2, - "aria-label": "直接派活给" + seat.label, - placeholder: "不经过丞相,直接交给" + seat.label + "办", - value: delegationText, - onChange: (event) => setDelegationText(event.target.value), - }), - ]), - h("div", { className: "sl-model-foot" }, [ - h("button", { - type: "button", - className: "sl-btn primary", - disabled: delegating || delegationText.trim() === "", - onClick: sendDelegation, - children: delegating ? "派发中…" : "派给" + seat.label, - }), - h("small", { children: "直接进该部门会话,丞相收不到这条" }), - ]), - ]) : null, - ]), - h("details", { className: "sl-advanced" }, [ - h("summary", { children: "高级信息" }), - h("dl", { className: "sl-advanced-list" }, [ - h("div", {}, [h("dt", { children: "角色标识" }), h("dd", { children: seat ? seat.role : "未选择" })]), - h("div", {}, [h("dt", { children: "Agent 预设" }), h("dd", { children: typeof presetForSeat === "string" && presetForSeat ? presetForSeat : "由宿主管理" })]), - h("div", {}, [h("dt", { children: "会话" }), h("dd", { children: targetId || "尚未建立" })]), - ]), - ]), - notice ? h("div", { className: notice.kind === "ok" ? "sl-ok" : "sl-error", role: "status", children: notice.text }) : null, - ]), - ]) - : h("section", { className: "sl-task-panel sl-side-tasks", "data-side-tasks": "1" }, [ - h("div", { className: "sl-section-title" }, [ - h("div", { className: "sl-section-heading" }, [ - h("span", { className: "sl-section-kicker", children: "任务队列" }), - h("h2", { children: "任务流转" }), - ]), - h("span", { className: "sl-section-count", children: "执行 " + buckets.in_progress.length + " · 待办 " + buckets.pending.length }), - ]), - h("ul", { className: "sl-tash" }, buckets.in_progress.concat(buckets.pending).slice(0, 8).map((task) => h("li", { key: task.id, title: task.description || "" }, [ - h("span", { className: "sl-task-state" }, [h(Dot, { status: task.status === "in_progress" ? "running" : "provisioning" })]), - h("div", { className: "sl-task-copy" }, [ - h("b", { children: task.subject || task.title || task.id }), - h("small", { children: task.status === "in_progress" ? "正在执行" : "等待受理" }), - ]), - h("em", { className: "sl-task-owner", children: roleLabel(task.ownerName) }), - ]))), - buckets.in_progress.length + buckets.pending.length === 0 - ? h("div", { className: "sl-task-empty" }, [ - h("span", { className: "sl-empty-mark", "aria-hidden": "true", children: "✓" }), - h("div", {}, [h("strong", { children: "当前没有待办任务" }), h("p", { children: "新任务受理后,会在这里显示执行进度与负责部门。" })]), - ]) - : null, - ]), - ]), - ]), - ]); - } - // #endregion - // #region 宿主适配 - function createHost(ctx) { - const sessions = ctx.sessions; - const conversations = new WeakMap(); - let selectedSessionId; - let lastAction = "尚未操作"; - const note = (text) => { lastAction = text; try { console.log("[三省六部] " + text); } catch (error) { /* 忽略 */ } }; - - /** layout 服务用可选查找:直接读 ctx.layout 会命中 inject 声明守卫。 */ - const layoutService = () => { - try { - if (typeof ctx.get === "function") { - const service = ctx.get("layout"); - if (service) return service; - } - } catch (error) { /* 退回直接读 */ } - try { return ctx.layout; } catch (error) { return undefined; } - }; - const panelStore = (() => { - const service = layoutService(); - return service && service.panelInfo ? service.panelInfo : undefined; - })(); - const sessionsStore = sessions && sessions.list; - const statusStore = (() => { - const candidates = []; - if (sessions && sessions.statuses) candidates.push(sessions.statuses); - try { - if (typeof ctx.get === "function") { - const service = ctx.get("sessionStatus"); - if (service) candidates.push(service); - } - } catch (error) { /* 忽略:拿不到时由 byId.running 兜底 */ } - return candidates.find((item) => item && typeof item.getSnapshot === "function" && typeof item.subscribe === "function"); - })(); - - /** 当前中央面板 id:null 表示正在看会话本体。 */ - const currentPanelId = () => { - if (!panelStore || typeof panelStore.getSnapshot !== "function") return null; - try { - const info = panelStore.getSnapshot(); - return info ? info.activePanelId : null; - } catch (error) { return null; } - }; - - const bindingOf = (sessionId) => { - try { return sessions.binding(sessionId); } catch (error) { return undefined; } - }; - - const courtState = { pending: false }; - const selectionSnapshot = () => { - try { - const store = ctx.uiWorkspace && ctx.uiWorkspace.selection; - return store && typeof store.getSnapshot === "function" ? (store.getSnapshot() || {}) : {}; - } catch (error) { return {}; } - }; - - /** 唯一的投递实现:所有入口都走这里,返回结构化结果而不是抛异常。 */ - const deliverPrompt = (sessionId, text) => { - if (!sessionId) return Promise.resolve({ ok: false, stage: "deliver", errorCode: "no-session", error: "没有可投递的会话" }); - const binding = bindingOf(sessionId); - if (!binding || !binding.session || typeof binding.session.prompt !== "function") { - return Promise.resolve({ ok: false, stage: "deliver", sessionId: sessionId, errorCode: "no-session", error: "该会话还没有可用的对话通道" }); - } - let pending; - try { - pending = binding.session.prompt.call(binding.session, [{ type: "text", text: text }], "queue"); - } catch (error) { - return Promise.resolve({ ok: false, stage: "deliver", sessionId: sessionId, errorCode: "deliver-threw", error: "投递时出错:" + String((error && error.message) || error) }); - } - return Promise.resolve(pending).then((result) => { - if (result && result.ok === false) { - return { ok: false, stage: "deliver", sessionId: sessionId, errorCode: "rejected", error: "宿主拒绝了这条消息:" + (result.error && result.error.message ? result.error.message : "原因未知") }; - } - return { ok: true, stage: "delivered", sessionId: sessionId, text: text }; - }, (error) => ({ ok: false, stage: "deliver", sessionId: sessionId, errorCode: "deliver-failed", error: "投递失败:" + String((error && error.message) || error) })); - }; - - /** 会话的对话快照(uiConversation 绑定按会话缓存,重复创建会丢掉已归并的节点)。 */ - const conversationOf = (sessionId) => { - let service; - try { service = ctx.uiConversation; } catch (error) { return undefined; } - if (!service) return undefined; - const binding = bindingOf(sessionId); - if (!binding) return undefined; - let target = conversations.get(binding); - if (target === undefined) { - try { - const conversation = service.binding(binding); - target = conversation && conversation.target ? conversation.target("chat") : undefined; - } catch (error) { - target = undefined; - } - conversations.set(binding, target); - } - return target; - }; - - /** 取会话最近一条助手/用户文本:chat 快照的 nodes 是按 key 索引的只读集合。 */ - const recentOf = (sessionId) => { - const target = conversationOf(sessionId); - if (!target) return ""; - let snapshot; - try { snapshot = target.getSnapshot(); } catch (error) { return ""; } - const nodes = snapshot && snapshot.nodes; - if (!nodes || typeof nodes.values !== "function") return ""; - const exchange = lastExchange(Array.from(nodes.values())); - return exchange.lastAssistant || exchange.lastUser; - }; - - /** 没有选中记录时,退回最近活跃的那个会话(整页版常用)。 */ - const newestSessionId = () => { - try { - const list = sessionsStore && typeof sessionsStore.getSnapshot === "function" ? sessionsStore.getSnapshot() : undefined; - const byId = list && list.byId ? list.byId : {}; - let best; - for (const key of Object.keys(byId)) { - const item = byId[key]; - if (!item || item.blank === true) continue; - const at = typeof item.updatedAt === "number" ? item.updatedAt : Date.parse(item.updatedAt || ""); - const score = Number.isFinite(at) ? at : 0; - if (!best || score > best.score) best = { id: item.id || key, score }; - } - return best ? best.id : undefined; - } catch (error) { return undefined; } - }; - - /** 主视图当前选中的会话:以 uiWorkspace 的选中记录为准(面板是 root 级槽)。 */ - const currentSession = () => { - try { - const saved = ctx.uiWorkspace && ctx.uiWorkspace.selection ? ctx.uiWorkspace.selection.getSnapshot() : undefined; - if (saved && saved.subagentAddress) return saved.subagentAddress.childSessionId; - if (saved && saved.sessionId) return saved.sessionId; - } catch (error) { /* 忽略:退回面板传入的选中 */ } - return selectedSessionId || newestSessionId(); - }; - - const presetsRemote = () => { - try { - const remote = ctx.remote; - if (!remote) return undefined; - const presets = remote.agentPresets; - return presets && typeof presets.list === "function" ? presets : undefined; - } catch (error) { return undefined; } - }; - - /** - * 取模型目录服务与某会话的目录。三种结果必须分开,否则 «宿主没有这个服务» 会被 - * 当成 «这个会话读不到目录»:{ service: false } 没有服务;{ error } 有服务但解析 - * 不到该会话;{ directory } 成功。 - */ - const modelDirectoryOf = (sessionId) => { - let service; - try { - service = ctx.modelDirectories || (typeof ctx.get === "function" ? ctx.get("modelDirectories") : undefined); - } catch (error) { - return { error: "读取模型目录服务失败:" + String((error && error.message) || error) }; - } - if (!service || typeof service.directoryFor !== "function") return { service: false }; - try { - return { directory: service.directoryFor(sessionId) }; - } catch (error) { - return { error: String((error && error.message) || error) }; - } - }; - - /** 全局模型清单(宿主一代一份):不依赖任何会话,是模型选择最稳的数据源。 */ - const modelCatalogOf = () => { - let service; - try { - service = ctx.modelDirectories || (typeof ctx.get === "function" ? ctx.get("modelDirectories") : undefined); - } catch (error) { - return { error: "读取模型目录服务失败:" + String((error && error.message) || error) }; - } - if (!service || typeof service.directoryFor !== "function") return { service: false }; - const catalog = service.catalog; - if (!catalog || typeof catalog.load !== "function" || !catalog.store || typeof catalog.store.getSnapshot !== "function") { - return { error: "当前宿主没有全局模型清单(modelDirectories.catalog)" }; - } - return { catalog }; - }; - /** 取宿主挂出来的 remote 子服务:先问 ctx.get,再退回 ctx.remote 的属性。 */ - const remoteService = (name, key) => { - try { - const service = typeof ctx.get === "function" ? ctx.get(name) : undefined; - if (service) return service; - } catch (error) { /* 宿主没挂这个服务 */ } - try { - const remote = ctx.remote; - return remote && remote[key]; - } catch (error) { return undefined; } - }; - - /** 会话 RPC 面:改模型只认 sessionId,不需要该会话在本页登记。 */ - const remoteSession = () => { - const session = remoteService("remote.session", "session"); - return session && typeof session.selectModel === "function" ? session : undefined; - }; - - /** 改模型时按这个顺序找执行者:部门自己 > 空闲会话 > 其它会话 > 丞相(只当执行上下文,不投递消息)。 */ - const routeCandidates = (preferredSessionId) => { - const lead = currentSession(); - const busy = []; - const idle = []; - try { - const snapshot = sessions.list && typeof sessions.list.getSnapshot === "function" ? sessions.list.getSnapshot() : undefined; - const ids = (snapshot && snapshot.ids) || []; - const byId = (snapshot && snapshot.byId) || {}; - for (const id of ids) { - if (id === preferredSessionId || id === lead) continue; - const running = Boolean(byId[id] && byId[id].running); - (running ? busy : idle).push(id); - } - } catch (error) { /* 忽略 */ } - const list = []; - if (preferredSessionId) list.push(preferredSessionId); - for (const id of idle) list.push(id); - for (const id of busy) list.push(id); - if (lead && list.indexOf(lead) < 0) list.push(lead); - return list; - }; - - /** 子会话投递面:用户直接派活给某个部门,绕开丞相。 */ - const remoteSubagents = () => { - const subagents = remoteService("remote.subagents", "subagents"); - return subagents && typeof subagents.prompt === "function" ? subagents : undefined; - }; - - /** 子会话地址:谁把我召来的。 */ - const subagentAddressOf = (sessionId) => { - if (!sessionId || !sessions || typeof sessions.subagentAddress !== "function") return undefined; - try { return sessions.subagentAddress(sessionId); } catch (error) { return undefined; } - }; - - const mintRequestId = () => { - try { - if (globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") return globalThis.crypto.randomUUID(); - } catch (error) { /* 忽略 */ } - return "req-" + Date.now().toString(36) + "-" + Math.random().toString(16).slice(2); - }; - - /** 指令 RPC 面:直接执行斜杠指令,不经过模型,也不进对话。 */ - const remoteCommands = () => { - const commands = remoteService("remote.commands", "commands"); - return commands && typeof commands.execute === "function" ? commands : undefined; - }; - - const sidebarNav = () => { - const candidates = []; - try { if (typeof ctx.get === "function") candidates.push(ctx.get("sidebarRight")); } catch (error) { /* 忽略 */ } - try { candidates.push(ctx.sidebarRight); } catch (error) { /* 忽略 */ } - return candidates.find((item) => item && (typeof item.openTabIn === "function" || typeof item.openTab === "function")); - }; - - const openSanshengTab = (sessionId) => { - const nav = sidebarNav(); - const target = sessionId || currentSession(); - if (!target) { - return { ok: false, error: "当前还没有打开任何会话,右侧栏页签是会话级的;先新建或打开一个会话再停靠。" }; - } - try { - const service = layoutService(); - if (service && typeof service.selectPanel === "function") service.selectPanel(null); - } catch (error) { /* 忽略:右栏可能已经可见 */ } - - const better = betterSidebarOf(ctx); - if (better && typeof better.openTab === "function") { - try { - better.openTab({ type: SANSENG_TAB_ID }, { sessionId: target }); - return { ok: true, text: "朝堂已停靠到右侧栏" }; - } catch (error) { /* 落到宿主原生右侧栏 */ } - } - - let opened = false; - const attempt = (left) => { - try { - if (nav && typeof nav.openTabIn === "function") nav.openTabIn(target, SANSENG_TAB_KIND); - else if (nav && typeof nav.openTab === "function") nav.openTab(SANSENG_TAB_KIND); - opened = true; - } catch (error) { - opened = false; - } - if (opened || left <= 0) return; - setTimeout(() => attempt(left - 1), 60); - }; - if (nav) attempt(8); - if (!nav) return { ok: false, error: "当前宿主没有右侧栏服务(sidebarRight),无法停靠到侧栏;整页形式仍可使用。" }; - return { ok: true, text: "朝堂已停靠到右侧栏" }; - }; - - // 会话头开关的失败原因:挂在 host 上,跨重渲染保留,成功后清空。 - let toggleNotice = null; - const toggleNoticeListeners = new Set(); - const setToggleNotice = (text) => { - const next = text ? String(text) : null; - if (next === toggleNotice) return; - toggleNotice = next; - for (const listener of Array.from(toggleNoticeListeners)) { - try { listener(); } catch (error) { /* 忽略:订阅方异常不影响开关 */ } - } - }; - const toggleNoticeStore = { - getSnapshot: () => toggleNotice, - subscribe(listener) { - if (typeof listener !== "function") return () => {}; - toggleNoticeListeners.add(listener); - return () => { toggleNoticeListeners.delete(listener); }; - }, - }; - - return { - sessionsStore, - statusStore, - panelStore, - getSelectedSession: currentSession, - setToggleNotice, - toggleNoticeStore, - setSelected(sessionId) { - selectedSessionId = sessionId; - }, - currentPanelId, - selectPanel(panelId) { - const service = layoutService(); - if (!service || typeof service.selectPanel !== "function") return false; - try { service.selectPanel(panelId); return true; } catch (error) { return false; } - }, - togglePanel() { - return this.selectPanel(currentPanelId() === PANEL_ID ? null : PANEL_ID); - }, - openSanshengTab, - memberModel(sessionId) { - const binding = bindingOf(sessionId); - if (!binding) return ""; - try { - const face = binding.session.projections.faceOf("modelSelection"); - const snapshot = face.getSnapshot(); - return modelLabel(snapshot && snapshot.next ? snapshot.next.model || snapshot.next : snapshot); - } catch (error) { return ""; } - }, - recentText(sessionId) { - if (!sessionId) return ""; - try { return recentOf(sessionId); } catch (error) { return ""; } - }, - /** 点「打开主对话」=开一个新对话:建好朝堂会话后把中央切到它,用户可以直接说话。 */ - openConversation() { - return this.openCourtSession({ formation: false }); - }, - /** 只跳到已有对话(不新建)。 */ - focusConversation() { - const target = currentSession(); - if (!target) return { ok: false, stage: "focus", errorCode: "no-session", error: "当前还没有任何会话,可以先点「打开主对话」开一个。" }; - try { ctx.uiWorkspace.openSession(target); } catch (error) { - return { ok: false, stage: "focus", errorCode: "open-failed", error: "打开会话失败:" + String((error && error.message) || error) }; - } - const service = layoutService(); - if (service && typeof service.selectPanel === "function") { - try { service.selectPanel(null); } catch (error) { /* 忽略 */ } - } - return { ok: true, stage: "focus", sessionId: target }; - }, - openSession(sessionId) { - let summary; - try { summary = sessions.list.getSnapshot().byId[sessionId]; } catch (error) { summary = undefined; } - const address = summary && summary.subagent && summary.subagent.address; - const parent = address && address.parentSessionId; - try { - if (parent && parent !== sessionId) { - ctx.uiWorkspace.openSession({ parentSessionId: parent, childSessionId: sessionId, mode: "continuable" }); - } else { - ctx.uiWorkspace.openSession(sessionId); - } - } catch (error) { - return false; - } - const service = layoutService(); - if (service && typeof service.selectPanel === "function") { - try { service.selectPanel(null); } catch (error) { /* 忽略 */ } - } - return true; - }, - loadPresets() { - const remote = presetsRemote(); - if (!remote) return Promise.resolve({ options: [], error: "当前宿主未提供 Agent 预设接口" }); - const chain = Promise.resolve() - .then(() => remote.list()) - .then((result) => { - if (!result || !result.ok) return { options: [], error: result && result.error ? result.error.message : "读取预设失败" }; - const presets = result.value && Array.isArray(result.value.presets) ? result.value.presets : []; - return { options: presets.map((preset) => ({ id: preset.id, name: preset.name || preset.id })), error: null }; - }, (error) => ({ options: [], error: "读取预设失败:" + String(error && error.message || error) })); - return withDeadline(chain, 6000, (error) => ({ - options: [], - error: error ? "读取预设失败:" + String(error && error.message || error) : "读取预设超时:宿主 6 秒没有响应", - })); - }, - loadCatalog(sessionId, role) { - const subagentOf = (id) => (typeof sessions.subagentAddress === "function" ? sessions.subagentAddress(id) !== undefined : false); - // 还没召见的部门没有会话:清单照样给,当前值取面板里固定过的那条。 - const isSubagent = sessionId ? subagentOf(sessionId) : true; - const fixed = isSubagent && role ? readSeatRoute(role) : undefined; - // 模型清单是全局的:宿主同时只维护一份,任何会话都能读到;会话只决定「当前选的是哪个」。 - const global = modelCatalogOf(); - if (global.service === false) { - return Promise.resolve({ options: [], current: undefined, inherited: false, error: "当前宿主没有模型目录服务(modelDirectories)", subagent: false, unresolved: false }); - } - if (!global.catalog) { - return Promise.resolve({ options: [], current: undefined, inherited: false, error: global.error, subagent: isSubagent, unresolved: false }); - } - const catalog = global.catalog; - const resolved = sessionId ? modelDirectoryOf(sessionId) : { service: true, directory: undefined }; - const directory = resolved.directory; - /** 该会话自己的当前模型;没在本页登记时为 undefined。 */ - const ownCurrent = () => { - if (!directory) return undefined; - try { - const snapshot = directory.store.getSnapshot(); - return snapshot && snapshot.current ? snapshot.current : undefined; - } catch (error) { return undefined; } - }; - const directoryError = () => { - if (!directory) return null; - try { return directory.store.getSnapshot().error || null; } catch (error) { return null; } - }; - const shape = (extra) => { - let value; - try { value = catalog.store.getSnapshot().value; } catch (error) { value = null; } - const own = ownCurrent(); - const fallback = value && value.default ? value.default : undefined; - return { - options: modelOptions(value), - current: fixed || own || fallback, - inherited: fixed ? false : own ? false : Boolean(fallback), - fixed: Boolean(fixed), - error: (extra && extra.error) || directoryError() || null, - subagent: isSubagent, - unresolved: Boolean(extra && extra.unresolved), - }; - }; - const cached = (message) => shape({ error: message, unresolved: !directory }); - const chain = Promise.resolve() - .then(() => catalog.load()) - .then(() => shape({ unresolved: !directory }), (error) => cached("读取模型清单失败:" + String((error && error.message) || error))); - return withDeadline(chain, 6000, () => cached("读取模型清单超时(显示已知缓存)")); - }, - selectModel(sessionId, payload) { - const resolved = modelDirectoryOf(sessionId); - if (resolved.service === false) return Promise.resolve({ ok: false, error: "当前宿主没有模型目录服务(modelDirectories)" }); - const directory = resolved.directory; - if (directory) { - return Promise.resolve() - .then(() => directory.select(payload)) - .then(() => { - const snapshot = directory.store.getSnapshot(); - return snapshot.error ? { ok: false, error: snapshot.error } : { ok: true }; - }, (error) => ({ ok: false, error: String((error && error.message) || error) })); - } - // 该部门会话没在本页登记时拿不到目录,但「改模型」是宿主 RPC,只认 sessionId。 - const remote = remoteSession(); - if (!remote) { - return Promise.resolve({ ok: false, error: "当前宿主没有保存模型的接口(remote.session.selectModel)" }); - } - const request = { sessionId, provider: payload.provider, model: payload.model }; - if (payload.reasoningEffort !== undefined) request.reasoningEffort = payload.reasoningEffort; - return Promise.resolve() - .then(() => remote.selectModel(request)) - .then((result) => { - if (result && result.ok) return { ok: true }; - const failure = result && result.error; - const detail = failure - ? (failure.code ? failure.code + ":" + failure.message : String(failure.message || failure)) - : "保存模型失败"; - return { ok: false, error: detail }; - }, (error) => ({ ok: false, error: String((error && error.message) || error) })); - }, - /** 子会话不能直接改模型,改由丞相会话把指令下发给模式插件。 */ - /** 子会话不能直接改模型:用 commands/execute 直接跑指令,全程不碰模型。 */ - routeModel(role, payload, preferredSessionId) { - const commands = remoteCommands(); - if (!commands) return Promise.resolve({ ok: false, error: "当前宿主没有直接执行指令的接口(remote.commands.execute)" }); - const line = "/" + DEPT_MODEL_COMMAND + " " + role + " " + payload.provider + " " + payload.model + - (payload.reasoningEffort ? " " + payload.reasoningEffort : ""); - // 先在部门自己的会话里执行;它冷着或被回收时再退到别的会话(指令只写全局路由表,不碰任何对话)。 - const candidates = routeCandidates(preferredSessionId); - const attempt = (index, lastError) => { - if (index >= candidates.length) return Promise.resolve({ ok: false, error: lastError || "没有可执行这条指令的会话" }); - const agent = candidates[index]; - // 宿主可能在忙(会话正在跑一轮)时把指令排进队列而不返回,界面就会永远停在「自动保存中…」。 - const call = withDeadline(Promise.resolve().then(() => commands.execute(agent, line, [])), 3000, () => TIMED_OUT); - return call - .then((result) => { - if (result === TIMED_OUT) return attempt(index + 1, "宿主正忙,没在 3 秒内回应(模型没改,稍后再试)"); - if (result && result.ok === false) { - const failure = result.error; - const detail = failure - ? (failure.code ? failure.code + ":" + failure.message : String(failure.message || failure)) - : "宿主拒绝了这条指令"; - return attempt(index + 1, detail); - } - const value = result && result.value !== undefined ? result.value : result; - const outcome = value && value.result !== undefined ? value.result : value; - if (outcome && outcome.kind === "success") return { ok: true, text: line, agent: agent }; - const detail = outcome && outcome.kind === "error" ? outcome.text : undefined; - return attempt(index + 1, detail || "宿主没有执行这条指令(可能还没有重启)"); - }, (error) => attempt(index + 1, String((error && error.message) || error))); - }; - return attempt(0, undefined); - }, - selectPreset(sessionId, presetId) { - const remote = presetsRemote(); - if (!remote || typeof remote.select !== "function") return Promise.resolve({ ok: false, error: "当前宿主未提供 Agent 预设接口" }); - return Promise.resolve() - .then(() => remote.select(sessionId, presetId)) - .then((result) => (result && result.ok ? { ok: true } : { ok: false, error: result && result.error ? result.error.message : "应用预设失败" }), - (error) => ({ ok: false, error: String(error && error.message || error) })); - }, - refresh(sessionId) { - const binding = bindingOf(sessionId); - if (binding && binding.session && binding.session.projections && typeof binding.session.projections.faceOf === "function") { - try { binding.session.projections.faceOf("agentPreset").getSnapshot(); } catch (error) { /* 忽略 */ } - } - if (typeof sessions.refreshProjections === "function") { - try { sessions.refreshProjections(sessionId).catch(() => {}); } catch (error) { /* 忽略 */ } - } - }, - getLastAction() { return lastAction; }, - /** 用户直接派活:走 subagent 投递,丞相完全不知道这条。 */ - dispatchToSeat(sessionId, text) { - const body = String(text === undefined || text === null ? "" : text).trim(); - if (body === "") return Promise.resolve({ ok: false, error: "先说清要派什么活" }); - if (!sessionId) return Promise.resolve({ ok: false, error: "该部门还没有会话,先让丞相组建朝班" }); - const remote = remoteSubagents(); - if (!remote) return Promise.resolve({ ok: false, error: "当前宿主没有子会话投递接口(remote.subagents.prompt)" }); - const address = subagentAddressOf(sessionId); - if (!address || !address.parentSessionId) return Promise.resolve({ ok: false, error: "这个会话不是子会话,直接在它自己的对话里说就行" }); - return Promise.resolve() - .then(() => remote.prompt({ - requestId: mintRequestId(), - parentSessionId: address.parentSessionId, - childSessionId: sessionId, - mode: "continuable", - delivery: "queue", - content: [{ type: "text", text: body }], - })) - .then((result) => (result && result.messageId ? { ok: true, messageId: result.messageId } : { ok: false, error: "投递失败" }), - (error) => ({ ok: false, error: String((error && error.message) || error) })); - }, - sendPrompt(sessionId, text) { - return deliverPrompt(sessionId, text); - }, - startFormation() { - const lead = currentSession(); - if (!lead) return Promise.resolve({ ok: false, stage: "deliver", errorCode: "no-session", error: "没有可用会话" }); - return deliverPrompt(lead, FORMATION_PROMPT).then((result) => (result.ok ? { ok: true, text: "已请丞相组建朝班" } : result)); - }, - - /** 新开一个独立朝堂会话:绝不把旨意或组建指令写进用户当前正在聊的对话。 */ - /** 新开一个独立朝堂会话:绝不把旨意或组建指令写进用户当前正在聊的对话。 */ - openCourtSession(options) { - const withFormation = !options || options.formation !== false; - if (courtState.pending) return Promise.resolve({ ok: false, stage: "create", errorCode: "busy", error: "正在创建朝堂会话,请稍候再点" }); - const snapshot = sessionsStore && typeof sessionsStore.getSnapshot === "function" ? sessionsStore.getSnapshot() : undefined; - const before = new Set(Object.keys((snapshot && snapshot.byId) || {})); - const beforeCount = before.size; - const beforeSelection = (selectionSnapshot() || {}).sessionId; - const ref = currentSession(); - let workspaceId; - try { workspaceId = ctx.uiWorkspace && ctx.uiWorkspace.currentWorkspaceId; } catch (error) { /* 忽略 */ } - if (!workspaceId && ref && snapshot && snapshot.byId && snapshot.byId[ref]) workspaceId = snapshot.byId[ref].workspaceId; - if (!workspaceId && snapshot && snapshot.ids && snapshot.ids.length) { - const first = snapshot.byId[snapshot.ids[0]]; - if (first && first.workspaceId) workspaceId = first.workspaceId; - } - const request = (ws) => { - note("请求新建会话,工作区=" + String(ws || "自动") + ",现有会话 " + beforeCount + " 个"); - try { return ctx.uiWorkspace.startSession(ws, { agentPreset: "sansheng-liubu" }); } catch (error) { - console.warn("[三省六部] 新建会话失败:", error); - return undefined; - } - }; - const waitNew = (left) => { - let now; - try { now = sessionsStore && typeof sessionsStore.getSnapshot === "function" ? sessionsStore.getSnapshot() : undefined; } catch (error) { now = undefined; } - const ids = (now && now.ids) || []; - for (const id of ids) if (!before.has(id)) return Promise.resolve(id); - const current = (selectionSnapshot() || {}).sessionId; - if (current && current !== beforeSelection && !before.has(current) && now && now.byId && now.byId[current]) return Promise.resolve(current); - if (left <= 0) return Promise.resolve(undefined); - return new Promise((resolve) => setTimeout(() => resolve(waitNew(left - 1)), 200)); - }; - const settle = (result) => { - courtState.pending = false; - note("开新朝堂:" + String((result && (result.text || result.error)) || result)); - return result; - }; - courtState.pending = true; - request(workspaceId); - return waitNew(15) - .then((first) => (first ? first : Promise.resolve().then(() => { request(undefined); return waitNew(30); }))) - .then((sessionId) => { - if (!sessionId) { - console.warn("[三省六部] 新会话未创建", { workspaceId: workspaceId, beforeCount: beforeCount }); - return settle({ ok: false, stage: "create", errorCode: "create-timeout", error: "宿主没有创建出新会话(工作区:" + String(workspaceId || "未识别") + ",原有会话 " + beforeCount + " 个)。可用左侧「新会话」手动建一个,并在顶部选「上朝」预设。" }); - } - selectedSessionId = sessionId; - try { ctx.uiWorkspace.openSession(sessionId); } catch (error) { /* 忽略 */ } - const service = layoutService(); - if (service && typeof service.selectPanel === "function") { - try { service.selectPanel(null); } catch (error) { /* 忽略 */ } - } - const shortId = sessionId.slice(0, 8); - if (!withFormation) { - return settle({ ok: true, stage: "created", sessionId: sessionId, text: "已开启新对话(" + shortId + "),可以直接说话" }); - } - return deliverPrompt(sessionId, FORMATION_PROMPT).then((sent) => { - const short = shortId; - if (!sent.ok) { - return settle({ ok: false, stage: "deliver", sessionId: sessionId, errorCode: sent.errorCode, error: "已新开朝堂会话(" + short + "),但组建指令没送达:" + sent.error }); - } - return settle({ ok: true, stage: "delivered", sessionId: sessionId, text: "已新开独立朝堂会话(" + short + "),丞相开始组建朝班" }); - }); - }) - .catch((error) => settle({ ok: false, stage: "create", errorCode: "unexpected", error: "创建朝堂会话时出错:" + String((error && error.message) || error) })); - }, - }; - } - - const FORMATION_PROMPT = [ - "【上朝】按三省六部流程组建朝班:", - "1. 立即创建 zhongshu(中书省)、menxia(门下省)、shangshu(尚书省)三个成员。", - "2. 在共享任务板建立“中书拟案 → 门下审议 → 尚书派工”依赖链,写清各任务 writeScopes。", - "3. 门下准奏后由尚书按职责分派:吏部(Agent 与技能维护)、户部(数据与计算)、礼部(内容与呈现)、兵部(环境运行与部署)、刑部(按风险专项测试)、工部(开发实现);只召集本任务真正用到的部门。", - "4. 每阶段完成后向我汇报,我确认后再进入下一阶段。", - ].join("\n"); - - - const EMPTY_SESSIONS = { byId: {}, projectionsBySession: {}, ids: [], phase: "ready" }; - - const TIMED_OUT = Symbol("timeout"); - /** 给可能永远不 settle 的宿主 Promise 加超时,超时后走 fallback,避免界面卡在「读取中」。 */ - function withDeadline(promise, ms, fallback) { - return new Promise((resolve) => { - let settled = false; - const timer = setTimeout(() => { - if (settled) return; - settled = true; - try { resolve(fallback()); } catch (error) { resolve(undefined); } - }, ms); - Promise.resolve(promise).then((value) => { - if (settled) return; - settled = true; - clearTimeout(timer); - resolve(value); - }, (error) => { - if (settled) return; - settled = true; - clearTimeout(timer); - try { resolve(fallback(error)); } catch (inner) { resolve(undefined); } - }); - }); - } - - /** - * 订阅宿主 store 的快照。main 是 root 级槽,自带的会话级 hook 在 root 作用域下不可靠, - * 面板改为直接订阅服务层 store:数据与会话页同源,且不依赖 slot 注入的 hook。 - * 用 useState + useEffect + subscribe,而不是 useSyncExternalStore: - * 宿主 store 的 getSnapshot 不保证每次返回同一引用,避免无限重渲染。 - */ - function useStoreSnapshot(store, fallback) { - const read = () => { - if (!store || typeof store.getSnapshot !== "function") return fallback; - try { return store.getSnapshot() || fallback; } catch (error) { return fallback; } - }; - const [snapshot, setSnapshot] = React.useState(read); - React.useEffect(() => { - if (!store || typeof store.subscribe !== "function") return undefined; - try { return store.subscribe(() => setSnapshot(read())); } catch (error) { return undefined; } - }, [store]); - return snapshot; - } - - /** 面板级错误兜底:任何渲染异常都显示成可见的诊断块,而不是让宿主隔离成空白。 */ - class PanelBoundary extends React.Component { - constructor(props) { - super(props); - this.state = { error: null }; - } - static getDerivedStateFromError(error) { - return { error }; - } - componentDidCatch(error) { - if (typeof console !== "undefined" && typeof console.error === "function") { - console.error("[三省六部] 面板渲染失败:", error); - } - } - render() { - const error = this.state.error; - if (!error) return this.props.children; - const message = error && error.message ? error.message : String(error); - return h("div", { className: "sl-crash", role: "alert" }, [ - h("strong", { children: "三省六部面板渲染失败" }), - h("pre", { children: message }), - h("p", { children: "请把上面这段信息发给开发者;界面其余部分不受影响。" }), - ]); - } - } - - /** 主视图选中记录:uiWorkspace 把 {sessionId, subagentAddress} 持久化在 dsh.sessions.current。 */ - function useWorkspaceSelection() { - const workspace = React.useContext(WorkspaceContext); - const read = () => { - if (!workspace || !workspace.selection) return {}; - try { return workspace.selection.getSnapshot() || {}; } catch (error) { return {}; } - }; - const [selection, setSelection] = React.useState(read); - React.useEffect(() => { - if (!workspace || !workspace.selection || typeof workspace.selection.subscribe !== "function") return undefined; - try { return workspace.selection.subscribe(() => setSelection(read())); } catch (error) { return undefined; } - }, [workspace]); - return selection; - } - - /** 会话若自身就是被寻址的子代理,返回它的地址;否则 undefined。 */ - function subagentAddressOf(sessions, sessionId) { - const summary = sessions.byId ? sessions.byId[sessionId] : undefined; - const direct = summary && summary.subagent && summary.subagent.address; - if (direct) return direct; - const bySession = sessions.projectionsBySession || {}; - for (const parentId of Object.keys(bySession)) { - const parent = bySession[parentId]; - const list = parent && parent.values ? parent.values.subagentCatalog : undefined; - if (Array.isArray(list) && list.some((entry) => entry && entry.id === sessionId)) { - return { parentSessionId: parentId, childSessionId: sessionId }; - } - } - return undefined; - } - - // #region 次要入口(会话头开关 / 侧栏置顶行 / 右侧栏页签) - /** - * 会话头入口。openSanshengTab() 失败(没有会话、宿主没有右侧栏服务)时, - * 0.5.0 会静默回退成 togglePanel(),用户点一下什么也看不到;这里把原因渲染出来, - * 并把失败原因挂在 host 的 toggleNoticeStore 上,跨重渲染保留。 - */ - function SanshengToggle(props) { - const host = props.host; - const info = useStoreSnapshot(host && host.panelStore, {}) || {}; - const notice = useStoreSnapshot(host && host.toggleNoticeStore, null); - const open = info.activePanelId === PANEL_ID; - return h("span", { className: "sl-toggle-wrap" }, [ - h("button", { - key: "btn", - type: "button", - className: "sl-toggle" + (open ? " active" : ""), - "data-sansheng-toggle": open ? "open" : "closed", - title: "三省六部:把朝堂停靠到右侧栏,主对话留在中央", - onClick: () => { - // 失败时只把原因显示在开关旁:0.5.0 起没有整页面板可回退, - // 再调 togglePanel() 只会把主区域切到一个不存在的面板上。 - const result = host.openSanshengTab(); - host.setToggleNotice(result && result.ok === false ? result.error : null); - }, - }, [ - h("span", { key: "mark", className: "sl-toggle-mark", children: "三省" }), - h("span", { key: "label", children: open ? "收起朝堂" : "三省六部" }), - ]), - notice ? h("span", { - key: "notice", - className: "sl-toggle-notice", - role: "status", - title: notice, - children: notice, - }) : null, - ]); - } - - - /** 左栏导航列的图标:细线「三」字样标,和宿主其它线性图标同一观感。 */ - function SanshengNavGlyph(props) { - const size = Number(props.size) || 18; - const active = props.active === true; - const bar = (key, y) => h("path", { key, d: "M6 " + y + "h6", stroke: "currentColor", strokeWidth: 1.2, strokeLinecap: "round" }); - return h("svg", { - width: size, - height: size, - viewBox: "0 0 18 18", - fill: "none", - "aria-hidden": "true", - "data-sansheng-glyph": active ? "active" : "idle", - }, [ - h("rect", { key: "box", x: 2.3, y: 2.3, width: 13.4, height: 13.4, rx: 4.2, stroke: "currentColor", strokeWidth: active ? 1.6 : 1.3, opacity: active ? 1 : 0.9 }), - bar("bar-a", 6.4), - bar("bar-b", 9), - bar("bar-c", 11.6), - ]); - } - - /** - * 把朝堂停靠到当前会话的右侧栏,然后把主区域退回原会话。 - * 抽成普通函数是为了让测试能直接驱动真实的成功/失败分支(测试替身不执行 useEffect)。 - * 成功返回 null;失败返回原因文本,并写进开关旁的提示存储。 - */ - function dockToSidebarTab(host) { - const result = host.openSanshengTab(); - if (result && result.ok) { - host.setToggleNotice(null); - host.selectPanel(null); - return null; - } - const reason = result && result.error ? result.error : "当前无法停靠到右侧栏。"; - host.setToggleNotice(reason); - return reason; - } - - /** - * 「插件」那一列点击后的落点。那一列的行只由 sidebar.panellist 驱动,点击写死走 - * selectPanel(id) → 向宿主索取 main 槽;这里给 main 一个重定向桩:有会话就立刻停靠到 - * 右侧栏并退回原会话,没有会话就把原因写在页面上。它不是第二套面板,也不承载聊天。 - */ - function SanshengDockRedirect(props) { - const host = props.host; - const [reason, setReason] = React.useState(null); - React.useEffect(() => { - const failure = dockToSidebarTab(host); - if (failure) setReason(failure); - }, []); - return h("div", { className: "sl-dock-stub", "data-sansheng-dock": "1" }, [ - h("span", { key: "mark", className: "sl-rail-mark", "aria-hidden": "true", children: "三省" }), - h("span", { key: "text", className: "sl-dock-stub-text", children: reason || "正在把朝堂停靠到右侧栏…" }), - ]); - } - - - function SanshengTabTitle() { - return h("div", { className: "sl-tab-title", "data-sansheng-tab-title": "1" }, [ - h("span", { key: "mark", className: "sl-tab-mark", children: "三省" }), - h("span", { key: "label", children: "朝堂" }), - ]); - } - - function SanshengTabBody(props) { - const host = props.host; - const sessionId = props.sessionId; - React.useEffect(() => { - if (sessionId && host.setSelected) host.setSelected(sessionId); - }, [sessionId]); - return h(PanelBoundary, null, h(SanshengPanel, { ...props, host, compact: true })); - } - - - /** 在原生 composer 注册 @ 部门入口;选择后进入对应子会话,消息仍由宿主输入框发送。 */ - function createSeatMentionSource(ctx, host) { - const candidates = (session, options) => { - try { - const list = ctx.sessions.list.getSnapshot(); - let sessionId = session && session.sessionId; - if (!sessionId && ctx.uiWorkspace && ctx.uiWorkspace.selection) { - sessionId = ctx.uiWorkspace.selection.getSnapshot().sessionId; - } - let address; - try { address = ctx.sessions.subagentAddress(sessionId); } catch (error) { address = undefined; } - if (!address) address = subagentAddressOf(list, sessionId); - const leadId = (address && address.parentSessionId) || sessionId; - const team = leadId && list.projectionsBySession && list.projectionsBySession[leadId] - ? list.projectionsBySession[leadId].values.agentTeam - : undefined; - const query = String((options && options.query) || "").trim(); - return Promise.resolve(seatMentionOptions(arrangeRoster(team)).filter((item) => - query.length === 0 || item.label.indexOf(query) >= 0 || item.description.indexOf(query) >= 0)); - } catch (error) { - return Promise.resolve([]); - } - }; - return { - trigger: "@", - name: "sansheng", - showGroupTitle: false, - candidates, - onPick({ candidate }) { - const sessionId = candidate && candidate.value; - if (typeof sessionId === "string" && sessionId.length > 0) { - Promise.resolve().then(() => { - try { host.openSession(sessionId); } catch (error) { /* 宿主导航失败时保留当前会话 */ } - }); - } - return { text: "" }; - }, - codec: { - clipboardText: (ref) => (ref && ref.label) || "", - serialize: (ref) => Promise.resolve((ref && ref.label) || ""), - }, - }; - } - - function registerSeatMentions(ctx, host) { - let triggers; - try { triggers = typeof ctx.get === "function" ? ctx.get("inputTriggers") : undefined; } catch (error) { triggers = undefined; } - if (!triggers || typeof triggers.registerSource !== "function") return; - ctx.effect(() => triggers.registerSource(createSeatMentionSource(ctx, host)), "三省六部: @ 部门成员"); - } - - /** better-sidebar 是可选的:没装时不要写进 inject,否则插件会被 park。 */ - function betterSidebarOf(ctx) { - const candidates = []; - try { if (typeof ctx.get === "function") candidates.push(ctx.get("betterSidebar")); } catch (error) { /* 忽略 */ } - try { candidates.push(ctx.betterSidebar); } catch (error) { /* 忽略 */ } - return candidates.find((item) => item && typeof item.registerTab === "function"); - } - // #endregion - - function apply(ctx) { - // 会话与输入框全部复用 DSH 原生界面;插件只向右侧栏注册朝堂页签。 - WorkspaceContext = React.createContext(undefined); - const workspace = ctx.uiWorkspace; - const host = createHost(ctx); - registerSeatMentions(ctx, host); - - ctx.slots.inject("conversation.session.header.actions", () => ctx.slots.register({ - name: "conversation.session.header.actions", - id: PANEL_ID + ":toggle", - order: 40, - }, (props) => h(SanshengToggle, { ...props, host }))); - - // 左侧栏导航列(插件 / 定时任务 / 任务看板 那一列):用户要求入口在那里。 - // 那一列的行全部来自 sidebar.panellist,点击写死走 selectPanel(id) 再向宿主索取 main 槽, - // 所以同时注册一个 main 重定向桩:点进去立刻停靠到右侧栏并退回原会话,不留空白主区域。 - ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({ - name: "sidebar.panellist", - id: PANEL_ID, - // 用户要求置顶并改叫「上朝」:order 取负值,排在「插件」以外的所有插件行之前。 - order: -100, - label: () => "上朝", - }, (props) => h(SanshengNavGlyph, props))); - - ctx.slots.inject("main", () => ctx.slots.register({ - name: "main", - key: PANEL_ID, - }, (props) => h(SanshengDockRedirect, { ...props, host }))); - - // 右侧栏回退:宿主自带 sidebarRight(better-sidebar 存在时不注册,避免两处同名页签)。 - const better = betterSidebarOf(ctx); - if (better) { - ctx.effect(() => better.registerTab({ - id: SANSENG_TAB_ID, - title: "三省六部", - description: "朝堂成员图、任务与配置;对话本体留在中央", - order: 5, - single: true, - component: (props) => h(PanelBoundary, null, h(SanshengPanel, { - host, - sessionId: props && props.scope ? props.scope.sessionId : undefined, - compact: true, - })), - }), "三省六部: better-sidebar 页签"); - } else { - try { - ctx.effect(() => { - try { - return ctx.sidebarRightTabs.register({ - id: SANSENG_TAB_ID, - kind: SANSENG_TAB_KIND, - priority: "builtin", - title: () => "三省六部", - }); - } catch (error) { - if (typeof console !== "undefined" && console.warn) console.warn("[三省六部] 右侧栏 tab 类型注册失败:", error); - return () => {}; - } - }, "三省六部: 右侧栏 tab 类型"); - } catch (error) { /* 老宿主没有该服务:会话头部入口和侧栏插槽仍可用 */ } - } - - ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({ - name: "sidebar.right.pane.tab", - key: SANSENG_TAB_ID, - }, (props) => h(SanshengTabBody, { ...props, host }))); - - ctx.slots.inject("sidebar.right.pane.tab.title", () => ctx.slots.register({ - name: "sidebar.right.pane.tab.title", - key: SANSENG_TAB_ID, - }, () => h(SanshengTabTitle, null))); - } - - exports.apply = apply; - exports.inject = ["slots", "sessions", "uiWorkspace", "uiConversation", "modelDirectories", "remote", "remote.agentPresets", "remote.session", "remote.subagents", "remote.commands", "sidebarRightTabs", "sidebarRight"]; - exports.SanshengPanel = SanshengPanel; - exports.PANEL_ID = PANEL_ID; - exports.SANSENG_TAB_ID = SANSENG_TAB_ID; - exports.SANSENG_TAB_KIND = SANSENG_TAB_KIND; - exports.createHost = createHost; - exports.__test = { - PANEL_ID, - SANSENG_TAB_ID, - SANSENG_TAB_KIND, - ROLE_IDS, - roleLabel, - roleMark, - modelLabel, - effortLabel, - arrangeRoster, - courtStats, - memberStatus, - tasksOfRole, - statusSummary, - modelOptions, - findModelOption, - modelSwitchPlan, - decreeText, - lastExchange, - shortText, - bucketsOf, - seatMentionOptions, - childRoleOf, - createSeatMentionSource, - dockToSidebarTab, - }; - return module.exports; - }, -}); diff --git a/panel/lib/model.js b/panel/lib/model.js deleted file mode 100644 index 3fee34f..0000000 --- a/panel/lib/model.js +++ /dev/null @@ -1,260 +0,0 @@ -// 三省六部:纯逻辑层(不依赖 React / DOM),便于在 node --test 中直接验证。 -// 这些函数只做数据投影与协议拼装:成员编排、状态归并、下旨文本、模型目录展开。 - -export const ROLE_IDS = Object.freeze(['lead', 'zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) - -export const ROLE_LABELS = Object.freeze({ - lead: '丞相', - zhongshu: '中书省', - menxia: '门下省', - shangshu: '尚书省', - libu: '吏部', - hubu: '户部', - lipu: '礼部', - bingbu: '兵部', - xingbu: '刑部', - gongbu: '工部', -}) - -export const ROLE_MARKS = Object.freeze({ - lead: '丞', - zhongshu: '中', - menxia: '门', - shangshu: '尚', - libu: '吏', - hubu: '户', - lipu: '礼', - bingbu: '兵', - xingbu: '刑', - gongbu: '工', -}) - -export const ROLE_DUTIES = Object.freeze({ - lead: '统筹全局,向用户汇报,最终交付', - zhongshu: '拟案规划,拆解任务与验收标准', - menxia: '审议准奏与交付验收,可否决', - shangshu: '派工调度,合成各部门成果', - libu: 'Agent 与技能维护、成员编制', - hubu: '数据、表格与计算,可复算结论', - lipu: '文档、汇报与可视化产出', - bingbu: '环境运行、调试与部署,掌武库', - xingbu: '按风险的专项测试与独立验证', - gongbu: '编码与工程实现', -}) - -/** 朝堂图布局:丞相居中在顶,三省为中层(左中书、中尚书、右门下),六部直隶尚书。 */ -export const LAYOUT = Object.freeze({ - lead: { row: 0, column: 'lead' }, - zhongshu: { row: 1, column: 'zhongshu' }, - shangshu: { row: 1, column: 'shangshu' }, - menxia: { row: 1, column: 'menxia' }, - libu: { row: 2, column: 'one' }, - hubu: { row: 2, column: 'two' }, - lipu: { row: 2, column: 'three' }, - bingbu: { row: 2, column: 'four' }, - xingbu: { row: 2, column: 'five' }, - gongbu: { row: 2, column: 'six' }, -}) - -export const STATUS_LABELS = Object.freeze({ - running: '运行中', - inactive: '空闲', - provisioning: '创建中', - failed: '失败', - absent: '未设官', -}) - -export const TASK_STATUS_LABELS = Object.freeze({ - pending: '待办', - in_progress: '执行中', - completed: '已完成', -}) - -/** 把 agentTeam 投影按官职编排成固定十席,缺员以 absent 占位,保证图结构稳定。 */ -export function arrangeRoster(team) { - const members = Array.isArray(team?.members) ? team.members : [] - const byRole = new Map() - for (const member of members) { - if (member?.name === undefined) continue - byRole.set(member.name, member) - } - return ROLE_IDS.map((role) => { - const member = byRole.get(role) - return { - role, - label: ROLE_LABELS[role], - mark: ROLE_MARKS[role], - duty: ROLE_DUTIES[role], - layout: LAYOUT[role], - id: member?.id, - member, - present: member !== undefined, - } - }) -} - -/** 运行状态(会话是否在跑)与任务状态(共享任务)必须分开表达,不能互相覆盖。 */ -export function memberStatus(member, running, summaryRunning) { - if (member === undefined) return 'absent' - if (member.phase !== undefined && member.phase !== 'active') return member.phase - return running === true || summaryRunning === true ? 'running' : 'inactive' -} - -export function roleLabel(role) { - return ROLE_LABELS[role] ?? '成员' -} - -export function roleMark(role) { - return ROLE_MARKS[role] ?? '员' -} - -export function modelLabel(model) { - if (typeof model === 'string') return model - if (!model || typeof model !== 'object') return '' - if (typeof model.name === 'string') return model.name - if (typeof model.model === 'string') return model.model - if (typeof model.id === 'string') return model.id - return '' -} - -export function effortLabel(effort) { - if (typeof effort !== 'string') return '' - const table = { minimal: '极低', low: '低', medium: '中', high: '高', max: '最高', xhigh: '极高' } - return table[effort] ?? effort -} - -export function taskBuckets(team) { - const tasks = Array.isArray(team?.tasks) ? team.tasks : [] - const buckets = { pending: [], in_progress: [], completed: [] } - for (const task of tasks) { - const key = task?.status - if (key === 'pending' || key === 'in_progress' || key === 'completed') buckets[key].push(task) - else buckets.pending.push(task) - } - return buckets -} - -export function tasksOfRole(team, role) { - const tasks = Array.isArray(team?.tasks) ? team.tasks : [] - return tasks.filter((task) => task?.ownerName === role || task?.ownerName === roleLabel(role)) -} - -/** 所选成员的运行状态 + 任务状态摘要,供图下配置区展示。 */ -export function statusSummary(seat, team, running, summaryRunning) { - const status = memberStatus(seat?.member, running, summaryRunning) - const owned = seat?.role === undefined ? [] : tasksOfRole(team, seat.role) - const buckets = taskBuckets({ tasks: owned }) - return { - status, - statusLabel: STATUS_LABELS[status] ?? status, - owned, - runningCount: buckets.in_progress.length, - pendingCount: buckets.pending.length, - completedCount: buckets.completed.length, - } -} - -/** 模型目录展开成扁平选项:每组 id 即 provider,行 id 为 provider/model。 */ -export function modelOptions(catalog) { - const options = [] - const groups = Array.isArray(catalog?.groups) ? catalog.groups : [] - for (const group of groups) { - const provider = group?.id ?? group?.provider - for (const model of Array.isArray(group?.models) ? group.models : []) { - if (!provider || !model?.id) continue - const efforts = Array.isArray(model.reasoning?.efforts) - ? model.reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name ?? effortLabel(effort.id) })) - : [] - options.push({ - provider, - model: model.id, - rowId: `${provider}/${model.id}`, - label: model.name ?? model.id, - efforts, - defaultEffort: model.reasoning?.defaultEffort, - }) - } - } - return options -} - -export function findModelOption(options, current) { - if (!current?.provider || !current?.model) return undefined - return options.find((option) => option.provider === current.provider && option.model === current.model) -} - -/** - * 下旨文本:把用户输入包装成明确的“切到某部门执行”指令,并附带当前朝堂上下文。 - * 部门会话是受控子会话,直接投递文本仍受角色提示词约束。 - */ -export function decreeText(role, text, team) { - const body = String(text ?? '').trim() - if (body === '') return '' - const buckets = taskBuckets(team) - const active = buckets.in_progress.map((task) => task.subject ?? task.title ?? task.id).filter(Boolean) - const head = `【丞相下旨 · ${roleLabel(role)}】` - const context = active.length > 0 ? `\n当前在办:${active.join(';')}` : '' - return `${head}\n${body}${context}` -} - -/** 交付物“部分 → 主责部门”清单:把共享任务按负责人归组成部门小结。 */ -export function deliverySummary(team) { - const tasks = Array.isArray(team?.tasks) ? team.tasks : [] - const byRole = new Map() - for (const task of tasks) { - const owner = task?.ownerName ?? 'lead' - const key = ROLE_IDS.includes(owner) ? owner : 'lead' - if (!byRole.has(key)) byRole.set(key, []) - byRole.get(key).push(task) - } - return ROLE_IDS.filter((role) => byRole.has(role)).map((role) => ({ - role, - label: ROLE_LABELS[role], - tasks: byRole.get(role), - completed: byRole.get(role).filter((task) => task?.status === 'completed').length, - })) -} - -export function shortText(value, limit = 120) { - const text = String(value ?? '').replace(/\s+/g, ' ').trim() - return text.length <= limit ? text : `${text.slice(0, limit - 1)}…` -} - -/** 从 chat 快照里取最后一条用户指令与最后一条助手文本,用于卡片上的“最近动静”。 */ -export function lastExchange(snapshot) { - if (!snapshot || typeof snapshot !== 'object') return { lastUser: '', lastAssistant: '' } - const nodes = [] - const values = typeof snapshot.nodes?.values === 'function' ? snapshot.nodes.values() : [] - for (const key of Array.isArray(values) ? values : Array.from(values ?? [])) { - const node = typeof snapshot.nodes?.get === 'function' ? snapshot.nodes.get(key) : undefined - if (node !== undefined) nodes.push(node) - } - let lastUser = '' - let lastAssistant = '' - for (const node of nodes) { - if (node.kind === 'user') { - const text = (Array.isArray(node.data?.content) ? node.data.content : []) - .filter((block) => block?.type === 'text') - .map((block) => block.text) - .join('\n') - if (text.trim() !== '') lastUser = shortText(text, 160) - } else if (node.kind === 'assistant-step') { - const text = (Array.isArray(node.data?.blocks) ? node.data.blocks : []) - .filter((block) => block?.kind === 'text') - .map((block) => block.text) - .join('\n') - if (text.trim() !== '') lastAssistant = shortText(text, 200) - } - } - return { lastUser, lastAssistant } -} - -/** 校验一次模型切换请求;子代理会话不允许改模型,返回原因便于提示。 */ -export function modelSwitchPlan(current, next, addressesSubagent) { - if (addressesSubagent === true) return { ok: false, reason: '子会话不能单独更换模型,请在丞相会话或新建会话时设置' } - if (!next?.provider || !next?.model) return { ok: false, reason: '未选择模型' } - const same = current?.provider === next.provider && current?.model === next.model - const effort = next.reasoningEffort ?? undefined - if (same && (current?.reasoningEffort ?? undefined) === effort) return { ok: false, reason: '与当前设置相同' } - return { ok: true, payload: { provider: next.provider, model: next.model, ...(effort === undefined ? {} : { reasoningEffort: effort }) } } -} diff --git a/panel/package.json b/panel/package.json deleted file mode 100644 index dcbe417..0000000 --- a/panel/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "dsh-sansheng-liubu-panel", - "version": "0.9.2", - "private": true, - "description": "三省六部 Agent 面板:在 DSH Web GUI 中常驻显示并切换团队 Agent", - "type": "module", - "main": "./index.js", - "exports": { - ".": "./index.js", - "./client": "./lib/client.js", - "./package.json": "./package.json" - }, - "files": [ - "index.js", - "cordis.patch.yml", - "lib/client.js", - "README.md", - "panel/test", - "scripts", - "icon.svg", - "locale" - ], - "dsh": { - "manifestVersion": 1, - "bundle": { - "patch": "./cordis.patch.yml" - }, - "client": { - "platform": "web", - "inject": [ - "@deepseek-ai/dsh-api-session-controller", - "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-workspace", - "@deepseek-ai/dsh-client-ui-model-selection" - ] - } - }, - "peerDependencies": { - "@deepseek-ai/cordis": "~4.0.5" - }, - "license": "MIT" -} diff --git a/panel/test/client.test.js b/panel/test/client.test.js deleted file mode 100644 index f9479ea..0000000 --- a/panel/test/client.test.js +++ /dev/null @@ -1,1121 +0,0 @@ -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 vm from 'node:vm' - -const here = dirname(fileURLToPath(import.meta.url)) -const source = readFileSync(join(here, '..', 'lib', 'client.js'), 'utf8') - -/** 用最小 React 替身加载客户端 bundle:只实现面板实际用到的钩子。 */ -function loadPlugin() { - let loaded - let styleCount = 0 - const React = { - createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }), - createContext: (value) => ({ Provider: 'provider', value }), - Component: class { constructor(props) { this.props = props; this.state = {} } }, - useContext: () => undefined, - Fragment: 'fragment', - useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}], - useRef: () => ({ current: null }), - useEffect: () => {}, - useCallback: (fn) => fn, - useMemo: (fn) => fn(), - } - const ReactDOM = { createPortal: (node) => node } - let cssText = '' - const document = { - getElementById: () => null, - querySelector: () => null, - createElement: () => { - const tag = { dataset: {}, appendChild() {}, setAttribute() {} } - let text = '' - Object.defineProperty(tag, 'textContent', { - get: () => text, - set: (value) => { text = String(value); cssText = text }, - }) - return tag - }, - head: { appendChild() { styleCount += 1 } }, - addEventListener() {}, - removeEventListener() {}, - body: {}, - } - const window = { - __ModuleLoader__: { - load(options) { - loaded = options - const module = { exports: options.factory((name) => { - if (name === 'react') return React - if (name === 'react-dom') return ReactDOM - if (name === 'react/jsx-runtime') return { jsx: () => null, jsxs: () => null, Fragment: 'fragment' } - throw new Error('unexpected require: ' + name) - }) } - loaded.exports = module.exports - }, - }, - } - const storage = new Map() - const localStorage = { - getItem: (key) => (storage.has(key) ? storage.get(key) : null), - setItem: (key, value) => { storage.set(key, String(value)) }, - removeItem: (key) => { storage.delete(key) }, - } - vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout, localStorage }, { filename: 'client.js' }) - return { loaded, exports: loaded.exports, styleCount: () => styleCount, css: () => cssText, storage } -} - -/** 全局模型清单的样板值:宿主一代只给一份,任何会话读到的都是它。 */ -const CATALOG_VALUE = { - default: { provider: 'deepseek', model: 'deepseek-chat' }, - failures: [], - groups: [ - { - id: 'deepseek', - name: 'DeepSeek', - models: [ - { id: 'deepseek-chat', name: 'DeepSeek Chat' }, - { id: 'deepseek-reasoner', name: 'DeepSeek Reasoner', reasoning: { defaultEffort: 'high', efforts: [{ id: 'high', name: '高' }] } }, - ], - }, - ], -} - -/** 模拟宿主 ctx:只实现面板调用到的服务面。 */ -function mockContext(prompts = []) { const registrations = [] - const injected = [] - const selections = [] - const tabTypes = [] - const openTabs = [] - let selection = { sessionId: 'lead-1' } - const sessionIds = ['lead-1'] - const sessionById = { 'lead-1': { id: 'lead-1', updatedAt: 1 } } - const sessionList = { - getSnapshot: () => ({ ids: sessionIds.slice(), byId: sessionById, projectionsBySession: {} }), - subscribe: () => () => {}, - } - const addSession = (id, workspaceId) => { - sessionIds.push(id) - sessionById[id] = { id, workspaceId, updatedAt: Date.now() } - return id - } - const selectionStore = { - getSnapshot: () => selection, - subscribe: () => () => {}, - set: (next) => { selection = next; selections.push(next) }, - } - let startSessionImpl - const ctx = { - effect(callback) { const dispose = callback(); return typeof dispose === 'function' ? dispose : () => {} }, - sessions: { - list: sessionList, - binding(sessionId) { - return { session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } } } - }, - subagentAddress: () => undefined, - refreshProjections: async () => {}, - }, - uiWorkspace: { - selection: selectionStore, - currentWorkspaceId: 'test-workspace', - startSession(workspaceId, options) { if (startSessionImpl) startSessionImpl(workspaceId, options) }, - openSession(target) { selections.push(target) }, - }, - uiConversation: { binding: () => ({ target: () => ({ getSnapshot: () => undefined }) }) }, - modelDirectories: { - catalog: { - load: async () => CATALOG_VALUE, - store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) }, - }, - directoryFor: () => ({ - load: async () => {}, - select: async () => ({ ok: true }), - store: { getSnapshot: () => ({ current: { provider: 'p', model: 'm' }, groups: [], failures: [], status: 'ready', error: null }) }, - }), - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - commands: { execute: async () => ({ ok: true, value: { commandId: 'cmd-1', result: { kind: 'success' } } }) }, - subagents: { prompt: async () => ({ messageId: 'msg-1' }) }, - }, - layout: { selectPanel(id) { selections.push(id) } }, - get(name) { - if (name === 'remote.commands') return ctx.remote.commands - if (name === 'remote.session') return ctx.remote.session - if (name === 'remote.subagents') return ctx.remote.subagents - return undefined - }, - sidebarRightTabs: { register(descriptor) { tabTypes.push(descriptor); return () => {} } }, - sidebarRight: { - openTab(kind, options) { openTabs.push({ sessionId: undefined, kind, options }) }, - openTabIn(sessionId, kind, options) { openTabs.push({ sessionId, kind, options }) }, - }, - slots: { - register(options, component) { - registrations.push({ options, component }) - return () => {} - }, - inject(slotName, callback) { - injected.push(slotName) - return callback() - }, - }, - } - return { - ctx, - registrations, - injected, - selections, - tabTypes, - openTabs, - prompts, - addSession, - setStartSession(fn) { startSessionImpl = fn }, - portal: { getSnapshot: () => ({}), subscribe: () => () => {} }, - } -} - -test('registers one web client bundle entry', () => { - const { loaded } = loadPlugin() - assert.equal(loaded.id, 'dsh-sansheng-liubu-panel') -}) - -test('exports the panel and the seat mention helpers', () => { - const { exports } = loadPlugin() - assert.equal(typeof exports.apply, 'function') - assert.equal(exports.PANEL_ID, 'sansheng-liubu') - assert.equal(typeof exports.SanshengPanel, 'function') - assert.equal(JSON.stringify(exports.inject), JSON.stringify(['slots', 'sessions', 'uiWorkspace', 'uiConversation', 'modelDirectories', 'remote', 'remote.agentPresets', 'remote.session', 'remote.subagents', 'remote.commands', 'sidebarRightTabs', 'sidebarRight'])) -}) - -test('registers the left nav row, one rail entry, the native header action and right sidebar tabs', () => { - const { exports } = loadPlugin() - const { ctx, registrations, injected } = mockContext() - exports.apply(ctx) - assert.deepEqual(injected, ['conversation.session.header.actions', 'sidebar.panellist', 'main', 'sidebar.right.pane.tab', 'sidebar.right.pane.tab.title']) - assert.equal(typeof exports.createHost(ctx).sendPrompt, 'function') - const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions') - assert.ok(toggle, '会话头保留打开朝堂侧栏的入口') - assert.equal(toggle.options.id, 'sansheng-liubu:toggle') - const nav = registrations.find((entry) => entry.options.name === 'sidebar.panellist') - assert.ok(nav, '左侧栏导航列也有入口') - assert.equal(nav.options.id, 'sansheng-liubu') - assert.equal(nav.options.label(), '上朝', '用户要求这行叫「上朝」') - assert.ok(nav.options.order < 0, '要排在其它插件行之前(置顶)') - assert.ok(Number.isFinite(nav.options.order), '导航列要给出排序,才能稳定落在固定位置') - const stub = registrations.find((entry) => entry.options.name === 'main') - assert.ok(stub, '那一列的点击会索取 main 槽,必须有落点') - assert.equal(stub.options.key, 'sansheng-liubu', 'main 用 key 与侧栏行对齐,不是再开一套面板') - const tab = registrations.find((entry) => entry.options.name === 'sidebar.right.pane.tab') - assert.ok(tab, '右侧栏注册朝堂页签') - assert.equal(tab.options.key, 'sansheng-liubu-tab') -}) - -test('左栏导航图标的「三」字样标按激活状态换描边', () => { - const { exports } = loadPlugin() - const { ctx, registrations } = mockContext() - exports.apply(ctx) - const nav = registrations.find((entry) => entry.options.name === 'sidebar.panellist') - // 注册项返回 h(SanshengNavGlyph, props),再调用一次才是真正的 svg 节点。 - const glyphOf = (props) => { - const wrapper = nav.component(props) - return wrapper.type(wrapper.props) - } - const idle = glyphOf({ size: 18, active: false }) - const active = glyphOf({ size: 18, active: true }) - assert.equal(idle.type, 'svg') - assert.equal(idle.props.width, 18) - assert.equal(idle.props['data-sansheng-glyph'], 'idle') - assert.equal(active.props['data-sansheng-glyph'], 'active') - // 替身的 createElement 把可变参数放进 children,数组实参会成为单层嵌套,这里拉平。 - const kids = (idle.children || []).flat() - assert.equal(kids.length, 4, '外框 + 三横') - const activeKids = (active.children || []).flat() - assert.ok(activeKids[0].props.strokeWidth > kids[0].props.strokeWidth, '激活态加粗') -}) - -test('导航列点击后把朝堂停靠到右侧栏,再退回原会话', () => { - const { exports } = loadPlugin() - const { dockToSidebarTab } = exports.__test - const calls = [] - const okHost = { - openSanshengTab: () => ({ ok: true }), - setToggleNotice: (value) => calls.push(['notice', value]), - selectPanel: (id) => calls.push(['selectPanel', id]), - } - assert.equal(dockToSidebarTab(okHost), null) - assert.deepEqual(calls, [['notice', null], ['selectPanel', null]], '成功后清掉提示并退出 main 槽') - - calls.length = 0 - const failHost = { - openSanshengTab: () => ({ ok: false, error: '当前还没有打开任何会话' }), - setToggleNotice: (value) => calls.push(['notice', value]), - selectPanel: (id) => calls.push(['selectPanel', id]), - } - assert.equal(dockToSidebarTab(failHost), '当前还没有打开任何会话') - assert.deepEqual(calls, [['notice', '当前还没有打开任何会话']], '失败时只写提示,不能把人留在一个不存在的面板上') -}) - - -test('summarizes the court into four sidebar stats', () => { - const { exports } = loadPlugin() - const { arrangeRoster, courtStats } = exports.__test - const seats = arrangeRoster({ - members: [ - { id: 'lead-1', name: 'lead', phase: 'active' }, - { id: 'z-1', name: 'zhongshu', phase: 'active' }, - { id: 'g-1', name: 'gongbu', phase: 'provisioning' }, - ], - tasks: [], - }) - const buckets = { - pending: [{ id: 'p1' }, { id: 'p2' }], - in_progress: [{ id: 'r1' }], - completed: [{ id: 'c1' }, { id: 'c2' }, { id: 'c3' }], - } - const running = new Set(['lead-1', 'z-1', 'g-1']) - const stats = Array.from(courtStats(seats, buckets, (entry) => running.has(entry.id))) - assert.deepEqual(Array.from(stats, (stat) => stat.label), ['在朝成员', '正在运行', '在办任务', '已完成']) - assert.deepEqual(Array.from(stats, (stat) => stat.value), [3, 3, 3, 3], '在办任务包含执行中与待办任务') - assert.deepEqual(Array.from(stats, (stat) => stat.key), ['members', 'running', 'pending', 'done']) - assert.deepEqual(Array.from(courtStats(undefined, undefined, () => true), (stat) => stat.value), [0, 0, 0, 0]) -}) - -test('lays the roster out as 丞相 / 三省 / 六部', () => { - const { exports } = loadPlugin() - const { arrangeRoster } = exports.__test - const seats = arrangeRoster({ - members: [ - { id: 'lead-1', name: 'lead', phase: 'active' }, - { id: 'z-1', name: 'zhongshu', phase: 'active' }, - { id: 'g-1', name: 'gongbu', phase: 'provisioning' }, - ], - tasks: [], - }) - assert.equal(seats.length, 10) - const byRole = Object.fromEntries(seats.map((seat) => [seat.role, seat])) - assert.equal(byRole.lead.row, 0) - assert.equal(byRole.zhongshu.row, 1) - assert.equal(byRole.shangshu.row, 1) - assert.equal(byRole.menxia.row, 1) - assert.equal(byRole.zhongshu.column, 0) - assert.equal(byRole.shangshu.column, 1) - assert.equal(byRole.menxia.column, 2) - assert.equal(byRole.gongbu.row, 2) - assert.equal(byRole.gongbu.present, true) - assert.equal(byRole.gongbu.id, 'g-1') - assert.equal(byRole.libu.present, false, '未设官的部门仍占位') - assert.equal(byRole.zhongshu.label, '中书省') - assert.deepEqual( - ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].map((role) => byRole[role].label), - ['吏部', '户部', '礼部', '兵部', '刑部', '工部'], - ) - assert.deepEqual( - ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].map((role) => byRole[role].row), - [2, 2, 2, 2, 2, 2], - '六部直属尚书省,同在第 2 排', - ) -}) - -test('exposes department sessions as native @ mention candidates', async () => { - const { exports } = loadPlugin() - const { arrangeRoster, seatMentionOptions, childRoleOf } = exports.__test - const seats = arrangeRoster({ - members: [ - { id: 'lead-1', name: 'lead', phase: 'active' }, - { id: 'z-1', name: 'zhongshu', phase: 'active' }, - { id: 'g-1', name: 'gongbu', phase: 'active' }, - ], - tasks: [], - }) - const options = seatMentionOptions(seats) - assert.deepEqual(Array.from(options, (item) => item.label), ['中书省', '工部']) - assert.deepEqual(Array.from(options, (item) => item.value), ['z-1', 'g-1']) - assert.match(options[1].description, /选择后进入该部门会话/) - assert.equal(childRoleOf(seats, 'g-1'), 'gongbu') - assert.equal(childRoleOf(seats, 'unknown'), undefined) - - const sources = [] - const { ctx } = mockContext() - ctx.get = (name) => name === 'inputTriggers' - ? { registerSource(source) { sources.push(source); return () => {} } } - : undefined - exports.apply(ctx) - assert.equal(sources.length, 1) - assert.equal(sources[0].trigger, '@') - - const { createSeatMentionSource } = exports.__test - let opened - const source = createSeatMentionSource({ - sessions: { - list: { getSnapshot: () => ({ projectionsBySession: { 'lead-1': { values: { agentTeam: { - members: [ - { id: 'lead-1', name: 'lead', phase: 'active' }, - { id: 'z-1', name: 'zhongshu', phase: 'active' }, - { id: 'g-1', name: 'gongbu', phase: 'active' }, - ], - } } } } }) }, - subagentAddress: () => ({ parentSessionId: 'lead-1', childSessionId: 'child-1' }), - }, - uiWorkspace: { selection: { getSnapshot: () => ({ sessionId: 'child-1' }) } }, - }, { openSession: (id) => { opened = id } }) - const matched = Array.from(await source.candidates({ sessionId: 'child-1' }, { query: '工' })) - assert.deepEqual(Array.from(matched, (item) => item.label), ['工部']) - const outcome = source.onPick({ candidate: matched[0] }) - assert.equal(outcome.text, '') - assert.deepEqual(Object.keys(outcome), ['text']) - await Promise.resolve() - assert.equal(opened, 'g-1') -}) - -test('separates running state from task state', () => { - const { exports } = loadPlugin() - const { memberStatus, bucketsOf, tasksOfRole, statusSummary } = exports.__test - assert.equal(memberStatus({ phase: 'active' }, true, false), 'running') - assert.equal(memberStatus({ phase: 'active' }, false, false), 'idle') - assert.equal(memberStatus({ phase: 'provisioning' }, false, false), 'provisioning') - assert.equal(memberStatus({ phase: 'failed' }, false, false), 'failed') - assert.equal(memberStatus(undefined, false, false), 'absent') - const tasks = [ - { id: 't1', subject: '规模', status: 'in_progress', ownerName: 'zhongshu' }, - { id: 't2', subject: '核对', status: 'completed', ownerName: 'menxia' }, - { id: 't3', subject: '备料', status: 'pending', ownerName: 'shangshu' }, - ] - const buckets = bucketsOf(tasks) - assert.equal(buckets.pending.length, 1) - assert.equal(buckets.in_progress.length, 1) - assert.equal(buckets.completed.length, 1) - assert.equal(tasksOfRole(tasks, 'menxia').length, 1) - const summary = statusSummary({ role: 'zhongshu', member: { phase: 'active' } }, { tasks }, true, false) - assert.equal(summary.status, 'running') - assert.equal(summary.statusLabel, '运行中') - assert.equal(summary.runningCount, 1) -}) - -test('builds model options with reasoning efforts', () => { - const { exports } = loadPlugin() - const { modelOptions, findModelOption, modelSwitchPlan } = exports.__test - const options = modelOptions({ - groups: [{ id: 'moonshotai-cn', models: [{ id: 'kimi-k3', name: 'Kimi K3', reasoning: { efforts: [{ id: 'high', name: '高' }], defaultEffort: 'high' } }] }], - }) - assert.equal(options.length, 1) - assert.equal(options[0].rowId, 'moonshotai-cn/kimi-k3') - assert.equal(options[0].provider, 'moonshotai-cn') - assert.equal(options[0].model, 'kimi-k3') - assert.equal(options[0].defaultEffort, 'high') - assert.equal(findModelOption(options, { provider: 'moonshotai-cn', model: 'kimi-k3' }).model, 'kimi-k3') - const plan = modelSwitchPlan({ provider: 'x', model: 'y' }, { provider: 'moonshotai-cn', model: 'kimi-k3', reasoningEffort: 'high' }, false) - assert.equal(plan.ok, true) - assert.equal(plan.payload.provider, 'moonshotai-cn') - assert.equal(plan.payload.reasoningEffort, 'high') - const subagentPlan = modelSwitchPlan(undefined, { provider: 'a', model: 'b' }, true) - assert.equal(subagentPlan.ok, true, '子会话改模型走模式插件的部门路由') - assert.equal(subagentPlan.via, 'command') - assert.equal(modelSwitchPlan({ provider: 'a', model: 'b' }, { provider: 'a', model: 'b' }, true).ok, false, '同样的选择不必再保存') -}) - -test('formats a decree with the target department', () => { - const { exports } = loadPlugin() - const text = exports.__test.decreeText('gongbu', ' 补一版安装脚本 ', { - tasks: [{ id: 't9', subject: '打包', status: 'in_progress' }], - }) - assert.match(text, /工部/) - assert.match(text, /补一版安装脚本/) - assert.match(text, /打包/) - assert.equal(exports.__test.decreeText('gongbu', ' ', {}), '') -}) - -test('reads the latest exchange from chat nodes', () => { - const { exports } = loadPlugin() - const exchange = exports.__test.lastExchange([ - { kind: 'user', anchorSeq: 1, data: { content: [{ type: 'text', text: '拟一份方案' }] } }, - { kind: 'assistant', anchorSeq: 2, data: { blocks: [{ kind: 'text', text: '已有方案草稿' }] } }, - ]) - assert.equal(exchange.lastUser, '拟一份方案') - assert.equal(exchange.lastAssistant, '已有方案草稿') -}) - -test('delivers a decree into the selected department session', async () => { - const { exports } = loadPlugin() - const prompts = [] - const { ctx } = mockContext(prompts) - exports.apply(ctx) - const host = exports.createHost(ctx) - const result = await host.sendPrompt('gongbu-1', '补一版安装脚本') - assert.equal(result.ok, true) - assert.equal(prompts.length, 1) - assert.equal(prompts[0].sessionId, 'gongbu-1') - assert.equal(prompts[0].mode, 'queue') - assert.equal(prompts[0].parts[0].text, '补一版安装脚本') -}) - -test('registers its page through better-sidebar when that plugin is installed', () => { - const { exports } = loadPlugin() - const { ctx, tabTypes, openTabs } = mockContext() - const registered = [] - ctx.betterSidebar = { - registerTab(descriptor) { registered.push(descriptor); return () => {} }, - openTab(seed, scope) { openTabs.push({ seed, scope }) }, - } - exports.apply(ctx) - - // 让位给 better-sidebar:不再重复注册宿主原生 tab 类型。 - assert.equal(tabTypes.length, 0) - assert.equal(registered.length, 1) - const descriptor = registered[0] - assert.equal(descriptor.id, exports.SANSENG_TAB_ID) - assert.equal(descriptor.single, true) - assert.equal(typeof descriptor.component, 'function') - - const host = exports.createHost(ctx) - const result = host.openSanshengTab('lead-1') - assert.equal(result.ok, true) - assert.equal(openTabs.length, 1) - assert.equal(openTabs[0].seed.type, exports.SANSENG_TAB_ID) - assert.equal(openTabs[0].scope.sessionId, 'lead-1') - - const tree = descriptor.component({ scope: { sessionId: 'lead-1' }, host }) - const panelEl = tree.children[0] - const rendered = panelEl.type(panelEl.props) - assert.equal(rendered.props['data-sansheng-compact'], '1', '朝堂页以紧凑形态渲染到侧边栏') -}) - -test('falls back to the newest session when nothing is selected', () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - // 空选中记录:模拟用户还没点开任何会话就打开朝堂页。 - ctx.uiWorkspace.selection.getSnapshot = () => ({}) - ctx.sessions.list.getSnapshot = () => ({ - ids: ['old-1', 'new-1', 'blank-1'], - byId: { - 'old-1': { id: 'old-1', updatedAt: '2026-11-01T00:00:00.000Z' }, - 'new-1': { id: 'new-1', updatedAt: '2026-11-07T00:00:00.000Z' }, - 'blank-1': { id: 'blank-1', blank: true, updatedAt: '2026-11-09T00:00:00.000Z' }, - }, - projectionsBySession: {}, - }) - exports.apply(ctx) - const host = exports.createHost(ctx) - assert.equal(host.getSelectedSession(), 'new-1') -}) - -test('opens an addressed child conversation with its parent', () => { - const { exports } = loadPlugin() - const { ctx, selections } = mockContext() - ctx.sessions.list.getSnapshot = () => ({ - ids: ['lead-1', 'child-1'], - byId: { 'child-1': { id: 'child-1', subagent: { address: { parentSessionId: 'lead-1', childSessionId: 'child-1' } } } }, - projectionsBySession: {}, - }) - exports.apply(ctx) - const host = exports.createHost(ctx) - host.openSession('child-1') - const target = selections.find((entry) => entry && typeof entry === 'object' && entry.childSessionId === 'child-1') - assert.ok(target, '子会话按 parent/child 地址打开') - assert.equal(target.parentSessionId, 'lead-1') - assert.equal(target.mode, 'continuable') -}) - -/** - * 回归:右侧栏页签由宿主注入 props,不应依赖会话级 hook 才能渲染; - * 面板必须只靠 host 的服务层 store 就能出图,否则会整片空白。 - */ -test('sidebar panel renders without slot-provided session hooks', () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - exports.apply(ctx) - const tree = exports.SanshengPanel({ host: exports.createHost(ctx) }) - let hasRoot = false - const classes = new Set() - const walk = (node) => { - if (Array.isArray(node)) { node.forEach(walk); return } - if (!node || typeof node !== 'object') return - const cls = node.props && node.props.className - if (typeof cls === 'string') { - cls.split(' ').forEach((name) => classes.add(name)) - if (cls.split(' ').includes('sl-root')) hasRoot = true - } - walk(node.children) - } - walk(tree) - assert.equal(hasRoot, true, '无会话级 hook 时仍渲染出面板根节点') - for (const name of ['sl-side-meta', 'sl-side-tabs', 'sl-map-head', 'sl-detail-title']) { - assert.ok(classes.has(name), `新版侧栏缺少 ${name}`) - } - assert.equal(classes.has('sl-left'), false, '侧栏形态不再包含独立聊天栏') - assert.equal(classes.has('sl-conv'), false) -}) - -test('renders a card-first court and a settings panel without duplicate decree input', () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - ctx.sessions.list.getSnapshot = () => ({ - ids: ['lead-1'], - byId: { 'lead-1': { id: 'lead-1' } }, - projectionsBySession: { - 'lead-1': { - values: { - agentTeam: { - members: [{ id: 'lead-1', name: 'lead', phase: 'active' }], - tasks: [], - }, - }, - }, - }, - }) - exports.apply(ctx) - const tree = exports.SanshengPanel({ host: exports.createHost(ctx) }) - const nodes = [] - const childrenOf = (node) => { - if (Array.isArray(node.children) && node.children.length > 0) return node.children - return node.props && node.props.children - } - const walk = (node) => { - if (Array.isArray(node)) { node.forEach(walk); return } - if (!node || typeof node !== 'object') return - nodes.push(node) - walk(childrenOf(node)) - } - walk(tree) - const seatElements = nodes.filter((node) => typeof node.type === 'function' && node.type.name === 'SeatCard') - assert.equal(seatElements.length, 10, '朝堂图始终保留十席卡片') - seatElements.forEach((node) => walk(node.type(node.props))) - const withClass = (name) => nodes.filter((node) => node.type && String(node.props?.className || '').split(' ').includes(name)) - const textOf = (node) => { - if (typeof node === 'string' || typeof node === 'number') return String(node) - if (Array.isArray(node)) return node.map(textOf).join('') - if (!node || typeof node !== 'object') return '' - return textOf(childrenOf(node)) - } - - assert.equal(withClass('sl-node').length, 10, '朝堂图始终保留十席卡片') - assert.equal(withClass('sl-node-check').length, 1, '只有当前部门显示选中勾') - assert.equal(withClass('sl-node-status').length, 10, '每张卡片都有独立状态行') - assert.equal(withClass('sl-ministry-group').length, 1, '六部收在同一个尚书省分组') - assert.equal(withClass('sl-sidebar').length, 1, '根节点是右侧栏形态') - assert.equal(withClass('sl-side-tabs').length, 1, '侧栏顶部有朝堂/任务切换') - assert.equal(nodes.filter((node) => node.props && node.props['data-side-tab']).length, 2) - assert.match(textOf(withClass('sl-side-tabs')[0]), /朝堂/) - assert.match(textOf(withClass('sl-side-tabs')[0]), /任务/) - assert.equal(withClass('sl-side-court').length, 1, '默认展示朝堂编制') - const courtTab = nodes.find((node) => node.props && node.props['data-side-tab'] === 'court') - assert.equal(courtTab.props['aria-selected'], true) - assert.equal(withClass('sl-left').length, 0, '不再保留重复的左侧聊天栏') - assert.equal(withClass('sl-conv').length, 0) - assert.equal(withClass('sl-left-nav').length, 0) - assert.equal(withClass('sl-task-jump').length, 0) - assert.equal(nodes.filter((node) => node.props && node.props['data-task-flow-jump'] === '1').length, 0) - assert.equal(withClass('sl-stat-pending')[0].type, 'button', '在办任务统计可直接切换到任务流转') - assert.equal(withClass('sl-stat-members')[0].type, 'button', '在朝成员统计可直接进入朝堂编制') - assert.equal(withClass('sl-stat-members')[0].props.title, '查看朝堂编制') - assert.equal(typeof withClass('sl-stat-members')[0].props.onClick, 'function') - const grid = withClass('sl-grid-6')[0] - assert.ok(grid, '六部使用独立网格') - const gridKids = Array.isArray(childrenOf(grid)) ? childrenOf(grid).flat(2) : [] - assert.equal(gridKids.filter((node) => typeof node?.type === 'function' && node.type.name === 'SeatCard').length, 6) - assert.equal(withClass('sl-conversation-action').length, 1, '设置区有明确的子 Agent 对话入口') - assert.match(textOf(withClass('sl-conversation-action')[0]), /丞相主会话/) - assert.equal(withClass('sl-advanced').length, 1, '技术信息收在高级信息里') - assert.equal(withClass('sl-detail-chip')[0] && textOf(withClass('sl-detail-chip')[0]), '固定职责') - assert.equal(withClass('sl-setting-block').length, 1) - assert.equal(withClass('sl-model-foot').length, 1) - assert.equal(nodes.filter((node) => node.type === 'textarea').length, 0, '不再提供重复的下旨输入框') - assert.equal(nodes.filter((node) => node.type === 'input').length, 0, '设置区没有可编辑的预设输入') - assert.equal(nodes.filter((node) => node.type === 'datalist').length, 0) - const text = textOf(tree) - assert.match(text, /输入 @ 选择部门/, '侧栏提示原生 @ 入口') - assert.doesNotMatch(text, /打开主对话/) - assert.doesNotMatch(text, /下旨/) - assert.doesNotMatch(text, /预设 ID 可直接填写/) - assert.match(text, /空闲/) - assert.doesNotMatch(text, /\bidle\b/) - assert.doesNotMatch(text, /项在办/, '窄卡片不塞任务计数,避免状态行换行') -}) - -test('sidebar tab wraps its content in a visible error boundary', () => { - const { exports } = loadPlugin() - const { ctx, registrations } = mockContext() - exports.apply(ctx) - const tab = registrations.find((entry) => entry.options.name === 'sidebar.right.pane.tab') - const tree = tab.component({}) - assert.ok(tree, '侧栏页签组件返回元素树') - let found = false - const walk = (node) => { - if (Array.isArray(node)) { node.forEach(walk); return } - if (!node || typeof node !== 'object') return - if (typeof node.type === 'function' && /PanelBoundary/.test(node.type.name || '')) found = true - const kids = Array.isArray(node.children) ? node.children : node.props && node.props.children - if (Array.isArray(kids)) kids.forEach(walk) - else if (kids) walk(kids) - } - if (typeof tree.type === 'function') walk(tree.type(tree.props)) - else walk(tree) - assert.equal(found, true, '内容被错误边界包住') -}) - -test('sendPrompt returns a structured error instead of throwing when the session is missing', async () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - ctx.sessions.binding = () => undefined - const host = exports.createHost(ctx) - const result = await host.sendPrompt('not-here', '测试') - assert.equal(result.ok, false) - assert.equal(result.errorCode, 'no-session') - assert.match(result.error, /对话通道|会话/) -}) - -test('opens an independent court session and delivers the formation prompt exactly once', async () => { - const { exports } = loadPlugin() - const { ctx, prompts, addSession, setStartSession } = mockContext() - setStartSession((workspaceId) => addSession('court-1', workspaceId)) - const host = exports.createHost(ctx) - const result = await host.openCourtSession() - assert.equal(result.ok, true, JSON.stringify(result)) - assert.equal(result.stage, 'delivered') - assert.equal(result.sessionId, 'court-1') - assert.equal(prompts.length, 1, '只投递一次组建指令') - assert.equal(prompts[0].sessionId, 'court-1') - const text = prompts[0].parts[0].text - assert.match(text, /组建朝班/) - assert.ok(text.indexOf('\n') > 0, '组建指令里应有真实换行') - assert.equal(text.indexOf('\\n'), -1, '不应出现字面反斜杠 n') -}) - -test('refuses a second court session request while the first one is pending', async () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - const host = exports.createHost(ctx) - const first = host.openCourtSession() - const second = await host.openCourtSession() - assert.equal(second.ok, false) - assert.equal(second.errorCode, 'busy') - const settled = await first - assert.equal(settled.ok, false) - assert.equal(settled.errorCode, 'create-timeout') -}) - -test('openConversation starts a usable conversation with the 上朝 preset and sends nothing', async () => { - const { exports } = loadPlugin() - const { ctx, prompts, addSession, setStartSession, selections } = mockContext() - const started = [] - setStartSession((workspaceId, options) => { started.push({ workspaceId, options }); addSession('court-2', workspaceId) }) - const host = exports.createHost(ctx) - const result = await host.openConversation() - assert.equal(result.ok, true, JSON.stringify(result)) - assert.equal(result.stage, 'created') - assert.equal(result.sessionId, 'court-2') - assert.equal(started.length, 1) - assert.equal(started[0].options.agentPreset, 'sansheng-liubu', '新对话带上朝预设') - assert.equal(prompts.length, 0, '只开对话,不自动发组建指令') - assert.ok(selections.indexOf('court-2') >= 0, '把中央切到新会话') -}) - -test('focusConversation jumps to the existing session and reports a missing one', () => { - const { exports } = loadPlugin() - const { ctx, selections } = mockContext() - const host = exports.createHost(ctx) - const jumped = host.focusConversation() - assert.equal(jumped.ok, true) - assert.equal(jumped.sessionId, 'lead-1') - assert.ok(selections.indexOf('lead-1') >= 0) - - const empty = mockContext() - empty.ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) } - empty.ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} } - const other = exports.createHost(empty.ctx) - const miss = other.focusConversation() - assert.equal(miss.ok, false) - assert.equal(miss.errorCode, 'no-session') -}) - -test('会话头开关拿不到会话时给出可见原因,而不是静默失效', () => { - const { exports } = loadPlugin() - const { ctx, registrations } = mockContext() - // 模拟「还没有打开任何会话」:会话列表与当前选中都为空。 - ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) } - ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} } - exports.apply(ctx) - const host = exports.createHost(ctx) - const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions') - assert.ok(toggle, '会话头入口已注册') - - // 把函数组件就地展开成一棵扁平节点表。宿主由注册项自己注入,测试不另造一份。 - const expand = (node) => { - if (Array.isArray(node)) return node.flatMap(expand) - if (!node || typeof node !== 'object') return [] - if (typeof node.type === 'function') return expand(node.type(node.props)) - return [node, ...expand(node.children), ...expand(node.props && node.props.children)] - } - const render = () => { - const wrapper = toggle.component({}) - return { host: wrapper.props.host, nodes: expand(wrapper) } - } - const withClass = (nodes, name) => nodes.filter((node) => String((node.props && node.props.className) || '').split(' ').includes(name)) - - const before = render() - assert.notEqual(before.host, host, '注册项注入的是它自己那份 host') - assert.equal(withClass(before.nodes, 'sl-toggle-notice').length, 0, '还没点击时不显示提示') - const button = before.nodes.find((node) => node.type === 'button') - assert.equal(typeof button.props.onClick, 'function') - button.props.onClick() - - const after = render() - const notices = withClass(after.nodes, 'sl-toggle-notice') - assert.equal(notices.length, 1, '失败原因要渲染出来,不能只回退不吭声') - assert.match(String(notices[0].props.children), /会话/) - assert.equal(notices[0].props.role, 'status') - assert.equal(notices[0].props.title, notices[0].props.children, '完整原因放在 title 里') - - after.host.setToggleNotice(null) - assert.equal(withClass(render().nodes, 'sl-toggle-notice').length, 0, '提示可以被清掉') -}) - -test('面板用到的每个 sl-* 类名都有对应 CSS 规则', () => { - const { css } = loadPlugin() - const text = css() - assert.ok(text.length > 2000, '样式已注入宿主') - const defined = new Set([...text.matchAll(/\.([a-zA-Z0-9_-]+)/g)].map((match) => match[1])) - const used = new Set() - for (const match of source.matchAll(/className:\s*"([^"$]*)"/g)) { - for (const token of match[1].split(/\s+/)) { - if (token.startsWith('sl-') && !token.endsWith('-')) used.add(token) - } - } - assert.ok(used.size > 30, '至少要扫到面板的类名') - const missing = [...used].filter((name) => !defined.has(name)).sort() - assert.deepEqual(missing, [], '不允许出现挂着类名却没有样式的元素') -}) - -test('响应式跟随侧栏容器宽度,而不是浏览器视口', () => { - const { css } = loadPlugin() - const text = css() - assert.match(text, /\.sl-root\{[^}]*container-type:inline-size/, '根节点要建立尺寸容器,才能按侧栏宽度断点') - assert.equal(/@media\s*\(\s*max-width/.test(text), false, '不得再用视口断点:侧栏宽度与浏览器窗口宽度无关') - const queries = [...text.matchAll(/@container slpanel \(max-width:(\d+)px\)/g)].map((match) => Number(match[1])) - assert.ok(queries.length >= 10, `容器断点太少:${queries.length}`) - for (const px of [1180, 980, 620]) { - assert.ok(queries.includes(px), `缺少 ${px}px 容器断点`) - } -}) - -test('部门设置里的最近活动单独占一行,不再和状态挤在同一行', () => { - const { css } = loadPlugin() - const rule = css().match(/\.sl-detail-status small\{([^}]*)\}/) - assert.ok(rule, '.sl-detail-status small 要有独立规则') - assert.match(rule[1], /flex:1 1 100%/, '最近活动要独占一整行') - assert.equal(/white-space:nowrap/.test(rule[1]), false, '不能强制单行,否则窄侧栏会横向挤压') -}) - -test('会话头开关失败时不再回退到不存在的整页面板', () => { - const { exports } = loadPlugin() - const { ctx, registrations, selections } = mockContext() - ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) } - ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} } - exports.apply(ctx) - const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions') - const expand = (node) => { - if (Array.isArray(node)) return node.flatMap(expand) - if (!node || typeof node !== 'object') return [] - if (typeof node.type === 'function') return expand(node.type(node.props)) - return [node, ...expand(node.children), ...expand(node.props && node.props.children)] - } - expand(toggle.component({})).find((node) => node.type === 'button').props.onClick() - assert.equal(selections.includes(exports.PANEL_ID), false, '失败时不得 selectPanel 到无 main 槽的面板') -}) - -/** 模型目录相关用例:宿主面按用例替换 modelDirectories。 */ -function catalogHost(overrides = {}) { - const { exports } = loadPlugin() - const context = mockContext() - Object.assign(context.ctx, overrides) - exports.apply(context.ctx) - return { ...context, host: exports.createHost(context.ctx) } -} - -test('宿主没有模型目录服务时,错误要说清是服务缺失', async () => { - const { host } = catalogHost({ modelDirectories: undefined }) - const result = await host.loadCatalog('lead-1') - assert.equal(result.options.length, 0) - assert.match(result.error, /没有模型目录服务/) - assert.notEqual(result.error, '当前宿主未提供模型目录', '不能再用那句笼统的误导文案') - const saved = await host.selectModel('lead-1', { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(saved.ok, false) - assert.match(saved.error, /没有模型目录服务/) -}) - -test('清单来自全局目录,不依赖哪个会话是否在本页登记', async () => { - const calls = [] - const { host } = catalogHost({ - modelDirectories: { - catalog: { - load: async () => CATALOG_VALUE, - store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) }, - }, - directoryFor(sessionId) { - calls.push(sessionId) - throw new Error('ui-model-selection: session "' + sessionId + '" resolved no scope') - }, - }, - }) - const result = await host.loadCatalog('libu') - assert.equal(result.error, null, '未登记的会话也要能列出模型') - assert.equal(result.options.map((option) => option.rowId).join(','), 'deepseek/deepseek-chat,deepseek/deepseek-reasoner') - assert.equal(result.inherited, true, '读不到该部门自己的选择时标成跟随默认') - assert.deepEqual(result.current, { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(result.unresolved, true, '界面据此提示「未在本页打开」') - assert.deepEqual(calls, ['libu']) -}) - -test('部门会话没在本页登记时,保存直接走宿主 RPC', async () => { - const sent = [] - const { host } = catalogHost({ - modelDirectories: { - catalog: { - load: async () => CATALOG_VALUE, - store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) }, - }, - directoryFor() { throw new Error('ui-model-selection: session "libu" resolved no binding') }, - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async (request) => { sent.push(request); return { ok: true } } }, - }, - }) - const saved = await host.selectModel('libu', { provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' }) - assert.equal(JSON.stringify(saved), JSON.stringify({ ok: true })) - assert.equal(JSON.stringify(sent), JSON.stringify([{ sessionId: 'libu', provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' }]), '要带 sessionId 和推理等级') -}) - -test('宿主拒绝保存时把原因原样带出', async () => { - const { host } = catalogHost({ - modelDirectories: { - catalog: { - load: async () => CATALOG_VALUE, - store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) }, - }, - directoryFor() { throw new Error('ui-model-selection: session "libu" resolved no binding') }, - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: false, error: { code: 'session/unknown', message: '没有这个会话' } }) }, - }, - }) - const saved = await host.selectModel('libu', { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(saved.ok, false) - assert.match(saved.error, /session\/unknown:没有这个会话/) -}) - -test('清单读取失败时说明是读清单失败,并保留已知缓存', async () => { - const { host } = catalogHost({ - modelDirectories: { - catalog: { - load: async () => { throw new Error('宿主断线') }, - store: { getSnapshot: () => ({ value: null, status: 'error', error: '宿主断线' }) }, - }, - directoryFor: () => ({ - load: async () => {}, - select: async () => ({ ok: true }), - store: { getSnapshot: () => ({ current: { provider: 'p', model: 'm' }, groups: [], failures: [], status: 'ready', error: null }) }, - }), - }, - }) - const result = await host.loadCatalog('lead-1') - assert.match(result.error, /读取模型清单失败:宿主断线/) - assert.deepEqual(result.current, { provider: 'p', model: 'm' }, '清单读不到时仍显示该会话已知的当前模型') - assert.equal(result.unresolved, false) -}) - -test('正常路径给出全局清单与该会话自己的当前选择', async () => { - const { host } = catalogHost() - const result = await host.loadCatalog('lead-1') - assert.equal(result.error, null) - assert.equal(result.unresolved, false) - assert.equal(result.inherited, false) - assert.equal(result.options.length, 2) - assert.deepEqual(result.current, { provider: 'p', model: 'm' }) -}) - -test('部门是子会话时,改模型靠宿主直接执行指令,不投递给模型', async () => { - const prompts = [] - const executed = [] - const { host } = catalogHost({ - sessions: { - list: () => [], - binding: (sessionId) => ({ - session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } }, - }), - subagentAddress: () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' }), - refreshProjections: async () => {}, - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - commands: { - execute: async (agentId, line, attachments) => { - executed.push({ agentId, line, attachments }) - return { commandId: 'cmd-1', result: { kind: 'success', text: '好' } } - }, - }, - }, - }) - const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' }) - assert.equal(result.ok, true) - assert.equal(prompts.length, 0, '不能向会话投递提示词,否则会触发模型思考') - assert.equal(executed.length, 1) - assert.equal(executed[0].agentId, 'lead-1') - assert.equal(executed[0].line, '/dept-model gongbu deepseek deepseek-chat high') - assert.equal(executed[0].attachments.length, 0) -}) - -test('宿主没有执行指令的接口时,报错要指明原因', async () => { - const { host } = catalogHost({ - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - }, - }) - const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(result.ok, false) - assert.match(result.error, /remote.commands.execute/) -}) - -test('指令接口挂在 ctx.get 上(官方挂法)时也照样静默执行', async () => { - const executed = [] - const commands = { - execute: async (agentId, line, attachments) => { - executed.push({ agentId, line, attachments }) - return { ok: true, value: { commandId: 'cmd-9', result: { kind: 'success', text: '已固定' } } } - }, - } - const { host, prompts } = catalogHost({ - get: (name) => (name === 'remote.commands' ? commands : undefined), - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - }, - }) - const result = await host.routeModel('libu', { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(result.ok, true) - assert.equal(prompts.length, 0, '走指令就不该往会话里投提示词') - assert.equal(executed.length, 1) - assert.equal(executed[0].line, '/dept-model libu deepseek deepseek-chat') -}) - -test('子会话的固定路由从面板记录里读出来当「当前模型」', async () => { - const { exports, storage } = loadPlugin() - storage.set('sansheng-liubu.route.gongbu', JSON.stringify({ provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' })) - const context = mockContext() - context.ctx.sessions.subagentAddress = () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' }) - exports.apply(context.ctx) - const host = exports.createHost(context.ctx) - const result = await host.loadCatalog('gongbu-1', 'gongbu') - assert.equal(result.fixed, true, '有固定路由时不算继承') - assert.equal(result.current.model, 'deepseek-reasoner') - assert.equal(result.current.reasoningEffort, 'high') -}) - -test('还没召见的部门也能先选好模型,保存走 /dept-model', async () => { - const { exports } = loadPlugin() - const { ctx } = mockContext() - exports.apply(ctx) - const host = exports.createHost(ctx) - - const catalog = await host.loadCatalog(undefined, 'libu') - assert.equal(catalog.options.length, 2, '没有会话也能拿到全局模型清单') - assert.equal(catalog.subagent, true, '未召见的部门同样按子会话处理') - assert.equal(catalog.error, null) - - const routed = await host.routeModel('libu', { provider: 'deepseek', model: 'deepseek-chat' }) - assert.equal(routed.ok, true) - assert.match(routed.text, /^\/dept-model libu deepseek deepseek-chat$/) - - // 详情区的模型设置对缺席席位也要渲染出来(不再是 seat.present 才给)。 - assert.match(source, /seat \? h\("div", \{ className: "sl-setting-block" \}, \[/, '模型设置绑定席位,而不是绑定「已召见」') -}) - -test('用户直接派活:走 subagent 投递,不经过丞相', async () => { - const delivered = [] - const { host } = catalogHost({ - sessions: { - list: { getSnapshot: () => ({ ids: ['lead-1', 'gongbu-1'], byId: {}, projectionsBySession: {} }), subscribe: () => () => {} }, - binding: () => ({ session: { prompt: async () => ({ ok: true }) } }), - subagentAddress: (sessionId) => (sessionId === 'gongbu-1' ? { parentSessionId: 'lead-1', childSessionId: 'gongbu-1' } : undefined), - refreshProjections: async () => {}, - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - commands: { execute: async () => ({ commandId: 'cmd-1', result: { kind: 'success' } }) }, - subagents: { prompt: async (request) => { delivered.push(request); return { messageId: 'msg-1' } } }, - }, - }) - const result = await host.dispatchToSeat('gongbu-1', '把安装脚本补完') - assert.equal(result.ok, true) - assert.equal(delivered.length, 1) - assert.equal(delivered[0].parentSessionId, 'lead-1') - assert.equal(delivered[0].childSessionId, 'gongbu-1') - assert.equal(delivered[0].mode, 'continuable') - assert.equal(delivered[0].delivery, 'queue') - assert.equal(JSON.stringify(delivered[0].content), JSON.stringify([{ type: 'text', text: '把安装脚本补完' }])) - assert.equal(typeof delivered[0].requestId, 'string') - assert.ok(delivered[0].requestId.length > 0, '每次投递都要带独立的 requestId') -}) - -test('不是子会话时,直接派活要说清原因', async () => { - const { host } = catalogHost() - const result = await host.dispatchToSeat('lead-1', '随便说说') - assert.equal(result.ok, false) - assert.match(result.error, /不是子会话/) -}) - -test('改模型优先在部门自己的会话里执行指令', async () => { - const executed = [] - const { host } = catalogHost({ - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - subagents: { prompt: async () => ({ messageId: 'msg-1' }) }, - commands: { - execute: async (agentId, line) => { - executed.push(agentId) - return { commandId: 'cmd-1', result: { kind: 'success', text: line } } - }, - }, - }, - }) - const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat' }, 'gongbu-1') - assert.equal(result.ok, true) - assert.equal(JSON.stringify(executed), JSON.stringify(['gongbu-1']), '第一步就该用部门自己的会话') -}) - -test('部门会话执行不了时退到别的会话,仍然不碰对话', async () => { - const executed = [] - const prompts = [] - const { host } = catalogHost({ - sessions: { - list: { getSnapshot: () => ({ ids: ['lead-1'], byId: {}, projectionsBySession: {} }), subscribe: () => () => {} }, - binding: (sessionId) => ({ session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } } }), - subagentAddress: () => undefined, - refreshProjections: async () => {}, - }, - remote: { - agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) }, - session: { selectModel: async () => ({ ok: true }) }, - subagents: { prompt: async () => ({ messageId: 'msg-1' }) }, - commands: { - execute: async (agentId) => { - executed.push(agentId) - if (agentId === 'gongbu-1') throw new Error('session "gongbu-1" resolved no scope') - return { commandId: 'cmd-1', result: { kind: 'success' } } - }, - }, - }, - }) - const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat' }, 'gongbu-1') - assert.equal(result.ok, true) - assert.equal(JSON.stringify(executed), JSON.stringify(['gongbu-1', 'lead-1'])) - assert.equal(prompts.length, 0, '退到别的会话也只是执行指令,不发消息') -}) diff --git a/preset.patch.yml b/preset.patch.yml deleted file mode 100644 index 0b088f2..0000000 --- a/preset.patch.yml +++ /dev/null @@ -1,22 +0,0 @@ -# 可选层:只有把下面的条目合并进 -# ~/.dsh/profiles/desktop/cordis.patch.yml -# 并彻底重启 DSH 之后,「上朝」才会出现在模式选择器里。 -# 不合并 = 永远不开;删掉 = 立即退出。 -# -# 合并方式(PowerShell,在 profile 目录下): -# $patch = Get-Content ~/.dsh/profiles/desktop/cordis.patch.yml -Raw -# Get-Content ./preset.patch.yml -Raw | Add-Content ~/.dsh/profiles/desktop/cordis.patch.yml -# 注意保持 YAML 顶层是「数组」:删掉文件里那行 `[]` 之后再把本文件内容接在末尾。 -- insert: - - id: preset-sansheng-liubu - name: '@deepseek-ai/dsh-agent-preset' - config: - id: sansheng-liubu - name: 上朝 - description: 丞相统筹,中书规划、门下审核、尚书调度,工部通过 Image-gen 进行视觉创作、礼部文档、兵部代码与工具武库。 - order: 30 - plugins: - - id: sansheng-liubu-policy - name: dsh-sansheng-liubu-mode - config: - presetId: sansheng-liubu diff --git a/scripts/check-install.mjs b/scripts/check-install.mjs deleted file mode 100644 index 0ee7e7a..0000000 --- a/scripts/check-install.mjs +++ /dev/null @@ -1,92 +0,0 @@ -import { readFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { homedir } from 'node:os' -import { dirname, join, resolve } from 'node:path' -import { pathToFileURL } from 'node:url' - -const profileDir = resolve(process.env.DSH_PROFILE_DIR ?? join(homedir(), '.dsh', 'profiles', 'desktop')) -const profilePath = join(profileDir, 'package.json') -const profile = JSON.parse(await readFile(profilePath, 'utf8')) -const profilePatchPath = join(profileDir, 'cordis.patch.yml') - -function assert(condition, message) { - if (!condition) throw new Error(message) -} - -/** 去掉整行注释后剩下的 YAML 主体。 */ -function withoutComments(source) { - return source.replace(/^\s*#.*$/gm, '').trim() -} - -for (const name of ['dsh-sansheng-liubu-mode', 'dsh-sansheng-liubu-panel']) { - assert(profile.dependencies?.[name]?.startsWith('link:'), `${name} must be a link dependency`) -} -// 面板常驻;模式故意不要求在 bundles 里——它必须由用户显式启用。 -assert( - profile.dsh?.profile?.bundles?.includes('dsh-sansheng-liubu-panel'), - 'panel must be listed in dsh.profile.bundles', // 面板是常驻 UI,不参与 Agent 策略 -) - -const requireFromProfile = createRequire(join(profileDir, 'package.json')) -const modeManifestPath = requireFromProfile.resolve('dsh-sansheng-liubu-mode/package.json') -const panelManifestPath = requireFromProfile.resolve('dsh-sansheng-liubu-panel/package.json') -const modeDir = dirname(modeManifestPath) -const modeManifest = JSON.parse(await readFile(modeManifestPath, 'utf8')) -const panelManifest = JSON.parse(await readFile(panelManifestPath, 'utf8')) - -assert(modeManifest.dsh?.bundle?.patch, 'mode package must declare dsh.bundle.patch') -assert(panelManifest.dsh?.bundle?.patch, 'panel package must declare dsh.bundle.patch') -assert(panelManifest.dsh?.client?.platform === 'web', 'panel must declare a web client') -assert(panelManifest.dsh?.client?.inject?.length > 0, 'panel must declare client injections') - -// 装包 ≠ 开模式:包自带的 patch 必须是空层,绝不能注册「上朝」预设。 -const bundlePatch = await readFile(join(modeDir, modeManifest.dsh.bundle.patch), 'utf8') -assert( - !/preset-sansheng-liubu/.test(bundlePatch), - 'bundle patch must not register the 上朝 preset; opting in goes through preset.patch.yml', -) -assert( - ['', '[]'].includes(withoutComments(bundlePatch)), - 'bundle patch must stay an empty layer so installing the mode changes nothing', -) - -// 可选层必须存在,并且能复现出同一个 preset id 与策略插件。 -const presetPatch = await readFile(join(modeDir, 'preset.patch.yml'), 'utf8') -assert(/id: preset-sansheng-liubu/.test(presetPatch), 'preset.patch.yml must declare preset-sansheng-liubu') -assert(/^\s+id: sansheng-liubu\s*$/m.test(presetPatch), 'preset.patch.yml must declare the sansheng-liubu preset id') -assert(/name: dsh-sansheng-liubu-mode/.test(presetPatch), 'preset.patch.yml must load dsh-sansheng-liubu-mode') - -let modeEnabled = false -try { - modeEnabled = /preset-sansheng-liubu/.test(await readFile(profilePatchPath, 'utf8')) -} catch { - // 没有 patch 文件 = 从未启用过 -} - -const mode = await import(pathToFileURL(join(modeDir, modeManifest.main)).href) -const panel = await import(pathToFileURL(join(dirname(panelManifestPath), panelManifest.main)).href) -assert(typeof mode.apply === 'function', 'mode host entry must export apply') -assert(typeof panel.apply === 'function', 'panel host must export apply') - -const clientSource = await readFile(join(dirname(panelManifestPath), 'lib', 'client.js'), 'utf8') -assert(clientSource.includes('id: "dsh-sansheng-liubu-panel"'), 'client bundle id must match the panel package name') -assert(clientSource.includes('"sidebar.right.pane.tab"'), 'client bundle must register the right sidebar tab') -// 0.5.4 起:「左侧栏导航列的一行 + main 重定向桩」是允许的(用户要求入口出现在那一列), -// 但范围严格限定为纯跳转:不得注册 panellist 的更多菜单动作,也不得注册整页面板。 -assert(clientSource.includes('"sidebar.panellist"'), 'client bundle must register the left nav row') -assert(clientSource.includes('name: "sidebar.panellist"'), 'left nav row must go through the panellist slot') -assert(clientSource.includes('name: "main"'), 'left nav row needs a main redirect stub to leave the workspace empty') -assert(clientSource.includes('SanshengDockRedirect'), 'main slot must only be the redirect stub, not a full-page panel') -assert(!/sidebar\.panellist\.actions/.test(clientSource), 'client bundle must not register panellist more-menu actions') -assert(!clientSource.includes('h(SanshengPanel, { ...props, host })'), 'main slot must not render the court panel itself') - -console.log(JSON.stringify({ - profile: profilePath, - mode: modeManifestPath, - panel: panelManifestPath, - bundles: profile.dsh.profile.bundles.filter((name) => name.startsWith('dsh-sansheng-')), - modeEnabled, - hint: modeEnabled - ? '「上朝」已启用:它只是模式选择器里的一个选项,不会自动成为新会话默认。' - : '「上朝」未启用(装包不等于开模式)。要当可选模式用:node scripts/mode.mjs on,再彻底重启 DSH。', -}, null, 2)) diff --git a/scripts/mode.mjs b/scripts/mode.mjs deleted file mode 100644 index 27fd102..0000000 --- a/scripts/mode.mjs +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env node -// 上朝的启用开关:只改 profile 的 cordis.patch.yml,不碰任何别的插件行。 -// -// node scripts/mode.mjs status # 现在开没开 -// node scripts/mode.mjs on # 让「上朝」出现在模式选择器里(仍需你在新会话中点选) -// node scripts/mode.mjs off # 彻底移除这个选项 -// -// 改动是一段带标记的 YAML,重复执行结果一致;不开模式时 profile 里不留任何痕迹。 - -import { readFile, writeFile } from 'node:fs/promises' -import { homedir } from 'node:os' -import { join, resolve } from 'node:path' - -const BEGIN = '# >>> 上朝 preset(scripts/mode.mjs 管理,勿手改)' -const END = '# <<< 上朝 preset' -const MARK = 'preset-sansheng-liubu' - -const profileDir = resolve(process.env.DSH_PROFILE_DIR ?? join(homedir(), '.dsh', 'profiles', 'desktop')) -const patchPath = join(profileDir, 'cordis.patch.yml') -const presetTemplatePath = resolve(import.meta.dirname, '..', 'preset.patch.yml') - -async function readOrEmpty(path) { - try { - return await readFile(path, 'utf8') - } catch (error) { - if (error.code === 'ENOENT') return '' - throw error - } -} - -/** preset.patch.yml 里真正要被合并的那几行(去掉说明注释)。 */ -async function presetBlock() { - const template = await readOrEmpty(presetTemplatePath) - const lines = template.split(/\r?\n/) - const start = lines.findIndex((line) => /^- insert:/.test(line)) - if (start < 0) throw new Error(`${presetTemplatePath} 里找不到 "- insert:" 起始行`) - return lines.slice(start).join('\n').trimEnd() -} - -/** 顶层若是空数组占位 `[]`,合并前要先去掉,否则 YAML 不再是单个数组。 */ -function dropEmptyRoot(text) { - const kept = text.split(/\r?\n/).filter((line) => line.trim() !== '[]') - return kept.join('\n').trimEnd() -} - -function isEnabled(text) { - return text.includes(MARK) -} - -function isManaged(text) { - return text.includes(BEGIN) -} - -function stripBlock(text) { - const lines = text.split(/\r?\n/) - const begin = lines.findIndex((line) => line.trim() === BEGIN) - const end = lines.findIndex((line) => line.trim() === END) - if (begin < 0 || end < begin) return null - return [...lines.slice(0, begin), ...lines.slice(end + 1)].join('\n') -} - -async function status() { - const text = await readOrEmpty(patchPath) - return { - profilePatch: patchPath, - enabled: isEnabled(text), - managed: isManaged(text), - } -} - -async function enable() { - const text = await readOrEmpty(patchPath) - if (isEnabled(text)) return { ...(await status()), changed: false, note: '已经启用,未改动' } - const body = dropEmptyRoot(text) - const parts = [body, BEGIN, await presetBlock(), END].filter((part) => part !== '') - await writeFile(patchPath, `${parts.join('\n')}\n`, 'utf8') - return { ...(await status()), changed: true, note: '已启用;彻底重启 DSH 后,新会话可选「上朝」' } -} - -async function disable() { - const text = await readOrEmpty(patchPath) - if (!isEnabled(text)) return { ...(await status()), changed: false, note: '本来就没启用,未改动' } - const stripped = stripBlock(text) - if (stripped === null) { - throw new Error(`${patchPath} 里的预设行不是本脚本写入的(缺少标记行),请手动删除后重试`) - } - const body = stripped.trimEnd() - const next = body === '' ? '[]\n' : `${body}\n` - await writeFile(patchPath, next, 'utf8') - return { ...(await status()), changed: true, note: '已关闭;彻底重启 DSH 后生效' } -} - -const action = (process.argv[2] ?? 'status').toLowerCase() -const handlers = { status, on: enable, off: disable } -const handler = handlers[action] -if (!handler) { - console.error(`未知动作:${action}(可用:status / on / off)`) - process.exit(2) -} - -try { - console.log(JSON.stringify(await handler(), null, 2)) -} catch (error) { - console.error(String(error?.message ?? error)) - process.exit(1) -} diff --git a/scripts/preview-workbench.mjs b/scripts/preview-workbench.mjs deleted file mode 100644 index 9b4dfdb..0000000 --- a/scripts/preview-workbench.mjs +++ /dev/null @@ -1,2993 +0,0 @@ -#!/usr/bin/env node -/** - * preview-workbench.mjs — 任意 DSH 客户端 bundle 的离线渲染 + 截图工具。 - * - * 与 scripts/preview.mjs 的区别:那个脚本是「朝堂侧栏」专用、演示数据写死; - * 这个脚本接受任意 bundle 路径,用 vm 在伪 window 上加载真实 bundle, - * 打桩 fetch 数据,用会真正重渲染的 hooks 替身跑完异步 effect, - * 把组件树序列化成 HTML,最后交给本机 Chrome 截图。 - * - * 用法: - * node scripts/preview-workbench.mjs --bundle= --out= --name= \ - * --theme=light|dark --width=400 - */ - -import vm from 'node:vm' -import { - existsSync, - mkdirSync, - readFileSync, - statSync, - writeFileSync, -} from 'node:fs' -import { dirname, join, resolve } from 'node:path' -import { fileURLToPath, pathToFileURL } from 'node:url' -import { spawnSync } from 'node:child_process' - -const HERE = dirname(fileURLToPath(import.meta.url)) -const ROOT = resolve(HERE, '..') -const SCRATCH = join(ROOT, '.scratch', 'preview-workbench') -const ROUTE_PREFIX = '/sansheng/workbench' -const LEAD_SESSION = 'sess-lead' - -function unrefTimer(timer) { - if (timer && typeof timer.unref === 'function') timer.unref() - return timer -} - -const CHROME_CANDIDATES = [ - 'C:/Program Files/Google/Chrome/Application/chrome.exe', - 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', - 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', - 'C:/Program Files/Microsoft/Edge/Application/msedge.exe', -] - -// #region 基础工具 - -function fail(message) { - const error = new Error(message) - error.previewFailure = true - throw error -} - -function log(message) { - process.stdout.write(`[preview-workbench] ${message}\n`) -} - -function ensureDir(path) { - mkdirSync(path, { recursive: true }) -} - -function parseArgs(argv) { - const options = { - bundle: 'workbench/panel/lib/client.js', - out: 'docs/preview', - name: 'v01-workbench-rail', - theme: 'light', - width: 400, - scale: 2, - chrome: null, - view: 'court', - open: '', - scenario: '', - live: false, - help: false, - } - const keys = { - bundle: 'bundle', - out: 'out', - name: 'name', - theme: 'theme', - width: 'width', - scale: 'scale', - chrome: 'chrome', - view: 'view', - open: 'open', - scenario: 'scenario', - } - for (let index = 0; index < argv.length; index += 1) { - const arg = argv[index] - if (arg === '--help' || arg === '-h') { - options.help = true - continue - } - if (!arg.startsWith('--')) fail(`无法识别的参数:${arg}`) - const body = arg.slice(2) - const eq = body.indexOf('=') - const rawKey = eq === -1 ? body : body.slice(0, eq) - if (rawKey === 'help') { - 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 - if (eq === -1) { - index += 1 - value = argv[index] - if (value === undefined) fail(`参数 --${rawKey} 缺少值`) - } else { - value = body.slice(eq + 1) - } - options[field] = value - } - 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 [ - '用法:', - ' node scripts/preview-workbench.mjs --bundle= --out= --name= \\', - ' --theme=light|dark --width=400', - '', - '选项:', - ' --bundle bundle 路径,默认 workbench/panel/lib/client.js', - ' --out 截图输出目录,默认 docs/preview', - ' --name 输出文件名前缀,默认 v01-workbench-rail', - ' --theme light | dark,默认 light', - ' --width 截图宽度(CSS px),默认 400', - ' --scale 设备像素比,默认 2', - ' --chrome Chrome/Edge 可执行文件路径,默认自动探测', - ' --view court | tasks | artifacts,先切到该页签再截图,默认 court', - ' --open 切到成果页后点开匹配这段文字的成果行(看详情抽屉)', - ' --scenario live 场景:court | tasks | cancel | revise | missing(默认按 --name 推断)', - ' --live 不打死数据:把 bundle 的 fetch 接到仓库内真实 Host 路由(内存账本)', - ' --help 显示本帮助', - ].join('\n') -} - -function chromeRun(chrome, args, label) { - const result = spawnSync(chrome, args, { - encoding: 'utf8', - windowsHide: true, - maxBuffer: 128 * 1024 * 1024, - timeout: 180000, - stdio: ['ignore', 'pipe', 'pipe'], - }) - if (result.error) fail(`${label} 调用 Chrome 失败:${result.error.message}`) - if (result.status !== 0) { - const stderr = String(result.stderr || '').trim().split(/\r?\n/).slice(-8).join('\n') - fail(`${label} 失败(Chrome 退出码 ${result.status})${stderr ? `:\n${stderr}` : ''}`) - } - return result -} - -function findChrome(explicit) { - const candidates = explicit ? [explicit, ...CHROME_CANDIDATES] : CHROME_CANDIDATES - for (const candidate of candidates) { - try { - if (candidate && statSync(candidate).isFile()) return candidate - } catch (error) { - // 继续找下一个 - } - } - fail(`找不到 Chrome/Edge。可用 --chrome= 指定。尝试过:\n${candidates.join('\n')}`) -} - -function readPngSize(pngPath) { - const bytes = readFileSync(pngPath) - if (bytes.length < 33) fail(`截图文件不完整:${pngPath}(${bytes.length} 字节)`) - if (bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') { - fail(`截图不是合法 PNG:${pngPath}`) - } - return { - width: bytes.readUInt32BE(16), - height: bytes.readUInt32BE(20), - bytes: bytes.length, - } -} - -// #endregion - -// #region 固定演示数据(形状对齐 workbench/host/service.mjs) - -const SEATS = [ - { roleId: 'lead', name: '丞相', short: '丞', tier: 'leaders', group: 'lead', column: 'span', row: 0, duty: '接需求、分流、协调、汇报', canDispatch: true }, - { roleId: 'zhongshu', name: '中书', short: '中', tier: 'leaders', group: 'sansheng', column: 'left', row: 1, duty: '调查、澄清、规划', canDispatch: false }, - { roleId: 'shangshu', name: '尚书', short: '尚', tier: 'leaders', group: 'sansheng', column: 'center', row: 1, duty: '分工建议、组织交付', canDispatch: true }, - { roleId: 'menxia', name: '门下', short: '门', tier: 'leaders', group: 'sansheng', column: 'right', row: 1, duty: '审议与整体审核', canDispatch: false }, - { roleId: 'libu', name: '吏部', short: '吏', tier: 'ministries', group: 'ministries', column: 'left', row: 2, duty: '角色和技能配置建议', canDispatch: false }, - { roleId: 'hubu', name: '户部', short: '户', tier: 'ministries', group: 'ministries', column: 'center', row: 2, duty: '数据、表格、计算', canDispatch: false }, - { roleId: 'lipu', name: '礼部', short: '礼', tier: 'ministries', group: 'ministries', column: 'right', row: 2, duty: '文档、内容、呈现', canDispatch: false }, - { roleId: 'bingbu', name: '兵部', short: '兵', tier: 'ministries', group: 'ministries', column: 'left', row: 3, duty: '环境、调试、部署', canDispatch: false }, - { roleId: 'xingbu', name: '刑部', short: '刑', tier: 'ministries', group: 'ministries', column: 'center', row: 3, duty: '测试与风险检查', canDispatch: false }, - { roleId: 'gongbu', name: '工部', short: '工', tier: 'ministries', group: 'ministries', column: 'right', row: 3, duty: '代码实现与工程产出', canDispatch: false }, -] - -const TASKS = [ - { - id: 'task_demo_running', - projectId: 'prj_demo1', - title: '生成离线预览截图', - objective: '在 400px 窄栏下渲染工作台并输出 light / dark 两张截图。', - acceptance: ['两张 PNG 宽度为 800px(2x)', '不修改被预览的 bundle'], - constraints: ['只写 .scratch 与 docs/preview'], - scope: 'preview', - ownerRoleId: 'gongbu', - sourceRoleId: 'shangshu', - originMessageRef: 'msg_demo_1', - returnTarget: 'shangshu', - status: 'running', - activeAttemptId: 'attempt_demo_running', - attempts: [ - { - id: 'attempt_demo_running', - projectId: 'prj_demo1', - taskId: 'task_demo_running', - state: 'running', - startedAt: '2026-11-09T22:10:00.000Z', - endedAt: null, - }, - ], - startedAt: '2026-11-09T22:10:00.000Z', - endedAt: null, - reportReceivedAt: null, - needsAttentionReason: null, - failureReason: null, - waitingReason: null, - revision: 3, - createdAt: '2026-11-09T22:09:00.000Z', - updatedAt: '2026-11-09T22:12:00.000Z', - open: true, - attemptCount: 1, - resultCount: 0, - }, - { - id: 'task_demo_attention', - projectId: 'prj_demo1', - title: '复核 2x 截图的验收口径', - objective: '确认 800px 宽的 PNG 是否满足交付要求,并记录结论。', - acceptance: ['给出明确的接受 / 不接受结论'], - constraints: ['不重启 DSH'], - scope: 'review', - ownerRoleId: 'xingbu', - sourceRoleId: 'lead', - originMessageRef: 'msg_demo_2', - returnTarget: 'lead', - status: 'needs_attention', - activeAttemptId: null, - attempts: [], - startedAt: '2026-11-09T22:05:00.000Z', - endedAt: null, - reportReceivedAt: null, - needsAttentionReason: '验收标准需要人工确认:是否接受 2x 设备像素比截图?', - failureReason: null, - waitingReason: null, - revision: 2, - createdAt: '2026-11-09T22:04:00.000Z', - updatedAt: '2026-11-09T22:14:00.000Z', - open: true, - attemptCount: 0, - resultCount: 0, - }, - { - id: 'task_demo_revision', - projectId: 'prj_demo1', - title: '修订:离线预览截图', - kind: 'revision', - objective: '按验收意见重拍 light 页并补一张成果详情。', - acceptance: ['修订后的截图进入成果账本'], - constraints: ['不重启 DSH'], - scope: 'preview', - ownerRoleId: 'gongbu', - sourceRoleId: 'xingbu', - originMessageRef: 'msg_demo_4', - returnTarget: 'xingbu', - status: 'queued', - activeAttemptId: null, - attempts: [], - startedAt: null, - endedAt: null, - reportReceivedAt: null, - needsAttentionReason: null, - failureReason: null, - waitingReason: null, - revision: 1, - createdAt: '2026-11-09T22:15:00.000Z', - updatedAt: '2026-11-09T22:16:00.000Z', - open: true, - attemptCount: 0, - resultCount: 0, - }, - { - id: 'task_demo_done', - projectId: 'prj_demo1', - title: '核对十席角色文案', - objective: '按 roles.mjs 校对十席名称、简写和职责。', - acceptance: ['十席全部一致'], - constraints: [], - scope: 'copy', - ownerRoleId: 'hubu', - sourceRoleId: 'zhongshu', - originMessageRef: 'msg_demo_3', - returnTarget: 'zhongshu', - status: 'completed', - activeAttemptId: null, - attempts: [ - { - id: 'attempt_demo_done', - projectId: 'prj_demo1', - taskId: 'task_demo_done', - state: 'completed', - startedAt: '2026-11-09T21:40:00.000Z', - endedAt: '2026-11-09T21:52:00.000Z', - }, - ], - startedAt: '2026-11-09T21:40:00.000Z', - endedAt: '2026-11-09T21:52:00.000Z', - reportReceivedAt: '2026-11-09T21:52:30.000Z', - needsAttentionReason: null, - failureReason: null, - waitingReason: null, - revision: 5, - createdAt: '2026-11-09T21:39:00.000Z', - updatedAt: '2026-11-09T21:53:00.000Z', - open: false, - attemptCount: 1, - resultCount: 1, - }, -] - -const ARTIFACTS = [ - { - id: 'artifact_demo_light', - projectId: 'prj_demo1', - taskId: 'task_demo_running', - ownerRoleId: 'gongbu', - fileRef: '.scratch/preview-workbench/v01-workbench-rail-400-light.png', - displayName: 'v01-workbench-rail-400-light.png', - mediaType: 'image/png', - versionOrHash: 'sha256:preview-demo-light', - verification: { status: 'verified' }, - sourceResultId: null, - createdAt: '2026-11-09T22:11:00.000Z', - updatedAt: '2026-11-09T22:11:00.000Z', - }, - { - id: 'artifact_demo_report', - projectId: 'prj_demo1', - taskId: 'task_demo_attention', - ownerRoleId: 'xingbu', - fileRef: 'docs/preview/巡检报告.md', - displayName: '巡检报告.md', - mediaType: 'text/markdown', - versionOrHash: 'sha256:preview-demo-report', - verification: { status: 'pending' }, - sourceResultId: null, - createdAt: '2026-11-09T22:13:00.000Z', - updatedAt: '2026-11-09T22:13:00.000Z', - }, - { - id: 'artifact_demo_missing', - projectId: 'prj_demo1', - taskId: 'task_demo_attention', - ownerRoleId: 'xingbu', - fileRef: '.scratch/preview-workbench/缺失的验收单.pdf', - displayName: '缺失的验收单.pdf', - mediaType: 'application/pdf', - versionOrHash: 'sha256:preview-demo-missing', - verification: { status: 'missing' }, - existence: 'missing', - revision: 1, - sourceResultId: null, - createdAt: '2026-11-09T22:13:20.000Z', - updatedAt: '2026-11-09T22:13:20.000Z', - }, - { - id: 'artifact_demo_unknown', - projectId: 'prj_demo1', - taskId: 'task_demo_running', - ownerRoleId: 'gongbu', - fileRef: '.scratch/preview-workbench/待核验的交付物.zip', - displayName: '待核验的交付物.zip', - mediaType: 'application/zip', - versionOrHash: 'sha256:preview-demo-unknown', - verification: { status: 'unknown' }, - existence: 'unknown', - revision: 1, - sourceResultId: null, - createdAt: '2026-11-09T22:13:40.000Z', - updatedAt: '2026-11-09T22:13:40.000Z', - }, - { - id: 'artifact_demo_revision', - projectId: 'prj_demo1', - taskId: 'task_demo_revision', - ownerRoleId: 'gongbu', - fileRef: 'docs/preview/v01-workbench-rail-400-light.png', - displayName: '预览截图(第 2 版).png', - mediaType: 'image/png', - versionOrHash: 'sha256:preview-demo-revision-2', - verification: { status: 'verified' }, - existence: 'present', - revision: 2, - revisesArtifactId: 'artifact_demo_light', - sourceResultId: null, - createdAt: '2026-11-09T22:16:10.000Z', - updatedAt: '2026-11-09T22:16:10.000Z', - }, -] - -const PROJECT = { - id: 'prj_demo1', - hostWorkspaceId: 'ws_demo', - displayNameCache: '演示项目', - canonicalRoot: 'C:\\demo', - status: 'active', - schemaVersion: 1, - revision: 4, - createdAt: '2026-11-09T20:00:00.000Z', - updatedAt: '2026-11-09T22:14:00.000Z', -} - -function buildSeats() { - const states = { - lead: 'idle', - gongbu: 'running', - xingbu: 'needs_attention', - } - return SEATS.map((seat) => { - const status = states[seat.roleId] || 'uninitialized' - const connected = status !== 'uninitialized' - const sessionId = connected ? `sess_${seat.roleId}` : null - const activeTask = TASKS.find( - (task) => task.ownerRoleId === seat.roleId && task.open, - ) - return { - roleId: seat.roleId, - name: seat.name, - short: seat.short, - tier: seat.tier, - group: seat.group, - column: seat.column, - row: seat.row, - duty: seat.duty, - canDispatch: seat.canDispatch, - connected, - pending: !connected, - pendingLabel: connected ? null : '尚未接通', - activeTaskId: activeTask ? activeTask.id : null, - binding: connected - ? { - id: `binding_${seat.roleId}`, - currentSessionId: sessionId, - bindingGeneration: 1, - status, - historyCount: 0, - revision: 1, - } - : null, - config: { - provider: 'magpie', - model: 'workbuddy/deepseek-v4.1-flash', - reasoningEffort: 'high', - configRevision: 3, - configured: true, - }, - session: { - running: seat.roleId === 'gongbu', - available: true, - }, - } - }) -} - -function buildBootstrap() { - const seats = buildSeats() - return { - projects: [ - { - ...PROJECT, - seatCount: SEATS.length, - taskCount: TASKS.length, - openTaskCount: TASKS.filter((task) => task.open).length, - }, - ], - projectId: PROJECT.id, - project: { ...PROJECT }, - seats, - layout: { - lead: ['lead'], - chancellery: ['zhongshu', 'shangshu', 'menxia'], - sansheng: ['zhongshu', 'shangshu', 'menxia'], - ministries: [ - ['libu', 'hubu', 'lipu'], - ['bingbu', 'xingbu', 'gongbu'], - ], - }, - tasks: TASKS, - artifacts: ARTIFACTS, - results: [], - eventSeq: 42, - } -} - -// #endregion - -// #region 伪浏览器环境 + fetch 打桩 - -function createDemoStorage() { - const store = new Map([ - [ - 'sansheng-liubu.route.gongbu', - JSON.stringify({ provider: 'deepseek', model: 'deepseek-v4', reasoningEffort: 'high' }), - ], - ]) - return { - getItem: (key) => (store.has(key) ? store.get(key) : null), - setItem: (key, value) => { store.set(key, String(value)) }, - removeItem: (key) => { store.delete(key) }, - clear: () => { store.clear() }, - key: () => null, - get length() { return store.size }, - } -} - -function routePath(input) { - const raw = typeof input === 'string' - ? input - : input && typeof input.url === 'string' - ? input.url - : String(input) - try { - return new URL(raw, 'http://preview.local').pathname - } catch (error) { - return raw.split('?')[0] - } -} - -function makeResponse(status, payload) { - const text = JSON.stringify(payload) - return { - ok: status >= 200 && status < 300, - status, - statusText: status === 200 ? 'OK' : 'Error', - headers: { get: (name) => (String(name).toLowerCase() === 'content-type' ? 'application/json' : null) }, - json: async () => JSON.parse(text), - text: async () => text, - clone() { return makeResponse(status, payload) }, - } -} - -function createFetchStub(theme, onUnknown) { - const unknown = new Set() - const routes = new Map([ - [`${ROUTE_PREFIX}/bootstrap`, () => buildBootstrap()], - [`${ROUTE_PREFIX}/events`, () => ({ events: [], reset: false, seq: 42, hasMore: false })], - [`${ROUTE_PREFIX}/projects`, () => buildBootstrap().projects], - [`${ROUTE_PREFIX}/seats`, () => buildSeats()], - [`${ROUTE_PREFIX}/layout`, () => buildBootstrap().layout], - [`${ROUTE_PREFIX}/tasks`, () => TASKS], - [`${ROUTE_PREFIX}/artifacts`, () => ARTIFACTS], - [`${ROUTE_PREFIX}/results`, () => []], - ]) - return async function fetchStub(input, init) { - const path = routePath(input) - const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase() - const factory = routes.get(path) - if (factory) return makeResponse(200, { ok: true, value: factory() }) - if (!unknown.has(path)) { - unknown.add(path) - if (typeof onUnknown === 'function') onUnknown(path, method) - } - // 未知路由不抛错:尽量让面板继续渲染,而不是整页空白。 - const fallback = path.endsWith('s') ? [] : {} - return makeResponse(200, { ok: true, value: fallback, previewStub: true }) - } -} - -function createBrowserEnv({ theme, fetchStub }) { - const styleTexts = [] - const listeners = new Map() - - const document = { - getElementById: () => null, - querySelector: () => null, - querySelectorAll: () => [], - createElement(tagName) { - return { - tagName: String(tagName).toUpperCase(), - dataset: {}, - style: {}, - classList: { add() {}, remove() {}, toggle() {}, contains: () => false }, - textContent: '', - innerHTML: '', - setAttribute() {}, - removeAttribute() {}, - appendChild() {}, - remove() {}, - addEventListener() {}, - removeEventListener() {}, - getBoundingClientRect: () => ({ width: 0, height: 0, top: 0, left: 0 }), - } - }, - createTextNode(text) { - return { textContent: String(text) } - }, - head: { - appendChild(node) { - if (node && typeof node.textContent === 'string' && node.textContent.trim() !== '') { - styleTexts.push(node.textContent) - } - }, - }, - body: { - appendChild() {}, - removeChild() {}, - }, - documentElement: { - dataset: {}, - style: {}, - classList: { add() {}, remove() {}, toggle() {}, contains: () => false }, - setAttribute() {}, - getAttribute: () => null, - }, - addEventListener(type, handler) { - const list = listeners.get(type) || [] - list.push(handler) - listeners.set(type, list) - }, - removeEventListener() {}, - visibilityState: 'visible', - hidden: false, - cookie: '', - } - - const window = { - document, - location: { href: 'http://preview.local/', pathname: '/', origin: 'http://preview.local', search: '' }, - navigator: { userAgent: 'preview-workbench', language: 'zh-CN', languages: ['zh-CN'], platform: 'Win32' }, - localStorage: createDemoStorage(), - sessionStorage: createDemoStorage(), - devicePixelRatio: 2, - innerWidth: 400, - innerHeight: 800, - matchMedia(query) { - const wantsDark = theme === 'dark' && /prefers-color-scheme\s*:\s*dark/i.test(String(query)) - return { - matches: wantsDark, - media: String(query), - addEventListener() {}, - removeEventListener() {}, - addListener() {}, - removeListener() {}, - onchange: null, - } - }, - getComputedStyle: () => ({ getPropertyValue: () => '' }), - // bundle 里有事件轮询(setTimeout 链 / setInterval)。这些计时器若保持 - // ref 状态,截图跑完后 Node 永远不会退出。unref 掉:只要主流程结束, - // 进程就能正常收尾,同时轮询在存活期间照常执行。 - requestAnimationFrame: (callback) => unrefTimer(setTimeout(() => callback(Date.now()), 0)), - cancelAnimationFrame: (handle) => clearTimeout(handle), - addEventListener(type, handler) { - const list = listeners.get(type) || [] - list.push(handler) - listeners.set(type, list) - }, - removeEventListener() {}, - fetch: fetchStub, - alert() {}, - focus() {}, - scrollTo() {}, - } - - class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} - } - class IntersectionObserver { - constructor(callback) { this.callback = callback } - observe() {} - unobserve() {} - disconnect() {} - } - class MutationObserver { - observe() {} - disconnect() {} - } - - return { document, window, styleTexts, ResizeObserver, IntersectionObserver, MutationObserver } -} - -// #endregion - -// #region 加载 bundle + React / hooks 替身 - -function createHooks() { - const slotMap = new Map() - const instanceMap = new Map() - const contextStack = [] - const keyStack = [] - const cursorStack = [] - let currentKey = null - let cursor = 0 - let dirty = false - let effectQueue = [] - let idCounter = 0 - - const markDirty = () => { dirty = true } - - const depsEqual = (a, b) => { - if (a === undefined) return false - if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false - return a.every((value, index) => Object.is(value, b[index])) - } - - const rootKey = '' - const slotsFor = (key) => { - let slots = slotMap.get(key) - if (!slots) { - slots = [] - slotMap.set(key, slots) - } - return slots - } - const useSlot = () => { - const key = currentKey === null ? rootKey : currentKey - const slots = slotsFor(key) - const index = cursor - cursor += 1 - if (!slots[index]) slots[index] = {} - return slots[index] - } - - class Component { - constructor(props) { - this.props = props || {} - this.state = {} - this.context = undefined - } - setState(partial) { - const next = typeof partial === 'function' ? partial(this.state) : partial - this.state = { ...this.state, ...(next || {}) } - markDirty() - } - forceUpdate() { markDirty() } - } - Component.prototype.isReactComponent = {} - - function createElement(type, config, ...children) { - const props = { ...(config || {}) } - if (children.length === 1) props.children = children[0] - else if (children.length > 1) props.children = children - return { type, props, children } - } - - function createContext(defaultValue) { - const context = { - _defaultValue: defaultValue, - _stack: [], - } - context.Provider = function ContextProvider(props) { - return props.children - } - context.Provider.__previewContext = context - context.Consumer = function ContextConsumer(props) { - const value = context._stack.length > 0 - ? context._stack[context._stack.length - 1] - : context._defaultValue - return typeof props.children === 'function' ? props.children(value) : null - } - context.Consumer.__previewContext = context - return context - } - - const React = { - createElement, - cloneElement: (element, extraProps, ...children) => { - const props = { ...(element.props || {}), ...(extraProps || {}) } - if (children.length === 1) props.children = children[0] - else if (children.length > 1) props.children = children - return { type: element.type, props, children } - }, - isValidElement: (value) => Boolean(value && typeof value === 'object' && value.type !== undefined), - createContext, - Component, - PureComponent: Component, - Fragment: 'fragment', - StrictMode: 'fragment', - Suspense: function Suspense(props) { return props.children }, - memo: (component) => component, - forwardRef: (render) => function ForwardRefComponent(props) { - return render(props, props && props.ref ? props.ref : { current: null }) - }, - useContext(context) { - if (!context || !Array.isArray(context._stack)) return undefined - return context._stack.length > 0 - ? context._stack[context._stack.length - 1] - : context._defaultValue - }, - useState(initial) { - const slot = useSlot() - if (!('value' in slot)) { - slot.value = typeof initial === 'function' ? initial() : initial - } - const setState = (next) => { - const value = typeof next === 'function' ? next(slot.value) : next - if (Object.is(value, slot.value)) return - slot.value = value - markDirty() - } - return [slot.value, setState] - }, - useReducer(reducer, initialArg, init) { - const slot = useSlot() - if (!('value' in slot)) { - slot.value = typeof init === 'function' ? init(initialArg) : initialArg - } - const dispatch = (action) => { - const value = reducer(slot.value, action) - if (Object.is(value, slot.value)) return - slot.value = value - markDirty() - } - return [slot.value, dispatch] - }, - useRef(initial) { - const slot = useSlot() - if (!('ref' in slot)) slot.ref = { current: initial } - return slot.ref - }, - useEffect(effect, deps) { - const slot = useSlot() - if (!depsEqual(slot.deps, deps)) { - slot.deps = deps ? deps.slice() : undefined - const previousCleanup = slot.cleanup - effectQueue.push(() => { - if (typeof previousCleanup === 'function') previousCleanup() - const cleanup = effect() - slot.cleanup = typeof cleanup === 'function' ? cleanup : undefined - }) - } - }, - useLayoutEffect(effect, deps) { - React.useEffect(effect, deps) - }, - useInsertionEffect(effect, deps) { - React.useEffect(effect, deps) - }, - useMemo(factory, deps) { - const slot = useSlot() - if (!depsEqual(slot.deps, deps)) { - slot.deps = deps ? deps.slice() : undefined - slot.value = factory() - } - return slot.value - }, - useCallback(fn, deps) { - const slot = useSlot() - if (!depsEqual(slot.deps, deps)) { - slot.deps = deps ? deps.slice() : undefined - slot.value = fn - } - return slot.value - }, - useImperativeHandle(ref, create, deps) { - const slot = useSlot() - if (!depsEqual(slot.deps, deps)) { - slot.deps = deps ? deps.slice() : undefined - const value = create() - if (ref && typeof ref === 'object') ref.current = value - else if (typeof ref === 'function') ref(value) - } - }, - useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - const slot = useSlot() - if (!slot.subscribed) { - slot.subscribed = true - try { - slot.value = getSnapshot() - } catch (error) { - slot.value = typeof getServerSnapshot === 'function' ? getServerSnapshot() : undefined - } - if (typeof subscribe === 'function') { - try { - const unsubscribe = subscribe(() => { - let next - try { - next = getSnapshot() - } catch (error) { - return - } - if (!Object.is(next, slot.value)) { - slot.value = next - markDirty() - } - }) - if (typeof unsubscribe === 'function') slot.unsubscribe = unsubscribe - } catch (error) { - // 预览里订阅失败不阻断渲染 - } - } - } - return slot.value - }, - useId() { - idCounter += 1 - return `:pv${idCounter}:` - }, - useDebugValue() {}, - useTransition() { return [false, (callback) => { callback() }] }, - useDeferredValue(value) { return value }, - } - - return { - React, - enter(key) { - keyStack.push(currentKey) - cursorStack.push(cursor) - currentKey = key - cursor = 0 - }, - leave() { - currentKey = keyStack.length > 0 ? keyStack.pop() : null - cursor = cursorStack.length > 0 ? cursorStack.pop() : 0 - }, - beginRender() { - cursor = 0 - effectQueue = [] - }, - runEffects() { - const queue = effectQueue - effectQueue = [] - for (const effect of queue) effect() - return queue.length - }, - consumeDirty() { - const value = dirty - dirty = false - return value - }, - instanceMap, - } -} - -function loadBundle(sourcePath, hooks, options) { - if (!existsSync(sourcePath)) fail(`找不到 bundle:${sourcePath}`) - const source = readFileSync(sourcePath, 'utf8').replace(/^\uFEFF/, '') - if (!source.includes('__ModuleLoader__')) { - fail(`${sourcePath} 看起来不是 DSH 客户端 bundle(未找到 __ModuleLoader__)。`) - } - - const { React } = hooks - const env = createBrowserEnv({ - theme: options.theme, - fetchStub: options.fetchStub || createFetchStub(options.theme, (path, method) => { - log(`fetch 未命中固定数据:${method} ${path}(返回空对象/数组占位)`) - }), - }) - const { document, window, styleTexts } = env - let loaded = null - - window.__ModuleLoader__ = { - load(registration) { - loaded = registration - const module = { exports: {} } - const requireStub = (name) => { - if (name === 'react') return React - throw new Error(`预览加载器不认识的模块:${name}(只支持 react)`) - } - const exported = registration.factory(requireStub) - if (exported !== undefined) module.exports = exported - loaded.exports = module.exports - }, - } - - const sandbox = { - window, - document, - console, - URL, - URLSearchParams, - Map, - Set, - WeakMap, - WeakSet, - Promise, - Symbol, - Proxy, - Reflect, - Date, - Math, - JSON, - Number, - String, - Boolean, - Array, - Object, - Error, - TypeError, - RangeError, - RegExp, - Intl, - TextEncoder, - TextDecoder, - setTimeout: (callback, delay, ...args) => unrefTimer(setTimeout(callback, delay, ...args)), - clearTimeout, - setInterval: (callback, delay, ...args) => unrefTimer(setInterval(callback, delay, ...args)), - clearInterval, - setImmediate, - clearImmediate, - queueMicrotask, - structuredClone, - fetch: window.fetch, - localStorage: window.localStorage, - sessionStorage: window.sessionStorage, - matchMedia: window.matchMedia, - requestAnimationFrame: window.requestAnimationFrame, - cancelAnimationFrame: window.cancelAnimationFrame, - getComputedStyle: window.getComputedStyle, - ResizeObserver: env.ResizeObserver, - IntersectionObserver: env.IntersectionObserver, - MutationObserver: env.MutationObserver, - devicePixelRatio: window.devicePixelRatio, - innerWidth: window.innerWidth, - innerHeight: window.innerHeight, - navigator: window.navigator, - location: window.location, - addEventListener: window.addEventListener, - removeEventListener: window.removeEventListener, - } - sandbox.globalThis = sandbox - sandbox.self = sandbox - - try { - vm.runInNewContext(source, sandbox, { filename: sourcePath, timeout: 30000 }) - } catch (error) { - fail(`加载 bundle 失败(${sourcePath}):\n${error && error.stack ? error.stack : error}`) - } - if (!loaded || !loaded.exports) fail(`bundle 没有调用 __ModuleLoader__.load:${sourcePath}`) - - // 保留 bundle 自己注册样式的插入顺序(后面的覆盖前面的),只做去重, - // 避免按长度排序改变级联顺序、把主题变量覆盖错。 - const seen = new Set() - const cssParts = [] - for (const text of styleTexts) { - if (!text || text.trim() === '' || seen.has(text)) continue - seen.add(text) - cssParts.push(text) - } - const css = cssParts.join('\n') - - return { - exports: loaded.exports, - css, - sourcePath, - document, - window, - styleTexts, - } -} - -// #endregion - -// #region vnode → HTML - -const VOID_TAGS = new Set([ - 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', - 'link', 'meta', 'param', 'source', 'track', 'wbr', -]) - -const ATTR_ALIASES = { - className: 'class', - htmlFor: 'for', - tabIndex: 'tabindex', - colSpan: 'colspan', - rowSpan: 'rowspan', - maxLength: 'maxlength', - minLength: 'minlength', - readOnly: 'readonly', - autoFocus: 'autofocus', - autoComplete: 'autocomplete', - viewBox: 'viewBox', - preserveAspectRatio: 'preserveAspectRatio', - strokeWidth: 'stroke-width', - strokeLinecap: 'stroke-linecap', - strokeLinejoin: 'stroke-linejoin', - strokeDasharray: 'stroke-dasharray', - fillRule: 'fill-rule', - clipRule: 'clip-rule', - xmlnsXlink: 'xmlns:xlink', -} - -const BOOLEAN_ATTRS = new Set([ - 'disabled', 'checked', 'selected', 'hidden', 'readonly', 'required', - 'multiple', 'open', 'autofocus', 'novalidate', 'formnovalidate', -]) - -function escapeText(value) { - return String(value) - .replace(/&/g, '&') - .replace(//g, '>') -} - -function escapeAttr(value) { - return String(value) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') -} - -function kebabStyleName(name) { - if (name.startsWith('--')) return name - if (name === 'msTransform') return '-ms-transform' - const prefixed = name.replace(/^(Webkit|Moz|O)(?=[A-Z])/, (match) => `-${match.toLowerCase()}`) - return prefixed.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`) -} - -const UNITLESS_STYLES = new Set([ - 'line-height', 'opacity', 'font-weight', 'z-index', 'flex', 'flex-grow', - 'flex-shrink', 'order', 'zoom', 'aspect-ratio', 'flex-basis', -]) - -function styleToString(style) { - if (!style || typeof style !== 'object') return '' - const parts = [] - for (const [name, raw] of Object.entries(style)) { - if (raw === null || raw === undefined || raw === false) continue - const key = kebabStyleName(name) - let value = raw - if (typeof value === 'number' && value !== 0 && !UNITLESS_STYLES.has(key)) value = `${value}px` - parts.push(`${key}:${value}`) - } - return parts.join(';') -} - -function buildAttributes(type, props) { - const attrs = [] - for (const [rawName, rawValue] of Object.entries(props || {})) { - if (rawName === 'children' || rawName === 'key' || rawName === 'ref') continue - if (rawName === '__self' || rawName === '__source') continue - if (rawName === 'dangerouslySetInnerHTML') continue - if (rawName === 'value' && type === 'select') continue - if (rawName === 'value' && type === 'option') continue - if (rawName === 'selected' && type === 'option') continue - if (typeof rawValue === 'function' || typeof rawValue === 'symbol') continue - if (rawValue === undefined || rawValue === null) continue - - let name = rawName - if (rawName === 'className') { - name = 'class' - } else if (ATTR_ALIASES[rawName]) { - name = ATTR_ALIASES[rawName] - } else if (!rawName.includes('-') && /[A-Z]/.test(rawName)) { - name = rawName.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`) - } - - if (name === 'class') { - const value = Array.isArray(rawValue) ? rawValue.filter(Boolean).join(' ') : String(rawValue) - if (value) attrs.push(`class="${escapeAttr(value)}"`) - continue - } - if (name === 'style') { - const value = styleToString(rawValue) - if (value) attrs.push(`style="${escapeAttr(value)}"`) - continue - } - if (name.startsWith('aria-') || name.startsWith('data-')) { - attrs.push(`${name}="${escapeAttr(String(rawValue))}"`) - continue - } - if (name === 'value' && type === 'option') continue - if (BOOLEAN_ATTRS.has(name)) { - if (rawValue === true || rawValue === '') attrs.push(`${name}=""`) - continue - } - if (rawValue === false) continue - if (rawValue === true) { - attrs.push(`${name}=""`) - continue - } - attrs.push(`${name}="${escapeAttr(String(rawValue))}"`) - } - return attrs.length ? ` ${attrs.join(' ')}` : '' -} - -function serializeNode(node, options = {}) { - if (!node) return '' - if (node.text !== undefined) return escapeText(node.text) - if (node.fragment) return node.children.map((child) => serializeNode(child, options)).join('') - - const { type, props, children } = node - if (typeof type !== 'string') fail(`序列化遇到非字符串标签:${String(type)}`) - - if (type === 'select') { - const attrs = buildAttributes(type, props) - const inner = children.map((child) => serializeNode(child, { selectValue: props.value })).join('') - return `${inner}` - } - - if (type === 'option') { - const attrs = [] - for (const [name, value] of Object.entries(props || {})) { - if (name === 'children' || name === 'key' || name === 'selected' || name === 'value') continue - if (value === undefined || value === null || value === false || typeof value === 'function') continue - attrs.push(`${name}="${escapeAttr(String(value))}"`) - } - if (props && props.value !== undefined && props.value !== null) attrs.push(`value="${escapeAttr(String(props.value))}"`) - const selected = (props && props.selected === true) - || (options.selectValue !== undefined && options.selectValue !== null && props && String(props.value) === String(options.selectValue)) - if (selected) attrs.push('selected=""') - const inner = children.map((child) => serializeNode(child, options)).join('') - return `${inner}` - } - - const attrs = buildAttributes(type, props) - if (VOID_TAGS.has(type)) return `<${type}${attrs}>` - const rawHtml = props && props.dangerouslySetInnerHTML && typeof props.dangerouslySetInnerHTML.__html === 'string' - ? props.dangerouslySetInnerHTML.__html - : null - const inner = rawHtml !== null - ? rawHtml - : children.map((child) => serializeNode(child, options)).join('') - return `<${type}${attrs}>${inner}` -} - -function pickChildren(node) { - const positional = Array.isArray(node.children) ? node.children : [] - const fromProps = node.props && node.props.children !== undefined ? node.props.children : undefined - const source = positional.length > 0 ? positional : fromProps === undefined ? [] : [fromProps] - const flat = [] - for (const item of source) { - if (Array.isArray(item)) flat.push(...item) - else flat.push(item) - } - return flat -} - -function mountNode(node, hooks, depth = 0, path = '0') { - if (depth > 200) fail('组件树递归超过 200 层,疑似存在渲染死循环。') - if (node === null || node === undefined || node === false || node === true) return null - if (typeof node === 'string' || typeof node === 'number') return { text: String(node) } - if (Array.isArray(node)) { - const children = [] - for (let index = 0; index < node.length; index += 1) { - const mounted = mountNode(node[index], hooks, depth + 1, `${path}/a${index}`) - if (mounted) children.push(mounted) - } - return { fragment: true, children } - } - if (typeof node !== 'object' || node.type === undefined) { - fail(`无法渲染的节点:${JSON.stringify(node)}`) - } - - const { type } = node - const props = node.props || {} - - if (typeof type === 'function') { - if (type.__previewContext && type.__previewContext._stack) { - const context = type.__previewContext - context._stack.push(props.value) - try { - return mountNode(type(props), hooks, depth + 1, `${path}/ctx`) - } finally { - context._stack.pop() - } - } - if (type.__previewContext && type.__previewContext._stack === undefined) { - return mountNode(type(props), hooks, depth + 1, `${path}/ctx`) - } - - const key = `${path}|${type.name || 'anonymous'}` - let output - if (type.prototype && typeof type.prototype.render === 'function') { - let instance = hooks.instanceMap.get(key) - if (!instance) { - instance = new type(props) - hooks.instanceMap.set(key, instance) - } - instance.props = props - output = instance.render() - if (typeof instance.componentDidMount === 'function') { - // 用 effect 队列在本次渲染后执行,避免在 render 里做副作用 - output = output - hooks.pendingLifecycle = hooks.pendingLifecycle || [] - hooks.pendingLifecycle.push(() => instance.componentDidMount()) - } - } else { - hooks.enter(key) - try { - output = type(props) - } finally { - hooks.leave() - } - } - return mountNode(output, hooks, depth + 1, `${key}/r`) - } - - if (type === 'fragment') { - const kids = pickChildren(node) - const children = [] - for (let index = 0; index < kids.length; index += 1) { - const mounted = mountNode(kids[index], hooks, depth + 1, `${path}/f${index}`) - if (mounted) children.push(mounted) - } - return { fragment: true, children } - } - - const kids = pickChildren(node) - const children = [] - for (let index = 0; index < kids.length; index += 1) { - const mounted = mountNode(kids[index], hooks, depth + 1, `${path}/h${index}`) - if (mounted) children.push(mounted) - } - return { type, props, children } -} - -// #endregion - -// #region 旧 bundle 的演示 ctx(createHost 需要) - -const DEMO_ROLES = SEATS.map((seat) => seat.roleId) -const DEMO_LABELS = Object.fromEntries(SEATS.map((seat) => [seat.roleId, seat.name])) -const DEMO_RUNNING = new Set(['shangshu', 'hubu', 'gongbu']) -const DEMO_STATUS_TEXT = - 'Chrome、Edge 和内置 Node 都可用。我把「真实组件预览生成器」交给队友做,现在已经能出图了。' -const DEMO_NODES = new Map([ - ['demo-1', { kind: 'assistant', anchorSeq: 1, data: { blocks: [{ kind: 'text', text: DEMO_STATUS_TEXT }] } }], -]) - -function createDemoContext() { - const members = DEMO_ROLES.map((role) => ({ id: `sess-${role}`, name: role, phase: 'active' })) - const tasks = [ - { id: 'task-1', subject: '拆解 0.5.1 侧栏验收清单', status: 'in_progress', ownerName: 'zhongshu' }, - { id: 'task-2', subject: '复算朝堂统计投影', status: 'in_progress', ownerName: 'hubu' }, - { id: 'task-3', subject: '补齐右侧栏窄宽度回归', status: 'pending', ownerName: 'xingbu' }, - { id: 'task-4', subject: '整理 @ 部门入口说明', status: 'pending', ownerName: 'lipu' }, - { id: 'task-5', subject: '删除未渲染的旧样式', status: 'completed', ownerName: 'gongbu' }, - { id: 'task-6', subject: '核对十席角色文案', status: 'completed', ownerName: 'libu' }, - ] - - const byId = {} - const ids = [] - for (const role of DEMO_ROLES) { - const id = `sess-${role}` - ids.push(id) - byId[id] = { - id, - name: DEMO_LABELS[role], - updatedAt: 1_760_000_000_000 + DEMO_ROLES.indexOf(role), - running: DEMO_RUNNING.has(role), - workspaceId: 'demo-workspace', - } - } - byId[LEAD_SESSION] = { ...byId[LEAD_SESSION], subagent: undefined } - - const team = { members, tasks } - const sessionList = { - getSnapshot: () => ({ - ids: ids.slice(), - byId, - projectionsBySession: { - [LEAD_SESSION]: { - sessionId: LEAD_SESSION, - values: { - agentTeam: team, - agentPreset: 'sansheng-liubu', - subagentCatalog: [], - }, - }, - }, - phase: 'ready', - }), - subscribe: () => () => {}, - } - - const statuses = new Map() - for (const role of DEMO_ROLES) { - statuses.set(`sess-${role}`, { running: DEMO_RUNNING.has(role) }) - } - const statusStore = { - getSnapshot: () => statuses, - subscribe: () => () => {}, - } - - const catalogSnapshot = { - status: 'ready', - error: null, - current: { provider: 'openai', model: 'gpt-6-astra', reasoningEffort: 'high' }, - default: { provider: 'openai', model: 'gpt-6-astra', reasoningEffort: 'high' }, - groups: [ - { - id: 'openai', - name: 'OpenAI', - models: [ - { - id: 'gpt-6-astra', - name: 'GPT-6 Astra', - reasoning: { - defaultEffort: 'high', - efforts: [ - { id: 'low', name: '低' }, - { id: 'medium', name: '中' }, - { id: 'high', name: '高' }, - ], - }, - }, - { - id: 'gpt-6-mini', - name: 'GPT-6 Mini', - reasoning: { - defaultEffort: 'medium', - efforts: [ - { id: 'low', name: '低' }, - { id: 'medium', name: '中' }, - ], - }, - }, - ], - }, - { - id: 'deepseek', - name: 'DeepSeek', - models: [ - { - id: 'deepseek-v4', - name: 'DeepSeek V4', - reasoning: { defaultEffort: 'high', efforts: [{ id: 'high', name: '高' }] }, - }, - ], - }, - ], - } - - const binding = { - session: { - projections: { - faceOf: () => ({ getSnapshot: () => ({ model: { name: 'GPT-6 Astra' } }) }), - }, - prompt: async () => ({ ok: true }), - }, - } - - const ctx = { - effect(callback) { - const dispose = callback() - return typeof dispose === 'function' ? dispose : () => {} - }, - sessions: { - list: sessionList, - statuses: statusStore, - binding: () => binding, - subagentAddress: (sessionId) => (sessionId === LEAD_SESSION ? undefined : { parentSessionId: LEAD_SESSION, childSessionId: sessionId }), - refreshProjections: async () => {}, - }, - uiWorkspace: { - selection: { - getSnapshot: () => ({ sessionId: LEAD_SESSION }), - subscribe: () => () => {}, - set: () => {}, - }, - currentWorkspaceId: 'demo-workspace', - openSession: () => {}, - startSession: () => {}, - }, - uiConversation: { - binding: () => ({ - target: () => ({ getSnapshot: () => ({ nodes: DEMO_NODES }) }), - }), - }, - modelDirectories: { - catalog: { - load: async () => ({ - default: catalogSnapshot.current, - groups: catalogSnapshot.groups, - failures: [], - }), - store: { getSnapshot: () => ({ value: catalogSnapshot, status: 'ready', error: null }) }, - }, - directoryFor: () => ({ - load: () => Promise.resolve(), - select: () => Promise.resolve({ ok: true }), - store: { - getSnapshot: () => catalogSnapshot, - subscribe: () => () => {}, - }, - }), - }, - remote: { - agentPresets: { - list: async () => ({ ok: true, value: { presets: [] } }), - select: async () => ({ ok: true }), - }, - session: { - selectModel: async () => ({ ok: true }), - }, - commands: { - execute: async (_agentId, line) => ({ commandId: 'preview-command', result: { kind: 'success', text: line } }), - }, - subagents: { - prompt: async () => ({ messageId: 'preview-msg' }), - }, - }, - get: () => undefined, - layout: { selectPanel: () => {} }, - sidebarRight: { openTab: () => {}, openTabIn: () => {} }, - sidebarRightTabs: { register: () => () => {} }, - slots: { register: () => () => {}, inject: (name, callback) => callback() }, - } - - return { ctx, team, catalogSnapshot } -} - -// #endregion - -// #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 - if (preview) { - if (typeof preview === 'function') { - return { component: preview, props: {}, mode: '__preview(function)' } - } - if (typeof preview === 'object') { - const component = preview.component || preview.default || preview.render - if (typeof component === 'function') { - return { component, props: preview.props || {}, mode: '__preview(object)' } - } - } - } - - const preferred = [ - 'SanshengWorkbenchPanel', - 'WorkbenchPanel', - 'SanshengPanel', - 'Workbench', - 'Panel', - 'default', - ] - for (const name of preferred) { - const value = exports && exports[name] - if (typeof value === 'function') { - return { component: value, props: {}, mode: `exports.${name}` } - } - } - - // 兜底:任何名字里带 panel/workbench 的函数组件 - for (const name of keys) { - const value = exports[name] - if (typeof value === 'function' && /panel|workbench/i.test(name) && !/^create/.test(name)) { - return { component: value, props: {}, mode: `exports.${name}(name-match)` } - } - } - - return { component: null, props: {}, mode: 'placeholder', keys } -} - -// #endregion - -// #region 渲染流程 - -async function tick(times = 4) { - for (let index = 0; index < times; index += 1) { - await new Promise((resolveTick) => setImmediate(resolveTick)) - } -} - -function flushLifecycle(hooks) { - const queue = hooks.pendingLifecycle || [] - hooks.pendingLifecycle = [] - for (const callback of queue) callback() -} - -async function settle(hooks, rootVNode, budgetMs = 1500) { - const started = Date.now() - let tree = null - let passes = 0 - let settled = false - while (passes < 80) { - passes += 1 - hooks.beginRender() - tree = mountNode(rootVNode, hooks, 0, 'root') - hooks.runEffects() - flushLifecycle(hooks) - await tick(3) - if (passes > 6) await new Promise((resolveWait) => setTimeout(resolveWait, 4)) - if (!hooks.consumeDirty()) { - // 给「effect 里再排一个短定时器」的组件一点时间:最多多等一个 60ms 窗口。 - if (passes <= 3 && Date.now() - started < 400) { - await new Promise((resolveWait) => setTimeout(resolveWait, 60)) - if (hooks.consumeDirty()) { - if (Date.now() - started > budgetMs) break - continue - } - } - settled = true - break - } - if (Date.now() - started > budgetMs) break - } - return { tree, passes, settled, elapsedMs: Date.now() - started } -} - -function mountedText(node) { - if (!node) return '' - if (node.text !== undefined) return String(node.text) - if (node.fragment) return node.children.map(mountedText).join('') - const parts = [] - if (node.props && typeof node.props.children === 'string') parts.push(node.props.children) - if (Array.isArray(node.children)) parts.push(node.children.map(mountedText).join('')) - return parts.join('') -} - -function findMounted(node, predicate) { - if (!node) return null - if (predicate(node)) return node - if (node.fragment) { - for (const child of node.children) { - const hit = findMounted(child, predicate) - if (hit) return hit - } - return null - } - if (Array.isArray(node.children)) { - for (const child of node.children) { - const hit = findMounted(child, predicate) - if (hit) return hit - } - } - return null -} - -function classNameOf(node) { - const value = node && node.props ? node.props.className : '' - return typeof value === 'string' ? value.split(/\s+/).filter(Boolean) : [] -} - -function clickMounted(node) { - if (!node || !node.props || typeof node.props.onClick !== 'function') return false - try { - node.props.onClick({ - preventDefault() {}, - stopPropagation() {}, - target: {}, - currentTarget: {}, - }) - return true - } catch (error) { - log(`模拟点击失败:${error && error.message ? error.message : error}`) - return false - } -} - -/* 静态 HTML 里没有 React 运行时,Chrome 里点页签不会触发组件状态。 - 这里直接在替身的 vnode 上调 onClick,再重渲染一遍抓取目标页签/抽屉。 */ -async function switchPreviewState(hooks, rootVNode, view, openText, initialTree) { - const labels = { court: '朝堂', tasks: '任务', artifacts: '成果' } - const label = labels[view] - const result = { clickedTab: null, openedArtifact: null } - if (!label) return { ...result, tree: initialTree, passes: 0 } - const tab = findMounted(initialTree, (node) => { - const classes = classNameOf(node) - return node.type === 'button' && classes.includes('wb-tab') && mountedText(node).includes(label) - }) - if (!tab) { - log(`没有找到「${label}」页签,保持当前视图`) - return { ...result, tree: initialTree, passes: 0 } - } - clickMounted(tab) - let next = await settle(hooks, rootVNode, 1500) - let extraPasses = next.passes - result.clickedTab = label - if (openText) { - const artifact = findMounted(next.tree, (node) => { - const classes = classNameOf(node) - if (!classes.includes('wb-artifact')) return false - const haystack = `${mountedText(node)} ${node.props && node.props.title ? node.props.title : ''}` - return haystack.includes(openText) - }) - if (!artifact) { - log(`成果页里没有匹配「${openText}」的行,抽屉不打开`) - } else if (clickMounted(artifact)) { - result.openedArtifact = openText - next = await settle(hooks, rootVNode, 1500) - extraPasses += next.passes - } - } - return { ...result, tree: next.tree, passes: extraPasses } -} - -/* 在真实 Chrome 里按最终 DOM 的 rect 重算连线。 - React 替身环境里 getBoundingClientRect 全是 0,bundle 的 measure() 会退到 - computeRailLayout 的几何坐标;那套坐标和真实 CSS 布局(rail 内边距、 - 行高、卡片实际高度)不是同一套,端点会落在卡片上方。这里在页面加载后 - 用真浏览器的 rect 重写 4 条 path,公式与 bundle 的 branchPathD / trunk 完全一致: - 分叉:M cx0 y0 V mid C cx0 y1 cx1 mid cx1 y1 (mid = y0 + (y1-y0)*0.55) - 主干:M cx bottom L cx group.top - 只跑一次(成功即 done),失败留给后续 tick 重试,不挂 MutationObserver。 */ -const WIRE_RECOMPUTE = ` -(function () { - var done = false; - function r(value) { return Math.round(Number(value) * 10) / 10; } - function rel(element, box) { - var rect = element.getBoundingClientRect(); - return { - top: rect.top - box.top, - bottom: rect.bottom - box.top, - left: rect.left - box.left, - cx: rect.left - box.left + rect.width / 2, - width: rect.width, - height: rect.height - }; - } - function recompute() { - if (done) return; - var tree = document.querySelector('.wb-tree'); - if (!tree) return; - var svg = tree.querySelector('svg.wb-wires'); - var leadEl = tree.querySelector('.wb-lead-row .wb-card'); - var trioEls = tree.querySelectorAll('.wb-trio > .wb-card'); - var groupEl = tree.querySelector('.wb-group'); - var pathEls = tree.querySelectorAll('svg.wb-wires path'); - if (!svg || !leadEl || trioEls.length < 3 || !groupEl || pathEls.length < 4) return; - - var box = tree.getBoundingClientRect(); - if (!box || !box.width || !box.height) return; - - var lead = rel(leadEl, box); - var sansheng = [rel(trioEls[0], box), rel(trioEls[1], box), rel(trioEls[2], box)]; - var group = rel(groupEl, box); - var before = []; - for (var i = 0; i < pathEls.length; i++) before.push(pathEls[i].getAttribute('d') || ''); - - var y0 = lead.bottom; - for (var j = 0; j < 3; j++) { - var y1 = sansheng[j].top; - if (!(y1 > y0)) return; - var mid = y0 + (y1 - y0) * 0.55; - pathEls[j].setAttribute('d', - 'M ' + r(lead.cx) + ' ' + r(y0) + - ' V ' + r(mid) + - ' C ' + r(lead.cx) + ' ' + r(y1) + ' ' + r(sansheng[j].cx) + ' ' + r(mid) + - ' ' + r(sansheng[j].cx) + ' ' + r(y1)); - } - if (!(group.top > sansheng[1].bottom)) return; - pathEls[3].setAttribute('d', - 'M ' + r(sansheng[1].cx) + ' ' + r(sansheng[1].bottom) + - ' L ' + r(sansheng[1].cx) + ' ' + r(group.top)); - - svg.setAttribute('width', String(Math.round(box.width))); - svg.setAttribute('height', String(Math.round(box.height))); - - var after = []; - for (var k = 0; k < pathEls.length; k++) after.push(pathEls[k].getAttribute('d') || ''); - var report = { - applied: true, - box: { width: box.width, height: box.height }, - lead: lead, - sansheng: sansheng, - group: group, - before: before, - after: after - }; - var marker = document.getElementById('pv-wires'); - if (!marker) { - marker = document.createElement('script'); - marker.type = 'application/json'; - marker.id = 'pv-wires'; - document.body.appendChild(marker); - } - marker.textContent = JSON.stringify(report); - document.documentElement.setAttribute('data-pv-wires', 'applied'); - done = true; - } - function tick() { - try { recompute(); } catch (error) { - document.documentElement.setAttribute('data-pv-wires', 'error:' + String(error && error.message || error)); - } - } - if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', tick); - else tick(); - requestAnimationFrame(function () { requestAnimationFrame(tick); }); - window.addEventListener('load', tick); - setTimeout(tick, 60); - setTimeout(tick, 250); - setTimeout(tick, 800); -})(); -` - -function buildPage({ css, panelHtml, width, theme }) { - const dark = theme === 'dark' - const shellCss = ` -*{box-sizing:border-box} -html,body{margin:0;padding:0} -body{ - background:#eef0f4;color:#1f2329; - font-family:"Segoe UI","Microsoft YaHei",-apple-system,BlinkMacSystemFont,"Helvetica Neue",Arial,sans-serif; - -webkit-font-smoothing:antialiased; -} -.pv-shell{width:${width}px;min-height:100vh;display:flex;flex-direction:column;background:#f7f8fa;overflow:hidden} -.pv-chat-head{ - flex:0 0 auto;display:flex;align-items:center;gap:8px; - padding:10px 12px;background:#ffffff;border-bottom:1px solid #e2e6ec; - font-size:12px;line-height:18px;color:#5b6472; -} -.pv-chat-avatar{ - width:24px;height:24px;border-radius:50%; - background:linear-gradient(135deg,#5b8def,#8a63f4);color:#fff; - display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600; -} -.pv-chat-title{font-weight:600;color:#1f2329;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -.pv-chat-sub{margin-left:auto;font-size:11px;color:#8b93a1;white-space:nowrap} -.pv-panel{flex:1 1 auto;min-height:0;padding:10px 12px 16px;overflow:visible} -.pv-shell .sl-root{height:auto!important;min-height:0!important;background:transparent!important;color:inherit} -.pv-shell .sl-body{background:transparent} -.pv-shell .sl-body-sidebar{padding:0;overflow:visible} -.pv-shell .sl-body-sidebar .sl-right{overflow:visible;padding-right:0} -.pv-placeholder{ - border:1px dashed #b6bfcc;border-radius:8px;padding:12px;background:#fff;color:#1f2329; - font-size:12px;line-height:1.5; -} -.pv-placeholder h3{margin:0 0 6px;font-size:13px} -.pv-placeholder pre{ - margin:8px 0 0;padding:8px;background:#f2f4f7;border-radius:6px; - font-size:11px;white-space:pre-wrap;word-break:break-all;color:#475063; -} -html.dark body{background:#0e1014;color:#e8eaee} -html.dark .pv-shell{background:#111318} -html.dark .pv-chat-head{background:#16181d;border-bottom-color:#262a32;color:#a9b0bd} -html.dark .pv-chat-title{color:#e8eaee} -html.dark .pv-chat-sub{color:#7f8794} -html.dark .pv-placeholder{background:#1a1d24;border-color:#333a46;color:#e8eaee} -html.dark .pv-placeholder pre{background:#22262f;color:#c7cedb} -` - - const darkOverride = dark - ? ` -/* 兜底:bundle 若用媒体查询切暗色,--blink-settings=preferredColorScheme=0 已生效; - 若用 .dark 类名切暗色,这里保证外壳的语义变量也进入暗色。 */ -html.dark{ - color-scheme:dark; - --dsw-alias-bg-layer-1:#1f222a; - --dsw-alias-bg-layer-2:#16181d; - --dsw-alias-bg-layer-3:rgba(255,255,255,.10); - --dsw-alias-label-primary:#e8eaee; - --dsw-alias-label-secondary:#b7bcc6; - --dsw-alias-label-tertiary:#8b93a1; - --dsw-alias-label-caption:#7f8794; - --dsw-alias-border-l1:rgba(255,255,255,.12); - --dsw-alias-border-l2:rgba(255,255,255,.18); - --dsw-alias-border-l3:rgba(255,255,255,.28); - --dsw-alias-state-business-primary:#6b8afd; - --dsw-alias-state-error-primary:#f2777a; -} -` - : '' - - const html = ` - - - - -三省六部 · 工作台预览 (${theme} / ${width}px) - - - -
-
-
三
-
三省六部 · 工作台
-
${theme} · ${width}px
-
-
-${panelHtml} -
-
- - - - - -` - return html -} - -function measureHeight(chrome, htmlPath, width, theme, profileDir) { - const args = [ - '--headless=new', - '--disable-gpu', - '--disable-crash-reporter', - '--disable-breakpad', - '--no-first-run', - '--hide-scrollbars', - `--window-size=${width},200`, - '--force-device-scale-factor=1', - '--virtual-time-budget=3000', - '--dump-dom', - `--user-data-dir=${profileDir}`, - ] - if (theme === 'dark') args.push('--blink-settings=preferredColorScheme=0') - args.push(pathToFileURL(htmlPath).href) - const result = chromeRun(chrome, args, '量高') - const dom = String(result.stdout || '') - const match = /id="pv-height"[^>]*>([0-9]+)]*>([\s\S]*?)<\/script>/.exec(dom) - if (wireMatch) { - const raw = wireMatch[1] - .replace(/"/g, '"') - .replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - try { - wires = JSON.parse(raw) - } catch (error) { - log(`连线重算结果解析失败:${error && error.message ? error.message : error}`) - } - } - return { height, wires, dom } -} - -function screenshot(chrome, htmlPath, pngPath, width, height, theme, scale, profileDir) { - const args = [ - '--headless=new', - '--disable-gpu', - '--disable-crash-reporter', - '--disable-breakpad', - '--no-first-run', - '--hide-scrollbars', - `--window-size=${width},${height}`, - `--force-device-scale-factor=${scale}`, - '--virtual-time-budget=2000', - `--screenshot=${pngPath}`, - `--user-data-dir=${profileDir}`, - ] - if (theme === 'dark') args.push('--blink-settings=preferredColorScheme=0') - args.push(pathToFileURL(htmlPath).href) - chromeRun(chrome, args, '截图') - if (!existsSync(pngPath)) fail(`Chrome 没有写出截图:${pngPath}`) - const size = readPngSize(pngPath) - const expectedWidth = width * scale - if (size.width !== expectedWidth) { - fail(`截图宽度异常:期望 ${expectedWidth}px,实际 ${size.width}px(${pngPath})`) - } - if (size.bytes < 3000) { - fail(`截图疑似空白:${pngPath} 只有 ${size.bytes} 字节`) - } - return size -} - -async function main() { - const options = parseArgs(process.argv.slice(2)) - if (options.help) { - process.stdout.write(`${usage()}\n`) - return - } - - const theme = String(options.theme) - if (theme !== 'light' && theme !== 'dark') fail(`--theme 只能是 light 或 dark,收到:${theme}`) - const width = Number.parseInt(options.width, 10) - if (!Number.isFinite(width) || width < 200 || width > 1200) fail(`--width 需要在 200–1200 之间,收到:${options.width}`) - const scale = Number.parseInt(options.scale, 10) - if (!Number.isFinite(scale) || scale < 1 || scale > 4) fail(`--scale 需要在 1–4 之间,收到:${options.scale}`) - const name = String(options.name) - if (!/^[A-Za-z0-9._-]+$/.test(name)) fail(`--name 只允许字母、数字、点、下划线和短横线,收到:${name}`) - const view = String(options.view || 'court') - if (!['court', 'tasks', 'artifacts'].includes(view)) fail(`--view 只能是 court / tasks / artifacts,收到:${view}`) - const openText = String(options.open || '') - 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) - ensureDir(SCRATCH) - ensureDir(outDir) - - if (!existsSync(bundlePath)) { - fail(`bundle 不存在:${bundlePath}\n(相对路径按仓库根目录解析:${ROOT})`) - } - - const pngPath = join(outDir, `${name}-${width}-${theme}.png`) - const htmlPath = join(SCRATCH, `${name}-${width}-${theme}.html`) - 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, fetchStub: live ? live.fetchLive : null }) - log(`bundle 导出键:${Object.keys(loaded.exports).join(', ') || '(空)'}`) - log(`捕获 CSS:${loaded.css.length} 字符`) - - const picked = pickComponent(loaded.exports) - log(`渲染入口:${picked.mode}`) - - let component = picked.component - let props = { ...picked.props } - let placeholder = false - let entryMode = picked.mode - - 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}`) - component = () => hooks.React.createElement( - 'div', - { className: 'pv-placeholder' }, - hooks.React.createElement('h3', null, '预览占位'), - hooks.React.createElement('p', null, '这个 bundle 没有导出 __preview,也没有可识别的默认面板组件。'), - hooks.React.createElement('pre', null, `导出键:${keyList}`), - ) - props = {} - } else if (typeof loaded.exports.createHost === 'function') { - try { - const demo = createDemoContext() - props = { - ...props, - host: loaded.exports.createHost(demo.ctx), - sessionId: LEAD_SESSION, - compact: true, - } - log('已用 createHost(ctx) 构造旧式 host') - } catch (error) { - log(`createHost 失败,改为直接传 props:${error && error.message ? error.message : error}`) - } - } - - 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) - const settleResult = await settle(hooks, rootVNode, 1500) - log(`渲染稳定:${settleResult.settled ? '是' : '否(达到 1.5s 预算)'},${settleResult.passes} 轮,${settleResult.elapsedMs}ms`) - - let tree = settleResult.tree - let stateSwitch = { clickedTab: null, openedArtifact: null } - 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 } - settleResult.passes += switched.passes - log(`视图切换:${stateSwitch.clickedTab || '(未切换)'}${stateSwitch.openedArtifact ? `,已打开成果「${stateSwitch.openedArtifact}」` : ''}`) - } - - const panelHtml = serializeNode(tree) - const html = buildPage({ css: loaded.css, panelHtml, width, theme }) - writeFileSync(htmlPath, html, 'utf8') - log(`HTML:${htmlPath}(${html.length} 字符,面板 DOM ${panelHtml.length} 字符)`) - - const chrome = findChrome(options.chrome) - log(`Chrome:${chrome}`) - const measured = measureHeight(chrome, htmlPath, width, theme, profileDir) - const height = measured.height - log(`页面 scrollHeight:${height}px`) - - const wires = measured.wires - if (wires && wires.applied) { - log(`连线重算:已按真实 DOM rect 重写 ${wires.after.length} 条 path`) - log(` 分叉[0] before:${wires.before[0]}`) - log(` 分叉[0] after :${wires.after[0]}`) - log(` 丞相底边 y=${wires.lead.bottom},三省顶边 y=${wires.sansheng.map((card) => card.top).join('/')},六部组顶边 y=${wires.group.top}`) - log(` 端点:分支终点 y 与卡片 top 相等;主干终点 y 与 group.top 相等(${wires.group.top})`) - } else { - log('连线重算:页面里没有 .wb-tree 或未写入 #pv-wires(旧 bundle / 占位渲染属正常)') - } - - const size = screenshot(chrome, htmlPath, pngPath, width, height, theme, scale, profileDir) - log(`截图:${pngPath}(${size.width}x${size.height},${size.bytes} 字节,scale=${scale})`) - - const sourceLines = readFileSync(fileURLToPath(import.meta.url), 'utf8').split(/\r?\n/).length - const report = { - bundle: bundlePath, - bundleBase: options.bundle, - bundleBytes: statSync(bundlePath).size, - 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, - pngSize: { width: size.width, height: size.height, bytes: size.bytes }, - scrollHeight: height, - passes: settleResult.passes, - settled: settleResult.settled, - elapsedMs: settleResult.elapsedMs, - cssLength: loaded.css.length, - exportKeys: Object.keys(loaded.exports), - wireRecompute: wires && wires.applied - ? { - applied: true, - box: wires.box, - branchBefore: wires.before[0], - branchAfter: wires.after[0], - trunkBefore: wires.before[3], - trunkAfter: wires.after[3], - leadBottom: wires.lead.bottom, - sanshengTops: wires.sansheng.map((card) => card.top), - groupTop: wires.group.top, - } - : 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`) -} - -main().catch((error) => { - if (error && error.previewFailure) { - process.stderr.write(`\n[preview-workbench] 失败:${error.message}\n`) - } else { - process.stderr.write(`\n[preview-workbench] 未预期错误:${error && error.stack ? error.stack : error}\n`) - } - process.exitCode = 1 -}) diff --git a/scripts/preview.mjs b/scripts/preview.mjs deleted file mode 100644 index 27f4264..0000000 --- a/scripts/preview.mjs +++ /dev/null @@ -1,1154 +0,0 @@ -#!/usr/bin/env node -/** - * scripts/preview.mjs — 零依赖侧栏预览生成器。 - * - * 做法: - * 1. 用 vm 加载真实的 panel/lib/client.js(复用 panel/test/client.test.js 的 - * window.__ModuleLoader__.load + 最小 React/document 替身思路),并捕获 - * bundle 注入到 - - -
- -
-
-${panelHtml} -
-
-
- - - - -`, - } -} - -// #endregion - -// #region 主流程 - -async function tick(times = 4) { - for (let i = 0; i < times; i += 1) { - await new Promise((resolveTick) => setImmediate(resolveTick)) - } -} - -async function settle(hooks, rootVNode) { - let tree = null - for (let pass = 0; pass < 40; pass += 1) { - hooks.beginRender() - tree = mountNode(rootVNode) - hooks.runEffects() - await tick() - if (!hooks.consumeDirty()) return tree - } - fail('面板在 40 次渲染后仍未稳定(可能存在状态更新死循环)。') -} - -function readPngSize(pngPath) { - const bytes = readFileSync(pngPath) - if (bytes.length < 33) fail(`截图文件不完整:${pngPath}(${bytes.length} 字节)`) - const signature = bytes.subarray(0, 8).toString('hex') - if (signature !== '89504e470d0a1a0a') fail(`截图不是合法 PNG:${pngPath}`) - return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), bytes: bytes.length } -} - -function measureHeight(chrome, htmlPath, pageWidth, windowWidth, profileDir) { - const args = [ - '--headless=new', - '--disable-gpu', - '--hide-scrollbars', - '--no-first-run', - '--no-default-browser-check', - '--disable-extensions', - '--disable-background-networking', - '--disable-sync', - '--mute-audio', - `--user-data-dir=${profileDir}`, - '--virtual-time-budget=3000', - `--window-size=${windowWidth},600`, - '--dump-dom', - pathToFileURL(htmlPath).href, - ] - const result = chromeRun(chrome, args, '测量页面高度') - const match = String(result.stdout || '').match(/id="pv-height"[^>]*>(\d+) 20000) { - fail(`测量到的页面高度不合理:${height}`) - } - return height -} - -function screenshot(chrome, htmlPath, pngPath, pageWidth, height, scale, profileDir, windowWidth) { - const args = [ - '--headless=new', - '--disable-gpu', - '--hide-scrollbars', - `--force-device-scale-factor=${scale}`, - '--no-first-run', - '--no-default-browser-check', - '--disable-extensions', - '--disable-background-networking', - '--disable-sync', - '--mute-audio', - `--user-data-dir=${profileDir}`, - '--virtual-time-budget=3000', - `--window-size=${windowWidth},${height}`, - `--screenshot=${pngPath}`, - pathToFileURL(htmlPath).href, - ] - chromeRun(chrome, args, '截图') - if (!existsSync(pngPath)) fail(`Chrome 没有生成截图:${pngPath}`) - const size = readPngSize(pngPath) - if (size.bytes < 5000) fail(`截图文件过小,可能是空白图:${pngPath}(${size.bytes} 字节)`) - return size -} - -async function main() { - const options = parseArgs(process.argv.slice(2)) - const chrome = options.htmlOnly ? null : findChrome(options.chrome) - const hooks = createHooks() - const bundle = loadBundle(options.source, hooks) - - if (typeof bundle.exports.SanshengPanel !== 'function') { - fail('bundle 没有导出 SanshengPanel,无法渲染。') - } - - const { React } = hooks - const { ctx } = createDemoContext(options) - const host = bundle.exports.createHost(ctx) - const rootVNode = React.createElement(bundle.exports.SanshengPanel, { - host, - sessionId: LEAD_SESSION, - compact: true, - }) - - let tree = await settle(hooks, rootVNode) - - if (options.view === 'tasks') { - const tab = findNode(tree, (node) => node.props && node.props['data-side-tab'] === 'tasks') - if (!tab || typeof tab.props.onClick !== 'function') { - fail('找不到「任务」页签,无法切换到 tasks 视图。') - } - tab.props.onClick() - tree = await settle(hooks, rootVNode) - const activeTab = findNode(tree, (node) => node.props && node.props['data-side-tab'] === 'tasks') - if (!activeTab || activeTab.props['aria-selected'] !== true) { - fail('点击「任务」页签后没有切换到任务视图。') - } - } - - if (options.view === 'court' && options.seat !== 'lead') { - const card = findNode(tree, (node) => node.props && node.props['data-role'] === options.seat) - if (!card || typeof card.props.onClick !== 'function') { - fail(`找不到「${options.seat}」席位,无法切到该部门详情。`) - } - card.props.onClick() - tree = await settle(hooks, rootVNode) - const selected = findNode(tree, (node) => node.props && node.props['data-role'] === options.seat) - if (!selected || selected.props['aria-pressed'] !== 'true') { - fail(`点击「${options.seat}」席位后没有切换到该部门详情。`) - } - } - - const panelHtml = serializeNode(tree) - if (!panelHtml.trim()) fail('序列化后的面板 HTML 为空。') - if (panelHtml.length < 2000) fail(`面板 HTML 过短(${panelHtml.length} 字符),可能渲染不完整。`) - if (panelHtml.includes('sl-crash')) fail('面板渲染进了错误边界(出现 .sl-crash)。') - - const rootNode = findNode(tree, (node) => node.type === 'div') - if (!rootNode || rootNode.props['data-sansheng-sidebar'] !== '1') { - fail('渲染结果不是侧栏形态(缺少 data-sansheng-sidebar="1")。') - } - - // 先落中间 HTML:即使后面的校验/截图失败,也能直接打开排查。 - const page = buildPage({ viewport: options.viewport, - css: bundle.css, - panelHtml, - width: options.width, - theme: options.theme, - view: options.view, - }) - const htmlPath = join(os.tmpdir(), `dsh-preview-${process.pid}-${Date.now()}.html`) - writeFileSync(htmlPath, page.html, 'utf8') - const htmlTarget = options.html || (options.htmlOnly ? resolve(options.out, `${options.name}.html`) : null) - if (htmlTarget) { - mkdirSync(dirname(htmlTarget), { recursive: true }) - writeFileSync(htmlTarget, page.html, 'utf8') - } - - if (options.view === 'court') { - const seatCount = (panelHtml.match(/data-role="/g) || []).length - if (seatCount !== 10) fail(`朝堂应该渲染 10 个席位,实际 ${seatCount} 个。`) - const missing = Object.values(DEMO_LABELS).filter((label) => !panelHtml.includes(label)) - if (missing.length > 0) fail(`面板缺少席位:${missing.join('、')}`) - for (const key of ['在朝成员', '正在运行', '在办任务', '已完成']) { - if (!panelHtml.includes(key)) fail(`统计区缺少「${key}」。`) - } - if (!panelHtml.includes('GPT-6 Astra')) fail('模型下拉没有渲染出「GPT-6 Astra」。') - if (!panelHtml.includes('>高<')) fail('推理等级下拉没有渲染出「高」。') - } else { - if (!panelHtml.includes('任务队列')) fail('任务视图缺少「任务队列」标题。') - const taskRows = (panelHtml.match(/class="sl-task-copy"/g) || []).length - if (taskRows !== 4) fail(`任务视图应该渲染 4 条任务,实际 ${taskRows} 条。`) - } - - if (options.htmlOnly) { - if (!htmlTarget) fail('内部错误:--html-only 没有解析出 HTML 输出路径。') - const bytes = statSync(htmlTarget).size - if (bytes < 5000) fail(`HTML 过小,可能渲染不完整:${htmlTarget}(${bytes} 字节)`) - try { rmSync(htmlPath, { force: true }) } catch { /* 忽略清理失败 */ } - process.stdout.write( - `✓ ${htmlTarget}\n` + - ` HTML-only · ${bytes} 字节 · 侧栏 ${options.width}px · ` + - `视图 ${options.view} · 主题 ${options.theme}\n` + - ` CSS ${bundle.css.length} 字符 · 面板 ${panelHtml.length} 字符 · 源 ${bundle.sourcePath}\n`, - ) - return - } - - const outDir = options.out - mkdirSync(outDir, { recursive: true }) - const pngPath = join(outDir, `${options.name}.png`) - - const profileDir = join(os.tmpdir(), `dsh-preview-chrome-${process.pid}-${Date.now()}`) - mkdirSync(profileDir, { recursive: true }) - - let size - try { - const measured = measureHeight(chrome, htmlPath, page.pageWidth, page.windowWidth, profileDir) - const height = Math.max(200, Math.ceil(measured) + 2) - size = screenshot(chrome, htmlPath, pngPath, page.pageWidth, height, options.scale, profileDir, page.windowWidth) - - const expectedWidth = page.windowWidth * options.scale - if (size.width !== expectedWidth) { - fail( - `截图宽度 ${size.width}px 与预期 ${expectedWidth}px(${page.windowWidth}×${options.scale})不符,` + - '页面可能被 Chrome 缩放或窗口尺寸未生效。', - ) - } - } finally { - try { rmSync(profileDir, { recursive: true, force: true }) } catch { /* 忽略清理失败 */ } - try { rmSync(htmlPath, { force: true }) } catch { /* 忽略清理失败 */ } - } - - const seatNote = options.view === 'court' ? ' · 十席齐全' : ' · 任务队列' - process.stdout.write( - `✓ ${pngPath}\n` + - ` ${size.width}×${size.height}px @${options.scale}x · 侧栏 ${options.width}px · ` + - `视图 ${options.view} · 主题 ${options.theme}${seatNote}\n` + - ` CSS ${bundle.css.length} 字符 · HTML ${panelHtml.length} 字符 · 源 ${bundle.sourcePath}\n`, - ) - if (options.html) process.stdout.write(` 中间 HTML:${options.html}\n`) -} - -main().catch((error) => { - if (error && error.previewFailure) { - process.stderr.write(`\n[preview] 失败:${error.message}\n`) - } else { - process.stderr.write(`\n[preview] 未预期的错误:\n${error && error.stack ? error.stack : error}\n`) - } - process.exit(1) -}) - -// #endregion diff --git a/scripts/workbench-install.mjs b/scripts/workbench-install.mjs deleted file mode 100644 index 578d1ce..0000000 --- a/scripts/workbench-install.mjs +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env node -// 工作台前端(workbench/panel)的安装开关:只动 profile 的 package.json、 -// bundles 列表,以及 node_modules 里的一个链接。它不碰 cordis.patch.yml, -// 也不改「上朝」预设——那是 scripts/mode.mjs 的事。 -// -// node scripts/workbench-install.mjs status # 现在装没装 -// node scripts/workbench-install.mjs on # 装上(需要彻底重启 DSH 才生效) -// node scripts/workbench-install.mjs off # 卸掉 -// -// 幂等:重复执行结果一致;不需要备份(版本历史由 Git 管)。 - -import { readFile, writeFile, mkdir, lstat, readlink, rm, symlink } from 'node:fs/promises' -import { existsSync } from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join, resolve } from 'node:path' - -const NAME = 'dsh-sansheng-liubu-workbench' -const REPO = resolve(import.meta.dirname, '..') -const TARGET = join(REPO, 'workbench', 'panel') -const profileDir = resolve(process.env.DSH_PROFILE_DIR ?? join(homedir(), '.dsh', 'profiles', 'desktop')) -const profilePath = join(profileDir, 'package.json') -const linkPath = join(profileDir, 'node_modules', NAME) - -/** Windows 上 `link:` 依赖写成正斜杠;反斜杠在 profile 里会被当成转义。 */ -const posix = (value) => value.replace(/\\/g, '/') - -async function readProfile() { - return JSON.parse(await readFile(profilePath, 'utf8')) -} - -async function writeProfile(profile) { - await writeFile(profilePath, `${JSON.stringify(profile, null, 2)}\n`, 'utf8') -} - -async function linkState() { - try { - const stat = await lstat(linkPath) - if (!stat.isSymbolicLink()) return { linked: false, note: '不是链接(可能有同名真实目录)' } - const actual = await readlink(linkPath) - const resolved = resolve(profileDir, 'node_modules', actual) - const ok = resolved.toLowerCase() === resolve(TARGET).toLowerCase() - return { linked: ok, target: actual, note: ok ? undefined : `链接指向 ${actual}` } - } catch (error) { - if (error.code === 'ENOENT') return { linked: false, note: '链接不存在' } - throw error - } -} - -async function status() { - const profile = await readProfile() - const link = await linkState() - const bundles = profile.dsh?.profile?.bundles ?? [] - return { - profile: profilePath, - target: TARGET, - targetExists: existsSync(join(TARGET, 'lib', 'client.js')), - dependency: profile.dependencies?.[NAME] ?? null, - inBundles: bundles.includes(NAME), - link, - installed: profile.dependencies?.[NAME] === `link:${posix(TARGET)}` && bundles.includes(NAME) && link.linked, - } -} - -async function ensureLink() { - await mkdir(dirname(linkPath), { recursive: true }) - const state = await linkState() - if (state.linked) return { changed: false } - if (existsSync(linkPath) || state.note === '不是链接(可能有同名真实目录)') await rm(linkPath, { recursive: true, force: true }) - // Windows 上用 junction:不需要管理员权限,跳转由文件系统处理。 - await symlink(TARGET, linkPath, process.platform === 'win32' ? 'junction' : 'dir') - return { changed: true } -} - -async function enable() { - if (!existsSync(join(TARGET, 'lib', 'client.js'))) { - throw new Error(`找不到 ${join(TARGET, 'lib', 'client.js')}:工作台前端还没构建出来,先别装。`) - } - const profile = await readProfile() - let changed = false - profile.dependencies ??= {} - const wanted = `link:${posix(TARGET)}` - if (profile.dependencies[NAME] !== wanted) { - profile.dependencies[NAME] = wanted - changed = true - } - profile.dsh ??= {} - profile.dsh.profile ??= {} - profile.dsh.profile.bundles ??= [] - if (!profile.dsh.profile.bundles.includes(NAME)) { - profile.dsh.profile.bundles.push(NAME) - changed = true - } - if (changed) await writeProfile(profile) - const link = await ensureLink() - return { - ...(await status()), - changed: changed || link.changed, - hint: changed || link.changed - ? '已装上。彻底退出并重启 DSH 后生效(客户端 bundle 在启动时加载,热更新不覆盖)。' - : '本来就已经装好,未改动。', - } -} - -async function disable() { - const profile = await readProfile() - let changed = false - if (profile.dependencies && NAME in profile.dependencies) { - delete profile.dependencies[NAME] - changed = true - } - const bundles = profile.dsh?.profile?.bundles - if (Array.isArray(bundles) && bundles.includes(NAME)) { - profile.dsh.profile.bundles = bundles.filter((name) => name !== NAME) - changed = true - } - if (changed) await writeProfile(profile) - let unlinked = false - try { - await rm(linkPath, { recursive: true, force: true }) - unlinked = true - } catch { - /* 链接本来就不在 */ - } - return { - ...(await status()), - changed: changed || unlinked, - hint: changed || unlinked ? '已卸掉。彻底重启 DSH 后生效。' : '本来就没装,未改动。', - } -} - -const action = (process.argv[2] ?? 'status').toLowerCase() -const handlers = { status, on: enable, off: disable } -const handler = handlers[action] -if (!handler) { - console.error(`未知动作:${action}(可用:status / on / off)`) - process.exit(2) -} - -try { - console.log(JSON.stringify(await handler(), null, 2)) -} catch (error) { - console.error(String(error?.message ?? error)) - process.exit(1) -} diff --git a/scripts/workbench-preflight.mjs b/scripts/workbench-preflight.mjs deleted file mode 100644 index 574af2f..0000000 --- a/scripts/workbench-preflight.mjs +++ /dev/null @@ -1,128 +0,0 @@ -// 重启前自检:只读,不改任何东西。 -// -// 目的:把「重启 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 diff --git a/test/policy.test.js b/test/policy.test.js deleted file mode 100644 index 632410e..0000000 --- a/test/policy.test.js +++ /dev/null @@ -1,164 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { - COURT_ROLES, - DEFAULT_ROUTES, - EXECUTION_TOOLSET, - inject, - roleFromMembership, - routeForRole, - toolsetForRole, - evaluateToolPolicy, - apply, -} from '../index.js' - -const approvedTask = ownerName => ({ id: 'exec-1', status: 'in_progress', ownerName, blockedBy: [] }) - -function mockRuntime(role = 'lead') { - const sections = new Map() - const tools = new Map() - const agent = { - ctx: { - effect: callback => callback(), - systemPrompt: { - getSectionOrder: () => 0, - section: section => { - if (sections.has(section.name)) throw new Error(`duplicate prompt ${section.name}`) - sections.set(section.name, section) - return () => sections.delete(section.name) - }, - }, - on: () => () => {}, - tools: { - register: definition => { tools.set(definition.name, definition); return () => tools.delete(definition.name) }, - guard: callback => { agent.guard = callback; return () => { delete agent.guard } }, - }, - }, - } - const ctx = { - agents: { list: () => [agent] }, - agentPresets: { composedPreset: () => 'sansheng-liubu' }, - agentTeams: { - tryMembership: () => role === 'unassigned' ? undefined : role === 'lead' ? { role: 'lead', name: 'lead' } : { role: 'teammate', name: role }, - listTasks: () => [], - }, - logger: { info: () => {}, warn: () => {} }, - on: () => () => {}, - } - return { ctx, agent, sections, tools } -} - -test('maps roles and preserves model routes', () => { - assert.equal(roleFromMembership(undefined), 'lead') - assert.equal(roleFromMembership({ role: 'lead', name: 'lead' }), 'lead') - assert.equal(roleFromMembership({ role: 'teammate', name: 'menxia' }), 'menxia') - assert.equal(routeForRole('lead', DEFAULT_ROUTES), undefined, '默认不强制模型,避免宿主缺少适配器') - assert.deepEqual(routeForRole('lead', { lead: { provider: 'p', model: 'm', reasoningEffort: 'high' } }), { provider: 'p', model: 'm', reasoningEffort: 'high' }) - assert.equal(routeForRole('gongbu', { minister: { provider: 'p', model: 'm' } }).model, 'm', '未列出的角色回退到 minister 路由') - assert.equal(inject.includes('sanshengLiubuGeneration'), false) - assert.equal(inject.includes('credentials'), false) -}) - -test('maps the normal unassigned primary agent to Chancellor automatically', () => { - const runtime = mockRuntime('unassigned') - const dispose = apply(runtime.ctx) - assert.match(runtime.sections.get('sansheng-liubu:role').text, /三省六部模式:丞相/) - dispose() -}) - -test('keeps execution file tools and planning roles read-only', () => { - for (const role of ['gongbu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu']) { - assert.deepEqual(toolsetForRole(role), EXECUTION_TOOLSET) - } - for (const role of ['gongbu', 'lipu', 'bingbu', 'xingbu']) { - assert.equal(evaluateToolPolicy(role, 'bash', [approvedTask(role)]), undefined) - } - assert.match(evaluateToolPolicy('menxia', 'write', []), /只读/) -}) - -test('keeps clerk and revenue ministries off the command line', () => { - for (const role of ['libu', 'hubu']) { - assert.equal(evaluateToolPolicy(role, 'write', [approvedTask(role)]), undefined) - assert.match(evaluateToolPolicy(role, 'bash', [approvedTask(role)]), /不属于/) - } - assert.match(evaluateToolPolicy('libu', 'pwsh', [approvedTask('libu')]), /不属于/) -}) - -test('keeps the court at ten seats', () => { - assert.equal(COURT_ROLES.length, 10) - assert.deepEqual([...COURT_ROLES].sort(), ['bingbu', 'gongbu', 'hubu', 'lead', 'libu', 'lipu', 'menxia', 'shangshu', 'xingbu', 'zhongshu']) - for (const role of COURT_ROLES.filter((entry) => entry !== 'lead')) { - assert.equal(roleFromMembership({ role: 'teammate', name: role }), role, `${role} 是可识别的朝堂角色`) - } - assert.equal(roleFromMembership({ role: 'lead', name: 'lead' }), 'lead', '丞相由主会话担任') -}) - -test('allows Image-gen generation, batch, and edit only for approved Gongbu work', () => { - for (const tool of ['generate_image', 'generate_images', 'edit_image']) { - assert.match(evaluateToolPolicy('gongbu', tool, []), /尚未准奏/) - assert.equal(evaluateToolPolicy('gongbu', tool, [approvedTask('gongbu')]), undefined) - assert.match(evaluateToolPolicy('libu', tool, [approvedTask('libu')]), /不属于/) - assert.match(evaluateToolPolicy('lead', tool, []), /只读/) - } -}) - -test('blocks non-Image-gen image tools', () => { - for (const tool of ['image_generate', 'codex_image_generate']) { - assert.match(evaluateToolPolicy('gongbu', tool, [approvedTask('gongbu')]), /只允许使用 Image-gen/) - } -}) - -test('does not register duplicate image tools', () => { - const runtime = mockRuntime('gongbu') - const dispose = apply(runtime.ctx) - assert.equal(runtime.tools.size, 0) - assert.deepEqual([...runtime.sections.keys()], ['sansheng-liubu:role']) - const prompt = runtime.sections.get('sansheng-liubu:role').text - assert.ok(prompt.includes('工部职责') || prompt.includes('你负责代码实现'), '工部提示词已注册且不重复') - dispose() -}) - -test('role prompt registration remains idempotent', () => { - const runtime = mockRuntime('gongbu') - const disposeFirst = apply(runtime.ctx) - const disposeSecond = apply(runtime.ctx) - assert.deepEqual([...runtime.sections.keys()], ['sansheng-liubu:role']) - assert.equal(runtime.tools.size, 0) - disposeFirst() - assert.ok(runtime.sections.has('sansheng-liubu:role')) - disposeSecond() - assert.equal(runtime.sections.size, 0) -}) - -test('keeps management tool audit and approval rules', () => { - const audit = [] - assert.equal(evaluateToolPolicy('lead', 'task_board_create', [], { audit: item => audit.push(item) }), undefined) - assert.equal(audit[0].authority, 'chancellor') - assert.match(evaluateToolPolicy('bingbu', 'automation_create', [approvedTask('bingbu')]), /门下省准奏记录/) -}) - -test('parses the department model command the panel sends', async () => { - const { parseDeptModelCommand, describeDeptRoutes, readStoredRoutes, writeStoredRoutes } = await import('../index.js') - assert.deepEqual(parseDeptModelCommand('gongbu deepseek deepseek-chat high'), { - action: 'set', - role: 'gongbu', - route: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' }, - }) - assert.equal(parseDeptModelCommand('gongbu deepseek deepseek-chat').route.reasoningEffort, undefined) - assert.equal(parseDeptModelCommand('').action, 'list') - assert.equal(parseDeptModelCommand('list').action, 'list') - assert.deepEqual(parseDeptModelCommand('clear gongbu'), { action: 'clear', role: 'gongbu' }) - assert.match(parseDeptModelCommand('hufu a b').reason, /未知部门/) - assert.match(parseDeptModelCommand('gongbu deepseek').reason, /用法/) - assert.match(describeDeptRoutes({ gongbu: { provider: 'p', model: 'm', reasoningEffort: 'high' } }), /gongbu=p\/m·high/) - - const { mkdtempSync, rmSync } = await import('node:fs') - const { tmpdir } = await import('node:os') - const { join } = await import('node:path') - const dir = mkdtempSync(join(tmpdir(), 'sansheng-routes-')) - const file = join(dir, 'nested', 'routes.json') - assert.equal(writeStoredRoutes(file, { bingbu: { provider: 'p', model: 'm' } }), true) - assert.deepEqual(readStoredRoutes(file).bingbu, { provider: 'p', model: 'm' }) - assert.deepEqual(readStoredRoutes(join(dir, 'missing.json')), {}, '读不到就当没有固定过') - rmSync(dir, { recursive: true, force: true }) -}) diff --git a/workbench/core/ids.mjs b/workbench/core/ids.mjs deleted file mode 100644 index 3c4817e..0000000 --- a/workbench/core/ids.mjs +++ /dev/null @@ -1,81 +0,0 @@ -// 稳定随机 ID:所有业务主键都由这里生成,名称/路径只作属性,不复用为键。 -// 随机源可注入,测试里给定字符表就能复现同一串 ID,避免断言依赖运气。 - -const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz' - -/** 方案里出现的所有前缀;拼错前缀属于开发期错误,直接抛而不是静默接受。 */ -export const ID_PREFIXES = Object.freeze({ - project: 'proj', - binding: 'bind', - config: 'cfg', - task: 'task', - dispatch: 'dsp', - attempt: 'att', - contextPacket: 'ctx', - result: 'res', - artifact: 'art', - event: 'evt', - authorization: 'auth', -}) - -export const ID_ENTITIES = Object.freeze(Object.keys(ID_PREFIXES)) - -/** 默认随机源:crypto.getRandomValues,取 0..35 的字符。 */ -export function cryptoRandom() { - const crypto = globalThis.crypto - if (!crypto || typeof crypto.getRandomValues !== 'function') { - throw new Error('缺少可用的随机源,请注入 random 参数') - } - const bytes = crypto.getRandomValues(new Uint8Array(8)) - // 除 36 取余有轻微偏差,但只用于 ID 唯一性,不用于安全令牌。 - return ALPHABET[bytes[0] % ALPHABET.length] -} - -/** - * 注入的随机源可以返回数字(映射到字母表)或单个字符(必须来自字母表)。 - * 两种都接受是为了测试能写 `() => 0` 这样最直白的桩。 - */ -function pick(random, index) { - const value = random(index) - if (typeof value === 'number') { - if (!Number.isInteger(value)) throw new Error('随机源必须返回整数或字母表内字符') - // 随机源常被测试当作递增计数器使用,数值可能超过字母表长度甚至为负; - // 先取绝对整数再取模,保证任意整数都能映射到合法字符。 - return ALPHABET[Math.abs(value) % 36] - } - const char = String(value) - if (char.length !== 1 || !ALPHABET.includes(char)) throw new Error(`随机源返回了字母表外字符: ${char}`) - return char -} - -/** - * 生成 `_<随机串>`。 - * 前缀既可用实体名('task')也可用前缀本身('task'),两者一致时可省心。 - */ -export function newId(prefix, options = {}) { - const { random = cryptoRandom, length = 12 } = options - const known = ID_PREFIXES[prefix] - const resolved = known ?? (Object.values(ID_PREFIXES).includes(prefix) ? prefix : undefined) - if (resolved === undefined) throw new Error(`未知 ID 前缀: ${prefix}`) - if (!Number.isInteger(length) || length < 4 || length > 64) throw new Error('ID 随机串长度须为 4..64') - let out = '' - for (let index = 0; index < length; index += 1) out += pick(random, index) - return `${resolved}_${out}` -} - -/** 每个实体一个绑定好随机源的生成器,便于在服务层统一注入并保持测试确定性。 */ -export function createIdFactory(options = {}) { - const { random = cryptoRandom, length = 12 } = options - const factory = {} - for (const entity of ID_ENTITIES) { - factory[entity] = () => newId(ID_PREFIXES[entity], { random, length }) - } - return Object.freeze(factory) -} - -/** 校验外部传入的 ID 形状(防伪 ID 进账;存在性仍由 store 查表)。 */ -export function isIdOf(entity, value) { - const prefix = ID_PREFIXES[entity] - if (typeof value !== 'string' || typeof prefix !== 'string') return false - return value.startsWith(`${prefix}_`) && value.length > prefix.length + 1 -} diff --git a/workbench/core/roles.mjs b/workbench/core/roles.mjs deleted file mode 100644 index 0a59a8c..0000000 --- a/workbench/core/roles.mjs +++ /dev/null @@ -1,192 +0,0 @@ -// 十席角色常量:新工作台的身份只来自可信的 (projectId, roleId) 绑定, -// 不再用 Team membership 推断,也不再让模型自报角色。 -// 布局按「丞相居中在顶 → 三省一列一个 → 六部两排(吏户礼 / 兵刑工)」给出, -// UI 直接按 order 渲染稳定三列,连线的上下级由结构表达,不靠坐标猜测。 - -/** - * column:布局列(lead 跨三列居中)。 - * row:视觉行号(0 丞相、1 三省、2/3 六部一排/二排)。 - * tier:leaders = 丞相与三省,ministries = 六部;分组只用于展示,不是 session 父子关系。 - */ -const SEATS = [ - { - id: 'lead', - name: '丞相', - short: '丞', - tier: 'leaders', - group: 'lead', - column: 'span', - row: 0, - duty: '接需求、分流、协调、汇报', - responsibility: '面向用户承接想法:判断是否需要开工、必要时派给具体部门,并把各部门结果汇总成对用户的一次交付。', - canDispatch: true, - }, - { - id: 'zhongshu', - name: '中书', - short: '中', - tier: 'leaders', - group: 'sansheng', - column: 'left', - row: 1, - duty: '调查、澄清、规划', - responsibility: '先把问题问清、把材料看全,再给出可执行的方案与验收标准草案,不直接产出最终交付物。', - canDispatch: false, - }, - { - id: 'shangshu', - name: '尚书', - short: '尚', - tier: 'leaders', - group: 'sansheng', - column: 'center', - row: 1, - duty: '分工建议、组织交付', - responsibility: '把已经明确的方案拆成部门分工并组织交付;六部直属于尚书这一同级分组,六部之间不是上下级。', - canDispatch: true, - }, - { - id: 'menxia', - name: '门下', - short: '门', - tier: 'leaders', - group: 'sansheng', - column: 'right', - row: 1, - duty: '审议与整体审核', - responsibility: '对方案和交付做独立审议,指出风险与不达标处。首版没有门下审核的任务必须如实标注“未审核”。', - canDispatch: false, - }, - { - id: 'libu', - name: '吏部', - short: '吏', - tier: 'ministries', - group: 'ministries', - column: 'left', - row: 2, - duty: '角色和技能配置建议', - responsibility: '对角色、技能与编制给出建议;职责不含绕过用户授权去改权限或其他项目设置。', - canDispatch: false, - }, - { - id: 'hubu', - name: '户部', - short: '户', - tier: 'ministries', - group: 'ministries', - column: 'center', - row: 2, - duty: '数据、表格、计算', - responsibility: '处理数据、表格与计算,结论应可复算。', - canDispatch: false, - }, - { - id: 'lipu', - name: '礼部', - short: '礼', - tier: 'ministries', - group: 'ministries', - column: 'right', - row: 2, - duty: '文档、内容、呈现', - responsibility: '负责文档、内容与呈现形式,产出可编辑的源文件。', - canDispatch: false, - }, - { - id: 'bingbu', - name: '兵部', - short: '兵', - tier: 'ministries', - group: 'ministries', - column: 'left', - row: 3, - duty: '环境、调试、部署', - responsibility: '负责环境、调试与部署;部署/发布等外部副作用仍服从用户授权与宿主审批。', - canDispatch: false, - }, - { - id: 'xingbu', - name: '刑部', - short: '刑', - tier: 'ministries', - group: 'ministries', - column: 'center', - row: 3, - duty: '测试与风险检查', - responsibility: '做测试与风险检查,给出可追溯的检查结果,而不是一句“已通过”。', - canDispatch: false, - }, - { - id: 'gongbu', - name: '工部', - short: '工', - tier: 'ministries', - group: 'ministries', - column: 'right', - row: 3, - duty: '代码实现与工程产出', - responsibility: '负责代码实现与工程产出,交付可编辑源文件与真实检查结果。', - canDispatch: false, - }, -] - -export const ROLE_IDS = Object.freeze(SEATS.map((seat) => seat.id)) - -const byId = new Map(SEATS.map((seat) => [seat.id, Object.freeze(seat)])) - -/** 稳定顺序(上表即布局顺序),UI 与初始化都按这个序写,避免每次渲染顺序抖动。 */ -export const ROLES = Object.freeze(ROLE_IDS.map((id) => byId.get(id))) - -/** 布局顺序 = 数组顺序;单独导出常量是为了让调用方不必依赖“数组被排序过”这个隐含约定。 */ -export const LAYOUT_ORDER = ROLE_IDS - -export const LEADERS = Object.freeze(ROLES.filter((seat) => seat.tier === 'leaders').map((seat) => seat.id)) -export const MINISTRIES = Object.freeze(ROLES.filter((seat) => seat.tier === 'ministries').map((seat) => seat.id)) - -export function isRoleId(value) { - return typeof value === 'string' && byId.has(value) -} - -/** 未知角色返回 undefined,由调用方决定报错文案(不同入口提示不同)。 */ -export function getRole(roleId) { - return byId.get(roleId) -} - -/** 找不到就抛:角色是内部常量,拼错属于代码错误而非用户输入错误。 */ -export function requireRole(roleId) { - const seat = byId.get(roleId) - if (seat === undefined) throw new Error(`未知角色: ${String(roleId)}`) - return seat -} - -export const ROLE_NAMES = Object.freeze(Object.fromEntries(ROLES.map((seat) => [seat.id, seat.name]))) - -/** 存储与显示的兼容映射:旧代码用“中书省/尚书省/门下省”,roleId 不变,名称不参与身份。 */ -export const ROLE_NAME_ALIASES = Object.freeze({ - zhongshu: Object.freeze(['中书省']), - shangshu: Object.freeze(['尚书省']), - menxia: Object.freeze(['门下省']), -}) - -/** 按布局把十席分成分组,供右侧部门树一次画完:top / sansheng / ministries 两排。 */ -export function layoutGroups() { - return { - lead: ROLES.filter((seat) => seat.id === 'lead').map((seat) => seat.id), - sansheng: ROLES.filter((seat) => seat.group === 'sansheng').map((seat) => seat.id), - ministries: [ - ROLES.filter((seat) => seat.tier === 'ministries' && seat.row === 2).map((seat) => seat.id), - ROLES.filter((seat) => seat.tier === 'ministries' && seat.row === 3).map((seat) => seat.id), - ], - } -} - -/** 首版允许主动派工的席:丞相默认,尚书在用户明确要求时经同一权限校验。 */ -export function canDispatch(roleId) { - return byId.get(roleId)?.canDispatch === true -} - -/** 初始化项目时用的角色清单(不创建会话,只建配置与绑定初值)。 */ -export function initialSeats() { - return ROLES.map((seat) => ({ roleId: seat.id, name: seat.name, tier: seat.tier })) -} diff --git a/workbench/core/states.mjs b/workbench/core/states.mjs deleted file mode 100644 index 69ca1c1..0000000 --- a/workbench/core/states.mjs +++ /dev/null @@ -1,138 +0,0 @@ -// 四套状态机分开维护:部门运行、任务结论、投递进度、单次尝试。 -// 合并成一个大状态会让“空闲”被当成“已完成”,正是方案 7.3/8.1 明确禁止的误判。 - -export const TASK_STATES = Object.freeze([ - 'draft', - 'queued', - 'running', - 'waiting_input', - 'needs_attention', - 'completed', - 'failed', - 'cancelled', -]) - -export const DISPATCH_STATES = Object.freeze(['prepared', 'sending', 'accepted', 'unknown', 'rejected']) - -export const ATTEMPT_STATES = Object.freeze([ - 'queued', - 'running', - 'succeeded', - 'failed', - 'cancel_requested', - 'cancelled', - 'unknown', -]) - -export const DEPARTMENT_STATES = Object.freeze(['uninitialized', 'idle', 'queued', 'running', 'unavailable']) - -/** - * Task:draft 校验通过且授权有效才入队;waiting_input 只能回到原任务的执行路径, - * completed 是唯一“可交付”终态;needs_attention 仍可补报后完成,也可显式失败/取消。 - * 终态(completed / failed / cancelled)不回到任何活动状态:重试一律新 attempt 或新任务。 - */ -const TASK_TRANSITIONS = Object.freeze({ - draft: Object.freeze(['queued', 'cancelled']), - queued: Object.freeze(['running', 'waiting_input', 'needs_attention', 'failed', 'cancelled']), - running: Object.freeze(['waiting_input', 'needs_attention', 'completed', 'failed', 'cancelled']), - waiting_input: Object.freeze(['queued', 'running', 'cancelled']), - needs_attention: Object.freeze(['running', 'completed', 'failed', 'cancelled']), - completed: Object.freeze([]), - failed: Object.freeze([]), - cancelled: Object.freeze([]), -}) - -/** Dispatch:发出不等于接收;超时可能 unknown,必须先对账,不能自动当失败重试。 */ -const DISPATCH_TRANSITIONS = Object.freeze({ - prepared: Object.freeze(['sending', 'rejected', 'unknown']), - sending: Object.freeze(['accepted', 'unknown', 'rejected']), - accepted: Object.freeze([]), - unknown: Object.freeze(['accepted', 'rejected']), - rejected: Object.freeze([]), -}) - -/** Attempt:cancel_requested 不等于已取消;unknown 必须先核对宿主运行再定终态。 */ -const ATTEMPT_TRANSITIONS = Object.freeze({ - queued: Object.freeze(['running', 'cancelled', 'failed', 'unknown']), - running: Object.freeze(['succeeded', 'failed', 'cancel_requested', 'unknown']), - cancel_requested: Object.freeze(['cancelled', 'succeeded', 'unknown']), - succeeded: Object.freeze([]), - failed: Object.freeze([]), - cancelled: Object.freeze([]), - unknown: Object.freeze(['succeeded', 'failed', 'cancelled', 'running']), -}) - -/** Department 只表达会话运行情况:unavailable 是绑定失效,仍保留旧引用。 */ -const DEPARTMENT_TRANSITIONS = Object.freeze({ - uninitialized: Object.freeze(['idle', 'queued', 'unavailable']), - idle: Object.freeze(['queued', 'running', 'unavailable']), - queued: Object.freeze(['running', 'idle', 'unavailable']), - running: Object.freeze(['idle', 'queued', 'unavailable']), - unavailable: Object.freeze(['uninitialized', 'idle']), -}) - -const MACHINES = Object.freeze({ - task: Object.freeze({ key: 'task', name: 'Task', states: TASK_STATES, transitions: TASK_TRANSITIONS }), - dispatch: Object.freeze({ key: 'dispatch', name: 'Dispatch', states: DISPATCH_STATES, transitions: DISPATCH_TRANSITIONS }), - attempt: Object.freeze({ key: 'attempt', name: 'Attempt', states: ATTEMPT_STATES, transitions: ATTEMPT_TRANSITIONS }), - department: Object.freeze({ key: 'department', name: 'Department', states: DEPARTMENT_STATES, transitions: DEPARTMENT_TRANSITIONS }), -}) - -export const STATE_MACHINES = Object.freeze( - Object.fromEntries(Object.entries(MACHINES).map(([key, machine]) => [key, Object.freeze({ - name: machine.name, - states: machine.states, - transitions: machine.transitions, - })])), -) - -export const TERMINAL_STATES = Object.freeze({ - task: Object.freeze(['completed', 'failed', 'cancelled']), - dispatch: Object.freeze(['accepted', 'rejected']), - attempt: Object.freeze(['succeeded', 'failed', 'cancelled']), - department: Object.freeze([]), -}) - -function machineOf(kind) { - const machine = MACHINES[kind] - if (machine === undefined) throw new Error(`未知状态机: ${String(kind)}`) - return machine -} - -export function statesOf(kind) { - return machineOf(kind).states -} - -export function isState(kind, value) { - return machineOf(kind).states.includes(value) -} - -export function allowedTransitions(kind, from) { - const machine = machineOf(kind) - if (!machine.states.includes(from)) throw new Error(`${machine.name} 未知状态: ${String(from)}`) - return machine.transitions[from] -} - -export function canTransition(kind, from, to) { - // 同状态重复写入不算迁移:事件重放时应由调用方静默忽略,而不是报错。 - if (from === to) return true - return allowedTransitions(kind, from).includes(to) -} - -const MACHINE_KEY = Object.freeze({ task: 'task', dispatch: 'dispatch', attempt: 'attempt', department: 'department' }) - -export function isTerminal(kind, state) { - return TERMINAL_STATES[machineOf(kind).key].includes(state) -} - -/** 非法迁移一律抛错:状态倒退还沉默会让故障矩阵里“终态不被覆盖”的保证失效。 */ -export function assertTransition(kind, from, to) { - const machine = machineOf(kind) - if (!machine.states.includes(from)) throw new Error(`${machine.name} 当前状态非法: ${String(from)}`) - if (!machine.states.includes(to)) throw new Error(`${machine.name} 目标状态非法: ${String(to)}`) - if (from === to) return to - if (!machine.transitions[from].includes(to)) { - throw new Error(`${machine.name} 不允许从 ${from} 迁移到 ${to}`) - } - return to -} diff --git a/workbench/core/store.mjs b/workbench/core/store.mjs deleted file mode 100644 index 8915cb3..0000000 --- a/workbench/core/store.mjs +++ /dev/null @@ -1,1019 +0,0 @@ -// 领域存储:内存表 + JSON 文件快照(先写 .tmp 再 rename)。 -// 只存业务账、引用和交接快照;聊天正文仍由 DSH 保存,这里不复制一份会过期的副本。 -// 所有写入都走 mutate():一次写入 = 一次事务,中途抛错就整体回滚,内存里不会留下半截状态。 - -import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join, resolve } from 'node:path' -import { createIdFactory, isIdOf, newId } from './ids.mjs' -import { ROLES, isRoleId } from './roles.mjs' -import { assertTransition, isTerminal, isState } from './states.mjs' - -export const SCHEMA_VERSION = 1 - -const COLLECTIONS = Object.freeze([ - 'projects', - 'bindings', - 'configs', - 'tasks', - 'dispatches', - 'attempts', - 'contextPackets', - 'results', - 'artifacts', - 'events', -]) - -const ENTITY_OF = Object.freeze({ - projects: 'project', - bindings: 'binding', - configs: 'config', - tasks: 'task', - dispatches: 'dispatch', - attempts: 'attempt', - contextPackets: 'contextPacket', - results: 'result', - artifacts: 'artifact', - events: 'event', -}) - -/** 跨项目校验用的引用表:source 实体上的某字段 → 目标实体。 */ -const REFERENCES = Object.freeze({ - tasks: Object.freeze({ - activeAttemptId: 'attempts', - sourceBindingId: 'bindings', - ownerBindingId: 'bindings', - }), - dispatches: Object.freeze({ - taskId: 'tasks', - attemptId: 'attempts', - contextPacketId: 'contextPackets', - bindingId: 'bindings', - }), - attempts: Object.freeze({ - taskId: 'tasks', - dispatchId: 'dispatches', - bindingId: 'bindings', - }), - contextPackets: Object.freeze({ taskId: 'tasks' }), - results: Object.freeze({ - taskId: 'tasks', - attemptId: 'attempts', - sourceBindingId: 'bindings', - }), - artifacts: Object.freeze({ - taskId: 'tasks', - sourceResultId: 'results', - // 修订关系:新成果指向被它替换的旧成果(必须同项目,跨项目一律拒绝)。 - revisesArtifactId: 'artifacts', - ownerBindingId: 'bindings', - }), - events: Object.freeze({}), -}) - -export class StoreError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'StoreError' - this.code = code - if (details !== undefined) this.details = details - } -} - -export function defaultStorePath(env = process.env) { - const home = env.DSH_HOME && String(env.DSH_HOME).trim() !== '' ? env.DSH_HOME : join(homedir(), '.dsh') - return join(resolve(home), 'sansheng-liubu', 'workbench.json') -} - -const nowIso = (clock) => new Date(clock()).toISOString() - -function bindingKey(projectId, roleId) { - return `${projectId}\u0000${roleId}` -} - -function emptyState() { - return { - schemaVersion: SCHEMA_VERSION, - revision: 0, - eventSeq: 0, - projects: new Map(), - bindings: new Map(), - configs: new Map(), - tasks: new Map(), - dispatches: new Map(), - attempts: new Map(), - contextPackets: new Map(), - results: new Map(), - artifacts: new Map(), - events: [], - } -} - -/** 深拷贝走 JSON:状态里只有可序列化数据,写文件同样是这个形状,避免两条路径不同步。 */ -function clone(value) { - return value === undefined ? undefined : JSON.parse(JSON.stringify(value)) -} - -function requireString(value, field) { - if (typeof value !== 'string' || value.trim() === '') { - throw new StoreError('INVALID_INPUT', `${field} 必须是非空字符串`) - } - return value -} - -/** 集合 → 主键字段,注册时统一生成 ID 并校验前缀。 */ -const KEY_FIELD = Object.freeze({ - projects: 'id', - bindings: 'id', - configs: 'id', - tasks: 'id', - dispatches: 'id', - attempts: 'id', - contextPackets: 'id', - results: 'id', - artifacts: 'id', - events: 'eventId', -}) - -export class WorkbenchStore { - /** - * @param {object} [options] - * @param {string} [options.file] 持久化路径;null/'' 表示纯内存(测试与只读投影用)。 - * @param {() => number} [options.clock] 注入时钟,测试可固定时间戳。 - * @param {() => string} [options.random] 注入随机源,测试可固定 ID。 - * @param {object} [options.env] 计算默认路径用的环境变量。 - */ - constructor(options = {}) { - const { file = defaultStorePath(options.env), clock = Date.now, random, env } = options - this.file = file === null || file === '' ? null : resolve(String(file)) - this.clock = clock - this.random = random - this.ids = createIdFactory(random === undefined ? {} : { random }) - - this.state = emptyState() - // 事务深度为 0 才是真正的提交点;嵌套写入并进外层事务,内层抛错由外层整体回滚。 - this._txDepth = 0 - this._stamp = null - this._dirty = false - this.env = env - } - - // ---------- 事务与生命周期 ---------- - - /** - * 一次事务提交所有内存变更并顺带落盘;payloads 里收集的 ID 说明“写成功”才对外可见。 - * 不自动落盘失败时的部分内存修改被丢弃,重试不会撞上幽灵记录。 - */ - mutate(payloads = () => null) { - const snapshot = this._txDepth === 0 ? this._captureState() : null - this._txDepth += 1 - const result = {} - let committed = false - let value - try { - value = payloads(result) - committed = true - } finally { - this._txDepth -= 1 - // 外层事务收尾:成功则递增版本并落盘;失败则回滚到事务开始时的快照。 - if (this._txDepth === 0) { - if (committed) { - this.state.revision += 1 - this._stamp = nowIso(this.clock) - this._dirty = true - try { - this.save() - } catch (error) { - if (snapshot !== null) this.state = snapshot - throw error - } - } else if (snapshot !== null) { - this.state = snapshot - } - } - } - return { ...result, value } - } - - /** 只读运行,不递增 revision,也不落盘。 */ - view(fn) { - return fn() - } - - save() { - if (this.file === null) return false - this._writeAtomically(this.serialize()) - this._dirty = false - return true - } - - load() { - if (this.file === null) return false - if (!existsSync(this.file)) return false - const raw = readFileSync(this.file, 'utf8') - this._applySnapshot(raw) - return true - } - - serialize() { - const state = this.state - return JSON.stringify({ - schemaVersion: state.schemaVersion, - revision: state.revision, - eventSeq: state.eventSeq, - projects: [...state.projects.values()], - bindings: [...state.bindings.values()], - configs: [...state.configs.values()], - tasks: [...state.tasks.values()], - dispatches: [...state.dispatches.values()], - attempts: [...state.attempts.values()], - contextPackets: [...state.contextPackets.values()], - results: [...state.results.values()], - artifacts: [...state.artifacts.values()], - events: state.events, - }) - } - - /** 投影给 UI 用:只读副本,避免调用方直接改 Map。 */ - snapshot() { - return clone({ - schemaVersion: this.state.schemaVersion, - revision: this.state.revision, - eventSeq: this.state.eventSeq, - savedAt: this._stamp ?? null, - projects: [...this.state.projects.values()], - bindings: [...this.state.bindings.values()], - configs: [...this.state.configs.values()], - tasks: [...this.state.tasks.values()], - dispatches: [...this.state.dispatches.values()], - attempts: [...this.state.attempts.values()], - contextPackets: [...this.state.contextPackets.values()], - results: [...this.state.results.values()], - artifacts: [...this.state.artifacts.values()], - events: this.state.events, - }) - } - - get revision() { - return this.state.revision - } - - get eventSeq() { - return this.state.eventSeq - } - - _captureState() { - return this._fromSnapshot(JSON.parse(this.serialize())) - } - - _writeAtomically(text) { - const dir = dirname(this.file) - mkdirSync(dir, { recursive: true }) - const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp` - try { - writeFileSync(tmp, text, 'utf8') - // Windows 上 rename 覆盖已存在文件可能失败(杀软/索引占用),失败时删旧再改名, - // 最坏情况是两个窗口都读到“空账”,但不会读到半截 JSON。 - try { - renameSync(tmp, this.file) - } catch (error) { - rmSync(this.file, { force: true }) - renameSync(tmp, this.file) - } - } finally { - rmSync(tmp, { force: true }) - } - } - - _applySnapshot(text) { - const parsed = JSON.parse(text) - this.state = this._fromSnapshot(parsed) - } - - _fromSnapshot(parsed) { - if (parsed === null || typeof parsed !== 'object') throw new StoreError('CORRUPT', '账本不是对象') - if (parsed.schemaVersion !== SCHEMA_VERSION) { - throw new StoreError('SCHEMA_MISMATCH', `账本 schemaVersion=${String(parsed.schemaVersion)},期望 ${SCHEMA_VERSION}`) - } - const state = emptyState() - state.revision = Number(parsed.revision) || 0 - state.eventSeq = Number(parsed.eventSeq) || 0 - for (const collection of COLLECTIONS) { - const list = Array.isArray(parsed[collection]) ? parsed[collection] : [] - if (collection === 'events') { - state.events = list - continue - } - const keyOf = collection === 'bindings' || collection === 'configs' - ? (row) => bindingKey(row.projectId, row.roleId) - : (row) => row[KEY_FIELD[collection]] - for (const row of list) state[collection].set(keyOf(row), row) - } - return state - } - - // ---------- 通用查询 ---------- - - getProject(id) { - return this.state.projects.get(id) - } - - listProjects() { - return [...this.state.projects.values()] - } - - getBinding(projectId, roleId) { - return this.state.bindings.get(bindingKey(projectId, roleId)) - } - - listBindings(projectId) { - return [...this.state.bindings.values()].filter((row) => projectId === undefined || row.projectId === projectId) - } - - getConfig(projectId, roleId) { - return this.state.configs.get(bindingKey(projectId, roleId)) - } - - listConfigs(projectId) { - return [...this.state.configs.values()].filter((row) => projectId === undefined || row.projectId === projectId) - } - - getTask(id) { - return this.state.tasks.get(id) - } - - listTasks(projectId) { - return [...this.state.tasks.values()].filter((row) => projectId === undefined || row.projectId === projectId) - } - - getDispatch(id) { - return this.state.dispatches.get(id) - } - - getAttempt(id) { - return this.state.attempts.get(id) - } - - listAttempts(taskId) { - return [...this.state.attempts.values()].filter((row) => taskId === undefined || row.taskId === taskId) - } - - getContextPacket(id) { - return this.state.contextPackets.get(id) - } - - getResult(id) { - return this.state.results.get(id) - } - - listResults(taskId) { - return [...this.state.results.values()].filter((row) => taskId === undefined || row.taskId === taskId) - } - - getArtifact(id) { - return this.state.artifacts.get(id) - } - - listArtifacts(projectId) { - return [...this.state.artifacts.values()].filter((row) => projectId === undefined || row.projectId === projectId) - } - - listEvents(projectId) { - return this.state.events.filter((row) => projectId === undefined || row.projectId === projectId) - } - - findDispatchByIdempotencyKey(projectId, key) { - return [...this.state.dispatches.values()].find( - (row) => row.projectId === projectId && row.idempotencyKey === key, - ) - } - - // ---------- 写入:项目 ---------- - - createProject(input) { - const hostWorkspaceId = requireString(input?.hostWorkspaceId, 'hostWorkspaceId') - const existing = [...this.state.projects.values()].find((row) => row.hostWorkspaceId === hostWorkspaceId) - if (existing !== undefined) { - throw new StoreError('DUPLICATE_PROJECT', `宿主工作区已登记为项目 ${existing.id}`, { projectId: existing.id }) - } - const id = this.ids.project() - const stamp = nowIso(this.clock) - return this.mutate((out) => { - const project = { - id, - hostWorkspaceId, - displayNameCache: input.displayNameCache ?? '', - canonicalRoot: input.canonicalRoot ?? null, - status: input.status ?? 'active', - schemaVersion: SCHEMA_VERSION, - revision: 1, - createdAt: stamp, - updatedAt: stamp, - } - this.state.projects.set(id, project) - // 首次进入只建十席配置初值与空绑定,不自动创建会话、不发模型请求。 - for (const seat of ROLES) { - const binding = this._emptyBinding(id, seat.id, stamp) - const config = this._emptyConfig(id, seat.id, stamp) - this.state.bindings.set(bindingKey(id, seat.id), binding) - this.state.configs.set(bindingKey(id, seat.id), config) - } - this._appendEvent({ type: 'project.created', projectId: id, payload: { hostWorkspaceId } }, stamp) - out.projectId = id - return id - }).value - } - - updateProject(id, patch) { - return this.mutate((out) => { - const project = this._project(id) - const stamp = nowIso(this.clock) - const next = { ...project, updatedAt: stamp, revision: project.revision + 1 } - if (patch?.displayNameCache !== undefined) next.displayNameCache = String(patch.displayNameCache) - if (patch?.canonicalRoot !== undefined) next.canonicalRoot = patch.canonicalRoot - if (patch?.status !== undefined) next.status = patch.status - this.state.projects.set(id, next) - out.written = 1 - return next - }).value - } - - _project(id) { - requireString(id, 'projectId') - const project = this.state.projects.get(id) - if (project === undefined) throw new StoreError('NOT_FOUND', `项目不存在: ${id}`) - return project - } - - // ---------- 写入:绑定 ---------- - - _emptyBinding(projectId, roleId, stamp) { - return { - id: this.ids.binding(), - projectId, - roleId, - currentSessionId: null, - bindingGeneration: 0, - historySessionRefs: [], - creationRequestId: null, - status: 'uninitialized', - revision: 1, - createdAt: stamp, - updatedAt: stamp, - } - } - - _emptyConfig(projectId, roleId, stamp) { - return { - id: this.ids.config(), - projectId, - roleId, - providerId: null, - modelId: null, - reasoningEffort: null, - rolePromptVersion: 1, - skillRefs: [], - permissionRef: null, - configRevision: 0, - updatedAt: stamp, - } - } - - ensureBinding(projectId, roleId) { - this._project(projectId) - this._role(roleId) - const existing = this.getBinding(projectId, roleId) - if (existing !== undefined) return existing - const stamp = nowIso(this.clock) - return this.mutate((out) => { - const binding = this._emptyBinding(projectId, roleId, stamp) - this.state.bindings.set(bindingKey(projectId, roleId), binding) - out.bindingId = binding.id - return binding - }).value - } - - /** - * 绑定会话:写入前先校验唯一性——同一 currentSessionId 不得同时属于两个 (projectId, roleId), - * 除非旧绑定已被 releaseBinding 释放(currentSessionId 置空并进入 historySessionRefs)。 - * bindingGeneration 每次换绑 +1:派发时固定它,旧消息不会被自动送进新会话。 - * 本部门已绑定另一会话时默认拒绝:静默覆盖等于把旧会话的历史从账上抹掉。 - * 只有调用方显式 allowReplace 才换绑,并仍把旧会话保留进 historySessionRefs。 - */ - bindSession(projectId, roleId, sessionId, options = {}) { - this._project(projectId) - this._role(roleId) - requireString(sessionId, 'sessionId') - return this.mutate((out) => { - const binding = this.getBinding(projectId, roleId) - if (binding === undefined) throw new StoreError('NOT_FOUND', '部门绑定不存在,请先 initializeProject') - const holder = this._sessionHolder(projectId, roleId, sessionId) - if (holder !== undefined) { - throw new StoreError('SESSION_CONFLICT', '会话已绑定到另一个项目或部门', { - sessionId, - heldBy: { projectId: holder.projectId, roleId: holder.roleId }, - }) - } - if (binding.currentSessionId !== null) { - if (binding.currentSessionId === sessionId) { - throw new StoreError('SESSION_CONFLICT', '该会话已是本部门的当前会话,无需重复绑定', { sessionId }) - } - if (options.allowReplace !== true) { - throw new StoreError('SESSION_CONFLICT', '本部门已绑定其他会话,请先 releaseBinding 或显式 allowReplace', { - currentSessionId: binding.currentSessionId, - }) - } - } - const stamp = nowIso(this.clock) - const history = binding.currentSessionId === null || options.allowReplace !== true - ? binding.historySessionRefs - : [ - ...binding.historySessionRefs, - { sessionId: binding.currentSessionId, releasedAt: stamp, bindingGeneration: binding.bindingGeneration }, - ] - const next = { - ...binding, - currentSessionId: sessionId, - historySessionRefs: history, - bindingGeneration: binding.bindingGeneration + 1, - creationRequestId: options.creationRequestId ?? null, - status: options.status ?? 'idle', - revision: binding.revision + 1, - updatedAt: stamp, - } - assertTransition('department', binding.status, next.status) - this.state.bindings.set(bindingKey(projectId, roleId), next) - this._appendEvent({ - type: 'binding.session_bound', - projectId, - roleId, - payload: { sessionId, bindingGeneration: next.bindingGeneration, bindingId: next.id }, - }, stamp) - out.bindingId = next.id - return next - }).value - } - - /** - * 释放当前会话:旧会话进入 historySessionRefs(不删除历史),供以后接续。 - * 释放后同一 sessionId 才能绑定到别处。 - */ - releaseBinding(projectId, roleId) { - return this.mutate((out) => { - const binding = this.getBinding(projectId, roleId) - if (binding === undefined) throw new StoreError('NOT_FOUND', '部门绑定不存在') - const sessionId = binding.currentSessionId - const stamp = nowIso(this.clock) - const history = sessionId === null - ? binding.historySessionRefs - : [...binding.historySessionRefs, { sessionId, releasedAt: stamp, bindingGeneration: binding.bindingGeneration }] - const next = { - ...binding, - currentSessionId: null, - historySessionRefs: history, - status: 'uninitialized', - revision: binding.revision + 1, - updatedAt: stamp, - } - this.state.bindings.set(bindingKey(projectId, roleId), next) - if (sessionId !== null) { - this._appendEvent({ type: 'binding.session_released', projectId, roleId, payload: { sessionId } }, stamp) - } - out.bindingId = next.id - return next - }).value - } - - setBindingStatus(projectId, roleId, status) { - return this.mutate((out) => { - const binding = this.getBinding(projectId, roleId) - if (binding === undefined) throw new StoreError('NOT_FOUND', '部门绑定不存在') - assertTransition('department', binding.status, status) - const stamp = nowIso(this.clock) - const next = { ...binding, status, revision: binding.revision + 1, updatedAt: stamp } - this.state.bindings.set(bindingKey(projectId, roleId), next) - out.bindingId = next.id - return next - }).value - } - - /** 会话归属查询:返回 nullptr 以外的唯一持有者(含跨项目),用于唯一性校验。 */ - _sessionHolder(projectId, roleId, sessionId) { - for (const row of this.state.bindings.values()) { - if (row.currentSessionId !== sessionId) continue - if (row.projectId === projectId && row.roleId === roleId) continue - return row - } - return undefined - } - - // ---------- 写入:配置(CAS) ---------- - - /** - * 保存某项目某部门的模型设置。expectedRevision 必须等于当前 configRevision, - * 否则抛 CAS_CONFLICT 并带回当前值,让 UI 提示后重应用,而不是静默覆盖另一标签页的修改。 - */ - saveConfig(projectId, roleId, desired, expectedRevision) { - this._project(projectId) - this._role(roleId) - if (!Number.isInteger(expectedRevision)) { - throw new StoreError('INVALID_INPUT', 'expectedRevision 必须是整数') - } - const provider = requireString(desired?.provider ?? desired?.providerId, 'provider') - const model = requireString(desired?.model ?? desired?.modelId, 'model') - const effort = desired?.reasoningEffort ?? null - if (effort !== null && typeof effort !== 'string') { - throw new StoreError('INVALID_INPUT', 'reasoningEffort 必须是字符串或 null') - } - return this.mutate((out) => { - const config = this.getConfig(projectId, roleId) - if (config === undefined) throw new StoreError('NOT_FOUND', '部门配置不存在') - if (config.configRevision !== expectedRevision) { - throw new StoreError('CAS_CONFLICT', '配置已被其他窗口修改', { - expectedRevision, - currentRevision: config.configRevision, - current: { - provider: config.providerId, - model: config.modelId, - reasoningEffort: config.reasoningEffort ?? null, - }, - }) - } - const stamp = nowIso(this.clock) - const next = { - ...config, - providerId: provider, - modelId: model, - reasoningEffort: effort, - configRevision: config.configRevision + 1, - updatedAt: stamp, - } - this.state.configs.set(bindingKey(projectId, roleId), next) - this._appendEvent({ - type: 'config.saved', - projectId, - roleId, - payload: { provider, model, reasoningEffort: effort, configRevision: next.configRevision }, - }, stamp) - out.configId = next.id - return next - }).value - } - - // ---------- 写入:任务 ---------- - - /** - * raw 模式的写入口:tasks.mjs 负责生命周期判断,store 只保证“存在、状态合法、归属正确”。 - * 直接调用的调用方必须自己先用 assertTransition,并且不能跳过 task.ts。 - */ - insertTask(task) { - return this.mutate((out) => { - // 先定 ID:显式传入的 ID 撞键按重复报错(调用方给了确定的键,不能偷偷换); - // 自动生成的 ID 撞键就再抽一次——ID 用尽属于随机源问题,重抽几次仍撞才算失败。 - const auto = task?.id === undefined - let candidate = task?.id ?? this.ids.task() - for (let retry = 0; auto && this.state.tasks.has(candidate) && retry < 8; retry += 1) { - candidate = this.ids.task() - } - if (this.state.tasks.has(candidate)) throw new StoreError('DUPLICATE_ID', `任务已存在: ${candidate}`) - const next = { ...task, id: candidate, revision: task?.revision ?? 1 } - this._assertTaskFields(next) - this.state.tasks.set(candidate, next) - out.taskId = candidate - return next - }).value - } - - updateTask(task) { - return this.mutate((out) => { - const current = this.state.tasks.get(task?.id) - if (current === undefined) throw new StoreError('NOT_FOUND', `任务不存在: ${String(task?.id)}`) - if (current.projectId !== task.projectId) { - throw new StoreError('CROSS_PROJECT', '任务的 projectId 不能被改写') - } - const next = { ...task, revision: current.revision + 1 } - assertTransition('task', current.status, next.status) - this.state.tasks.set(next.id, next) - out.taskId = next.id - return next - }).value - } - - _assertTaskFields(task) { - requireString(task.id, 'task.id') - isIdOf('task', task.id) || (() => { throw new StoreError('INVALID_ID', `任务 ID 形状非法: ${task.id}`) })() - this._project(task.projectId) - if (!isRoleId(task.ownerRoleId)) throw new StoreError('INVALID_ROLE', `未知主责部门: ${String(task.ownerRoleId)}`) - if (!isRoleId(task.sourceRoleId)) throw new StoreError('INVALID_ROLE', `未知来源部门: ${String(task.sourceRoleId)}`) - if (!isState('task', task.status)) throw new StoreError('INVALID_STATE', `未知任务状态: ${String(task.status)}`) - return task - } - - _role(roleId) { - if (!isRoleId(roleId)) throw new StoreError('INVALID_ROLE', `未知角色: ${String(roleId)}`) - return roleId - } - - // ---------- 写入:派发(幂等) ---------- - - /** - * 幂等键 (projectId, idempotencyKey) 唯一:重复点击派工返回既有记录并标 duplicate, - * 绝不生成第二条 dispatch——投递可能已经发生,重写一条等于假装配送两次。 - */ - recordDispatch(input) { - const projectId = requireString(input?.projectId, 'projectId') - const key = requireString(input?.idempotencyKey, 'idempotencyKey') - this._project(projectId) - const existing = this.findDispatchByIdempotencyKey(projectId, key) - if (existing !== undefined) return { dispatch: clone(existing), duplicate: true } - return this.mutate((out) => { - const stamp = nowIso(this.clock) - const dispatch = { - id: this.ids.dispatch(), - projectId, - taskId: input.taskId ?? null, - attemptId: input.attemptId ?? null, - sourceSessionId: input.sourceSessionId ?? null, - targetSessionId: input.targetSessionId ?? null, - bindingId: input.bindingId ?? null, - bindingGeneration: input.bindingGeneration ?? 0, - contextPacketId: input.contextPacketId ?? null, - idempotencyKey: key, - status: input.status ?? 'prepared', - hostMessageId: null, - createdAt: stamp, - updatedAt: stamp, - } - if (!isState('dispatch', dispatch.status)) { - throw new StoreError('INVALID_STATE', `未知派发状态: ${String(dispatch.status)}`) - } - // 先落库再校验:派发与自己的 attemptId 是同一事务内的前向引用, - // 若先校验会读不到刚创建的 dispatch 自身(历史 bug:所有派发失败)。 - this.state.dispatches.set(dispatch.id, dispatch) - this._checkReferences({ ...dispatch, source: 'dispatches' }) - this._appendEvent({ type: 'dispatch.recorded', projectId, payload: { dispatchId: dispatch.id, idempotencyKey: key } }, stamp) - out.dispatchId = dispatch.id - return { dispatch, duplicate: false } - }).value - } - - /** 派发状态推进:接受状态必须由宿主回执驱动,不允许调用方跳过 sending 直接 accepted 之外的猜测。 */ - updateDispatch(id, patch) { - return this.mutate((out) => { - const current = this.state.dispatches.get(id) - if (current === undefined) throw new StoreError('NOT_FOUND', `派发不存在: ${id}`) - const next = { ...current, ...patch, id: current.id, projectId: current.projectId } - if (patch?.status !== undefined) assertTransition('dispatch', current.status, patch.status) - const stamp = nowIso(this.clock) - next.updatedAt = stamp - this.state.dispatches.set(id, next) - out.dispatchId = id - return next - }).value - } - - // ---------- 写入:尝试 / 上下文包 ---------- - - insertAttempt(attempt) { - return this.mutate((out) => { - const id = attempt?.id ?? this.ids.attempt() - const next = { ...attempt, id } - if (!isState('attempt', next.state)) throw new StoreError('INVALID_STATE', `未知尝试状态: ${String(next.state)}`) - this._checkReferences({ ...next, source: 'attempts' }) - this.state.attempts.set(id, next) - out.attemptId = id - return next - }).value - } - - updateAttempt(id, patch) { - return this.mutate((out) => { - const current = this.state.attempts.get(id) - if (current === undefined) throw new StoreError('NOT_FOUND', `尝试不存在: ${id}`) - if (patch?.state !== undefined) assertTransition('attempt', current.state, patch.state) - const next = { ...current, ...patch, id, projectId: current.projectId, taskId: current.taskId } - this.state.attempts.set(id, next) - out.attemptId = id - return next - }).value - } - - insertContextPacket(packet) { - return this.mutate((out) => { - const id = packet?.id ?? this.ids.contextPacket() - const next = { ...packet, id } - this._checkReferences({ ...next, source: 'contextPackets' }) - this.state.contextPackets.set(id, next) - out.contextPacketId = id - return next - }).value - } - - // ---------- 写入:结果(幂等) / 成果 ---------- - - /** - * 结果去重:同一 (attemptId, reportVersion) 或同一条源消息只登记一次。 - * 完成事件重复到达是常态(刷新、重连、双窗口),重写一次结果会把检查与未完成项覆盖成“最新一次”的假象。 - */ - recordResult(input) { - const projectId = requireString(input?.projectId, 'projectId') - const attemptId = requireString(input?.attemptId, 'attemptId') - const reportVersion = input.reportVersion ?? 1 - const sourceMessageRef = input.sourceMessageRef ?? null - const existing = this._findDuplicateResult(projectId, attemptId, reportVersion, sourceMessageRef) - if (existing !== undefined) return { result: clone(existing), duplicate: true } - return this.mutate((out) => { - const stamp = nowIso(this.clock) - const result = { - id: this.ids.result(), - projectId, - taskId: input.taskId ?? null, - attemptId, - reportVersion, - summary: String(input.summary ?? ''), - artifactRefs: Array.isArray(input.artifactRefs) ? [...input.artifactRefs] : [], - checks: Array.isArray(input.checks) ? clone(input.checks) : [], - remainingItems: Array.isArray(input.remainingItems) ? [...input.remainingItems] : [], - blockedReason: input.blockedReason ?? null, - sourceMessageRef: sourceMessageRef ?? null, - createdAt: stamp, - } - this._checkReferences({ ...result, source: 'results' }) - this.state.results.set(result.id, result) - this._appendEvent({ type: 'result.recorded', projectId, payload: { resultId: result.id, attemptId } }, stamp) - out.resultId = result.id - return { result, duplicate: false } - }).value - } - - _findDuplicateResult(projectId, attemptId, reportVersion, sourceMessageRef) { - for (const row of this.state.results.values()) { - if (row.projectId !== projectId || row.attemptId !== attemptId) continue - if (row.reportVersion === reportVersion) return row - if (sourceMessageRef !== null && row.sourceMessageRef === sourceMessageRef) return row - } - return undefined - } - - recordArtifact(input) { - return this.mutate((out) => { - const stamp = nowIso(this.clock) - const artifact = { - id: input?.id ?? this.ids.artifact(), - projectId: input?.projectId, - taskId: input?.taskId ?? null, - ownerRoleId: input?.ownerRoleId, - fileRef: input?.fileRef ?? null, - displayName: input?.displayName ?? '', - mediaType: input?.mediaType ?? 'application/octet-stream', - versionOrHash: input?.versionOrHash ?? null, - verification: input?.verification ?? { status: 'unverified' }, - sourceResultId: input?.sourceResultId ?? null, - // 修订链:revisesArtifactId 指向被替换的旧版本,revision 从 1 起递增。 - // 只在登记时写入,之后不原地改——历史版本必须能追。 - revisesArtifactId: input?.revisesArtifactId ?? null, - revision: Number.isInteger(input?.revision) && input.revision > 0 ? input.revision : 1, - revisionOfTaskId: input?.revisionOfTaskId ?? null, - createdAt: stamp, - } - if (!isRoleId(artifact.ownerRoleId)) throw new StoreError('INVALID_ROLE', `未知主责部门: ${String(artifact.ownerRoleId)}`) - this._checkReferences({ ...artifact, source: 'artifacts' }) - this.state.artifacts.set(artifact.id, artifact) - out.artifactId = artifact.id - return artifact - }).value - } - - // ---------- 事件日志 / outbox ---------- - - /** - * 追加事件:seq 单调递增,eventId 作为去重键(重复完成事件只登记一次)。 - * 事件与业务写入同一次 mutate,崩溃时要么一起在,要么一起不在。 - */ - appendEvent(event) { - return this.mutate((out) => { - const row = this._appendEvent(event, nowIso(this.clock)) - out.eventId = row.eventId - return row - }).value - } - - _appendEvent(event, stamp) { - // 事件 ID 额外带首个事件自增号:即使调用方注入常量随机源(测试),eventId 仍唯一。 - const eventId = event?.eventId ?? this._nextEventId() - if (this.state.events.some((row) => row.eventId === eventId)) { - throw new StoreError('DUPLICATE_EVENT', `事件已登记: ${eventId}`) - } - this.state.eventSeq += 1 - const row = { - eventId, - seq: this.state.eventSeq, - type: requireString(event?.type, 'event.type'), - projectId: event?.projectId ?? null, - roleId: event?.roleId ?? null, - taskId: event?.taskId ?? null, - attemptId: event?.attemptId ?? null, - payload: clone(event?.payload ?? {}), - createdAt: stamp, - processedAt: event?.processedAt ?? null, - // outbox 投递标记:null 表示尚未确认送达,ack 后写时间戳,事件本身保留审计。 - deliveredAt: event?.deliveredAt ?? null, - } - this.state.events.push(row) - return row - } - - _nextEventId() { - const base = newId('event', this.random === undefined ? {} : { random: this.random }) - const taken = this.state.events.some((row) => row.eventId === base) - return taken ? `${base}.${this.state.eventSeq + 1}` : base - } - - // ---------- 归属校验 ---------- - - _checkReferences(entity) { - const collection = entity.source - const table = REFERENCES[collection] - if (table === undefined) return - if (entity.projectId === undefined || entity.projectId === null) return - if (!isIdOf('project', entity.projectId) || !this.state.projects.has(entity.projectId)) { - throw new StoreError('CROSS_PROJECT', `引用的项目不存在或 ID 非法: ${String(entity.projectId)}`) - } - for (const [field, target] of Object.entries(table)) { - const value = entity[field] - if (value === undefined || value === null) continue - const row = this.state[target].get(value) - if (row === undefined) { - throw new StoreError('NOT_FOUND', `${field} 指向的${target}不存在: ${value}`) - } - if (row.projectId !== entity.projectId) { - throw new StoreError('CROSS_PROJECT', `跨项目引用被拒绝: ${field}=${value} 属于 ${row.projectId}`) - } - } - } - - /** - * 显式归属检查,供服务层在写入前校验外部传入的 task/attempt/artifact ID。 - * 不猜身份:调用方带上的 projectId 必须与目标记录一致,否则拒绝。 - */ - assertProjectOwns(projectId, collection, id) { - const table = this.state[collection] - if (!(table instanceof Map)) throw new StoreError('INVALID_INPUT', `未知集合: ${collection}`) - const row = table.get(id) - if (row === undefined) throw new StoreError('NOT_FOUND', `${collection} 中不存在 ${id}`) - if (row.projectId !== projectId) { - throw new StoreError('CROSS_PROJECT', `${collection}/${id} 不属于项目 ${projectId}`) - } - return row - } - - /** 非终态尝试:宿主重启后要对账的对象。 */ - listOpenAttempts() { - return [...this.state.attempts.values()].filter((row) => !isTerminal('attempt', row.state)) - } - - /** - * 未完成的 outbox:processedAt 与 deliveredAt 都为空的事件,按 seq 升序。 - * options.limit 为正整数时只取最早的前 limit 条(投递端分批拉取用);不传或非法则返回全部,保持旧行为。 - * 只读:不递增 revision,也不落盘。 - */ - listPendingEvents(projectId, options = {}) { - const rows = this.state.events - .filter((row) => row.processedAt === null && (row.deliveredAt ?? null) === null) - .filter((row) => projectId === undefined || row.projectId === projectId) - .slice() - .sort((left, right) => left.seq - right.seq) - const limit = options?.limit - if (!Number.isInteger(limit) || limit <= 0) return rows - return rows.slice(0, limit) - } - - /** - * outbox 的 ack:把属于 projectId、且 eventId 在 eventIds 中的事件标记为已投递(deliveredAt)。 - * 不物理删除——投递记录要能审计;重复 ack、未知 id、别的项目的事件都静默忽略(不跨项目写)。 - * 返回 {delivered}:本次实际新标记的条数;一条都没标时不进 mutate,也就不会白增 revision。 - */ - markEventDelivered(projectId, eventIds) { - requireString(projectId, 'projectId') - // 项目不存在与其它方法一致抛 NOT_FOUND;纯查询校验,失败时不留任何写入。 - if (!this.state.projects.has(projectId)) { - throw new StoreError('NOT_FOUND', `项目不存在: ${projectId}`) - } - if (!Array.isArray(eventIds)) throw new StoreError('INVALID_INPUT', 'eventIds 必须是数组') - const wanted = new Set(eventIds.filter((id) => typeof id === 'string' && id !== '')) - const targets = wanted.size === 0 - ? [] - : this.state.events.filter((row) => wanted.has(row.eventId) && row.projectId === projectId && (row.deliveredAt ?? null) === null) - if (targets.length === 0) return { delivered: 0 } - const stamp = nowIso(this.clock) - return this.mutate(() => { - for (const row of targets) row.deliveredAt = stamp - return { delivered: targets.length } - }).value - } -} - -/** 集合名 → 实体名,供 UI 或日志把表名翻译成实体。 */ -export function entityOf(collection) { - return ENTITY_OF[collection] ?? null -} diff --git a/workbench/core/tasks.mjs b/workbench/core/tasks.mjs deleted file mode 100644 index 92a3f27..0000000 --- a/workbench/core/tasks.mjs +++ /dev/null @@ -1,436 +0,0 @@ -// 任务生命周期:纯函数 + 显式副作用端口。 -// 判定永远不读聊天文本,只认结构化报告、宿主真实终态和可解析的成果引用—— -// 这是“agent 说已完成”与“任务完成”分开的落点。 -// 副作用(写 store、入队、回传)由调用方注入,core 本身不碰网络和调度。 - -import { assertTransition, isState, isTerminal } from './states.mjs' -import { isRoleId } from './roles.mjs' - -export class TaskError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'TaskError' - this.code = code - if (details !== undefined) this.details = details - } -} - -const TASK_BASE_TRANSITIONS = Object.freeze([ - ['draft', 'queued'], - ['queued', 'running'], - ['running', 'waiting_input'], - ['running', 'needs_attention'], - ['running', 'completed'], - ['running', 'failed'], - ['waiting_input', 'queued'], - ['waiting_input', 'running'], - ['needs_attention', 'completed'], - ['needs_attention', 'running'], - ['needs_attention', 'failed'], - // 取消可在任何非终态发起 - ['draft', 'cancelled'], - ['queued', 'cancelled'], - ['running', 'cancelled'], - ['waiting_input', 'cancelled'], - ['needs_attention', 'cancelled'], - // 入队后模型不可用:允许直接失败并保留错误 - ['queued', 'failed'], -]) - -export const TASK_TRANSITIONS = Object.freeze(TASK_BASE_TRANSITIONS.map(([from, to]) => Object.freeze([from, to]))) - -const TERMINAL_TASK_STATES = Object.freeze(['completed', 'failed', 'cancelled']) - -/** seq 比较:仅当新事件 seq 严格大于已见 seq 才视为“更新”。 */ -export function isStaleSeq(lastSeq, nextSeq) { - if (lastSeq === null || lastSeq === undefined) return false - if (!Number.isFinite(nextSeq)) return true - return nextSeq <= lastSeq -} - -/** 乱序/重复事件:达到终态后任何“回到活动态”的事件都必须忽略,而不是报错中断处理。 */ -export function isRegressingEvent(currentStatus, nextStatus) { - if (TERMINAL_TASK_STATES.includes(currentStatus)) return currentStatus !== nextStatus - return false -} - -function transition(state, next, extra = {}) { - assertTransition('task', state, next) - return next -} - -function requireString(value, field) { - if (typeof value !== 'string' || value.trim() === '') { - throw new TaskError('INVALID_INPUT', `${field} 必须是非空字符串`) - } - return value -} - -function requireTask(task) { - if (task === null || typeof task !== 'object' || typeof task.id !== 'string') { - throw new TaskError('INVALID_TASK', '任务记录不合法') - } - return task -} - -/** - * createTask:只建草稿。draft 不等于入队,校验通过且授权有效后才 startTask 入队。 - * ownerRoleId 与 sourceRoleId 都必须是已知席,来源席默认丞相。 - */ -export function createTask(options, deps = {}) { - const { projectId, title, objective, acceptance = [], ownerRoleId, sourceRoleId = 'lead', originMessageRef = null, scope = null, constraints = [], returnTarget = null } = options ?? {} - requireString(projectId, 'projectId') - requireString(title, 'title') - requireString(objective, 'objective') - if (!isRoleId(ownerRoleId)) throw new TaskError('INVALID_ROLE', `未知主责部门: ${String(ownerRoleId)}`) - if (!isRoleId(sourceRoleId)) throw new TaskError('INVALID_ROLE', `未知来源部门: ${String(sourceRoleId)}`) - const id = typeof deps.newTaskId === 'function' ? deps.newTaskId() : undefined - const stamp = typeof deps.now === 'function' ? deps.now() : new Date().toISOString() - return { - ...(id === undefined ? {} : { id }), - projectId, - title, - objective, - acceptance: Array.isArray(acceptance) ? [...acceptance] : [String(acceptance)], - constraints: Array.isArray(constraints) ? [...constraints] : [], - scope: scope ?? null, - ownerRoleId, - sourceRoleId, - originMessageRef, - returnTarget, - status: 'draft', - activeAttemptId: null, - attempts: [], - startedAt: null, - endedAt: null, - reportReceivedAt: null, - needsAttentionReason: null, - failureReason: null, - waitingReason: null, - revision: 1, - createdAt: stamp, - updatedAt: stamp, - } -} - -/** 入队:唯一需要的前置是 draft,或者 waiting_input 拿到补充。 */ -export function startTask(task, deps = {}) { - requireTask(task) - if (task.status !== 'draft' && task.status !== 'waiting_input') { - throw new TaskError('INVALID_STATE', `只有草稿或待补充的任务可以入队,当前 ${task.status}`) - } - const stamp = stampOf(deps) - return { - ...task, - status: transition(task.status, 'queued'), - waitingReason: null, - revision: task.revision + 1, - updatedAt: stamp, - } -} - -/** - * beginAttempt:队列中的任务进入执行,并绑定一次尝试。 - * 每次重试都是新 attempt,旧尝试(及旧结果引用)保留,不覆盖成“第一次就成功”。 - */ -export function beginAttempt(task, attempt, deps = {}) { - requireTask(task) - if (task.status !== 'queued' && task.status !== 'waiting_input' && task.status !== 'needs_attention' && task.status !== 'running') { - throw new TaskError('INVALID_STATE', `任务 ${task.status} 不能开始新的尝试`) - } - // 是否“仍有活动尝试”不能只看 activeAttemptId 是否为空: - // 取消/失败/对账后,Attempt 已转 cancelled/failed/succeeded 终态,但任务的 activeAttemptId 仍指向它(保留审计), - // 若只看非空就会把取消后的重试挡在 ACTIVE_ATTEMPT 上。deps.attemptLookup 由调用方注入(core 不读 store), - // 只有明确查到“非终态”尝试时才算有活动尝试;查不到(undefined/null)时保持旧行为,按非空处理。 - // 另:attempt 的 unknown 是待对账状态,不算终态,仍会挡住重试。 - const hasActiveAttempt = task.activeAttemptId !== null && task.activeAttemptId !== undefined - && !isSettledAttempt(task.activeAttemptId, deps) - // running 下换尝试等于重试:必须先把旧尝试对账(失败/取消),否则两次运行会同时往一个任务里写结果。 - if (task.status === 'running' && hasActiveAttempt) { - throw new TaskError('ACTIVE_ATTEMPT', '当前尝试仍在运行,先对账再重试') - } - if (attempt === null || typeof attempt !== 'object' || typeof attempt.id !== 'string') { - throw new TaskError('INVALID_ATTEMPT', '尝试记录不合法') - } - if (attempt.projectId !== task.projectId) { - throw new TaskError('CROSS_PROJECT', '尝试与任务不属于同一项目') - } - if (attempt.taskId !== task.id) { - throw new TaskError('CROSS_TASK', '尝试挂在别的任务上') - } - if (task.status === 'needs_attention' && hasActiveAttempt) { - throw new TaskError('ACTIVE_ATTEMPT', '仍有未对账的尝试,先完成或标记失败') - } - const stamp = stampOf(deps) - return { - ...task, - status: transition(task.status, 'running'), - activeAttemptId: attempt.id, - attempts: [...task.attempts, attempt.id], - startedAt: task.startedAt ?? stamp, - needsAttentionReason: null, - waitingReason: null, - revision: task.revision + 1, - updatedAt: stamp, - } -} - -/** 结构化报告是否“可信”:summary 非空、成果引用形状正确、检查是真实结果而非空话。 */ -export function validateReport(report) { - const errors = [] - if (report === null || typeof report !== 'object') return ['报告必须是对象'] - if (!report.attemptId || typeof report.attemptId !== 'string') errors.push('缺少 attemptId') - if (!report.taskId || typeof report.taskId !== 'string') errors.push('缺少 taskId') - if (typeof report.summary !== 'string' || report.summary.trim() === '') errors.push('结果摘要为空') - if (report.artifactRefs !== undefined) { - if (!Array.isArray(report.artifactRefs)) errors.push('artifactRefs 必须是数组') - else { - for (const ref of report.artifactRefs) { - if (typeof ref !== 'string' || !ref.startsWith('art_')) errors.push(`成果引用形状非法: ${String(ref)}`) - } - } - } - if (report.checks !== undefined && !Array.isArray(report.checks)) errors.push('checks 必须是数组') - return errors -} - -/** - * 三条完成条件各占一票,缺一条都不能标 completed: - * 1. 可信结构化报告(有摘要、有检查、没有未解决阻塞) - * 2. 宿主运行终态成功(由调用方从宿主取得,不能猜“空闲=成功”) - * 3. 成果引用有效(引用指向本项目现存成果,或被显式标为不可用) - */ -export function checkCompletion(input) { - const { report = null, runTerminal = null, artifactRefs = [], artifactLookup = null } = input ?? {} - const blockers = [] - let reportOk = false - if (report !== null) { - const errors = validateReport(report) - if (errors.length > 0) blockers.push(...errors) - else if (typeof report.blockedReason === 'string' && report.blockedReason.trim() !== '') { - blockers.push('报告标记了阻塞原因') - } else reportOk = true - } else { - blockers.push('未收到结构化报告') - } - const runOk = runTerminal === 'succeeded' - if (runTerminal === null) blockers.push('宿主运行尚未结束') - else if (!runOk) blockers.push(`宿主运行终态为 ${String(runTerminal)}`) - const refs = Array.isArray(artifactRefs) ? artifactRefs : [] - const invalidRefs = [] - for (const ref of refs) { - if (typeof ref !== 'string' || !ref.startsWith('art_')) invalidRefs.push(String(ref)) - else if (typeof artifactLookup === 'function') { - const artifact = artifactLookup(ref) - if (artifact === undefined || artifact === null) invalidRefs.push(ref) - else if (artifact.verification?.status === 'missing') invalidRefs.push(ref) - } - } - if (invalidRefs.length > 0) blockers.push(`成果引用无效: ${invalidRefs.join(', ')}`) - // 纯分析任务允许没有文件,所以“引用为空”本身不算失败,但登记结果时不能伪造附件。 - return { reportOk, runOk, refsValid: invalidRefs.length === 0, blockers, ok: reportOk && runOk && invalidRefs.length === 0 } -} - -/** - * 完成判定三分支: - * - 报告 + 终态成功 + 成果有效 → completed - * - 只有报告(运行未结束) → 保持 running 等终态(waiting 只是“候选结果已存”) - * - 只有终态(无报告) → needs_attention,提供补报入口,不显示已完成 - */ -export function evaluateCompletion(task, input, deps = {}) { - return decide(task, { kind: 'completion', ...input }, deps) -} - -/** - * 统一事件入口:先按 seq 去重、再按状态机判定。旧 seq 或终态后的事件返回 - * { applied:false, stale:true, task },让调用方知道“什么都没变”而不是误以为写入失败。 - */ -export function decide(task, event, deps = {}) { - requireTask(task) - if (event === null || typeof event !== 'object') throw new TaskError('INVALID_EVENT', '事件必须是对象') - const nextSeq = event.seq - if (nextSeq !== undefined && isStaleSeq(task.lastSeq ?? null, nextSeq)) { - return { applied: false, stale: true, task } - } - const stamp = stampOf(deps) - const base = nextSeq === undefined ? task : { ...task, lastSeq: nextSeq } - const commit = (next) => ({ - applied: true, - stale: false, - task: applyStamp({ ...next, id: task.id, projectId: task.projectId }, next, stamp, base), - }) - - switch (event.kind) { - case 'completion': { - if (isTerminal('task', task.status)) return { applied: false, stale: true, task, reason: '任务已终态' } - const verdict = checkCompletion(event) - if (!verdict.reportOk && verdict.runOk) { - return commit({ - ...base, - status: transition(task.status, 'needs_attention'), - needsAttentionReason: '宿主运行已结束但没有有效的结构化报告', - reportReceivedAt: base.reportReceivedAt ?? null, - }) - } - // 用户主动停止的会话,运行终态是 cancelled 而不是"成功但没报告": - // 这一票足以把任务收成 cancelled,不需要也不可能再等到结构化报告。 - if (event.runTerminal === 'cancelled' && !verdict.reportOk) { - return commit({ ...base, status: transition(task.status, 'cancelled'), endedAt: stamp }) - } - if (!verdict.ok) { - // 报告不完整:只记录候选报告,等下一次带完整信息的事件。 - return { applied: false, stale: false, task: base, reason: verdict.blockers.join('; '), verdict } - } - return commit({ - ...base, - status: transition(task.status, 'completed'), - reportReceivedAt: stamp, - needsAttentionReason: null, - failureReason: null, - }) - } - case 'report': { - if (isTerminal('task', task.status)) return { applied: false, stale: true, task } - const errors = validateReport(event.report) - if (errors.length > 0) throw new TaskError('INVALID_REPORT', errors.join('; '), { errors }) - // 报告先到:保存候选结果,等待宿主终态。 - return commit({ ...base, reportReceivedAt: stamp, needsAttentionReason: null }) - } - case 'run_terminal': { - if (isTerminal('task', task.status)) return { applied: false, stale: true, task } - const state = event.runTerminal - if (state === 'succeeded') { - // 只有报告已经到达,才可能在这里直接完成;否则留给 completion 判定。 - if (base.reportReceivedAt !== null && base.status === 'running') { - return commit({ ...base, status: transition(task.status, 'completed') }) - } - return { applied: false, stale: false, task: base, reason: '等待结构化报告' } - } - if (state === 'cancelled') { - return commit({ ...base, status: transition(task.status, 'cancelled'), endedAt: stamp }) - } - return commit({ - ...base, - status: transition(task.status, 'needs_attention'), - needsAttentionReason: `宿主运行终态为 ${String(state)}`, - }) - } - case 'input_required': { - if (task.status !== 'running' && task.status !== 'queued') { - return { applied: false, stale: false, task, reason: `任务 ${task.status} 不接受待补充状态` } - } - return commit({ ...base, status: transition(task.status, 'waiting_input'), waitingReason: String(event.reason ?? '') }) - } - case 'input_supplied': { - if (task.status !== 'waiting_input') return { applied: false, stale: false, task, reason: '任务不在待补充状态' } - return commit({ ...base, status: transition(task.status, 'running'), waitingReason: null }) - } - case 'retry': { - if (task.status !== 'failed' && task.status !== 'cancelled') { - return { applied: false, stale: false, task, reason: '只有失败或已取消的任务可以重试(新任务)' } - } - throw new TaskError('RETRY_REQUIRES_NEW_TASK', '失败/取消后的重试必须创建新任务与新尝试,不能复活旧记录') - } - default: - throw new TaskError('UNKNOWN_EVENT', `未知事件类型: ${String(event.kind)}`) - } -} - -/** 结束时间只写一次:重复到达的终态事件不应改动“最后一次改动时间”。 */ -function applyStamp(task, next, stamp, base) { - const now = { ...base, ...next, updatedAt: stamp } - // completed/failed/cancelled 结束时间只写一次,重复写入会伪造“最后一次改动时间”。 - if (TERMINAL_TASK_STATES.includes(now.status) && now.endedAt === null) now.endedAt = stamp - if (!Number.isFinite(now.revision) || now.revision < 1) now.revision = 1 - else if (now.status !== task.status) now.revision = task.revision + 1 - return now -} - -function stampOf(deps) { - return typeof deps.now === 'function' ? deps.now() : new Date().toISOString() -} - -/** - * activeAttemptId 指向的尝试是否已对账(终态)。 - * 调用方通过 deps.attemptLookup(attemptId) 提供当前 Attempt 记录;core 不直接读 store。 - * unknown 是“待核对宿主”的中间态,不是终态,因此仍然算活动尝试。 - */ -function isSettledAttempt(attemptId, deps) { - const lookup = deps?.attemptLookup - if (typeof lookup !== 'function') return false - const record = lookup(attemptId) - if (record === null || record === undefined || typeof record !== 'object') return false - return isTerminal('attempt', record.state) -} - -// ---------- 便捷包装:每个都只调用 decide,签名简单便于调用方阅读 ---------- - -export function requestInput(task, reason, deps = {}) { - return decide(task, { kind: 'input_required', reason, seq: deps.seq }, deps) -} - -export function supplyInput(task, deps = {}) { - return decide(task, { kind: 'input_supplied', seq: deps.seq }, deps) -} - -export function completeTask(task, input, deps = {}) { - return decide(task, { kind: 'completion', ...input, seq: input?.seq }, deps) -} - -/** 失败必须带原因:没有原因的失败在详情页无法给出恢复入口。 */ -export function failTask(task, reason, deps = {}) { - requireTask(task) - requireString(reason, 'reason') - if (isTerminal('task', task.status)) { - return { applied: false, stale: true, task, reason: '任务已终态' } - } - const stamp = stampOf(deps) - return { - applied: true, - stale: false, - task: { - ...task, - status: transition(task.status, 'failed'), - failureReason: reason, - updatedAt: stamp, - endedAt: task.endedAt ?? stamp, - revision: task.revision + 1, - }, - } -} - -/** 取消是请求,不是结果:这里只落“已取消”的业务结论,宿主的 cancel_requested 另记在 attempt。 */ -export function cancelTask(task, reason = '用户取消', deps = {}) { - requireTask(task) - if (isTerminal('task', task.status)) { - return { applied: false, stale: true, task, reason: '任务已终态' } - } - const stamp = stampOf(deps) - return { - applied: true, - stale: false, - task: { - ...task, - status: transition(task.status, 'cancelled'), - failureReason: task.failureReason ?? null, - cancelReason: reason, - updatedAt: stamp, - endedAt: task.endedAt ?? stamp, - revision: task.revision + 1, - }, - } -} - -/** 把 decide 的结果套到 store 上:只有 applied 才写,避免陈旧事件产生 revision 抖动。 */ -export function applyDecision(store, taskId, decision) { - if (store === undefined || store === null) throw new TaskError('INVALID_STORE', '需要 store') - if (decision === null || typeof decision !== 'object') throw new TaskError('INVALID_DECISION', '判定结果不合法') - if (decision.applied !== true) return decision - const saved = store.updateTask(decision.task) - return { ...decision, task: saved } -} - -/** 任务是否仍在进行(UI 需要区分终态与活动态,但不允许显示百分比)。 */ -export function isOpenTask(task) { - return task !== null && typeof task === 'object' && isState('task', task.status) && !isTerminal('task', task.status) -} diff --git a/workbench/host/contract.mjs b/workbench/host/contract.mjs deleted file mode 100644 index 719784b..0000000 --- a/workbench/host/contract.mjs +++ /dev/null @@ -1,144 +0,0 @@ -// 部门 ↔ 程序的内部操作契约(方案 §6)。 -// -// 四个动作是唯一的“业务事实来源”: -// dispatchTask / reportTaskResult / requestTaskInput / syncDecision -// 部门在会话里怎么说话都不影响账本;账本只认这四条结构化调用。 -// -// 部门在没有自建 HTTP 通道时,用一段可解析的行内指令表达这四个动作: -// 【三省六部】{"action":"reportTaskResult","taskId":"task_…","attemptId":"att_…",…} -// 指令行必须单独成行,前缀固定、正文是单行 JSON。解析器宁可返回 null 也不猜测: -// 解析失败的行当普通文本,绝不用“看起来像”的句子更新任务状态(方案明令禁止)。 -// -// 这里只做“文本 ↔ 结构化调用”的纯转换,不碰网络、不碰 store,便于单测。 - -export const CONTRACT_ACTION_PREFIX = '【三省六部】' - -/** 四个合法动作:多一个少一个都属于“意图不明”,直接拒绝而不是猜。 */ -export const CONTRACT_ACTIONS = Object.freeze([ - 'dispatchTask', - 'reportTaskResult', - 'requestTaskInput', - 'syncDecision', -]) - -const ACTION_SET = new Set(CONTRACT_ACTIONS) - -export class ContractError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'ContractError' - this.code = code - if (details !== undefined) this.details = details - } -} - -/** - * 从一段部门输出里取出全部契约行。 - * - * 返回 { calls, invalid }: - * - calls:解析成功的调用,按出现顺序; - * - invalid:看起来像契约行但 JSON 坏了/缺 action 的行(附原文,便于在 UI 上提示重发)。 - * - * 一个动作只接受一行一条。同一行里塞数组视为格式错误:批量派发必须逐条写, - * 否则“派发到一半失败”无法解释是哪一条。 - */ -export function parseContractLines(text) { - const calls = [] - const invalid = [] - if (typeof text !== 'string' || text === '') return { calls, invalid } - const lines = text.split(/\r?\n/) - for (const raw of lines) { - const line = raw.trim() - if (!line.startsWith(CONTRACT_ACTION_PREFIX)) continue - const body = line.slice(CONTRACT_ACTION_PREFIX.length).trim() - let parsed - try { - parsed = JSON.parse(body) - } catch (error) { - invalid.push({ line: raw, reason: `JSON 解析失败:${error.message}` }) - continue - } - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { - invalid.push({ line: raw, reason: '契约正文必须是单个对象' }) - continue - } - if (typeof parsed.action !== 'string' || !ACTION_SET.has(parsed.action)) { - invalid.push({ line: raw, reason: `未知动作:${String(parsed.action)}` }) - continue - } - calls.push({ action: parsed.action, payload: parsed }) - } - return { calls, invalid } -} - -/** 给部门用的指令模板:只描述字段,不塞业务判断,避免模板把“已完成”写成结论。 */ -const TEMPLATES = Object.freeze({ - dispatchTask: { - taskId: 'task_…', - targetRoleId: 'gongbu', - idempotencyKey: '<同一任务同一意图固定不变>', - packet: { objective: '…', acceptance: ['…'], constraints: [], materialRefs: [] }, - }, - reportTaskResult: { - taskId: 'task_…', - attemptId: 'att_…', - reportVersion: 1, - summary: '做了什么、结果是什么', - checks: [{ name: '检查项', ok: true, detail: '证据' }], - artifactRefs: ['art_…'], - }, - requestTaskInput: { - taskId: 'task_…', - attemptId: 'att_…', - reason: '缺什么、为什么必须由用户决定', - }, - syncDecision: { - taskId: 'task_…', - decision: 'approve | reject | retry', - note: '可选说明', - }, -}) - -/** 渲染成可直接贴进部门系统提示的一小段说明。 */ -export function describeContract() { - const lines = [ - `需要走程序的动作,请单独起一行,写作:${CONTRACT_ACTION_PREFIX}{…单行 JSON…}`, - '平台只认下面四个动作,且只认结构化字段——在正文里写“已完成”不会改变任务状态。', - ] - for (const action of CONTRACT_ACTIONS) { - lines.push(`· ${action}:${JSON.stringify(TEMPLATES[action])}`) - } - return lines.join('\n') -} - -/** - * 单条调用的轻量校验(字段存在性与形状)。业务级校验(归属、状态机、幂等)在 service 层, - * 这里只拦“明显没法处理”的调用,让错误尽早、可读地回到部门。 - */ -export function validateContractCall(call) { - const errors = [] - if (call === null || typeof call !== 'object') return ['调用必须是对象'] - if (!ACTION_SET.has(call.action)) errors.push(`未知动作:${String(call.action)}`) - const payload = call.payload ?? {} - if (typeof payload.taskId !== 'string' || payload.taskId.trim() === '') errors.push('缺少 taskId') - switch (call.action) { - case 'dispatchTask': - if (typeof payload.idempotencyKey !== 'string' || payload.idempotencyKey.trim() === '') { - errors.push('dispatchTask 必须带 idempotencyKey(同一意图固定不变)') - } - break - case 'reportTaskResult': - if (typeof payload.attemptId !== 'string' || payload.attemptId.trim() === '') errors.push('reportTaskResult 必须带 attemptId') - if (typeof payload.summary !== 'string' || payload.summary.trim() === '') errors.push('reportTaskResult 必须带非空 summary') - break - case 'requestTaskInput': - if (typeof payload.reason !== 'string' || payload.reason.trim() === '') errors.push('requestTaskInput 必须带 reason') - break - case 'syncDecision': - if (typeof payload.decision !== 'string' || payload.decision.trim() === '') errors.push('syncDecision 必须带 decision') - break - default: - break - } - return errors -} diff --git a/workbench/host/dispatch-service.mjs b/workbench/host/dispatch-service.mjs deleted file mode 100644 index b16fde0..0000000 --- a/workbench/host/dispatch-service.mjs +++ /dev/null @@ -1,211 +0,0 @@ -// DispatchService:把“账本里的一纸派发”变成“部门会话里真实收到的一条消息”。 -// -// 方案 §7.5 的时序在这里落成四段,每一步失败都有明确去向: -// prepared → 选定会话与配置快照 → sending → prompt(requestId=attemptId) -// ├─ 成功 → accepted -// ├─ 宿主明确拒绝 → rejected(任务保留在排队态,可重试,不算业务失败) -// └─ 超时/断线 → unknown(先查证再决定,绝不自动当失败重发) -// -// 幂等的两层:dispatch 行按 (projectId, idempotencyKey) 去重;prompt 按 attemptId 当 requestId。 -// 因此“用户连点两次”与“发送超时后重试”都不会让部门收到两条任务单。 - -import { buildDispatchText } from './session-adapter.mjs' -import { describeContract } from './contract.mjs' - -export const DISPATCH_OUTCOMES = Object.freeze(['accepted', 'rejected', 'unknown']) - -export class DispatchError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'DispatchError' - this.code = code - if (details !== undefined) this.details = details - } -} - -/** - * @param {object} options - * @param {object} options.store WorkbenchStore - * @param {object} options.service 工作台服务 - * @param {object} options.sessions createSessionAdapter 的产物 - * @param {(message: string) => void} [options.log] - * @param {string} [options.clientTimeZone] 派发提示里的时区,默认 Asia/Shanghai - */ -export function createDispatchService(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') - } - if (service === undefined || typeof service.dispatchTask !== 'function') { - throw new DispatchError('NO_SERVICE', 'DispatchService 需要工作台服务') - } - if (sessions === undefined || typeof sessions.sendPrompt !== 'function') { - throw new DispatchError('NO_SESSIONS', 'DispatchService 需要会话适配层') - } - - const contractGuide = describeContract() - - /** - * 派发一个已入队任务。返回 { dispatch, attempt, outcome, duplicate }。 - * - * 注意顺序:先写账(dispatch+attempt,同一次事务)再发消息。发送前崩溃只会留下 - * prepared 行,对账器会把它当“未发出”处理;先发后写则会出现“部门已收到但账上没有”。 - */ - async function dispatch(input = {}) { - const projectId = requireText(input.projectId, 'projectId') - const taskId = requireText(input.taskId, 'taskId') - const idempotencyKey = requireText(input.idempotencyKey, 'idempotencyKey') - - // 1) 账务:去重 + 校验 + 落 prepared - const prepared = service.dispatchTask({ - projectId, - taskId, - idempotencyKey, - sourceRoleId: input.sourceRoleId, - targetRoleId: input.targetRoleId, - targetSessionId: input.targetSessionId, - bindingGeneration: input.bindingGeneration, - packet: input.packet, - attemptId: input.attemptId, - }) - const { dispatch, attempt, duplicate } = splitPrepared(prepared) - - if (duplicate) { - // 重复点击:什么都不再做,返回既有结论(含 unknown 的历史要由对账处理)。 - return { dispatch, attempt, outcome: outcomeOf(dispatch), duplicate: true } - } - if ((dispatch.status ?? dispatch.state) === 'accepted') return { dispatch, attempt, outcome: 'accepted', duplicate: false } - - // 2) 发送:先把 dispatch 推到 sending,再动宿主,避免“宿主已收但账上还是 prepared”。 - 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 - ? null - : store.getContextPacket(attempt.contextPacketId) - const roleName = input.roleName ?? null - - try { - // 3) 固定本轮配置:模型只在发送前覆写一次,运行中改配置不影响这一轮。 - // 默认不碰宿主会话的模型选择:部门模型由政策插件在 agent/request 上按角色覆写, - // 再调 selectModel 既重复,又会让宿主后台把全局默认模型存成本部门的(A06)。 - // 只有显式 applyModelToSessions:true 时才落这一步。 - const snapshot = attempt?.effectiveConfigSnapshot ?? null - if (applyModelToSessions && snapshot !== null && snapshot.provider && snapshot.model) { - await sessions.applyModel({ - sessionId: attempt.sessionId, - provider: snapshot.provider, - model: snapshot.model, - reasoningEffort: snapshot.reasoningEffort ?? undefined, - }) - } - const text = buildDispatchText({ task, packet, contractGuide, roleName }) - const result = await sessions.sendPrompt({ - sessionId: attempt.sessionId, - requestId: attempt.id, - text, - mode: input.mode ?? 'queue', - clientTimeZone, - }) - if (result.accepted !== true) { - markRejected({ dispatch, attempt, reason: '宿主未确认接收' }) - return { dispatch: store.getDispatch(dispatch.id), attempt, outcome: 'rejected', duplicate: false } - } - // 宿主确认接收 = 这一轮真的开始跑:任务与尝试同时进 running。 - // 只改尝试不改任务,运行终态就无处落地(completion 会因任务仍在 queued 而被丢弃)。 - service.startAttempt({ - projectId: dispatch.projectId, - taskId: dispatch.taskId, - attemptId: attempt.id, - hostRunId: null, - }) - markAccepted({ dispatch, attempt }) - return { dispatch: store.getDispatch(dispatch.id), attempt: store.getAttempt(attempt.id), outcome: 'accepted', duplicate: false } - } catch (error) { - const code = error?.code ?? 'unknown' - if (code === 'conflict' || code === 'rejected') { - markRejected({ dispatch, attempt, reason: error?.message ?? String(error) }) - return { dispatch: store.getDispatch(dispatch.id), attempt, outcome: 'rejected', duplicate: false } - } - // 超时、断线、context 丢失:一律 unknown —— 先查证,不重发。 - markUnknown({ dispatch, attempt, reason: code }) - log(`[sansheng-liubo] 派发 ${dispatch.id} 结果未知(${code}):${error?.message ?? error}`) - return { dispatch: store.getDispatch(dispatch.id), attempt, outcome: 'unknown', duplicate: false } - } - } - - /** - * 对 unknown 的派发做查证:问宿主该会话是否有过这次 attempt 的请求。 - * 查不到就保持 unknown(再次对账),查到有 → accepted;宿主明确从未收到 → rejected。 - */ - async function verifyUnknown(dispatchId) { - const dispatch = store.getDispatch(dispatchId) - if (dispatch === undefined) throw new DispatchError('NOT_FOUND', `派发不存在:${dispatchId}`) - 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, { status: 'accepted', state: 'accepted', verifiedAt: new Date().toISOString() }) - if (attempt.state === 'unknown') { - store.updateAttempt(attempt.id, { state: 'running', hostRunId: attempt.hostRunId ?? null }) - } - return { dispatch: store.getDispatch(dispatch.id), outcome: 'accepted', changed: true } - } - - function splitPrepared(result) { - // service.dispatchTask 返回 { dispatch, attempt, task, roleId, duplicate }(形状见 P1 Phase2)。 - if (result === null || typeof result !== 'object' || result.dispatch === undefined) { - throw new DispatchError('BAD_PREPARED', '服务返回的派发结果形状不正确') - } - return { dispatch: result.dispatch, attempt: result.attempt ?? null, duplicate: result.duplicate === true } - } - - function markAccepted({ dispatch, attempt }) { - const stamp = new Date().toISOString() - store.mutate(() => { - store.updateDispatch(dispatch.id, { status: 'accepted', state: 'accepted', acceptedAt: stamp }) - if (attempt !== null && attempt.state === 'queued') { - store.updateAttempt(attempt.id, { state: 'running', startedAt: stamp }) - } - }) - } - - function markRejected({ dispatch, attempt, reason }) { - const stamp = new Date().toISOString() - store.mutate(() => { - 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 ?? '') }) - } - }) - } - - function markUnknown({ dispatch, attempt, reason }) { - const stamp = new Date().toISOString() - store.mutate(() => { - 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' }) - } - }) - } - - return Object.freeze({ dispatch, verifyUnknown }) -} - -function outcomeOf(dispatch) { - 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' -} - -function requireText(value, field) { - if (typeof value !== 'string' || value.trim() === '') { - throw new DispatchError('INVALID_INPUT', `${field} 必须是非空字符串`, { field }) - } - return value -} diff --git a/workbench/host/index.mjs b/workbench/host/index.mjs deleted file mode 100644 index 5fcc048..0000000 --- a/workbench/host/index.mjs +++ /dev/null @@ -1,229 +0,0 @@ -// Host 侧装配:把账本、业务服务、会话层和 HTTP 路由接在一起。 -// -// 这一层是唯一知道“账本文件在哪、损坏了怎么办”的地方: -// - 账本损坏(不是 JSON / schemaVersion 不符)时不崩溃:把坏文件改名留存, -// 从空账本启动,并把 warning 交给调用方(index.js / 诊断页)显示。 -// 悄悄删掉或不说话都会让人以为“历史记录丢了”。 -// - 宿主没有 webServer 时照常返回 service,只是路由不注册,registered=false; -// 若宿主稍后提供了 webServer,用 ctx.inject 补注册一次(不重复建 store)。 -// - 宿主没有 sessionController 时,工作台仍能读写账本(投影可用), -// 但派发只落账不投递,UI 显示“尚未接通”,绝不假装成功。 -// -// 与 workbench-host.mjs 的关系:那边是「账本 + 会话层 + 对账」的纯逻辑外壳, -// 这边负责文件、损坏隔离、HTTP 与生命周期,并把路由钩子接到外壳上。 - -import { existsSync, renameSync } from 'node:fs' -import { WorkbenchStore, SCHEMA_VERSION } from '../core/store.mjs' -import { corruptPathFor, ensureSidecarDir, resolveSidecarDir, resolveStorePath } from './paths.mjs' -import { registerWorkbenchRoutes } from './routes.mjs' -import { createWorkbenchHost as createWorkbenchShell } from './workbench-host.mjs' - -export { createWorkbenchService } from './service.mjs' -export { - createWorkbenchHost as createWorkbenchShell, - CONTRACT_ACTIONS, - CONTRACT_ACTION_PREFIX, - describeContract, - parseContractLines, - WORKBENCH_HOST_VERSION, -} from './workbench-host.mjs' -export { - buildRouteTable, - listWorkbenchRoutes, - registerWorkbenchRoutes, - MAX_BODY_BYTES, - ROUTE_PREFIX, -} from './routes.mjs' -export { - SIDECAR_DIR_NAME, - corruptPathFor, - ensureSidecarDir, - quarantineFile, - readJsonSafe, - resolveSidecarDir, - resolveSidecarFile, - resolveStorePath, - writeFileAtomic, - writeJsonAtomic, -} from './paths.mjs' - -/** - * 创建 Host 侧工作台。 - * - * @param {object|null} ctx 宿主上下文(可为 null:服务仍可用,只是没有路由/会话)。 - * @param {object} [options] - * @param {string} [options.file] 账本路径;默认 %DSH_HOME%/sansheng-liubu/workbench.json。 - * @param {object} [options.env] 计算默认路径用的环境变量。 - * @param {() => number} [options.clock] 注入时钟。 - * @param {() => string} [options.random] 注入随机源(测试里固定 ID 用)。 - * @param {boolean} [options.load=true] 是否从磁盘加载既有账本。 - * @param {string} [options.presetId] 部门会话使用的 agentPreset,默认「上朝」。 - * @param {boolean} [options.startReconciler=true] 是否启动周期对账。 - * @param {number} [options.longPollMs] 事件长轮询上限(毫秒)。 - * @param {number} [options.pollIntervalMs] 长轮询内部检查间隔(毫秒)。 - * @returns {object} 见文件末尾 return 语句的字段说明。 - */ -export function createWorkbenchHost(ctx, options = {}) { - const env = options.env ?? process.env - const clock = options.clock ?? Date.now - const file = options.file === undefined ? resolveStorePath(env) : options.file - const warnings = [] - const log = typeof options.log === 'function' ? options.log : () => {} - - // 测试与嵌入场景可以自带账本;自带时不碰磁盘路径,也不做损坏隔离(那是文件的责任)。 - const injectedStore = options.store ?? null - const store = injectedStore ?? new WorkbenchStore({ - file, - clock, - env, - ...(options.random === undefined ? {} : { random: options.random }), - }) - - if (injectedStore === null && options.load !== false && file !== null && file !== '') { - ensureSidecarDir(env) - if (existsSync(file)) { - try { - store.load() - } catch (error) { - // 损坏与版本不符都是“这个文件不能用”:改名留存后从空账本启动。 - // 绝不覆盖原文件——里面可能是用户唯一一份历史。 - const stamp = new Date(clock()).toISOString().replace(/[:.]/g, '-') - let quarantined = corruptPathFor(file, stamp) - try { - renameSync(file, quarantined) - } catch (renameError) { - // 改名失败(被占用/权限不足):不能继续往同一个文件写,退回纯内存账本。 - quarantined = null - warnings.push( - `账本损坏且无法改名留存(${renameError?.code ?? 'UNKNOWN'}):${error?.message ?? ''};本次使用内存账本`, - ) - } - if (quarantined !== null) { - warnings.push( - `账本损坏(${error?.code ?? 'ERROR'}:${error?.message ?? ''}),已改名留存为 ${quarantined},以空账本启动`, - ) - } - } - } - } - - // 外壳持有 store 与 service,并在宿主有能力时装配会话层/派发/对账。 - const shell = createWorkbenchShell(ctx, { - store, - presetId: options.presetId, - startReconciler: options.startReconciler, - clock, - // 成果文件是否还在,由宿主文件系统回答(A23 失效显示);测试可注入替身。 - fileExists: options.fileExists ?? existsSync, - }) - const service = shell.service - - const hooks = routeHooks(shell, service) - let routes = registerWorkbenchRoutes(ctx, service, { ...options, ...hooks }) - let registered = routes.registered !== false - if (!registered) warnings.push(`工作台接口未注册:${routes.reason ?? '宿主未提供 webServer'}`) - - // 宿主稍后才提供 webServer 时补注册一次;cordis 会在依赖出现时回调, - // 插件卸载时随作用域一起清理,不需要手工跟踪。 - if (!registered && ctx !== null && typeof ctx?.inject === 'function') { - try { - ctx.inject(['webServer'], (scoped) => { - if (registered) return - const late = registerWorkbenchRoutes({ webServer: scoped?.webServer }, service, { ...options, ...hooks }) - if (late.registered === false) return - routes = late - registered = true - }) - } catch (error) { - warnings.push(`工作台接口补注册失败:${error?.message ?? error}`) - } - } - - // 会话层也可能晚到:apply 时 sessionController 还没装好,等它出现再挂载一次, - // 这样用户不必为了「接通部门」而多重启一次 DSH。 - if (shell.hasSessions === false && ctx !== null && typeof ctx?.inject === 'function') { - try { - ctx.inject(['sessionController'], (scoped) => { - if (shell.hasSessions === true) return - const controller = scoped?.sessionController ?? scoped?.remote?.session ?? null - if (controller === null) return - if (!shell.attachSessions(controller)) return - log('[sansheng-liubo] 会话层已就绪,部门可以接通与派发') - }) - } catch (error) { - warnings.push(`会话层补挂失败:${error?.message ?? error}`) - } - } - - shell.start() - - const dispose = () => { - try { - routes() - } finally { - shell.dispose() - } - } - - return { - store, - service, - shell, - routes, - get sessions() { - return shell.sessions - }, - get reconciler() { - return shell.reconciler - }, - get dispatchService() { - return shell.dispatchService - }, - get hasSessions() { - return shell.hasSessions - }, - attachSessions: shell.attachSessions, - presetId: shell.presetId, - connectDepartment: shell.connectDepartment, - dispatchTask: shell.dispatchTask, - ingestAgentOutput: shell.ingestAgentOutput, - file: store.file, - sidecarDir: resolveSidecarDir(env), - get registered() { - return registered - }, - warning: warnings.length === 0 ? null : warnings.join(';'), - warnings, - /** 卸载路由与后台服务(幂等);账本不删除,下次启动继续用。 */ - dispose, - schemaVersion: SCHEMA_VERSION, - } -} - -/** - * 路由钩子:只有宿主真有能力时才接管,否则让路由退回“只落账”的保守路径。 - * 这样“没接通”永远不会被伪装成“已发送”。 - */ -function routeHooks(shell, service) { - return { - connect: (input) => shell.connectDepartment(input), - ingest: (input) => shell.ingestAgentOutput(input), - // 会话层可能晚到,所以钩子恒挂:真挂上了就走派发,没挂上就退回「只落账」, - // 绝不把「没接通」伪装成「已发送」。 - dispatch: (input) => { - if (shell.hasSessions === true) return shell.dispatchTask(input) - return service.dispatchTask({ - projectId: input.projectId, - taskId: input.taskId, - idempotencyKey: input.idempotencyKey, - sourceRoleId: input.sourceRoleId, - targetRoleId: input.targetRoleId, - targetSessionId: input.targetSessionId, - bindingGeneration: input.bindingGeneration, - packet: input.packet, - }) - }, - } -} - -export default createWorkbenchHost diff --git a/workbench/host/paths.mjs b/workbench/host/paths.mjs deleted file mode 100644 index 79ca54b..0000000 --- a/workbench/host/paths.mjs +++ /dev/null @@ -1,118 +0,0 @@ -// 侧车(sidecar)路径与目录:业务账、导出物都放在宿主允许的位置,不进项目目录。 -// 默认 %DSH_HOME%/sansheng-liubu/;没有 DSH_HOME 时退回 ~/.dsh。 -// env 可注入:测试与多实例部署用同一套函数,不读第二份全局配置。 -// -// 原子写在 store 里还有一份(先写 .tmp 再 rename);这里只给 HTTP/导出这类 -// “宿主侧杂项文件”用同一套规则,避免两处对“半截文件”的处理不一致。 - -import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join, resolve } from 'node:path' - -export const SIDECAR_DIR_NAME = 'sansheng-liubu' - -/** 侧车目录:DSH_HOME 优先,其次 ~/.dsh;相对路径按当前目录解析,不做猜测。 */ -export function resolveSidecarDir(env = process.env) { - const raw = env && typeof env.DSH_HOME === 'string' ? env.DSH_HOME.trim() : '' - const home = raw === '' ? join(homedir(), '.dsh') : raw - return resolve(home, SIDECAR_DIR_NAME) -} - -/** - * 账本文件路径。DSH_SANSHENG_WORKBENCH_FILE 可整体改写(用于独立测试实例); - * 它必须指向具体文件名,不能只是目录,否则会在目录名上写半截 JSON。 - */ -export function resolveStorePath(env = process.env) { - const override = env && typeof env.DSH_SANSHENG_WORKBENCH_FILE === 'string' - ? env.DSH_SANSHENG_WORKBENCH_FILE.trim() - : '' - if (override !== '') return resolve(override) - return join(resolveSidecarDir(env), 'workbench.json') -} - -/** 派生路径:同一侧车目录下按用途分开,便于用户自己备份或清理而不碰账本。 */ -export function resolveSidecarFile(name, env = process.env) { - if (typeof name !== 'string' || name.trim() === '') throw new Error('name 必须是非空字符串') - if (name.includes('/') || name.includes('\\')) throw new Error('name 只能是一级文件名,不能带目录分隔符') - return join(resolveSidecarDir(env), name) -} - -/** 目录级入口:所有写入前都先建目录,缺目录不该表现为“保存失败”。 */ -export function ensureSidecarDir(env = process.env) { - const dir = resolveSidecarDir(env) - mkdirSync(dir, { recursive: true }) - return dir -} - -/** 损坏文件的改名后缀:.corrupt-<时间戳>,保留现场且不覆盖下一次的结果。 */ -export function corruptPathFor(file, stamp = Date.now()) { - return `${file}.corrupt-${stamp}` -} - -/** - * 把可能损坏的文件挪到一边:返回新路径;文件不存在返回 null(不算错误)。 - * 只改名不删除——损坏的账本里可能有用户唯一的业务记录,删掉就等于替用户做了决定。 - */ -export function quarantineFile(file, stamp = Date.now()) { - if (!existsSync(file)) return null - let target = corruptPathFor(file, stamp) - let attempt = 1 - while (existsSync(target)) { - target = `${corruptPathFor(file, stamp)}-${attempt}` - attempt += 1 - } - renameSync(file, target) - return target -} - -/** - * 原子写文本:同目录 .tmp → rename。 - * Windows 上覆盖 rename 可能因杀软/索引占用失败,退化成“删旧再改名”; - * 最坏情况是目标短暂缺失,而不是留下半截内容。 - */ -export function writeFileAtomic(file, text) { - const target = resolve(file) - mkdirSync(dirname(target), { recursive: true }) - const tmp = `${target}.${process.pid}.${Date.now()}.tmp` - try { - writeFileSync(tmp, String(text), 'utf8') - try { - renameSync(tmp, target) - } catch { - rmSync(target, { force: true }) - renameSync(tmp, target) - } - } finally { - rmSync(tmp, { force: true }) - } - return target -} - -/** - * 原子写 JSON:两空格缩进加尾换行,适合人读与 git diff。 - * 不能序列化的值(BigInt、循环引用)直接抛错,不写一份“看起来写成了”的内容。 - */ -export function writeJsonAtomic(file, value) { - const text = `${JSON.stringify(value, null, 2)}\n` - return writeFileAtomic(file, text) -} - -/** 读 JSON;文件不存在或解析失败都返回 fallback,让调用方决定是否报错。 */ -export function readJsonSafe(file, fallback = null) { - try { - if (!existsSync(file)) return fallback - return JSON.parse(readFileSync(file, 'utf8')) - } catch { - return fallback - } -} - -/** 文件是否可读且非空;用于“成果文件已被删除”这类检查,不做内容解析。 */ -export function fileLooksUsable(file) { - try { - const info = statSync(file) - return info.isFile() && info.size > 0 - } catch { - return false - } -} diff --git a/workbench/host/reconciler.mjs b/workbench/host/reconciler.mjs deleted file mode 100644 index 4f1d9a4..0000000 --- a/workbench/host/reconciler.mjs +++ /dev/null @@ -1,181 +0,0 @@ -// Reconciler:把“部门会话里真实发生了什么”折算成 attempt 的终态。 -// -// 方案 §7.4 的硬约束:宿主运行结束 ≠ 业务完成。所以这里只做“运行终态”的判定, -// 业务完成由 tasks.decide 用(结构化报告 + 运行终态 + 成果引用)三票共同决定。 -// -// 数据来源只有两类可信信号: -// 1. 宿主 follow 事件里的 turn/结束信号(附加 latest.assistant-stream 之外的持久帧); -// 2. 主动查询 controller.list() 里该会话的 running 位。 -// 绝不从聊天文本推断“做完了”。 - -import { classifyHostError } from './session-adapter.mjs' - -export const RECONCILER_DEFAULT_INTERVAL_MS = 30000 -export const RECONCILER_MIN_INTERVAL_MS = 5000 - -/** - * @param {object} options - * @param {object} options.store WorkbenchStore - * @param {object} options.service 工作台服务(reportRunTerminal / markDispatch / syncDecision…) - * @param {object} options.sessions createSessionAdapter 的产物 - * @param {() => number} [options.clock] - * @param {(message: string) => void} [options.log] - */ -export function createReconciler(options = {}) { - const { store, service, sessions, clock = Date.now, log = () => {} } = options - if (store === undefined || typeof store.listOpenAttempts !== 'function') { - throw new Error('createReconciler 需要 WorkbenchStore') - } - if (service === undefined || typeof service.reportRunTerminal !== 'function') { - throw new Error('createReconciler 需要工作台服务') - } - let timer = null - let running = false - - /** - * 单次对账。返回结构化结果供日志与测试断言,不吞异常也不抛出: - * 一个会话查不到不该阻断其它会话的对账。 - */ - async function reconcileOnce() { - if (running) return { skipped: true, reason: 'busy', checked: 0, changed: [] } - running = true - const outcome = { skipped: false, checked: 0, changed: [], errors: [] } - try { - const open = store.listOpenAttempts() - for (const attempt of open) { - outcome.checked += 1 - try { - const change = await reconcileAttempt(attempt) - if (change !== null) outcome.changed.push(change) - } catch (error) { - outcome.errors.push({ attemptId: attempt.id, message: messageOf(error) }) - log(`[sansheng-liubo] 对账 ${attempt.id} 失败:${messageOf(error)}`) - } - } - } finally { - running = false - } - return outcome - } - - /** - * 单个 attempt 的对账: - * - 宿主问不到(null)→ 什么也不改,等下一轮(宁可晚,不可猜); - * - 还在跑 → 只把 queued 推进到 running,不改结论; - * - 已停 → 依 state 决定:cancel_requested 转 cancelled,其余转 succeeded(再交 completion 三票判定)。 - */ - async function reconcileAttempt(attempt) { - const projectId = attempt.projectId - let task = store.getTask(attempt.taskId) - if (task === undefined) return null - const runningFlag = await sessions.isRunning(attempt.sessionId) - if (runningFlag === null) return null - const now = new Date(clock()).toISOString() - - if (runningFlag) { - if (attempt.state === 'queued') { - store.updateAttempt(attempt.id, { state: 'running', hostRunId: attempt.hostRunId ?? null, heartbeatAt: now }) - // 任务要跟着进 running:只有任务处于 running 时,运行终态才能折算成 - // completed / needs_attention / cancelled,否则终态会被状态机丢弃。 - if (task.status === 'queued') { - try { - // service.startAttempt 会同时把任务推进到 running,并把最新任务读回来。 - const started = service.startAttempt({ - projectId, - taskId: task.id, - attemptId: attempt.id, - hostRunId: attempt.hostRunId ?? null, - }) - task = started.task ?? task - } catch (error) { - log(`[sansheng-liubo] 任务 ${task.id} 推进 running 被拒:${messageOf(error)}`) - } - } - return { attemptId: attempt.id, from: 'queued', to: 'running' } - } - return null - } - - // 宿主说会话不跑了:这是“运行终态 = 正常结束”,不是业务完成。 - // 用户点过停止(cancel_requested)的尝试记为 cancelled,不当成成功运行。 - // 用户点过停止:可能是适配器已经写过 cancel_requested,也可能只是刚发出停止请求 - // (cancel() 是同步 accepted,不等于已停)。两种都按取消收口,否则"取消与成功竞争"里 - // 被取消的这一次会被记成成功运行,任务显示已完成。 - const cancelRequested = attempt.state === 'cancel_requested' || sessions.wasCancelRequested(attempt.sessionId) - if (attempt.state === 'running' || attempt.state === 'queued' || cancelRequested) { - const nextState = cancelRequested ? 'cancelled' : 'succeeded' - // running 不能直接到 cancelled:用户请求过停止的,先记 cancel_requested 再收口, - // 状态机与审计都保留"请求过停止"这一步。 - if (nextState === 'cancelled' && attempt.state !== 'cancel_requested') { - store.updateAttempt(attempt.id, { state: 'cancel_requested', cancelRequestedAt: now }) - } - store.updateAttempt(attempt.id, { state: nextState, endedAt: now }) - applyTerminal({ attempt, task, terminal: nextState === 'cancelled' ? 'cancelled' : 'succeeded' }) - return { attemptId: attempt.id, from: attempt.state, to: nextState } - } - return null - } - - function applyTerminal({ attempt, task, terminal }) { - try { - // 任务侧:run_terminal 只是“一票”。没报告时只会变 needs_attention,不会变 completed。 - service.reportRunTerminal({ - projectId: attempt.projectId, - taskId: attempt.taskId, - attemptId: attempt.id, - runTerminal: terminal, - }) - } catch (error) { - // 状态机拒绝重复/乱序终态是正常情况:记一行,不抛出。 - log(`[sansheng-liubo] 任务 ${task.id} 记录运行终态被拒:${messageOf(error)}`) - } - } - - /** 一个会话里出现了新的 assistant 完成回合:作为“可能已结束”的信号触发一次定向对账。 */ - async function onSessionFrame({ sessionId }) { - const open = store.listOpenAttempts().filter((row) => row.sessionId === sessionId) - if (open.length === 0) return { checked: 0 } - for (const attempt of open) { - try { - await reconcileAttempt(attempt) - } catch (error) { - log(`[sansheng-liubo] 帧触发对账失败:${messageOf(error)}`) - } - } - return { checked: open.length } - } - - function start({ intervalMs = RECONCILER_DEFAULT_INTERVAL_MS } = {}) { - if (timer !== null) return - const period = Math.max(RECONCILER_MIN_INTERVAL_MS, Number(intervalMs) || RECONCILER_DEFAULT_INTERVAL_MS) - timer = setInterval(() => { - reconcileOnce().catch((error) => log(`[sansheng-liubo] 周期对账异常:${messageOf(error)}`)) - }, period) - // 宿主退出时不要让定时器把进程吊住。 - if (typeof timer.unref === 'function') timer.unref() - } - - function stop() { - if (timer !== null) { - clearInterval(timer) - timer = null - } - } - - return Object.freeze({ - reconcileOnce, - reconcileAttempt, - onSessionFrame, - start, - stop, - get scheduled() { - return timer !== null - }, - }) -} - -function messageOf(error) { - return error instanceof Error ? error.message : String(error) -} - -export { classifyHostError } diff --git a/workbench/host/routes.mjs b/workbench/host/routes.mjs deleted file mode 100644 index 0541e94..0000000 --- a/workbench/host/routes.mjs +++ /dev/null @@ -1,445 +0,0 @@ -// 工作台 HTTP 路由:把 service 暴露给宿主 Web 服务。 -// -// 设计取舍: -// - 全部 exact 路由,不做前缀匹配:/sansheng/workbench/xxx 未登记的一律 404, -// 不会因为前缀相同就把未知路径交给某个 handler 兜底。 -// - 非 GET 只接受 POST(其余方法 405),未实现的路径 404,参数错误 400,体过大 413。 -// - 统一包装 { ok:true, value } / { ok:false, error:{ code, message, details? } }, -// Content-Type 带 charset、Cache-Control: no-store、Content-Length 手写。 -// - 事件通道用长轮询而不是 SSE:宿主侧只是一个普通 HTTP handler, -// 浏览器刷新/断线重连后靠 since 补齐天然幂等,不需要管连接生命周期; -// 最长挂 25 秒,远低于常见代理/浏览器的空闲超时,也不占住宿主的事件循环。 -// - 任何 ctx.webServer 的缺失都在 registerWorkbenchRoutes 里探测并降级: -// 返回一个 no-op 的 dispose,route 列表照常给出,便于诊断而不至于让插件加载失败。 - -import { ServiceError } from './service.mjs' - -export const ROUTE_PREFIX = '/sansheng/workbench' - -/** 请求体字节上限:契约里最大的是交接材料(摘录 + 引用),256 KB 足够且能挡住误传大文件。 */ -export const MAX_BODY_BYTES = 256 * 1024 - -/** 长轮询最长挂起时间(毫秒)。浏览器重连后靠 since 补齐,所以不需要真正的无限等待。 */ -export const DEFAULT_LONG_POLL_MS = 25_000 - -/** 轮询间隔:太密会白烧 CPU,太疏会让“有新事件立刻返回”的承诺打折。 */ -const POLL_INTERVAL_MS = 1_000 - -/** 业务错误码 → HTTP 状态码。未列出的统一 400。 */ -const STATUS_OF_CODE = Object.freeze({ - INVALID_INPUT: 400, - INVALID_ROLE: 400, - INVALID_STATE: 400, - DISPATCH_INVALID: 400, - ATTEMPT_MISMATCH: 400, - REPORT_INVALID: 400, - NOT_FOUND: 404, - CROSS_PROJECT: 409, - CONFIG_CONFLICT: 409, - SESSION_CONFLICT: 409, - DUPLICATE_PROJECT: 409, - INTERNAL: 500, -}) - -function statusOf(error) { - if (error instanceof ServiceError) return STATUS_OF_CODE[error.code] ?? 400 - if (error !== null && typeof error === 'object' && typeof error.code === 'string') { - return STATUS_OF_CODE[error.code] ?? 400 - } - return 500 -} - -/** 响应写出:统一头 + 手写 Content-Length,HEAD 不写体。 */ -function sendJson(res, status, payload, extraHeaders = undefined) { - const body = JSON.stringify(payload) - const headers = { - 'Content-Type': 'application/json; charset=utf-8', - 'Cache-Control': 'no-store', - 'Content-Length': Buffer.byteLength(body), - ...(extraHeaders ?? {}), - } - res.writeHead(status, headers) - res.end(body) - return body -} - -function sendOk(res, value, extraHeaders) { - return sendJson(res, 200, { ok: true, value }, extraHeaders) -} - -function sendError(res, error) { - const status = statusOf(error) - const code = typeof error?.code === 'string' ? error.code : 'INTERNAL' - const message = status === 500 && !(error instanceof ServiceError) - ? '内部错误' - : (typeof error?.message === 'string' ? error.message : '请求失败') - const payload = { ok: false, error: { code, message } } - if (error?.details !== undefined) payload.error.details = error.details - return sendJson(res, status, payload) -} - -/** - * 读请求体:按字节累计,超限立即拒绝(不再继续读,避免被巨大体拖住)。 - * 空体视为 {},让无参 POST 也能走同一个入口。 - */ -async function readJsonBody(req, limit = MAX_BODY_BYTES) { - const chunks = [] - let total = 0 - for await (const chunk of req) { - const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) - total += buffer.length - if (total > limit) { - const error = new ServiceError('INVALID_INPUT', `请求体超过 ${limit} 字节上限`, { limit }) - error.httpStatus = 413 - throw error - } - chunks.push(buffer) - } - const text = Buffer.concat(chunks).toString('utf8').trim() - if (text === '') return {} - try { - const parsed = JSON.parse(text) - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw new Error('not an object') - } - return parsed - } catch { - const error = new ServiceError('INVALID_INPUT', '请求体必须是 JSON 对象') - error.httpStatus = 400 - throw error - } -} - -async function readBody(req, limit) { - try { - return await readJsonBody(req, limit) - } catch (error) { - // 体超限与 JSON 非法是 HTTP 层语义,借 httpStatus 覆盖默认映射。 - if (typeof error.httpStatus === 'number') { - const wrapped = new ServiceError(error.code, error.message, error.details) - wrapped.httpStatus = error.httpStatus - throw wrapped - } - throw error - } -} - -/** 从 URL 里取查询参数(不依赖宿主框架,纯 node URL)。 */ -function queryOf(url) { - const index = typeof url === 'string' ? url.indexOf('?') : -1 - if (index < 0) return new URLSearchParams('') - const rest = url.slice(index + 1) - const hash = rest.indexOf('#') - return new URLSearchParams(hash < 0 ? rest : rest.slice(0, hash)) -} - -function pathOf(url) { - if (typeof url !== 'string') return '' - const cut = url.search(/[?#]/) - return cut < 0 ? url : url.slice(0, cut) -} - -/** - * 长轮询:最多挂 maxWaitMs,期间每 pollIntervalMs 检查一次是否有新事件; - * 一旦有就立刻返回(不等到窗口结束),没有就等到窗口结束返回空列表 + 当前 seq。 - * 客户端断开(req 触发 close)时立即结束,不留悬挂计时器。 - */ -async function waitForEvents(service, projectId, since, options) { - const maxWaitMs = options.longPollMs ?? DEFAULT_LONG_POLL_MS - const pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS - const immediate = service.listEvents(projectId, since, options.eventLimit === undefined ? {} : { limit: options.eventLimit }) - if (immediate.events.length > 0 || immediate.reset) return immediate - const deadline = Date.now() + maxWaitMs - while (Date.now() < deadline) { - const remain = deadline - Date.now() - await sleep(Math.max(1, Math.min(pollIntervalMs, remain))) - const fresh = service.listEvents(projectId, since, options.eventLimit === undefined ? {} : { limit: options.eventLimit }) - if (fresh.events.length > 0 || fresh.reset) return fresh - } - return service.listEvents(projectId, since, options.eventLimit === undefined ? {} : { limit: options.eventLimit }) -} - -function sleep(ms) { - return new Promise((resolve) => { - const timer = setTimeout(resolve, ms) - // 计时器不应阻止进程退出(测试里尤其明显)。 - if (typeof timer.unref === 'function') timer.unref() - }) -} - -/** 统一 handler 包装:方法校验、异常兜底、响应头注入。 */ -function wrap(handler, { methods = ['POST'], allowBody = true, bodyLimit = MAX_BODY_BYTES } = {}) { - return async (req, res) => { - try { - const method = String(req.method ?? 'GET').toUpperCase() - if (!methods.includes(method)) { - res.setHeader('Allow', methods.join(', ')) - sendJson(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: `仅支持 ${methods.join(', ')}` } }) - return - } - const body = allowBody && method === 'POST' ? await readBody(req, bodyLimit) : {} - const url = req.url ?? '' - const value = await handler({ req, res, body, method, query: queryOf(url), path: pathOf(url) }) - // handler 自己已经写过响应(例如长轮询中途断开)时不再写第二遍。 - if (res.writableEnded === true) return - const headers = value !== null && typeof value === 'object' && value.__headers !== undefined ? value.__headers : undefined - const payload = headers === undefined ? value : value.payload - sendOk(res, payload, headers) - } catch (error) { - if (res.writableEnded === true) return - const status = typeof error?.httpStatus === 'number' ? error.httpStatus : statusOf(error) - const code = typeof error?.code === 'string' ? error.code : 'INTERNAL' - const payload = { ok: false, error: { code, message: error?.message ?? '请求失败' } } - if (error?.details !== undefined) payload.error.details = error.details - sendJson(res, status, payload) - } - } -} - -/** - * 路由表:path → handler 定义。集中声明,便于诊断页一次性列出全部端点。 - * 每个 handler 都从 body/query 取参数并原样交给 service,不在路由层做业务判断。 - */ -export function buildRouteTable(service, options = {}) { - const select = options.projectIdFrom === undefined ? (body) => body.projectId : options.projectIdFrom - return Object.freeze({ - [`${ROUTE_PREFIX}/bootstrap`]: { - method: 'GET', - handler: async ({ query }) => service.bootstrap(query.get('projectId') ?? undefined), - }, - [`${ROUTE_PREFIX}/project`]: { - method: 'POST', - handler: async ({ body }) => service.registerProject({ - hostWorkspaceId: body.hostWorkspaceId, - displayNameCache: body.displayNameCache, - canonicalRoot: body.canonicalRoot, - }), - }, - [`${ROUTE_PREFIX}/bind`]: { - method: 'POST', - handler: async ({ body }) => service.bindDepartmentSession({ - projectId: select(body), - roleId: body.roleId, - sessionId: body.sessionId, - allowReplace: body.allowReplace, - creationRequestId: body.creationRequestId, - }), - }, - [`${ROUTE_PREFIX}/config`]: { - method: 'POST', - handler: async ({ body }) => service.saveDepartmentConfig({ - projectId: select(body), - roleId: body.roleId, - provider: body.provider, - model: body.model, - reasoningEffort: body.reasoningEffort, - expectedRevision: body.expectedRevision, - }), - }, - [`${ROUTE_PREFIX}/task`]: { - method: 'POST', - handler: async ({ body }) => service.createTask({ - projectId: select(body), - title: body.title, - objective: body.objective, - acceptance: body.acceptance, - constraints: body.constraints, - scope: body.scope, - ownerRoleId: body.ownerRoleId, - sourceRoleId: body.sourceRoleId, - originMessageRef: body.originMessageRef, - returnTarget: body.returnTarget, - status: body.status, - }), - }, - [`${ROUTE_PREFIX}/task/cancel`]: { - method: 'POST', - handler: async ({ body }) => service.cancelTask({ - projectId: select(body), - taskId: body.taskId, - reason: body.reason, - }), - }, - [`${ROUTE_PREFIX}/connect`]: { - method: 'POST', - handler: async ({ body }) => { - if (typeof options.connect !== 'function') { - throw new ServiceError('INVALID_STATE', '宿主未提供会话能力,暂时无法接通部门') - } - return options.connect({ - projectId: select(body), - roleId: body.roleId, - sessionId: body.sessionId, - agentPreset: body.agentPreset, - }) - }, - }, - [`${ROUTE_PREFIX}/dispatch`]: { - method: 'POST', - handler: async ({ body }) => { - const ledger = { - projectId: select(body), - taskId: body.taskId, - idempotencyKey: body.idempotencyKey, - sourceRoleId: body.sourceRoleId, - targetRoleId: body.targetRoleId, - targetSessionId: body.targetSessionId, - bindingGeneration: body.bindingGeneration, - packet: body.packet, - } - // 有 Host 会话能力时走 DispatchService:它会真的把任务单送进部门会话, - // 并把 prepared → sending → accepted/rejected/unknown 走完。 - // 没有会话层时只落账(prepared),UI 据此显示“尚未接通”,绝不假装已发送。 - if (typeof options.dispatch === 'function') { - return options.dispatch({ - ...ledger, - sourceSessionId: body.sourceSessionId, - mode: body.mode, - roleName: body.roleName, - }) - } - return service.dispatchTask(ledger) - }, - }, - [`${ROUTE_PREFIX}/ingest`]: { - method: 'POST', - handler: async ({ body }) => { - if (typeof options.ingest !== 'function') { - throw new ServiceError('INVALID_STATE', '宿主未提供契约解析能力') - } - return options.ingest({ - projectId: select(body), - roleId: body.roleId, - text: body.text, - }) - }, - }, - [`${ROUTE_PREFIX}/result`]: { - method: 'POST', - handler: async ({ body }) => service.reportTaskResult({ - projectId: select(body), - taskId: body.taskId, - attemptId: body.attemptId, - report: body.report, - runTerminal: body.runTerminal, - artifactRefs: body.artifactRefs, - checks: body.checks, - remainingItems: body.remainingItems, - blockedReason: body.blockedReason, - sourceMessageRef: body.sourceMessageRef, - reportVersion: body.reportVersion, - }), - }, - [`${ROUTE_PREFIX}/artifact/revision`]: { - method: 'POST', - handler: async ({ body }) => service.requestArtifactRevision({ - projectId: select(body), - artifactId: body.artifactId, - instruction: body.instruction, - ownerRoleId: body.ownerRoleId, - sourceRoleId: body.sourceRoleId, - title: body.title, - acceptance: body.acceptance, - constraints: body.constraints, - status: body.status, - originMessageRef: body.originMessageRef, - 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 }) => { - const projectId = query.get('projectId') ?? undefined - const since = Number(query.get('since') ?? 0) - if (query.get('since') !== null && !Number.isFinite(since)) { - throw new ServiceError('INVALID_INPUT', 'since 必须是数字', { field: 'since' }) - } - const immediateOnly = query.get('wait') === '0' - if (immediateOnly || (options.longPollMs ?? DEFAULT_LONG_POLL_MS) <= 0) { - return service.listEvents(projectId, since, { limit: options.eventLimit }) - } - return waitForEvents(service, projectId, since, { - ...options, - // 客户端断开时不再等满窗口:把当前结果写回去(或让外层发现已结束)。 - onAbort: () => { - if (res.writableEnded !== true && res.destroyed !== true) { - sendOk(res, service.listEvents(projectId, since, { limit: options.eventLimit }), { Connection: 'close' }) - } - }, - }) - }, - }, - }) -} - -/** - * 注册路由。宿主没有 webServer(或没有 register)时返回 no-op dispose, - * 并在返回值上标 registered:false,调用方可据此提示“宿主不支持工作台接口”。 - * - * @returns {() => void} dispose:卸载全部已注册路由;重复调用无副作用。 - */ -export function registerWorkbenchRoutes(ctx, service, options = {}) { - const disposes = [] - const server = ctx?.webServer - if (server === undefined || server === null || typeof server.register !== 'function') { - const noop = () => {} - noop.registered = false - noop.reason = '宿主未提供 webServer.register' - return noop - } - const table = buildRouteTable(service, options) - const bodyLimit = options.maxBodyBytes ?? MAX_BODY_BYTES - try { - for (const [path, def] of Object.entries(table)) { - const methods = def.method === 'GET' ? ['GET'] : ['POST'] - const handler = wrap(def.handler, { methods, allowBody: def.method === 'POST', bodyLimit }) - const dispose = server.register({ kind: 'exact', path, handler }) - if (typeof dispose === 'function') disposes.push(dispose) - } - } catch (error) { - // 部分注册失败:先把已注册的回滚,避免留下半套路由(前端会看到一多半 404)。 - for (const dispose of disposes.reverse()) { - try { - dispose() - } catch { - // 卸载失败不影响主流程:宿主要么已卸载,要么进程即将重启。 - } - } - throw error - } - let disposed = false - const dispose = () => { - if (disposed) return - disposed = true - for (const fn of disposes.reverse()) { - try { - fn() - } catch { - // 同上:dispose 必须幂等且不抛。 - } - } - } - dispose.registered = true - dispose.paths = Object.keys(table) - return dispose -} - -/** 供诊断页使用:列出全部端点与其方法。 */ -export function listWorkbenchRoutes() { - return Object.entries(buildRouteTable({ bootstrap: () => null }, {})).map(([path, def]) => ({ path, method: def.method })) -} diff --git a/workbench/host/service.mjs b/workbench/host/service.mjs deleted file mode 100644 index 1aca849..0000000 --- a/workbench/host/service.mjs +++ /dev/null @@ -1,1483 +0,0 @@ -// 工作台业务服务:纯业务,不碰 HTTP、不碰宿主会话 API。 -// -// 三类职责: -// 1. 入口校验(项目隔离):凡是以实体 ID 为参数的调用,先确认项目存在, -// 再确认目标记录属于该项目。伪造 ID 与跨项目引用各自返回确定的错误码, -// 且不泄露“别的项目里有没有这条记录”。 -// 2. 契约操作:registerProject / listSeats / bindDepartmentSession / saveDepartmentConfig / -// createTask / dispatchTask / reportTaskResult / requestTaskInput / syncDecision。 -// 3. 投影:bootstrap 一次拿全(项目列表 + 十席 + 任务 + 成果),UI 只读投影。 -// -// 幂等与状态机全部下沉到 core:store.recordDispatch / store.recordResult 自带去重, -// tasks.decide 负责完成判定。这里只做三件事:组织一次事务、把 core 异常翻成带 code 的业务错误、 -// 保证任何返回值都是副本(调用方改返回值改不到账本)。 - -import { isIdOf } from '../core/ids.mjs' -import { ROLES, isRoleId, layoutGroups } from '../core/roles.mjs' -import { isTerminal } from '../core/states.mjs' -import { - applyDecision, - beginAttempt, - cancelTask as cancelTaskDecision, - createTask as createTaskRecord, - decide, - isOpenTask, - startTask, -} from '../core/tasks.mjs' -import { StoreError } from '../core/store.mjs' - -export const WORKBENCH_SERVICE_VERSION = 1 - -/** 错误码:路由层据此映射 HTTP 状态码,调用方据此分支,永远不解析 message。 */ -export const SERVICE_CODES = Object.freeze({ - INVALID_INPUT: 'INVALID_INPUT', - INVALID_ROLE: 'INVALID_ROLE', - NOT_FOUND: 'NOT_FOUND', - CROSS_PROJECT: 'CROSS_PROJECT', - CONFIG_CONFLICT: 'CONFIG_CONFLICT', - SESSION_CONFLICT: 'SESSION_CONFLICT', - DUPLICATE_PROJECT: 'DUPLICATE_PROJECT', - INVALID_STATE: 'INVALID_STATE', - DISPATCH_INVALID: 'DISPATCH_INVALID', - ATTEMPT_MISMATCH: 'ATTEMPT_MISMATCH', - REPORT_INVALID: 'REPORT_INVALID', - INTERNAL: 'INTERNAL', -}) - -export class ServiceError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'ServiceError' - this.code = code - if (details !== undefined) this.details = details - } -} - -// ---------- 纯工具 ---------- - -function requireText(value, field) { - if (typeof value !== 'string' || value.trim() === '') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `${field} 必须是非空字符串`, { field }) - } - return value -} - -function optionalText(value, field) { - if (value === undefined || value === null) return null - if (typeof value !== 'string') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `${field} 必须是字符串或 null`, { field }) - } - return value -} - -function requireRole(value, field) { - if (!isRoleId(value)) { - throw new ServiceError(SERVICE_CODES.INVALID_ROLE, `${field} 不是已知部门: ${String(value)}`, { field }) - } - return value -} - -function requireBool(value, field) { - if (value === undefined) return false - if (typeof value !== 'boolean') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `${field} 必须是布尔值`, { field }) - } - return value -} - -function optionalArray(value, field) { - if (value === undefined || value === null) return [] - if (!Array.isArray(value)) throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `${field} 必须是数组`, { field }) - return value.map((item) => (typeof item === 'string' ? item : JSON.parse(JSON.stringify(item)))) -} - -/** 深拷贝:对外只给副本,避免调用方拿到账本里的同一个对象。 */ -function copy(value) { - return value === undefined || value === null ? value : JSON.parse(JSON.stringify(value)) -} - -/** store 的 Getter 名 → 实体名(ID 前缀)与集合名(归属校验用)。 */ -const GETTERS = Object.freeze({ - project: { get: 'getProject', entity: 'project', prefix: 'project' }, - task: { get: 'getTask', entity: 'task', prefix: 'task' }, - attempt: { get: 'getAttempt', entity: 'attempt', prefix: 'attempt' }, - dispatch: { get: 'getDispatch', entity: 'dispatch', prefix: 'dispatch' }, - result: { get: 'getResult', entity: 'result', prefix: 'result' }, - artifact: { get: 'getArtifact', entity: 'artifact', prefix: 'artifact' }, -}) - -/** - * 宿主运行终态:只认 成功 / 失败 / 取消 / 仍在跑。 - * 未知字符串一律拒绝——把 "done" 当成功正是方案 §7.3 明令禁止的猜测。 - */ -const RUN_TERMINALS = Object.freeze(['succeeded', 'failed', 'cancelled', 'running']) -function normalizeRunTerminal(value, field = 'runTerminal') { - if (value === undefined || value === null) return null - if (typeof value !== 'string' || !RUN_TERMINALS.includes(value)) { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `${field} 取值非法: ${String(value)}`, { allowed: RUN_TERMINALS }) - } - return value -} - -/** 宿主终态 → attempt 状态。attempt 跟着落,但业务结论只由 tasks.decide 给。 */ -const ATTEMPT_STATE_OF_RUN = Object.freeze({ succeeded: 'succeeded', failed: 'failed', cancelled: 'cancelled' }) - -export function createWorkbenchService(options = {}) { - const { store, clock = Date.now, env = process.env, fileExists = null } = options - if (store === undefined || store === null || typeof store.mutate !== 'function') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, 'createWorkbenchService 需要 WorkbenchStore') - } - - const nowIso = () => new Date(clock()).toISOString() - - // ---------- 异常翻译 ---------- - - /** - * core 的异常统一翻成 ServiceError,保留 code 与 details。 - * CROSS_PROJECT 的 message 改写成不含其他项目 ID 的版本,避免把归属泄露出去。 - */ - function translate(error) { - if (error instanceof ServiceError) return error - if (error instanceof StoreError) { - const details = error.details - switch (error.code) { - case 'CROSS_PROJECT': - return new ServiceError(SERVICE_CODES.CROSS_PROJECT, '引用的记录不属于本项目', details) - case 'NOT_FOUND': - return new ServiceError(SERVICE_CODES.NOT_FOUND, error.message, details) - case 'CAS_CONFLICT': - return new ServiceError(SERVICE_CODES.CONFIG_CONFLICT, error.message, details) - case 'SESSION_CONFLICT': - return new ServiceError(SERVICE_CODES.SESSION_CONFLICT, error.message, details) - case 'DUPLICATE_PROJECT': - return new ServiceError(SERVICE_CODES.DUPLICATE_PROJECT, error.message, details) - case 'INVALID_ROLE': - return new ServiceError(SERVICE_CODES.INVALID_ROLE, error.message, details) - case 'INVALID_INPUT': - return new ServiceError(SERVICE_CODES.INVALID_INPUT, error.message, details) - case 'DUPLICATE_ID': - // ID 由随机源生成却撞了已有记录:属于宿主侧内部故障,不是调用方的错, - // 更不能伪装成"当前状态不接受该操作"。 - return new ServiceError(SERVICE_CODES.INTERNAL, `生成的主键重复(${error.message}),请检查随机源`, { ...details, storeCode: error.code }) - default: - // INVALID_STATE / INVALID_ID / CORRUPT 等:状态机与形状问题, - // 对调用方而言都是“当前数据不接受这个操作”,归到 INVALID_STATE,code 保留在 details。 - return new ServiceError(SERVICE_CODES.INVALID_STATE, error.message, { ...details, storeCode: error.code }) - } - } - // tasks.mjs 的 TaskError:code 语义已经够用,原样带出(INVALID_STATE / ACTIVE_ATTEMPT / CROSS_TASK 等)。 - if (error !== null && typeof error === 'object' && typeof error.code === 'string' && typeof error.message === 'string') { - return new ServiceError(error.code, error.message, error.details) - } - const wrapped = new ServiceError(SERVICE_CODES.INTERNAL, error instanceof Error ? error.message : String(error)) - wrapped.cause = error - return wrapped - } - - /** 包一层:把同步异常翻译成 ServiceError,调用点就不必逐处 try/catch。 */ - function guard(fn) { - return (...args) => { - try { - return fn(...args) - } catch (error) { - throw translate(error) - } - } - } - - // ---------- 项目隔离 ---------- - - /** - * 项目必须存在。不存在与伪造同一个返回:凡不可见的项目都是 NOT_FOUND, - * 调用方无法用它区分“没有这个项目”和“这个项目不属于你”。 - */ - function projectIdOf(input) { - const projectId = input === null || typeof input !== 'object' ? input : input.projectId - if (typeof projectId !== 'string' || !isIdOf('project', projectId)) { - throw new ServiceError(SERVICE_CODES.NOT_FOUND, '项目不存在', { field: 'projectId' }) - } - const project = store.getProject(projectId) - if (project === undefined) throw new ServiceError(SERVICE_CODES.NOT_FOUND, '项目不存在', { field: 'projectId' }) - return project - } - - /** - * 归属校验的公共实现:先验项目,再验 ID 形状,最后验归属。 - * - ID 形状非法或查不到 → NOT_FOUND(伪造/已删不可区分) - * - 查到了但 projectId 不符 → CROSS_PROJECT - * 返回值里不带任何其他项目的字段。 - */ - function ownedRow(project, kind, id, field) { - const spec = GETTERS[kind] - if (typeof id !== 'string' || !isIdOf(spec.prefix, id)) { - throw new ServiceError(SERVICE_CODES.NOT_FOUND, `${field} 不存在`, { field }) - } - const row = store[spec.get](id) - if (row === undefined || row === null) throw new ServiceError(SERVICE_CODES.NOT_FOUND, `${field} 不存在`, { field }) - if (row.projectId !== project.id) { - throw new ServiceError(SERVICE_CODES.CROSS_PROJECT, `${field} 不属于本项目`, { field }) - } - return row - } - - const requireTask = (project, id) => ownedRow(project, 'task', id, 'taskId') - const requireAttempt = (project, id) => ownedRow(project, 'attempt', id, 'attemptId') - - function requireSeat(project, roleId) { - requireRole(roleId, 'roleId') - const binding = store.getBinding(project.id, roleId) - const config = store.getConfig(project.id, roleId) - if (binding === undefined || config === undefined) { - throw new ServiceError(SERVICE_CODES.NOT_FOUND, `项目中缺少 ${roleId} 的席位记录,账本可能未初始化`, { roleId }) - } - // 引用校验要用 bindings.id 这个真实键;角色名不是键。 - // 注意 core 的 store.state.bindings 以 `${projectId}\u0000${roleId}` 为键, - // 所以派发时直接内联绑定对象,不再把 binding.id 透传给 _checkReferences。 - return { binding, config } - } - - // ---------- 项目 ---------- - - /** - * 路径归一:Windows 大小写不敏感、反斜杠与正斜杠等价、末尾分隔符不算差异。 - * 约定用不了真实 canonicalize(junction / 短路径要碰文件系统),所以只做到“字符串级等价”, - * 命中时明确说这是识别到的冲突,而不是宣称已经做了完全隔离。 - */ - function normalizeRoot(path) { - if (typeof path !== 'string' || path.trim() === '') return null - return path.trim().replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase() - } - - /** - * A20:同一目录(含父子目录、junction 指向同一目标)不能登记成两个互不相干的项目。 - * 只识别、不篡改:命中就报明确的 relation,调用方要么换目录,要么显式 allowSharedRoot。 - */ - function rootConflict(self, canonicalRoot) { - const mine = normalizeRoot(canonicalRoot) - if (mine === null) return null - for (const other of store.listProjects()) { - if (other.id === self?.id) continue - const theirs = normalizeRoot(other.canonicalRoot) - if (theirs === null) continue - if (mine === theirs) { - return { relation: 'same', otherProjectId: other.id, otherHostWorkspaceId: other.hostWorkspaceId, otherRoot: other.canonicalRoot } - } - if (mine.startsWith(`${theirs}/`) || theirs.startsWith(`${mine}/`)) { - return { relation: 'nested', otherProjectId: other.id, otherHostWorkspaceId: other.hostWorkspaceId, otherRoot: other.canonicalRoot } - } - } - return null - } - - /** - * 登记项目。同一 hostWorkspaceId 只会得到一个 projectId: - * UI 重复进入同一工作区不该产生两个项目,也不该把已有任务晾在新项目里。 - */ - const registerProject = guard((input = {}) => { - const hostWorkspaceId = requireText(input.hostWorkspaceId, 'hostWorkspaceId') - const displayNameCache = input.displayNameCache === undefined ? '' : String(input.displayNameCache ?? '') - const canonicalRoot = optionalText(input.canonicalRoot, 'canonicalRoot') - const existing = store.listProjects().find((row) => row.hostWorkspaceId === hostWorkspaceId) - // 目录冲突先查:两个工作区挂在同一目录(或父子目录)时,任务与会话会互相串, - // 这不是“用户想要两个项目”,而是登记错误,必须在写账之前拦住。 - const conflict = rootConflict(existing, canonicalRoot) - if (conflict !== null && input.allowSharedRoot !== true) { - throw new ServiceError( - SERVICE_CODES.DUPLICATE_PROJECT, - conflict.relation === 'same' - ? '这个目录已经登记为另一个项目了;同一个目录不会自动隔离' - : '这个目录与已登记的项目是父子关系,两者不会自动隔离', - { ...conflict, hint: 'allowSharedRoot' }, - ) - } - if (existing !== undefined) { - const patch = {} - if (existing.displayNameCache !== displayNameCache) patch.displayNameCache = displayNameCache - if (existing.canonicalRoot !== canonicalRoot) patch.canonicalRoot = canonicalRoot - const project = Object.keys(patch).length > 0 ? store.updateProject(existing.id, patch) : existing - return { project: copy(project), duplicate: true, sharedRoot: conflict } - } - try { - const projectId = store.createProject({ hostWorkspaceId, displayNameCache, canonicalRoot }) - return { project: copy(store.getProject(projectId)), duplicate: false, sharedRoot: conflict } - } catch (error) { - // 两个窗口同时登记:唯一性在 store 内检查,竞态也归成 duplicate。 - if (error instanceof StoreError && error.code === 'DUPLICATE_PROJECT') { - const again = store.listProjects().find((row) => row.hostWorkspaceId === hostWorkspaceId) - if (again !== undefined) return { project: copy(again), duplicate: true, sharedRoot: conflict } - } - throw error - } - }) - - /** 项目列表:只给投影需要的计数,不把其他项目的实体带出来。 */ - function listProjects() { - return store.listProjects().map((project) => { - const tasks = store.listTasks(project.id) - return { - ...copy(project), - seatCount: ROLES.length, - taskCount: tasks.length, - openTaskCount: tasks.filter((task) => isOpenTask(task)).length, - } - }) - } - - function getProject(projectId) { - return copy(projectIdOf({ projectId })) - } - - // ---------- 十席 ---------- - - /** - * 十席布局 + 每席现状。 - * connected=false 即“尚未接通”:没有会话或绑定失效时,UI 不能显示可派工。 - */ - function seatView(project, seat) { - const binding = store.getBinding(project.id, seat.id) - const config = store.getConfig(project.id, seat.id) - const sessionId = binding?.currentSessionId ?? null - const status = binding?.status ?? 'uninitialized' - const connected = sessionId !== null && status !== 'unavailable' - const activeTask = store - .listTasks(project.id) - .filter((task) => task.ownerRoleId === seat.id && isOpenTask(task)) - .sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt)))[0] - return { - roleId: seat.id, - name: seat.name, - short: seat.short, - tier: seat.tier, - group: seat.group, - column: seat.column, - row: seat.row, - duty: seat.duty, - canDispatch: seat.canDispatch === true, - connected, - pending: !connected, - pendingLabel: connected ? null : (status === 'unavailable' ? '绑定失效,需重新接通' : '尚未接通'), - activeTaskId: activeTask?.id ?? null, - binding: { - id: binding?.id ?? null, - currentSessionId: sessionId, - // 生成序号是派发时的护栏:换绑后旧序号失效,旧消息不会被送进新会话。 - bindingGeneration: binding?.bindingGeneration ?? 0, - status, - historyCount: binding?.historySessionRefs?.length ?? 0, - revision: binding?.revision ?? 0, - }, - // 只给 provider/model/effort 名字与修订号,不给任何凭据。 - config: { - provider: config?.providerId ?? null, - model: config?.modelId ?? null, - reasoningEffort: config?.reasoningEffort ?? null, - configRevision: config?.configRevision ?? 0, - configured: Boolean(config?.providerId && config?.modelId), - }, - } - } - - /** 配置的对外视图:provider/model 与账本的 providerId/modelId 只在这一处转换。 */ - function configView(config) { - if (config === undefined || config === null) return null - return { - roleId: config.roleId ?? null, - provider: config.providerId ?? null, - model: config.modelId ?? null, - reasoningEffort: config.reasoningEffort ?? null, - configRevision: config.configRevision ?? 0, - updatedAt: config.updatedAt ?? null, - } - } - - function listSeats(projectId) { - const project = projectIdOf({ projectId }) - return ROLES.map((seat) => seatView(project, seat)) - } - - function layout() { - return layoutGroups() - } - - // ---------- 绑定 ---------- - - /** - * 绑定部门会话。唯一性与“已绑定时是否允许替换”都在 store 里判定, - * 这里只把 SESSION_CONFLICT / CROSS_PROJECT 原样带出(含 code 与 details.heldBy), - * 让 UI 能说清“这个会话正在被谁持有”,而不是笼统的 500。 - */ - const bindDepartmentSession = guard((input = {}) => { - const project = projectIdOf(input) - const roleId = requireRole(input.roleId, 'roleId') - const sessionId = requireText(input.sessionId, 'sessionId') - const allowReplace = requireBool(input.allowReplace, 'allowReplace') - const creationRequestId = optionalText(input.creationRequestId, 'creationRequestId') - try { - const binding = store.bindSession(project.id, roleId, sessionId, { allowReplace, creationRequestId }) - return { binding: copy(binding), seat: seatView(project, ROLES.find((seat) => seat.id === roleId)) } - } catch (error) { - if (error instanceof StoreError && error.code === 'SESSION_CONFLICT') { - // 失败分支不带 seat:绑定没变,别让前端误以为状态已更新。 - throw translate(error) - } - throw translate(error) - } - }) - - /** 解除绑定:旧会话进历史,不删除记录。释放后同一 sessionId 才能绑到别处。 */ - const releaseDepartmentSession = guard((input = {}) => { - const project = projectIdOf(input) - const roleId = requireRole(input.roleId, 'roleId') - requireSeat(project, roleId) - return { binding: copy(store.releaseBinding(project.id, roleId)) } - }) - - /** 部门运行态(uninitialized/idle/queued/running/unavailable),由适配器回执驱动。 */ - const setDepartmentStatus = guard((input = {}) => { - const project = projectIdOf(input) - const roleId = requireRole(input.roleId, 'roleId') - requireSeat(project, roleId) - const status = requireText(input.status, 'status') - return { binding: copy(store.setBindingStatus(project.id, roleId, status)) } - }) - - // ---------- 配置(CAS) ---------- - - /** - * 保存部门模型设置。CAS 冲突必须把“当前值”一起返回, - * 否则 UI 只能提示“保存失败”,用户无从判断是自己过时还是别人改的。 - */ - const saveDepartmentConfig = guard((input = {}) => { - const project = projectIdOf(input) - const roleId = requireRole(input.roleId, 'roleId') - requireSeat(project, roleId) - if (!Number.isInteger(input.expectedRevision)) { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, 'expectedRevision 必须是整数', { field: 'expectedRevision' }) - } - if (input.reasoningEffort !== undefined && input.reasoningEffort !== null - && typeof input.reasoningEffort !== 'string') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, 'reasoningEffort 必须是字符串或 null', { field: 'reasoningEffort' }) - } - try { - const config = store.saveConfig(project.id, roleId, { - provider: input.provider, - model: input.model, - reasoningEffort: input.reasoningEffort ?? null, - }, input.expectedRevision) - // 出参用对外口径(provider/model),不把账本里的 providerId/modelId 漏给 UI: - // 两套命名混用迟早在某处接错。 - return { config: configView(config), configRevision: config.configRevision } - } catch (error) { - if (error instanceof StoreError && error.code === 'CAS_CONFLICT') { - const details = error.details ?? {} - throw new ServiceError(SERVICE_CODES.CONFIG_CONFLICT, '配置已被其他窗口修改,请读回后再保存', { - roleId, - expectedRevision: details.expectedRevision ?? input.expectedRevision, - currentRevision: details.currentRevision ?? null, - current: details.current ?? null, - }) - } - throw error - } - }) - - /** - * 先做不花 ID 的前置校验(角色、状态取值、部门是否接通), - * 再进主流程取 ID。失败时一个 ID 都不该被消耗:ID 是业务主键, - * 让失败请求"吃掉"ID 会让重试与断言都对不上。 - */ - function preflightCreateTask(input) { - if (input === null || typeof input !== 'object') return input - const sourceRoleId = input.sourceRoleId === undefined ? 'lead' : requireRole(input.sourceRoleId, 'sourceRoleId') - const ownerRoleId = requireRole(input.ownerRoleId, 'ownerRoleId') - const wanted = input.status === undefined ? 'queued' : input.status - if (wanted !== 'queued' && wanted !== 'draft') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `新建任务只能是 queued 或 draft,收到 ${String(wanted)}`, { field: 'status' }) - } - if (wanted === 'queued' && typeof input.projectId === 'string' && isIdOf('project', input.projectId)) { - const binding = store.getBinding(input.projectId, ownerRoleId) - if (binding?.currentSessionId === null || binding?.currentSessionId === undefined) { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, `${ownerRoleId} 尚未接通会话,不能直接入队;可先存草稿`, { - roleId: ownerRoleId, - hint: 'draft', - }) - } - } - return input - } - - // ---------- 任务 ---------- - - /** - * 建任务。默认直接入队(queued);status='draft' 时保持草稿。 - * 入队前要求主责部门已接通:派给一个没有会话的部门只会在派发阶段撞 unknown。 - */ - const createTask = guard((input = {}) => { - input = preflightCreateTask(input) - const project = projectIdOf(input) - const ownerRoleId = requireRole(input.ownerRoleId, 'ownerRoleId') - const sourceRoleId = input.sourceRoleId === undefined ? 'lead' : requireRole(input.sourceRoleId, 'sourceRoleId') - const wanted = input.status === undefined ? 'queued' : input.status - if (wanted !== 'queued' && wanted !== 'draft') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `新建任务只能是 queued 或 draft,收到 ${String(wanted)}`, { field: 'status' }) - } - if (wanted === 'queued') { - const binding = store.getBinding(project.id, ownerRoleId) - if (binding?.currentSessionId === null || binding?.currentSessionId === undefined) { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, `${ownerRoleId} 尚未接通会话,不能直接入队;可先存草稿`, { - roleId: ownerRoleId, - hint: 'draft', - }) - } - } - // 先按入队语义校验通过再取 ID:校验失败不该消耗掉一个 ID, - // 否则同一测试里连续建任务的 ID 会与预期错位。 - const record = createTaskRecord({ - projectId: project.id, - title: input.title, - objective: input.objective, - acceptance: optionalArray(input.acceptance, 'acceptance'), - constraints: optionalArray(input.constraints, 'constraints'), - scope: input.scope ?? null, - ownerRoleId, - sourceRoleId, - originMessageRef: optionalText(input.originMessageRef, 'originMessageRef'), - returnTarget: input.returnTarget ?? null, - }, { newTaskId: () => store.ids.task(), now: nowIso }) - const queued = wanted === 'queued' ? startTask(record, { now: nowIso }) : record - return { task: copy(store.insertTask(queued)) } - }) - - function getTask(projectId, taskId) { - const project = projectIdOf({ projectId }) - return copy(requireTask(project, taskId)) - } - - /** 任务列表:附开放标记与尝试/结果计数,UI 不必为每行再发请求。 */ - function listTasks(projectId, filter = {}) { - const project = projectIdOf({ projectId }) - if (filter.ownerRoleId !== undefined) requireRole(filter.ownerRoleId, 'ownerRoleId') - return store - .listTasks(project.id) - .filter((task) => filter.status === undefined || task.status === filter.status) - .filter((task) => filter.ownerRoleId === undefined || task.ownerRoleId === filter.ownerRoleId) - .sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt))) - .map((task) => ({ - ...copy(task), - open: isOpenTask(task), - attemptCount: store.listAttempts(task.id).length, - resultCount: store.listResults(task.id).length, - })) - } - - /** - * 取消任务。业务上立即落 cancelled,但运行的尝试只到 cancel_requested: - * 宿主取消是另一条腿,不能在这里假装已经停了(宿主记录 L6:cancel 不撤回排队消息)。 - */ - const cancelTask = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - const reason = input.reason === undefined ? '用户取消' : requireText(input.reason, 'reason') - const decision = cancelTaskDecision(task, reason, { now: nowIso }) - const applied = applyDecision(store, task.id, decision) - let attempt = null - let cancelRequest = null - const activeId = task.activeAttemptId - if (activeId !== null && activeId !== undefined) { - const current = store.getAttempt(activeId) - if (current !== undefined && current.projectId === project.id && !isTerminal('attempt', current.state)) { - if (current.state === 'queued') { - attempt = store.updateAttempt(current.id, { state: 'cancelled', endedAt: nowIso() }) - } else if (current.state === 'running') { - attempt = store.updateAttempt(current.id, { state: 'cancel_requested', cancelRequestedAt: nowIso() }) - // 交给适配器去调宿主 cancel;这里只声明“该取消哪个运行”。 - cancelRequest = { projectId: project.id, taskId: task.id, attemptId: current.id, hostRunId: current.hostRunId ?? null } - } else { - attempt = current - } - } - } - return { - task: copy(applied.task), - applied: applied.applied === true, - reason: applied.reason ?? null, - attempt: copy(attempt), - cancelRequest, - } - }) - - // ---------- 派发 ---------- - - /** - * dispatchTask:一次事务写三样东西——dispatch(prepared) + contextPacket + attempt(queued)。 - * 三者同生共死,崩溃时不会留下“有派发没尝试”或“有尝试没交接材料”的半条记录。 - * - * 幂等:同一 (projectId, idempotencyKey) 只会有一条 dispatch。 - * 命中时把挂在它上面的 attempt/上下文包一起返回,duplicate=true,不新建任何记录—— - * 派发可能已经投递出去,重写一条等于假装配送了两次。 - */ - const dispatchTask = guard((input = {}) => { - const project = projectIdOf(input) - let task = requireTask(project, input.taskId) - const idempotencyKey = requireText(input.idempotencyKey, 'idempotencyKey') - - const existing = store.findDispatchByIdempotencyKey(project.id, idempotencyKey) - if (existing !== undefined) return dispatchView(existing, true) - - if (isTerminal('task', task.status)) { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, `任务已终态(${task.status}),不能再次派发`, { status: task.status }) - } - if (task.status === 'running') { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, '任务正在执行,派发前需先对账当前尝试', { status: task.status }) - } - const targetRoleId = input.targetRoleId === undefined ? task.ownerRoleId : requireRole(input.targetRoleId, 'targetRoleId') - if (targetRoleId !== task.ownerRoleId) { - throw new ServiceError(SERVICE_CODES.DISPATCH_INVALID, '派发目标必须与任务主责部门一致', { - targetRoleId, - ownerRoleId: task.ownerRoleId, - }) - } - const sourceRoleId = input.sourceRoleId === undefined ? task.sourceRoleId : requireRole(input.sourceRoleId, 'sourceRoleId') - const target = requireSeat(project, targetRoleId) - const sessionId = input.targetSessionId === undefined ? target.binding.currentSessionId : optionalText(input.targetSessionId, 'targetSessionId') - if (sessionId === null || sessionId === undefined) { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, `${targetRoleId} 尚未接通会话,不能派发`, { roleId: targetRoleId }) - } - if (target.binding.currentSessionId !== null && target.binding.currentSessionId !== sessionId) { - // 调用方拿着旧会话号派发:这是换绑后的典型故障,必须显式失败而不是投给新会话。 - throw new ServiceError(SERVICE_CODES.SESSION_CONFLICT, 'targetSessionId 与当前绑定不一致,请重新读取席位后再派发', { - currentSessionId: target.binding.currentSessionId, - }) - } - if (input.bindingGeneration !== undefined && input.bindingGeneration !== target.binding.bindingGeneration) { - throw new ServiceError(SERVICE_CODES.SESSION_CONFLICT, 'bindingGeneration 已变化,派发目标可能已被换绑', { - expected: input.bindingGeneration, - current: target.binding.bindingGeneration, - }) - } - const sourceBinding = store.getBinding(project.id, sourceRoleId) - const sourceSessionId = input.sourceSessionId === undefined - ? sourceBinding?.currentSessionId ?? null - : optionalText(input.sourceSessionId, 'sourceSessionId') - const packet = input.packet === undefined || input.packet === null ? {} : input.packet - if (typeof packet !== 'object' || Array.isArray(packet)) { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, 'packet 必须是对象', { field: 'packet' }) - } - // 修订任务默认把「要改的那份成果 + 版本」带进交接材料: - // 主责部门不需要回头翻记录,也不会改到别的版本上。 - const revisionMaterials = task.scope?.kind === 'artifact-revision' && typeof task.scope.artifactId === 'string' - ? [{ 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() - const dispatchId = store.ids.dispatch() - const contextPacketId = store.ids.contextPacket() - // 交接材料版本号:同任务内递增,重派不覆盖上一版的验收标准与摘录。 - const version = [...store.state.contextPackets.values()] - .filter((row) => row.taskId === task.id) - .reduce((max, row) => Math.max(max, Number(row.version) || 0), 0) + 1 - - store.insertContextPacket({ - id: contextPacketId, - projectId: project.id, - taskId: task.id, - version, - objective: packet.objective ?? task.objective, - acceptance: packet.acceptance === undefined ? task.acceptance : optionalArray(packet.acceptance, 'packet.acceptance'), - constraints: packet.constraints === undefined ? task.constraints : optionalArray(packet.constraints, 'packet.constraints'), - originMessageRef: packet.originMessageRef ?? task.originMessageRef, - excerpts: optionalArray(packet.excerpts, 'packet.excerpts'), - materialRefs: normalizeMaterialRefs( - packet.materialRefs === undefined ? revisionMaterials : packet.materialRefs, - project, - ), - authorizationRefs: optionalArray(packet.authorizationRefs, 'packet.authorizationRefs'), - scope: packet.scope ?? task.scope, - expectedOutputs: optionalArray(packet.expectedOutputs, 'packet.expectedOutputs'), - returnTarget: packet.returnTarget ?? task.returnTarget ?? { roleId: task.sourceRoleId }, - createdAt: stamp, - }) - - // 注意顺序:dispatches 的引用表会校验 attemptId 与 contextPacketId, - // 所以必须先有 attempt 与上下文包,再写派发;否则 recordDispatch 会报“引用不存在”。 - store.insertAttempt({ - id: attemptId, - projectId: project.id, - taskId: task.id, - dispatchId: null, - // 不传 bindingId:core 的 bindings 表以 projectId+roleId 复合键存放,binding.id 不是键。 - // 席位归属已由 requireSeat(project, targetRoleId) 保证。 - sessionId, - hostRunId: null, - state: 'queued', - // 派发时把模型设置快照下来:之后改配置不影响这一次运行。 - effectiveConfigSnapshot: { - provider: target.config.providerId, - model: target.config.modelId, - reasoningEffort: target.config.reasoningEffort ?? null, - configRevision: target.config.configRevision, - }, - error: null, - createdAt: stamp, - startedAt: null, - endedAt: null, - }) - - const recorded = store.recordDispatch({ - projectId: project.id, - taskId: task.id, - attemptId, - sourceSessionId, - targetSessionId: sessionId, - // 同上:席位归属由 requireSeat 保证,这里只记换绑护栏用的 generation。 - bindingGeneration: target.binding.bindingGeneration, - contextPacketId, - idempotencyKey, - status: 'prepared', - }) - // attempt 先插、派发后写:这里把 dispatchId 补回尝试,两表互指成立。 - store.updateAttempt(attemptId, { dispatchId: recorded.dispatch.id }) - return recorded.dispatch.id - }) - - return dispatchView(store.getDispatch(committed.value), false) - }) - - /** 把一条 dispatch 连同挂在它上面的尝试、上下文包、任务一起投影。 */ - function dispatchView(dispatch, duplicate) { - const attempt = dispatch.attemptId === null ? null : store.getAttempt(dispatch.attemptId) - const packet = dispatch.contextPacketId === null ? null : store.getContextPacket(dispatch.contextPacketId) - const task = dispatch.taskId === null ? null : store.getTask(dispatch.taskId) - return { - dispatch: copy(dispatch), - attempt: copy(attempt ?? null), - contextPacket: copy(packet ?? null), - task: copy(task ?? null), - duplicate, - } - } - - /** 派发状态推进(由适配器拿宿主回执驱动):走 store 的状态机,不接受跳跃。 */ - const markDispatch = guard((input = {}) => { - const project = projectIdOf(input) - const dispatch = ownedRow(project, 'dispatch', input.dispatchId, 'dispatchId') - const patch = {} - if (input.status !== undefined) patch.status = input.status - if (input.hostMessageId !== undefined) patch.hostMessageId = optionalText(input.hostMessageId, 'hostMessageId') - return { dispatch: copy(store.updateDispatch(dispatch.id, patch)) } - }) - - // ---------- 结果 ---------- - - /** - * 登记尝试推进(适配器在宿主侧拿到 runId/开跑回执后调用)。 - * 用 core 的 beginAttempt:任务进入 running 且 activeAttemptId 指向这次尝试。 - */ - const startAttempt = guard((input = {}) => { - const project = projectIdOf(input) - // taskId 可省:Attempt 自己知道属于哪个任务。传入时必须与它对上, - // 免得 UI 拿错 ID 把别的任务推进 running。 - const attempt = requireAttempt(project, input.attemptId) - const task = requireTask(project, input.taskId ?? attempt.taskId) - if (attempt.taskId !== task.id) { - throw new ServiceError(SERVICE_CODES.ATTEMPT_MISMATCH, '尝试不属于该任务', { attemptId: attempt.id }) - } - const hostRunId = optionalText(input.hostRunId, 'hostRunId') - let next = attempt - if (attempt.state === 'queued') { - next = store.updateAttempt(attempt.id, { state: 'running', hostRunId, startedAt: nowIso() }) - } else if (hostRunId !== null && attempt.hostRunId !== hostRunId) { - next = store.updateAttempt(attempt.id, { hostRunId }) - } - // core 的 beginAttempt 只计算新对象不写库,所以这里显式落库: - // 成功即“任务进入 running 且 activeAttemptId 指向这次尝试”。 - // 只把 Attempt 推到 running 是不够的:任务的 run_terminal 判定要求它当时处于 running, - // 否则"运行结束但无报告"会被当成"还在排队",needs_attention 永远落不下来。 - // core 的 beginAttempt 在任务仍为 queued 时会连同任务一起推进到 running。 - const decision = beginAttempt(task, next, { now: nowIso, attemptLookup: (id) => store.getAttempt(id) }) - const persisted = store.updateTask(decision) - return { task: copy(persisted), attempt: copy(store.getAttempt(attempt.id)), applied: true, reason: null } - }) - - /** - * reportTaskResult:登记结构化结果 + 完成判定,一次事务内完成。 - * - * 去重先于一切写入:同一 (attemptId, reportVersion) 或同一条 sourceMessageRef - * 只登记一次,命中时返回旧结果且 applied=false,不重跑判定、不动 revision。 - * - * 判定交给 core/tasks.decide(kind:'completion'),服务层实际落地四种结果: - * 1. completed —— 报告可信 + 宿主终态 succeeded + 成果引用有效; - * 2. needs_attention—— 宿主终态 succeeded 但报告不可信(含标记了阻塞原因); - * 3. 保持不变(applied:false) —— 报告可信但宿主还没结束(candidate),等终态再定, - * 此处把报告登记进账,任务停在 running/queued,不显示已完成; - * 4. 等待结构化报告 —— 报告先到、终态后到的顺序由 reportRunTerminal 补齐。 - * 任务已终态时迟到报告只登记、不改结论(stale)。 - */ - const reportTaskResult = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - const attempt = requireAttempt(project, input.attemptId) - if (attempt.taskId !== task.id) { - throw new ServiceError(SERVICE_CODES.ATTEMPT_MISMATCH, '尝试不属于该任务', { attemptId: attempt.id }) - } - const report = input.report - if (report === null || typeof report !== 'object' || Array.isArray(report)) { - throw new ServiceError(SERVICE_CODES.REPORT_INVALID, 'report 必须是对象', { field: 'report' }) - } - const summary = requireText(report.summary, 'report.summary') - const runTerminal = normalizeRunTerminal(input.runTerminal ?? report.runTerminal) - const artifactRefs = optionalArray(input.artifactRefs ?? report.artifactRefs, 'artifactRefs') - // 成果引用必须指向本项目现存成果:账上查不到就是伪造或已删,直接拒绝,不记空引用。 - for (const ref of artifactRefs) { - ownedRow(project, 'artifact', ref, 'artifactRefs') - } - const sourceMessageRef = optionalText(input.sourceMessageRef, 'sourceMessageRef') - const reportVersion = input.reportVersion === undefined ? 1 : input.reportVersion - if (!Number.isInteger(reportVersion) || reportVersion < 1) { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, 'reportVersion 必须是正整数', { field: 'reportVersion' }) - } - const blockedReason = typeof input.blockedReason === 'string' && input.blockedReason.trim() !== '' - ? input.blockedReason - : (typeof report.blockedReason === 'string' && report.blockedReason.trim() !== '' ? report.blockedReason : null) - - const duplicateRow = findResult(project.id, attempt.id, reportVersion, sourceMessageRef) - if (duplicateRow !== undefined) { - return { - result: copy(duplicateRow), - duplicate: true, - task: copy(store.getTask(task.id)), - decision: { applied: false, duplicate: true, reason: '结果已登记,重复事件不重新判定' }, - } - } - - const recorded = store.recordResult({ - projectId: project.id, - taskId: task.id, - attemptId: attempt.id, - reportVersion, - summary, - artifactRefs, - checks: optionalArray(input.checks ?? report.checks, 'checks'), - remainingItems: optionalArray(input.remainingItems ?? report.remainingItems, 'remainingItems'), - blockedReason, - sourceMessageRef, - }) - if (recorded.duplicate) { - return { - result: copy(recorded.result), - duplicate: true, - task: copy(store.getTask(task.id)), - decision: { applied: false, duplicate: true, reason: '结果已登记' }, - } - } - - if (isTerminal('task', task.status)) { - return { - result: copy(recorded.result), - duplicate: false, - task: copy(store.getTask(task.id)), - decision: { applied: false, stale: true, reason: `任务已终态(${task.status}),迟到报告只登记不判定` }, - } - } - - // 尝试对齐:报告意味着运行已经开始;宿主给了终态就同步落 attempt,但业务结论仍看 decide。 - let liveAttempt = attempt - if (liveAttempt.state === 'queued') { - liveAttempt = store.updateAttempt(attempt.id, { state: 'running', startedAt: nowIso() }) - } - if (runTerminal !== null && ATTEMPT_STATE_OF_RUN[runTerminal] !== undefined - && !isTerminal('attempt', liveAttempt.state) && liveAttempt.state !== 'cancel_requested') { - liveAttempt = store.updateAttempt(attempt.id, { state: ATTEMPT_STATE_OF_RUN[runTerminal], endedAt: nowIso() }) - } - - const reportForJudge = { - taskId: task.id, - attemptId: attempt.id, - summary, - artifactRefs, - checks: optionalArray(input.checks ?? report.checks, 'checks'), - ...(blockedReason === null ? {} : { blockedReason }), - } - const judged = store.mutate(() => { - const fresh = store.getTask(task.id) - // 运行还没结束:走 core 的“报告先到”分支,只登记报告时间(候选),任务保持原状态。 - // 不能走 completion 判定——那会把“还没跑完”误判成 needs_attention,等于替宿主宣布结束。 - if (runTerminal === null || runTerminal === 'running') { - const pending = decide(fresh, { kind: 'report', report: reportForJudge }, { now: nowIso }) - if (pending.applied === true) store.updateTask(pending.task) - const summary = summarize(pending) - return { - task: store.getTask(task.id), - summary: { ...summary, reason: summary.reason ?? '报告已登记为候选,等待宿主运行结束' }, - } - } - const decision = decide(fresh, { - kind: 'completion', - report: reportForJudge, - runTerminal, - artifactRefs, - artifactLookup: (ref) => store.getArtifact(ref), - }, { now: nowIso }) - if (decision.applied === true) { - const applied = applyDecision(store, task.id, decision) - return { task: applied.task, summary: summarize(applied) } - } - return { task: fresh, summary: summarize(decision) } - }) - - return { - result: copy(recorded.result), - duplicate: false, - task: copy(judged.value.task), - attempt: copy(liveAttempt), - decision: judged.value.summary, - } - }) - - function findResult(projectId, attemptId, reportVersion, sourceMessageRef) { - return store.listResults(undefined) - .filter((row) => row.projectId === projectId && row.attemptId === attemptId) - .find((row) => row.reportVersion === reportVersion - || (sourceMessageRef !== null && row.sourceMessageRef === sourceMessageRef)) - } - - /** 判定摘要:UI 与日志只读这几项,不解析整条任务。 */ - function summarize(decision) { - const verify = decision.verdict ?? null - return { - applied: decision.applied === true, - stale: decision.stale === true, - status: decision.task?.status ?? null, - reason: decision.reason ?? null, - blockers: verify?.blockers ?? (decision.applied === true ? [] : (decision.reason === undefined ? [] : [decision.reason])), - // 三条完成条件各自的结论,UI 可逐条显示为什么还没完成。 - verdict: verify === null ? null : { reportOk: verify.reportOk, runOk: verify.runOk, refsValid: verify.refsValid, ok: verify.ok }, - } - } - - /** - * 宿主终态单独到达(结果先到、终态后到)。只有“报告已到 + running”才会在这里完成; - * 其余按 core 的 run_terminal 分支落 needs_attention 或保持不变。 - */ - const reportRunTerminal = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - if (isTerminal('task', task.status)) { - // 任务已有结论(取消/完成/失败):迟到的宿主回执只能核对尝试,不能改判。 - return { task: copy(task), attempt: null, decision: { applied: false, stale: true, status: task.status, reason: '任务已终态' } } - } - const runTerminal = normalizeRunTerminal(input.runTerminal) - if (runTerminal === null || runTerminal === 'running') { - return { task: copy(task), attempt: null, decision: { applied: false, status: task.status, reason: '尚未到终态' } } - } - let attempt = null - const attemptId = input.attemptId === undefined ? task.activeAttemptId : input.attemptId - if (attemptId !== null && attemptId !== undefined) { - attempt = requireAttempt(project, attemptId) - if (!isTerminal('attempt', attempt.state) && attempt.state !== 'cancel_requested' - && ATTEMPT_STATE_OF_RUN[runTerminal] !== undefined) { - attempt = store.updateAttempt(attempt.id, { state: ATTEMPT_STATE_OF_RUN[runTerminal], endedAt: nowIso() }) - } - } - const judged = store.mutate(() => { - const fresh = store.getTask(task.id) - if (runTerminal === 'running') { - // 报告正文已在 reportTaskResult 里登记,这里只需确认“仍在跑”这一事实。 - return { task: fresh, summary: { applied: false, stale: false, status: fresh.status, reason: '尚未到终态' } } - } - // 运行已结束、任务却还停在 queued(适配器没来得及推进):先补一次 running, - // 否则 completion 会被状态机丢弃,任务卡在排队态,日志与 UI 都会说谎。 - let live = fresh - if (live.status === 'queued') { - live = store.updateTask({ ...live, status: 'running', startedAt: nowIso() }) - } - if (isTerminal('task', live.status)) { - return { task: live, summary: { applied: false, stale: true, status: live.status, reason: '任务已终态' } } - } - const report = input.report ?? latestReport(project, live, attempt?.id ?? null) - const vote = (event) => decide(live, event, { now: nowIso }) - let decision - if (report !== null) { - // 报告已在账本里:按三条完成条件整体判一次(报告+终态成功+成果有效才 completed)。 - decision = vote({ - kind: 'completion', - report, - runTerminal, - artifactRefs: report.artifactRefs ?? [], - artifactLookup: (ref) => store.getArtifact(ref), - }) - } else { - // 没收到报告、宿主却已正常结束:按"成功但无报告"记完成判定 → needs_attention - // (宿主跑完不等于业务完成,不能判 completed);failed / cancelled 各有归宿。 - // 用 report: null 明确表达"确实没有报告",不靠缺省字段碰运气。 - decision = vote({ - kind: 'completion', - report: null, - runTerminal, - artifactRefs: [], - artifactLookup: (ref) => store.getArtifact(ref), - }) - } - if (decision.applied === true) { - const applied = applyDecision(store, task.id, decision) - return { task: applied.task, summary: summarize(applied) } - } - return { task: live, summary: summarize(decision) } - }) - return { task: copy(judged.value.task), attempt: copy(attempt), decision: judged.value.summary } - }) - - // ---------- 待补充 / 同步决定 ---------- - - /** requestTaskInput:明确缺什么就进入 waiting_input,只等用户补充,不广播其他部门。 */ - const requestTaskInput = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - const reason = requireText(input.reason, 'reason') - const missingItems = optionalArray(input.missingItems, 'missingItems') - const judged = store.mutate(() => { - const fresh = store.getTask(task.id) - const decision = decide(fresh, { - kind: 'input_required', - reason, - payload: { missingItems, scope: input.scope ?? null }, - }, { now: nowIso }) - if (decision.applied === true) { - const applied = applyDecision(store, task.id, decision) - return { task: applied.task, summary: summarize(applied) } - } - return { task: fresh, summary: summarize(decision) } - }) - return { - task: copy(judged.value.task), - applied: judged.value.summary.applied, - reason: judged.value.summary.reason, - missingItems, - } - }) - - /** supplyTaskInput:用户补齐后回到原任务,不扩大范围、不新建任务。 */ - const supplyTaskInput = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - const judged = store.mutate(() => { - const fresh = store.getTask(task.id) - const decision = decide(fresh, { kind: 'input_supplied' }, { now: nowIso }) - if (decision.applied === true) { - const applied = applyDecision(store, task.id, decision) - return { task: applied.task, summary: summarize(applied) } - } - return { task: fresh, summary: summarize(decision) } - }) - return { task: copy(judged.value.task), applied: judged.value.summary.applied, reason: judged.value.summary.reason } - }) - - /** 取出该任务最近一次登记的结构化报告;没有就返回 null(由完成判定判成 needs_attention)。 */ - function latestReport(project, task, attemptId) { - const rows = store.listResults(task.id).filter((row) => row.taskId === task.id - && (attemptId === null || row.attemptId === attemptId)) - if (rows.length === 0) return null - const last = rows.reduce((max, row) => (Number(row.reportVersion) >= Number(max.reportVersion) ? row : max), rows[0]) - // taskId / attemptId 必须一起带上:core 的 validateReport 把它们当作报告可信度的一部分, - // 少一个就会判成“缺少 attemptId”,完成判定直接掉进 needs_attention。 - return { - taskId: last.taskId, - attemptId: last.attemptId, - summary: last.summary, - checks: last.checks ?? [], - blockedReason: last.blockedReason ?? null, - artifactRefs: last.artifactRefs ?? [], - } - } - - /** - * syncDecision:把用户在某条会话里明确同意/否决的决定,定向同步给指定任务或丞相。 - * 最小实现:只登记一条带来源与选中片段的事件,不解析整段聊天、不广播给十席。 - */ - const syncDecision = guard((input = {}) => { - const project = projectIdOf(input) - const content = requireText(input.content, 'content') - const sourceSessionId = optionalText(input.sourceSessionId, 'sourceSessionId') - const roleId = input.roleId === undefined ? 'lead' : requireRole(input.roleId, 'roleId') - const task = input.taskId === undefined || input.taskId === null ? null : requireTask(project, input.taskId) - const event = store.appendEvent({ - type: 'decision.synced', - projectId: project.id, - roleId, - taskId: task?.id ?? null, - payload: { content, sourceSessionId, scope: input.scope ?? null, taskId: task?.id ?? null }, - }) - return { event: copy(event), task: copy(task), roleId } - }) - - // ---------- 成果 ---------- - - /** - * A23:成果文件被删/移走后,界面要显示「失效」而不是照旧显示可打开。 - * 这里不读文件内容、不改账本,只在投影时按注入的 fileExists 探一次。 - * 探不了(没接文件系统、fileRef 不是本地路径)就是 unknown,绝不猜成 ok。 - */ - function artifactView(artifact) { - if (artifact === null || artifact === undefined) return null - const path = typeof artifact.fileRef === 'string' && artifact.fileRef.trim() !== '' ? artifact.fileRef.trim() : null - let existence = 'unknown' - if (path !== null && typeof fileExists === 'function') { - try { - existence = fileExists(path) ? 'ok' : 'missing' - } catch { - existence = 'unknown' - } - } - return { ...copy(artifact), existence } - } - - /** - * 交接材料引用(A09):两种可追溯形态,别的一律拒绝。 - * - 字符串:历史数据里的自由文本引用,原样保留 - * - {artifactId}:必须是本项目的成果;版本缺省取该成果当前版本,显式给了就按给的记 - * - {attachmentId}:附件的宿主侧 ID,允许带 name/mime/size 供阅读 - * 显式拒绝跨项目成果引用:交接材料不能成为越权读取的通道。 - */ - function normalizeMaterialRefs(value, project) { - const list = optionalArray(value, 'packet.materialRefs') - return list.map((ref, index) => { - if (typeof ref === 'string') { - if (ref.trim() === '') throw new ServiceError(SERVICE_CODES.INVALID_INPUT, '材料引用不能是空字符串', { field: `materialRefs[${index}]` }) - return ref - } - if (ref === null || typeof ref !== 'object' || Array.isArray(ref)) { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, '材料引用必须是字符串或 {artifactId} / {attachmentId} 对象', { - field: `materialRefs[${index}]`, - }) - } - if (typeof ref.artifactId === 'string' && ref.artifactId !== '') { - const artifact = store.getArtifact(ref.artifactId) - if (artifact === undefined) { - throw new ServiceError(SERVICE_CODES.NOT_FOUND, '材料引用指向的成果不存在', { field: `materialRefs[${index}]` }) - } - if (artifact.projectId !== project.id) { - throw new ServiceError(SERVICE_CODES.CROSS_PROJECT, '材料引用指向的成果属于别的项目', { - field: `materialRefs[${index}]`, - }) - } - const revision = Number.isInteger(ref.revision) && ref.revision > 0 ? ref.revision : Number(artifact.revision ?? 1) - const out = { artifactId: artifact.id, revision } - // 名字只是给人读的,默认取成果自己的显示名;显式给了就以调用方为准。 - const title = typeof ref.title === 'string' && ref.title !== '' - ? ref.title - : (typeof artifact.displayName === 'string' && artifact.displayName !== '' ? artifact.displayName : '') - if (title !== '') out.title = title - return out - } - if (typeof ref.attachmentId === 'string' && ref.attachmentId !== '') { - const out = { attachmentId: ref.attachmentId } - if (typeof ref.name === 'string' && ref.name !== '') out.name = ref.name - if (typeof ref.mime === 'string' && ref.mime !== '') out.mime = ref.mime - if (Number.isInteger(ref.size) && ref.size > 0) out.size = ref.size - return out - } - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, '材料引用缺少 artifactId 或 attachmentId', { - field: `materialRefs[${index}]`, - }) - }) - } - - /** 登记成果引用:只记引用与校验结论,不复制文件内容,也不改文件本体。 */ - const registerArtifact = guard((input = {}) => { - const project = projectIdOf(input) - const task = requireTask(project, input.taskId) - const ownerRoleId = input.ownerRoleId === undefined ? task.ownerRoleId : requireRole(input.ownerRoleId, 'ownerRoleId') - const sourceResultId = input.sourceResultId === undefined || input.sourceResultId === null - ? null - : ownedRow(project, 'result', input.sourceResultId, 'sourceResultId').id - // 修订链:只有指向本项目既有成果才认,跨项目一律 CROSS_PROJECT。 - const revisesArtifactId = input.revisesArtifactId === undefined || input.revisesArtifactId === null - ? null - : ownedRow(project, 'artifact', input.revisesArtifactId, 'revisesArtifactId').id - const previous = revisesArtifactId === null ? null : store.getArtifact(revisesArtifactId) - const artifact = store.recordArtifact({ - projectId: project.id, - taskId: task.id, - ownerRoleId, - fileRef: optionalText(input.fileRef, 'fileRef'), - displayName: input.displayName === undefined ? '' : String(input.displayName), - mediaType: input.mediaType === undefined ? 'application/octet-stream' : String(input.mediaType), - versionOrHash: optionalText(input.versionOrHash, 'versionOrHash'), - verification: input.verification ?? { status: 'unverified' }, - sourceResultId, - revisesArtifactId, - revision: previous === null ? 1 : Number(previous.revision ?? 1) + 1, - revisionOfTaskId: previous === null ? null : (previous.revisionOfTaskId ?? previous.taskId ?? null), - }) - return { artifact: artifactView(artifact) } - }) - - /** - * 成果修订(方案路径 B):在成果区点“找主责部门修改”,只开一条修订任务给原主责部门, - * 不重跑整套三省。任务把原成果与版本写进 scope,派发时自动进交接材料。 - */ - const requestArtifactRevision = guard((input = {}) => { - const project = projectIdOf(input) - const artifact = ownedRow(project, 'artifact', input.artifactId, 'artifactId') - const instruction = requireText(input.instruction, 'instruction') - const ownerRoleId = input.ownerRoleId === undefined ? artifact.ownerRoleId : requireRole(input.ownerRoleId, 'ownerRoleId') - const sourceRoleId = input.sourceRoleId === undefined ? 'lead' : requireRole(input.sourceRoleId, 'sourceRoleId') - const wanted = input.status === undefined ? 'draft' : input.status - if (wanted !== 'queued' && wanted !== 'draft') { - throw new ServiceError(SERVICE_CODES.INVALID_INPUT, `修订任务只能是 queued 或 draft,收到 ${String(wanted)}`, { field: 'status' }) - } - if (wanted === 'queued') { - const binding = store.getBinding(project.id, ownerRoleId) - if (binding?.currentSessionId === null || binding?.currentSessionId === undefined) { - throw new ServiceError(SERVICE_CODES.INVALID_STATE, `${ownerRoleId} 尚未接通会话,不能直接入队;可先存草稿`, { - roleId: ownerRoleId, - hint: 'draft', - }) - } - } - const record = createTaskRecord({ - projectId: project.id, - title: input.title === undefined ? `修改成果:${artifact.displayName || artifact.id}` : String(input.title), - objective: instruction, - acceptance: optionalArray(input.acceptance, 'acceptance'), - constraints: optionalArray(input.constraints, 'constraints'), - scope: { - kind: 'artifact-revision', - artifactId: artifact.id, - revision: Number(artifact.revision ?? 1), - sourceTaskId: artifact.taskId ?? null, - }, - ownerRoleId, - sourceRoleId, - originMessageRef: optionalText(input.originMessageRef, 'originMessageRef'), - returnTarget: input.returnTarget ?? { roleId: sourceRoleId }, - }, { newTaskId: () => store.ids.task(), now: nowIso }) - const withChain = { - ...record, - kind: 'revision', - reviseOfArtifactId: artifact.id, - reviseOfTaskId: artifact.taskId ?? null, - artifactRevision: Number(artifact.revision ?? 1), - } - const queued = wanted === 'queued' ? startTask(withChain, { now: nowIso }) : withChain - return { task: copy(store.insertTask(queued)), artifact: artifactView(artifact) } - }) - - function listArtifacts(projectId) { - const project = projectIdOf({ projectId }) - return store.listArtifacts(project.id).map(artifactView) - } - - function getArtifact(projectId, artifactId) { - const project = projectIdOf({ projectId }) - return artifactView(ownedRow(project, 'artifact', artifactId, 'artifactId')) - } - - function getAttempt(projectId, attemptId) { - const project = projectIdOf({ projectId }) - return copy(requireAttempt(project, attemptId)) - } - - // ---------- 事件 ---------- - - /** - * 事件轮询数据源:since 之后的本项目事件,按 seq 升序。 - * - since 超出当前 seq(账本被替换/回滚)→ reset=true,前端应全量重拉而不是空等; - * - 只返回本项目事件;projectId 为空时返回全局(宿主内部用,UI 不传)。 - */ - function listEvents(projectId, since = 0, optionsArg = {}) { - let scope = null - if (projectId !== undefined && projectId !== null && projectId !== '') { - scope = projectIdOf({ projectId }).id - } - const cursor = Number(since) - const start = Number.isFinite(cursor) && cursor > 0 ? Math.floor(cursor) : 0 - const limit = Number.isInteger(optionsArg.limit) && optionsArg.limit > 0 ? optionsArg.limit : 200 - const all = store.listEvents(scope === null ? undefined : scope) - const fresh = all.filter((row) => row.seq > start).sort((left, right) => left.seq - right.seq) - return { - events: fresh.slice(0, limit).map(copy), - seq: store.eventSeq, - reset: start > store.eventSeq, - hasMore: fresh.length > limit, - } - } - - // ---------- 投影 ---------- - - /** - * bootstrap:一次拿全。projectId 为空时取列表第一个; - * 传入的项目不可见按 NOT_FOUND 报错,不泄露其他项目是否存在。 - */ - function bootstrap(projectId) { - const projects = listProjects() - let selectedId = null - if (projectId !== undefined && projectId !== null && projectId !== '') { - selectedId = projectIdOf({ projectId }).id - } else if (projects.length > 0) { - selectedId = projects[0].id - } - if (selectedId === null) { - return { - projects, - projectId: null, - project: null, - seats: [], - layout: layout(), - tasks: [], - artifacts: [], - results: [], - eventSeq: store.eventSeq, - } - } - const project = store.getProject(selectedId) - const taskIds = new Set(store.listTasks(selectedId).map((task) => task.id)) - return { - projects, - projectId: selectedId, - project: copy(project), - seats: listSeats(selectedId), - layout: layout(), - tasks: listTasks(selectedId), - artifacts: store.listArtifacts(selectedId).map(artifactView), - results: store.listResults(undefined).filter((row) => taskIds.has(row.taskId)).map(copy), - eventSeq: store.eventSeq, - } - } - - // ---------- 事件:每次状态变更都写一条 outbox ---------- - - /** - * 哪些操作要发事件:凡是「UI 需要立刻看到」的写操作。 - * 放在出口统一包一层而不是各函数里各写一遍——漏一处就是一个静默不刷新的 bug。 - * syncDecision 自己已经登记了 decision.synced,这里跳过,避免同一动作两条事件。 - */ - const EVENT_OPS = new Set([ - 'registerProject', - 'bindDepartmentSession', - 'releaseDepartmentSession', - 'setDepartmentStatus', - 'saveDepartmentConfig', - 'createTask', - 'cancelTask', - 'dispatchTask', - 'markDispatch', - 'startAttempt', - 'reportTaskResult', - 'reportRunTerminal', - 'requestTaskInput', - 'supplyTaskInput', - 'registerArtifact', - 'requestArtifactRevision', - ]) - - /** 从返回值里找这次写入属于哪个项目;找不到就不带项目(全局事件)。 */ - function projectIdOfResult(value, input) { - const candidates = [ - value?.project?.id, - value?.task?.projectId, - value?.binding?.projectId, - value?.dispatch?.projectId, - value?.attempt?.projectId, - value?.config?.projectId, - value?.artifact?.projectId, - value?.result?.projectId, - input?.projectId, - ] - return candidates.find((id) => typeof id === 'string' && id !== '') ?? null - } - - /** - * 事件只是“给 UI 的增量提示”,写入失败绝不能让业务失败: - * 账已经落对了,事件补不上顶多让界面晚一拍,靠 /bootstrap 仍能自愈。 - */ - function emitChange(op, value, input) { - try { - const projectId = projectIdOfResult(value, input) - const roleId = value?.task?.ownerRoleId - ?? value?.binding?.roleId - ?? value?.attempt?.roleId - ?? input?.roleId - ?? null - store.appendEvent({ - type: `state.${op}`, - projectId, - roleId, - taskId: value?.task?.id ?? input?.taskId ?? null, - attemptId: value?.attempt?.id ?? input?.attemptId ?? null, - payload: { op }, - }) - } catch { - // 见上:事件不是业务前置条件。 - } - } - - const api = { - version: WORKBENCH_SERVICE_VERSION, - store, - clock, - env, - // 项目 - registerProject, - listProjects, - getProject, - // 十席 - listSeats, - layout, - // 绑定与配置 - bindDepartmentSession, - releaseDepartmentSession, - setDepartmentStatus, - saveDepartmentConfig, - // 任务 - createTask, - getTask, - listTasks, - cancelTask, - // 派发 - dispatchTask, - markDispatch, - startAttempt, - // 结果 - reportTaskResult, - reportRunTerminal, - requestTaskInput, - supplyTaskInput, - syncDecision, - // 成果 - registerArtifact, - requestArtifactRevision, - listArtifacts, - getArtifact, - getAttempt, - // 投影与事件 - bootstrap, - listEvents, - // 供路由与测试复用 - translate, - } - - const wrapped = {} - for (const [name, fn] of Object.entries(api)) { - if (typeof fn !== 'function' || !EVENT_OPS.has(name)) { - wrapped[name] = fn - continue - } - wrapped[name] = (...args) => { - const value = fn(...args) - emitChange(name, value, args[0]) - return value - } - } - return Object.freeze(wrapped) -} diff --git a/workbench/host/session-adapter.mjs b/workbench/host/session-adapter.mjs deleted file mode 100644 index f40c9ad..0000000 --- a/workbench/host/session-adapter.mjs +++ /dev/null @@ -1,307 +0,0 @@ -// 会话适配层:把 Host 的 SessionController 收敛成“派发只需要几个动作”。 -// -// 依据 docs/v0.1-宿主能力记录.md(P0 实测的类型层事实): -// - create({workspaceId}) 幂等:同一 workspace 已绑定时返回同一个会话,不会造出第二个; -// - create 里没有 creationRequestId,也没有 cwd+workspaceId 同时给的用法(会 bad-request); -// - prompt 的 requestId 才是真幂等键(跨重启有效),所以 attemptId 直接当 requestId 用; -// - cancel() 只是“请求取消”,accepted:true ≠ 已取消,终态必须靠 follow/对账得到。 -// -// 这一层只做三件事:拿到会话、送一条消息、听它的事件。其余判定留在核心层。 - -export class SessionAdapterError extends Error { - constructor(code, message, details = undefined) { - super(message) - this.name = 'SessionAdapterError' - this.code = code - if (details !== undefined) this.details = details - } -} - -/** 把宿主抛出的杂异常收敛成“可重试 / 必失败”两类,reconciler 依赖这个区分。 */ -export function classifyHostError(error) { - const code = error && typeof error.code === 'string' ? error.code : '' - const message = error instanceof Error ? error.message : String(error) - if (code === 'session/conflict' || /session\/conflict/.test(message)) return 'conflict' - if (code === 'session/model-unavailable' || /model-unavailable/.test(message)) return 'model_unavailable' - if (code === 'session/agent-busy' || /agent-busy/.test(message)) return 'busy' - if (code === 'session/writer-held' || /writer-held/.test(message)) return 'transient' - if (/timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|socket hang up/i.test(message)) return 'transient' - return 'unknown' -} - -/** - * @param {object} options - * @param {object} options.sessionController Host 的 ctx.sessionController(或同形状替身)。 - * @param {(event: object) => void} [options.onEvent] 订阅回调:任意会话事件(对账与 UI 都用它)。 - * @param {(message: string) => void} [options.log] 诊断日志出口;默认吞掉。 - */ -export function createSessionAdapter(options = {}) { - const { sessionController, onEvent, log = () => {} } = options - if (sessionController === undefined || sessionController === null || typeof sessionController.prompt !== 'function') { - throw new SessionAdapterError('NO_SESSION_CONTROLLER', '会话适配层需要 Host 的 sessionController') - } - const controller = sessionController - /** 正在跑 follow 的会话:sessionId → { controller: AbortController, done: Promise } */ - const followers = new Map() - // 被用户明确要求停止过的会话(只影响对账收口,不影响派发)。 - const cancelRequested = new Set() - let disposed = false - - function ensureAlive() { - if (disposed) throw new SessionAdapterError('DISPOSED', '会话适配层已释放') - } - - /** - * 拿到(或复用)一个会话。上层传入的 sessionId 是 store 里登记的绑定; - * 为空时用 workspaceId 建一个新会话,并把 host 返回的 id 交回给上层登记。 - */ - async function ensureSession({ workspaceId, sessionId, agentPreset } = {}) { - ensureAlive() - if (typeof sessionId === 'string' && sessionId.trim() !== '') { - // 已有绑定:不重建,只确认宿主能看到它(看不到就交给上层判定绑定失效)。 - const known = await inspectSession(sessionId) - return { sessionId, created: false, known } - } - if (typeof workspaceId !== 'string' || workspaceId.trim() === '') { - throw new SessionAdapterError('NO_TARGET', '既没有绑定会话也没有 workspaceId,无法接通部门') - } - const request = { workspaceId } - if (typeof agentPreset === 'string' && agentPreset.trim() !== '') request.agentPreset = agentPreset - try { - const value = await controller.create(request) - if (value === null || typeof value !== 'object' || typeof value.sessionId !== 'string') { - throw new SessionAdapterError('BAD_CREATE_RESULT', '宿主 create 未返回 sessionId') - } - return { sessionId: value.sessionId, created: true, agentPreset: value.agentPreset ?? null } - } catch (error) { - throw new SessionAdapterError(classifyHostError(error), `接通部门会话失败:${messageOf(error)}`, { cause: error }) - } - } - - async function inspectSession(sessionId) { - if (typeof controller.inspect !== 'function') return null - try { - return await controller.inspect(sessionId) - } catch { - return null - } - } - - /** - * 送一条消息。requestId 由调用方(attemptId)给,重试同一条 attempt 不会重复投递; - * 超时/未知一律抛 transient,由 reconciler 决定是查证还是标 unknown。 - */ - async function sendPrompt({ sessionId, requestId, text, mode = 'queue', signal, clientTimeZone } = {}) { - ensureAlive() - if (typeof sessionId !== 'string' || sessionId.trim() === '') { - throw new SessionAdapterError('NO_SESSION', '送消息前必须有 sessionId') - } - if (typeof text !== 'string' || text.trim() === '') { - throw new SessionAdapterError('EMPTY_PROMPT', '送消息内容为空') - } - if (typeof requestId !== 'string' || requestId.trim() === '') { - throw new SessionAdapterError('NO_REQUEST_ID', '送消息必须带 requestId(幂等键)') - } - const request = { - requestId, - sessionId, - mode: mode === 'steer' ? 'steer' : 'queue', - content: [{ type: 'text', text }], - } - if (typeof clientTimeZone === 'string' && clientTimeZone !== '') request.clientTimeZone = clientTimeZone - try { - const value = await controller.prompt(request, signal) - return { accepted: value?.accepted === true } - } catch (error) { - throw new SessionAdapterError(classifyHostError(error), `投递失败:${messageOf(error)}`, { cause: error }) - } - } - - /** - * 取消只是“请求取消”;调用方必须等 follow 上的终态或对账结果,不能直接当已停。 - * 这里额外记下"这个会话被用户要求停过",对账时用它把停跑结果收口成 cancelled, - * 避免"取消与成功竞争"里被取消的那一次被记成成功运行。 - */ - function requestCancel(sessionId) { - ensureAlive() - try { - const value = controller.cancel({ sessionId }) - if (value?.accepted === true) cancelRequested.add(sessionId) - return { accepted: value?.accepted === true } - } catch (error) { - throw new SessionAdapterError(classifyHostError(error), `取消失败:${messageOf(error)}`, { cause: error }) - } - } - - /** 该会话是否被明确要求过停止(跨本次进程有效;宿主重启后由 attempt 状态兜底)。 */ - function wasCancelRequested(sessionId) { - return cancelRequested.has(sessionId) - } - - /** 新一轮派发成功投递后可清掉停止标记:同一会话的下一次运行不该继承上一次的取消意图。 */ - function clearCancelRequest(sessionId) { - return cancelRequested.delete(sessionId) - } - - /** 每次派发都显式覆写模型:宿主 selectModel 会顺手改全局默认,所以用快照固定本轮。 */ - async function applyModel({ sessionId, provider, model, reasoningEffort } = {}) { - ensureAlive() - if (typeof controller.selectModel !== 'function') return { selected: false, reason: 'controller 无 selectModel' } - if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '') { - return { selected: false, reason: '未配置模型' } - } - const request = { sessionId, provider, model } - if (typeof reasoningEffort === 'string' && reasoningEffort !== '') request.reasoningEffort = reasoningEffort - try { - const value = await controller.selectModel(request) - return { selected: true, selection: value?.selected ?? null } - } catch (error) { - // 模型不可用是“本次派发不能开工”,不是“任务失败”,交由上层标 unavailable 并保留任务。 - throw new SessionAdapterError(classifyHostError(error), `模型切换失败:${messageOf(error)}`, { cause: error }) - } - } - - async function getSessionSummary(sessionId) { - if (typeof controller.list !== 'function') return null - try { - const value = await controller.list({}, new AbortController().signal) - const items = Array.isArray(value?.items) ? value.items : [] - return items.find((row) => row.sessionId === sessionId) ?? null - } catch { - return null - } - } - - /** 宿主是否还在跑这个会话:null 表示问不到(不当成“已结束”)。 */ - async function isRunning(sessionId) { - const summary = await getSessionSummary(sessionId) - if (summary === null) return null - return summary.running === true - } - - /** - * 订阅会话事件。alreadyAttached 时不重复起流:同一个会话只留一条 follow, - * 避免双窗口/重启后重建出两条流导致事件重复。 - */ - function follow(sessionId, { onFrame } = {}) { - ensureAlive() - if (followers.has(sessionId)) return followers.get(sessionId).handle - if (typeof controller.follow !== 'function') throw new SessionAdapterError('NO_FOLLOW', 'controller 无 follow') - const abort = new AbortController() - const handle = { sessionId, stop: () => abort.abort() } - const done = (async () => { - try { - const address = { sessionId } - const stream = controller.follow({ address }, abort.signal) - for await (const frame of stream) { - if (disposed || abort.signal.aborted) break - if (frame?.type === 'assistant-stream') continue - try { - if (typeof onFrame === 'function') onFrame(frame) - if (typeof onEvent === 'function') onEvent({ sessionId, frame }) - } catch (error) { - log(`[sansheng-liubu] 处理会话帧失败:${messageOf(error)}`) - } - } - } catch (error) { - if (!abort.signal.aborted) log(`[sansheng-liubu] 会话流中断:${messageOf(error)}`) - } finally { - followers.delete(sessionId) - } - })() - followers.set(sessionId, { handle, done }) - return handle - } - - function unfollow(sessionId) { - const entry = followers.get(sessionId) - if (entry === undefined) return false - entry.handle.stop() - return true - } - - function dispose() { - disposed = true - for (const entry of followers.values()) entry.handle.stop() - followers.clear() - } - - return Object.freeze({ - ensureSession, - inspectSession, - sendPrompt, - requestCancel, - wasCancelRequested, - clearCancelRequest, - applyModel, - getSessionSummary, - isRunning, - follow, - unfollow, - dispose, - get following() { - return [...followers.keys()] - }, - }) -} - -function messageOf(error) { - return error instanceof Error ? error.message : String(error) -} - -/** - * 把一条材料引用写成人能读的一行,并保留可追溯的 ID。 - * - 字符串:原样(历史数据里的自由文本引用) - * - {artifactId, revision}:成果引用,带版本号 - * - {attachmentId, name, mime, size}:附件引用(A09 附件级交接) - */ -export function describeMaterialRef(ref) { - if (typeof ref === 'string') return ref - if (ref === null || typeof ref !== 'object') return String(ref) - if (typeof ref.artifactId === 'string' && ref.artifactId !== '') { - const version = Number.isInteger(ref.revision) && ref.revision > 0 ? `(第 ${ref.revision} 版)` : '' - const title = typeof ref.title === 'string' && ref.title !== '' ? ` ${ref.title}` : '' - return `成果${title} ${ref.artifactId}${version}` - } - if (typeof ref.attachmentId === 'string' && ref.attachmentId !== '') { - const bits = [] - if (typeof ref.name === 'string' && ref.name !== '') bits.push(ref.name) - if (typeof ref.mime === 'string' && ref.mime !== '') bits.push(ref.mime) - if (Number.isInteger(ref.size) && ref.size > 0) bits.push(`${ref.size} 字节`) - const suffix = bits.length === 0 ? '' : `(${bits.join(' · ')})` - return `附件 ${ref.attachmentId}${suffix}` - } - return JSON.stringify(ref) -} - -/** - * 把一次派发写成部门能直接执行的提示词。只放事实(任务、验收、材料、回传方式), - * 不写“请确认已完成”这类引导语——完成判定只认结构化报告。 - */ -export function buildDispatchText({ task, packet, contractGuide, roleName } = {}) { - const lines = [] - const name = typeof roleName === 'string' && roleName !== '' ? roleName : '你' - lines.push(`【任务单 ${task?.id ?? ''}】${task?.title ?? ''}`) - if (typeof task?.objective === 'string' && task.objective !== '') lines.push(`目标:${task.objective}`) - const acceptance = Array.isArray(packet?.acceptance) && packet.acceptance.length > 0 ? packet.acceptance : task?.acceptance - if (Array.isArray(acceptance) && acceptance.length > 0) { - lines.push('验收标准:') - for (const item of acceptance) lines.push(`- ${String(item)}`) - } - const constraints = Array.isArray(packet?.constraints) ? packet.constraints : task?.constraints - if (Array.isArray(constraints) && constraints.length > 0) { - lines.push('约束:') - for (const item of constraints) lines.push(`- ${String(item)}`) - } - const refs = Array.isArray(packet?.materialRefs) ? packet.materialRefs : [] - if (refs.length > 0) { - lines.push('相关材料:') - for (const ref of refs) lines.push(`- ${describeMaterialRef(ref)}`) - } - lines.push('') - lines.push(`完成后请用结构化回传(不要只在正文里说“已完成”,那样不算完成):`) - lines.push(typeof contractGuide === 'string' && contractGuide !== '' ? contractGuide : '') - lines.push('') - lines.push(`(你是本项目的 ${name};任务与成果归属由程序按项目登记,不要自行改派给其他部门。)`) - return lines.join('\n') -} diff --git a/workbench/host/workbench-host.mjs b/workbench/host/workbench-host.mjs deleted file mode 100644 index 5844f7c..0000000 --- a/workbench/host/workbench-host.mjs +++ /dev/null @@ -1,212 +0,0 @@ -// 工作台 Host 外壳:把 store + service + 适配层 + 两个后台服务组装成一个可挂载组件。 -// -// 挂载方式(index.js 里): -// const host = createWorkbenchHost(ctx, { store, presetId }) -// ctx.effect(() => () => host.dispose(), 'sansheng-liubo: workbench') -// -// 能力探测优先:宿主没有 sessionController 时,工作台仍然能读写账本(投影可用), -// 但任何“派发/接通”都返回 NO_SESSION_CONTROLLER,UI 显示“尚未接通”,绝不假装成功。 - -import { WorkbenchStore, defaultStorePath } from '../core/store.mjs' -import { createWorkbenchService } from './service.mjs' -import { createSessionAdapter } from './session-adapter.mjs' -import { createDispatchService } from './dispatch-service.mjs' -import { createReconciler } from './reconciler.mjs' -import { CONTRACT_ACTIONS, CONTRACT_ACTION_PREFIX, parseContractLines, describeContract } from './contract.mjs' - -export const WORKBENCH_HOST_VERSION = 1 - -/** - * @param {object} ctx Host 插件上下文(cordis Context) - * @param {object} [options] - * @param {object} [options.store] 已有 store(测试注入);缺省按环境建一个。 - * @param {object} [options.service] 已有 service;缺省按 store 新建。给了 service 就必须同时给 store, - * 否则两边的账不是同一本。 - * @param {string} [options.presetId] 部门会话使用的 agentPreset,首版沿用「上朝」。 - * @param {boolean} [options.startReconciler] 是否启动周期对账,默认 true。 - */ -export function createWorkbenchHost(ctx, options = {}) { - const log = (message) => { - try { - ctx?.logger?.info?.(message) - } catch { - /* 日志失败不能影响业务 */ - } - } - - const store = options.store ?? createStore(options) - const service = options.service ?? createWorkbenchService({ store, clock: options.clock, fileExists: options.fileExists }) - - // 会话层是可选能力:宿主没有 sessionController(或版本不提供)时整体降级。 - // 注意 apply 时宿主可能还没把 sessionController 装好,所以这里只是「尝试挂载」, - // 真正的挂载动作集中在 mountSessions,宿主晚到时由 attachSessions 再补一次。 - let sessions = null - let dispatchService = null - let reconciler = null - let hasSessions = false - let started = false - - function mountSessions(controller) { - const usable = controller !== null && typeof controller?.prompt === 'function' - if (!usable) return false - if (sessions !== null) return true - try { - sessions = createSessionAdapter({ sessionController: controller, log }) - } catch (error) { - log(`[sansheng-liubo] 会话层不可用:${error?.message ?? error}`) - sessions = null - return false - } - 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() - return true - } - - /** 宿主稍后才提供 sessionController 时补挂(不重启也能用)。返回是否挂上。 */ - function attachSessions(controller) { - const mounted = mountSessions(controller ?? null) - if (!mounted) log('[sansheng-liubo] 会话控制器仍不可用,派发继续保持“只落账”') - return mounted - } - - mountSessions(ctx?.sessionController ?? ctx?.remote?.session ?? null) - - const presetId = typeof options.presetId === 'string' && options.presetId !== '' ? options.presetId : 'sansheng-liubu' - - /** - * 接通某个部门的会话:已有绑定就直接用,没有就按 workspace 建一个并登记。 - * 绑定替换由 store 的 bindSession 判定(allowReplace),账上和宿主保持一致。 - */ - async function connectDepartment(input = {}) { - const projectId = requireText(input.projectId, 'projectId') - const roleId = requireText(input.roleId, 'roleId') - const project = store.getProject(projectId) - if (project === undefined) throw new Error('项目不存在') - if (sessions === null) { - throw new Error('宿主未提供会话能力,暂时无法接通部门(账本仍可读写)') - } - const binding = store.getBinding(projectId, roleId) - const existing = binding?.currentSessionId ?? null - if (existing !== null) { - const known = await sessions.inspectSession(existing) - if (known !== null) return { sessionId: existing, created: false, seat: seatOf(projectId, roleId) } - } - const target = await sessions.ensureSession({ - workspaceId: project?.hostWorkspaceId, - sessionId: input.sessionId ?? null, - agentPreset: input.agentPreset ?? presetId, - }) - // 账上登记:同一会话被别的部门占用时 store 会拒绝,正是我们要的“会话独占”。 - const saved = service.bindDepartmentSession({ - projectId, - roleId, - sessionId: target.sessionId, - allowReplace: existing !== null, - }) - return { sessionId: target.sessionId, created: target.created === true, seat: saved.seat } - } - - function seatOf(projectId, roleId) { - return service.listSeats(projectId).find((seat) => seat.roleId === roleId) ?? null - } - - /** 派发(对 UI 的唯一入口)。没有会话层时返回明确错误,不假装已发送。 */ - async function dispatchTask(input = {}) { - if (dispatchService === null) { - return { ok: false, code: 'NO_SESSION_CONTROLLER', message: '宿主未提供会话能力,派发已停在工作台账内' } - } - return dispatchService.dispatch(input) - } - - /** 处理部门输出里的契约行:只认结构化字段,解析失败的行原样返回给 UI 提示。 */ - function ingestAgentOutput({ projectId, roleId, text } = {}) { - const parsed = parseContractLines(text) - const applied = [] - const failed = [] - for (const call of parsed.calls) { - try { - applied.push(applyContractCall({ projectId, roleId, call })) - } catch (error) { - failed.push({ action: call.action, code: error?.code ?? 'unknown', message: error?.message ?? String(error) }) - } - } - return { applied, failed, invalid: parsed.invalid } - } - - function applyContractCall({ projectId, roleId, call }) { - const payload = { ...call.payload, projectId } - switch (call.action) { - case 'dispatchTask': - if (payload.sourceRoleId === undefined) payload.sourceRoleId = roleId - return { action: call.action, result: service.dispatchTask(payload) } - case 'reportTaskResult': - return { action: call.action, result: service.reportTaskResult(payload) } - case 'requestTaskInput': - return { action: call.action, result: service.requestTaskInput(payload) } - case 'syncDecision': - return { action: call.action, result: service.syncDecision(payload) } - default: - throw new Error(`未知动作:${String(call.action)}`) - } - } - - function start() { - if (started) return - started = true - if (options.startReconciler !== false && reconciler !== null) reconciler.start() - } - - function dispose() { - if (reconciler !== null) reconciler.stop() - if (sessions !== null) sessions.dispose() - started = false - } - - return Object.freeze({ - version: WORKBENCH_HOST_VERSION, - store, - service, - // 会话层可能晚到:用 getter,调用方总能读到最新挂载结果。 - get sessions() { - return sessions - }, - get reconciler() { - return reconciler - }, - get dispatchService() { - return dispatchService - }, - get hasSessions() { - return hasSessions - }, - attachSessions, - presetId, - connectDepartment, - dispatchTask, - ingestAgentOutput, - bootstrap: (projectId) => service.bootstrap(projectId), - listEvents: (projectId, since, opts) => service.listEvents(projectId, since, opts), - start, - dispose, - }) -} - -function createStore(options) { - const file = options.storeFile ?? defaultStorePath(process.env) - const store = new WorkbenchStore({ file }) - try { - store.load() - } catch { - // 读到坏账本时不静默清空:由 paths.quarantineFile 在 HTTP 层隔离,这里保持空账可写。 - } - return store -} - -function requireText(value, field) { - if (typeof value !== 'string' || value.trim() === '') throw new Error(`${field} 必须是非空字符串`) - return value -} - -export { CONTRACT_ACTIONS, CONTRACT_ACTION_PREFIX, parseContractLines, describeContract } diff --git a/workbench/panel/lib/client.js b/workbench/panel/lib/client.js deleted file mode 100644 index 43ba526..0000000 --- a/workbench/panel/lib/client.js +++ /dev/null @@ -1,2242 +0,0 @@ -window.__ModuleLoader__.load({ - id: "dsh-sansheng-liubu-workbench", - factory: (require) => { - var module = { exports: {} }; - var exports = module.exports; - Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); - - const React = require("react"); - const h = React.createElement; - - // --------------------------------------------------------------------- - // 常量与纯函数(不依赖宿主、不依赖 DOM,供单测直接调用) - // --------------------------------------------------------------------- - - const API_BASE = "/sansheng/workbench"; - const TAB_ID = "sansheng-liubu-workbench"; - const TAB_KIND = "sansheng-liubu-workbench"; - const CSS_ID = "dsh-sansheng-liubu-workbench/workbench.css"; - const RAIL_WIDTH_KEY = "sansheng.workbench.railWidth"; - const MAIN_SWITCH_KEY = "sansheng.workbench.main"; - const RAIL_MIN = 340; - const RAIL_MAX = 600; - const RAIL_DEFAULT = 400; - - const ROLE_ORDER = [ - "lead", - "zhongshu", - "shangshu", - "menxia", - "libu", - "hubu", - "lipu", - "bingbu", - "xingbu", - "gongbu", - ]; - - const ROLE_META = { - lead: { name: "丞相", mark: "丞", kicker: "主代理", tier: "leaders", group: "lead", column: "span", row: 0, duty: "接需求、分流、协调、汇报" }, - zhongshu: { name: "中书", mark: "中", kicker: "省", tier: "sansheng", group: "sansheng", column: "left", row: 1, duty: "起草方案、拆解路径" }, - shangshu: { name: "尚书", mark: "尚", kicker: "省", tier: "sansheng", group: "sansheng", column: "center", row: 1, duty: "总揽执行、调度六部" }, - menxia: { name: "门下", mark: "门", kicker: "省", tier: "sansheng", group: "sansheng", column: "right", row: 1, duty: "审核把关、封驳纠偏" }, - libu: { name: "吏部", mark: "吏", kicker: "部", tier: "ministries", group: "ministries", column: "left", row: 2, duty: "人事、配置、席位" }, - hubu: { name: "户部", mark: "户", kicker: "部", tier: "ministries", group: "ministries", column: "center", row: 2, duty: "资源、预算、账目" }, - lipu: { name: "礼部", mark: "礼", kicker: "部", tier: "ministries", group: "ministries", column: "right", row: 2, duty: "文档、规范、对外表达" }, - bingbu: { name: "兵部", mark: "兵", kicker: "部", tier: "ministries", group: "ministries", column: "left", row: 3, duty: "执行、工具、攻坚" }, - xingbu: { name: "刑部", mark: "刑", kicker: "部", tier: "ministries", group: "ministries", column: "center", row: 3, duty: "测试、审查、问责" }, - gongbu: { name: "工部", mark: "工", kicker: "部", tier: "ministries", group: "ministries", column: "right", row: 3, duty: "工程、构建、基础设施" }, - }; - - const STATUS_LABELS = { - uninitialized: "未接通", - idle: "空闲", - queued: "排队", - running: "正在运行", - unavailable: "不可用", - needs_attention: "需人处理", - }; - - const EFFORT_LABELS = { - minimal: "极低", - low: "低", - medium: "中", - high: "高", - none: "无", - }; - - const TASK_STATUS_LABELS = { - draft: "草稿", - queued: "排队", - running: "执行中", - waiting_input: "待输入", - needs_attention: "需人处理", - completed: "已完成", - failed: "失败", - cancelled: "已取消", - }; - - function assign(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - if (!source) continue; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key]; - } - } - return target; - } - - function clamp(value, low, high) { - var number = Number(value); - if (!isFinite(number)) return low; - return Math.min(high, Math.max(low, number)); - } - - function round(value) { - return Math.round(Number(value) * 10) / 10; - } - - function statusOf(status) { - if (typeof status !== "string" || status === "") return "未接通"; - return STATUS_LABELS[status] || "未知"; - } - - function seatDisplayName(seat) { - if (!seat) return ""; - var meta = ROLE_META[seat.roleId] || {}; - // short 是单字简称(丞/中/尚…),只能在最后兜底;完整名优先。 - return seat.name || meta.name || seat.short || seat.roleId || ""; - } - - function formatModelLine(config) { - if (!config || typeof config !== "object") return "跟随宿主"; - var provider = typeof config.provider === "string" ? config.provider.trim() : ""; - var model = typeof config.model === "string" ? config.model.trim() : ""; - var effort = typeof config.reasoningEffort === "string" ? config.reasoningEffort.trim() : ""; - if (!provider || !model) return "跟随宿主"; - var effortText = effort ? " · " + (EFFORT_LABELS[effort] || effort) : ""; - // model 自带 provider 前缀(如 magpie/workbuddy/deepseek-v4)时只留最后一段, - // 避免一行放不下、也避免 provider 重复;完整路径留在卡片 title 里。 - if (model.indexOf("/") >= 0) return model.slice(model.lastIndexOf("/") + 1) + effortText; - return provider + "/" + model + effortText; - } - - function modelTitle(config) { - if (!config || typeof config !== "object") return "跟随宿主(未单独配置模型)"; - var provider = typeof config.provider === "string" ? config.provider.trim() : ""; - var model = typeof config.model === "string" ? config.model.trim() : ""; - var effort = typeof config.reasoningEffort === "string" ? config.reasoningEffort.trim() : ""; - if (!provider || !model) return "跟随宿主(未单独配置模型)"; - return provider + "/" + model + (effort ? " · " + (EFFORT_LABELS[effort] || effort) : ""); - } - - function mergeEvents(current, incoming) { - var seen = new Set(); - var merged = []; - var batches = [current || [], incoming || []]; - for (var b = 0; b < batches.length; b++) { - var rows = batches[b]; - for (var i = 0; i < rows.length; i++) { - var row = rows[i]; - if (!row || typeof row !== "object") continue; - var key = row.eventId !== undefined && row.eventId !== null - ? "id:" + String(row.eventId) - : row.seq !== undefined && row.seq !== null - ? "seq:" + String(row.seq) - : null; - if (key === null || seen.has(key)) continue; - seen.add(key); - merged.push(row); - } - } - merged.sort(function (left, right) { - return (Number(left.seq) || 0) - (Number(right.seq) || 0); - }); - return merged; - } - - function apiPath(name, query) { - var clean = String(name === undefined || name === null ? "" : name).replace(/^\/+/, ""); - var path = API_BASE + (clean ? "/" + clean : ""); - if (query && typeof query === "object") { - var parts = []; - var keys = Object.keys(query); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = query[key]; - if (value === undefined || value === null) continue; - parts.push(encodeURIComponent(key) + "=" + encodeURIComponent(String(value))); - } - if (parts.length > 0) path += "?" + parts.join("&"); - } - return path; - } - - function pickProjectId(data, hostWorkspaceId) { - var projects = data && Array.isArray(data.projects) ? data.projects : []; - if (hostWorkspaceId) { - for (var i = 0; i < projects.length; i++) { - var project = projects[i]; - if (project && project.hostWorkspaceId === hostWorkspaceId && project.id) return project.id; - } - return null; - } - if (data && typeof data.projectId === "string" && data.projectId) return data.projectId; - for (var j = 0; j < projects.length; j++) { - if (projects[j] && projects[j].id) return projects[j].id; - } - return null; - } - - /** - * 纯几何布局:400px 栏宽时给出与 docs/preview/v01-nodes-*.png 一致的坐标。 - * 返回 nodes 每项都有 id / x / y / col / row(六部 row 为 2、3), - * 不依赖 DOM,列表渲染与单测共用,避免两套尺寸。 - */ - function computeRailLayout(width) { - var railWidth = Number(width) > 0 ? Number(width) : 400; - var padding = 12; - var gap = 10; - var sixGap = 8; - var groupPad = 8; - var leadHeight = 80; - var sanHeight = 80; - var sixHeight = 74; - var sectionGap = 26; - // 丞相与三省之间留出分叉展开的垂直空间,和 CSS 的 .wb-trio margin-top 保持一致。 - var leadGap = 48; - - var inner = Math.max(0, railWidth - padding * 2); - var columnWidth = Math.max(0, (inner - gap * 2) / 3); - var leadWidth = Math.min(184, inner); - var leadX = (railWidth - leadWidth) / 2; - - var nodes = []; - function node(roleId, box) { - var meta = ROLE_META[roleId]; - return assign({ - id: roleId, - roleId: roleId, - name: meta.name, - mark: meta.mark, - tier: meta.tier, - group: meta.group, - }, box); - } - - nodes.push(node("lead", { - x: leadX, - y: 0, - w: leadWidth, - h: leadHeight, - col: 1, - row: 0, - span: 3, - cx: leadX + leadWidth / 2, - })); - - var sanY = leadHeight + leadGap; - var sanIds = ["zhongshu", "shangshu", "menxia"]; - for (var i = 0; i < sanIds.length; i++) { - var sanX = padding + i * (columnWidth + gap); - nodes.push(node(sanIds[i], { - x: sanX, - y: sanY, - w: columnWidth, - h: sanHeight, - col: i, - row: 1, - cx: sanX + columnWidth / 2, - })); - } - - var groupY = sanY + sanHeight + sectionGap; - var sixY = groupY + groupPad; - var sixWidth = Math.max(0, (inner - groupPad * 2 - sixGap * 2) / 3); - var sixIds = ["libu", "hubu", "lipu", "bingbu", "xingbu", "gongbu"]; - for (var j = 0; j < sixIds.length; j++) { - var gridRow = j < 3 ? 0 : 1; - var col = j % 3; - var sixX = padding + groupPad + col * (sixWidth + sixGap); - nodes.push(node(sixIds[j], { - x: sixX, - y: sixY + gridRow * (sixHeight + sixGap), - w: sixWidth, - h: sixHeight, - col: col, - row: gridRow + 2, - gridRow: gridRow, - cx: sixX + sixWidth / 2, - })); - } - - var groupHeight = groupPad * 2 + sixHeight * 2 + sixGap; - - return { - width: railWidth, - padding: padding, - gap: gap, - leadWidth: leadWidth, - columnWidth: columnWidth, - nodes: nodes, - lead: nodes[0], - sansheng: nodes.slice(1, 4), - ministries: nodes.slice(4), - groups: { - lead: { x: leadX, y: 0, w: leadWidth, h: leadHeight, cx: railWidth / 2 }, - sansheng: { x: padding, y: sanY, w: inner, h: sanHeight }, - ministries: { x: padding, y: groupY, w: inner, h: groupHeight, cx: railWidth / 2 }, - }, - wires: { - lead: { x: railWidth / 2, y: leadHeight }, - ministries: { x: railWidth / 2, y: groupY }, - }, - height: groupY + groupHeight + 16, - }; - } - - // 分叉线:先垂直下行到 mid,再用两次控制点把切线转正, - // 终点处以垂直切线落到卡片顶边中点(C 的第二个控制点与终点同 x)。 - function branchPathD(cx0, y0, cx1, y1) { - var mid = y0 + (y1 - y0) * 0.55; - return "M " + round(cx0) + " " + round(y0) + - " V " + round(mid) + - " C " + round(cx0) + " " + round(y1) + " " + round(cx1) + " " + round(mid) + - " " + round(cx1) + " " + round(y1); - } - - // 由几何布局生成连线:丞相底中点 → 三省顶中点,尚书底中点 → 六部组顶边。 - // 真实测量走 DOM rect,量不到时走这里;两边共用同一套 M/V/C 公式。 - function wirePathsFromLayout(layout) { - var paths = []; - var lead = layout.lead; - var sansheng = layout.sansheng; - var y0 = lead.y + lead.h; - for (var i = 0; i < sansheng.length; i++) { - var card = sansheng[i]; - var y1 = card.y; - if (!(y1 > y0)) continue; - paths.push({ - key: "lead-" + card.id, - kind: "branch", - d: branchPathD(lead.cx, y0, card.cx, y1), - }); - } - var shangshu = null; - for (var j = 0; j < sansheng.length; j++) { - if (sansheng[j].id === "shangshu") shangshu = sansheng[j]; - } - var group = layout.groups.ministries; - if (shangshu) { - paths.push({ - key: "trunk", - kind: "trunk", - d: "M " + round(shangshu.cx) + " " + round(shangshu.y + shangshu.h) + - " L " + round(shangshu.cx) + " " + round(group.y), - }); - } - return paths; - } - - function isSeatOnlyEventBatch(events) { - if (!events || events.length === 0) return false; - for (var i = 0; i < events.length; i++) { - var type = String((events[i] && events[i].type) || ""); - if (!/^(seat|department|binding|config)\./.test(type)) return false; - } - return true; - } - - function describeError(error) { - if (!error) return "请求失败"; - var code = error.code ? String(error.code) : ""; - var message = error.message ? String(error.message) : ""; - var text = ""; - if (code && message && message.indexOf(code) < 0) text = code + ":" + message; - else text = message || code || String(error); - var details = error.details; - if (details && typeof details === "object" && typeof details.hint === "string" && details.hint) { - text += "(" + details.hint + ")"; - } - return text; - } - - // --------------------------------------------------------------------- - // HTTP:统一同源、解包 {ok,value}、失败抛 error.code - // --------------------------------------------------------------------- - - async function request(method, name, query, body, options) { - var init = { - method: method, - credentials: "same-origin", - headers: { Accept: "application/json" }, - }; - if (body !== undefined) { - init.headers["Content-Type"] = "application/json"; - init.body = JSON.stringify(body); - } - if (options && options.signal) init.signal = options.signal; - - var response; - try { - response = await fetch(apiPath(name, query), init); - } catch (cause) { - var network = new Error("网络请求失败:" + (cause && cause.message ? cause.message : String(cause))); - network.code = "NETWORK"; - throw network; - } - - var payload = null; - try { - payload = await response.json(); - } catch (cause) { - payload = null; - } - - if (!response.ok || !payload || payload.ok !== true) { - var failure = (payload && payload.error) || {}; - var error = new Error(failure.message || "请求失败(HTTP " + response.status + ")"); - error.code = failure.code || "HTTP_" + response.status; - error.details = failure.details; - error.status = response.status; - throw error; - } - return payload.value; - } - - function apiGet(name, query, options) { - return request("GET", name, query, undefined, options); - } - - function apiPost(name, body, query, options) { - return request("POST", name, query, body, options); - } - - // --------------------------------------------------------------------- - // 宿主服务探测(都不是 public API,缺了要让插件照常加载,不能 park) - // --------------------------------------------------------------------- - - function readService(ctx, name) { - try { - if (ctx && typeof ctx.get === "function") { - var service = ctx.get(name); - if (service) return service; - } - } catch (error) { - // 宿主没有这个服务;忽略。 - } - try { - return ctx ? ctx[name] : undefined; - } catch (error) { - return undefined; - } - } - - function betterSidebarOf(ctx) { - var candidates = [readService(ctx, "betterSidebar"), ctx && ctx.betterSidebar]; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; - if (candidate && typeof candidate.registerTab === "function") return candidate; - } - return null; - } - - function sidebarRightTabsOf(ctx) { - var service = readService(ctx, "sidebarRightTabs"); - if (service && typeof service.register === "function") return service; - return null; - } - - function effectOf(ctx, factory, label) { - if (ctx && typeof ctx.effect === "function") return ctx.effect(factory, label); - try { - return factory(); - } catch (error) { - console.warn("[sansheng-workbench] " + label + " 注册失败", error); - return undefined; - } - } - - function workspaceIdOf(ctx) { - var workspace = ctx && ctx.uiWorkspace; - if (!workspace) return null; - var direct = workspace.currentWorkspaceId || workspace.workspaceId; - if (direct) return String(direct); - try { - var selection = workspace.selection && typeof workspace.selection.getSnapshot === "function" - ? workspace.selection.getSnapshot() - : null; - if (selection && selection.workspaceId) return String(selection.workspaceId); - } catch (error) { - // 忽略:拿不到工作区就退回 bootstrap 自带 projectId。 - } - return null; - } - - function displayNameOf(ctx, workspaceId) { - var workspace = ctx && ctx.uiWorkspace; - var name = workspace && (workspace.currentWorkspaceName || workspace.workspaceName || workspace.displayName); - if (typeof name === "string" && name) return name; - return workspaceId ? "工作区 " + workspaceId : ""; - } - - function canonicalRootOf(ctx) { - var workspace = ctx && ctx.uiWorkspace; - var root = workspace && ( - workspace.currentWorkspaceRoot || - workspace.workspaceRoot || - (workspace.currentWorkspace && workspace.currentWorkspace.root) - ); - return typeof root === "string" && root ? root : null; - } - - async function resolveWorkbenchProject(ctx) { - var hostWorkspaceId = workspaceIdOf(ctx); - var value = await apiGet("bootstrap"); - var targetId = pickProjectId(value, hostWorkspaceId); - - if (hostWorkspaceId && !targetId) { - var body = { - hostWorkspaceId: hostWorkspaceId, - displayNameCache: displayNameOf(ctx, hostWorkspaceId), - }; - var root = canonicalRootOf(ctx); - if (root) body.canonicalRoot = root; - - var created = null; - try { - created = await apiPost("project", body); - } catch (error) { - if (error && error.code === "DUPLICATE_PROJECT" && error.details && error.details.projectId) { - targetId = error.details.projectId; - } else { - throw error; - } - } - if (created) { - targetId = (created.project && created.project.id) || created.id || targetId; - } - if (!targetId) { - value = await apiGet("bootstrap"); - targetId = pickProjectId(value, hostWorkspaceId) || value.projectId || null; - } - } - - if (targetId && value.projectId !== targetId) { - value = await apiGet("bootstrap", { projectId: targetId }); - } - if (!targetId) targetId = value.projectId || null; - return { projectId: targetId, value: value }; - } - - async function findBoundProject(ctx, sessionId) { - var cached = BOUND_PROJECT_CACHE.get(sessionId); - if (cached) return cached; - var first = await apiGet("bootstrap"); - var projects = Array.isArray(first.projects) ? first.projects : []; - var hostWorkspaceId = workspaceIdOf(ctx); - var ordered = projects.slice().sort(function (left, right) { - var leftMatch = left && left.hostWorkspaceId === hostWorkspaceId ? 1 : 0; - var rightMatch = right && right.hostWorkspaceId === hostWorkspaceId ? 1 : 0; - return rightMatch - leftMatch; - }); - - function hasSession(value) { - var seats = value && Array.isArray(value.seats) ? value.seats : []; - for (var i = 0; i < seats.length; i++) { - var binding = seats[i] && seats[i].binding; - if (!binding) continue; - if (binding.currentSessionId === sessionId || binding.sessionId === sessionId) return true; - } - return false; - } - - if (first.projectId && hasSession(first)) { - BOUND_PROJECT_CACHE.set(sessionId, first.projectId); - return first.projectId; - } - for (var i = 0; i < ordered.length; i++) { - var project = ordered[i]; - if (!project || !project.id || project.id === first.projectId) continue; - var value = await apiGet("bootstrap", { projectId: project.id }); - if (hasSession(value)) { - BOUND_PROJECT_CACHE.set(sessionId, project.id); - return project.id; - } - } - return null; - } - - function openSession(ctx, sessionId) { - var workspace = ctx && ctx.uiWorkspace; - try { - if (workspace && typeof workspace.openSession === "function") { - workspace.openSession(sessionId); - return true; - } - var selection = workspace && workspace.selection; - if (selection && typeof selection.set === "function") { - selection.set({ sessionId: sessionId }); - return true; - } - throw new Error("宿主未提供打开会话的接口(uiWorkspace.openSession)"); - } catch (error) { - return error && error.message ? error.message : String(error); - } - } - - // --------------------------------------------------------------------- - // 样式(照 .scratch/mock-nodes/rail.html 与 docs/preview/v01-nodes-400-*.png) - // --------------------------------------------------------------------- - - const CSS = [ - ".wb-rail{--wb-bg:#f7f9fc;--wb-card:#ffffff;--wb-line:#e3e8ef;--wb-line-strong:#c7d8f5;--wb-ink:#0f172a;--wb-ink-2:#475467;--wb-ink-3:#98a2b3;--wb-blue:#3b82f6;--wb-green:#22c55e;--wb-amber:#f59e0b;--wb-gray:#94a3b8;--wb-wire:#c9d6ea;--wb-dashed:#d7e1f0;--wb-group-bg:rgba(255,255,255,.55);position:relative;display:flex;flex-direction:column;height:100%;min-height:0;min-width:0;background:var(--wb-bg);color:var(--wb-ink);font-size:12px;line-height:1.4;font-family:inherit;overflow:hidden}", - ".wb-rail *,.wb-rail *::before,.wb-rail *::after{box-sizing:border-box}", - ".wb-head{flex:none;display:flex;align-items:baseline;justify-content:space-between;gap:8px;padding:10px 14px 8px}", - ".wb-title{font-size:12px;font-weight:600;color:var(--wb-ink-2);letter-spacing:.01em}", - ".wb-meta{font-size:10.5px;color:var(--wb-ink-3);white-space:nowrap}", - ".wb-tabs{flex:none;display:flex;gap:2px;margin:0 12px 8px;padding:2px;border:1px solid var(--wb-line);border-radius:8px;background:var(--wb-card)}", - ".wb-tab{flex:1 1 0;min-width:0;border:0;background:transparent;color:var(--wb-ink-3);font:inherit;font-size:11px;line-height:1.2;padding:4px 6px;border-radius:6px;cursor:pointer}", - ".wb-tab.is-active{background:var(--wb-bg);color:var(--wb-ink);font-weight:600;box-shadow:0 1px 2px rgba(16,24,40,.05)}", - ".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}", - ".wb-wires{position:absolute;left:0;top:0;z-index:0;pointer-events:none;overflow:visible}", - ".wb-wire{fill:none;stroke:var(--wb-wire);stroke-width:1.2;stroke-linecap:round}", - ".wb-lead-row{display:flex;justify-content:center;padding-top:4px}", - ".wb-trio{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:48px}", - ".wb-group{position:relative;margin-top:26px;padding:8px;border:1px dashed var(--wb-dashed);border-radius:12px;background:var(--wb-group-bg)}", - ".wb-group-label{position:absolute;top:-9px;left:10px;padding:0 5px;border-radius:4px;background:var(--wb-bg);color:var(--wb-ink-3);font-size:9.5px;line-height:18px;letter-spacing:.02em}", - ".wb-six{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}", - ".wb-card{position:relative;z-index:1;display:flex;flex-direction:column;gap:1px;min-width:0;padding:8px 10px;border:1px solid var(--wb-line);border-radius:10px;background:var(--wb-card);box-shadow:0 1px 2px rgba(16,24,40,.04);color:inherit;font:inherit;text-align:left;cursor:pointer;transition:border-color .12s ease,box-shadow .12s ease,transform .12s ease}", - ".wb-card:hover{border-color:var(--wb-line-strong)}", - ".wb-card:focus-visible{outline:2px solid var(--wb-blue);outline-offset:2px}", - ".wb-card.is-lead{width:min(184px,100%);margin:0 auto;padding:9px 12px;border-color:var(--wb-line-strong);background:linear-gradient(180deg,#fbfdff 0%,#ffffff 100%)}", - ".wb-card.is-running{border-color:var(--wb-blue);box-shadow:0 0 0 2px rgba(59,130,246,.14),0 2px 8px rgba(59,130,246,.12)}", - ".wb-card.is-attention{border-color:var(--wb-amber)}", - ".wb-card.is-unavailable{opacity:.72}", - ".wb-kicker{font-size:10px;color:var(--wb-ink-3);letter-spacing:.02em}", - ".wb-name{font-size:15px;font-weight:600;line-height:1.25;color:var(--wb-ink)}", - ".wb-model{font-size:11px;letter-spacing:-.01em;color:var(--wb-ink-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - ".wb-status{display:flex;align-items:center;gap:5px;margin-top:1px;font-size:11px;color:var(--wb-ink-2);white-space:nowrap;min-width:0}", - ".wb-card.has-connect .wb-status{padding-right:30px}", - ".wb-status>span:last-child{overflow:hidden;text-overflow:ellipsis}", - ".wb-card{min-width:0}", - ".wb-connect{max-width:calc(100% - 10px);padding:2px 5px;font-size:9.5px}", - ".wb-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--wb-gray)}", - ".wb-dot.is-idle{background:var(--wb-green)}", - ".wb-dot.is-running{background:var(--wb-blue)}", - ".wb-dot.is-attention{background:var(--wb-amber)}", - ".wb-connect{position:absolute;right:8px;bottom:7px;z-index:2;padding:3px 6px;border:1px solid var(--wb-line-strong);border-radius:5px;background:var(--wb-card);color:var(--wb-ink-2);font:inherit;font-size:10px;line-height:1;cursor:pointer}", - ".wb-connect:hover{border-color:var(--wb-blue);color:var(--wb-blue)}", - ".wb-connect:disabled{opacity:.6;cursor:default}", - ".wb-list{display:flex;flex-direction:column;gap:6px;padding:2px 0 8px}", - ".wb-list-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 2px;color:var(--wb-ink-2);font-size:11px}", - ".wb-small-btn{border:1px solid var(--wb-line-strong);border-radius:6px;background:var(--wb-card);color:var(--wb-ink-2);font:inherit;font-size:10.5px;line-height:1;padding:4px 7px;cursor:pointer}", - ".wb-small-btn:hover{border-color:var(--wb-blue);color:var(--wb-blue)}", - ".wb-small-btn:disabled{opacity:.6;cursor:default}", - ".wb-task{border:1px solid var(--wb-line);border-radius:9px;background:var(--wb-card);padding:8px 9px;display:flex;flex-direction:column;gap:2px}", - ".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}", - ".wb-textarea{min-height:44px;resize:vertical}", - ".wb-form-row{display:flex;gap:6px;align-items:center;justify-content:flex-end}", - ".wb-artifact{display:flex;flex-direction:column;gap:2px;width:100%;text-align:left;border:1px solid var(--wb-line);border-radius:9px;background:var(--wb-card);color:inherit;font:inherit;padding:8px 9px;cursor:pointer}", - ".wb-artifact:hover{border-color:var(--wb-line-strong)}", - ".wb-artifact-name{font-size:12px;font-weight:600;color:var(--wb-ink);word-break:break-word}", - ".wb-artifact-meta{font-size:10.5px;color:var(--wb-ink-3)}", - ".wb-artifact.is-missing{border-style:dashed;border-color:#f2b8b5;background:#fff6f5}", - ".wb-artifact.is-missing .wb-artifact-name{color:#b42318}", - ".wb-artifact-flag{color:#b42318}", - ".wb-artifact-flag.is-unknown{color:var(--wb-ink-3)}", - ".wb-missing-note{margin:0;padding:7px 8px;border:1px solid #f2b8b5;border-radius:7px;background:#fff6f5;color:#b42318;font-size:11px;line-height:1.5}", - ".wb-task-tag{display:inline-block;margin-right:4px;padding:0 4px;border-radius:4px;background:rgba(59,130,246,.12);color:#2563eb;font-size:9.5px;font-weight:600}", - ".wb-task.is-new{outline:2px solid var(--wb-blue);outline-offset:1px}", - ".wb-drawer{position:absolute;top:0;right:0;bottom:0;z-index:6;display:flex;flex-direction:column;gap:8px;width:min(280px,82%);padding:12px;overflow-y:auto;border-left:1px solid var(--wb-line);background:var(--wb-card);box-shadow:-8px 0 24px rgba(16,24,40,.08)}", - ".wb-drawer-head{display:flex;align-items:center;justify-content:space-between;gap:8px}", - ".wb-drawer-title{font-size:12px;font-weight:600;color:var(--wb-ink-2)}", - ".wb-icon-btn{border:0;background:transparent;color:var(--wb-ink-3);font:inherit;font-size:16px;line-height:1;padding:2px 4px;border-radius:4px;cursor:pointer}", - ".wb-icon-btn:hover{background:var(--wb-bg);color:var(--wb-ink)}", - ".wb-field{display:flex;flex-direction:column;gap:2px}", - ".wb-field-label{font-size:10px;color:var(--wb-ink-3);letter-spacing:.02em}", - ".wb-field-value{font-size:11.5px;color:var(--wb-ink);word-break:break-word}", - ".wb-drawer-body{margin:0;font-size:11.5px;line-height:1.55;color:var(--wb-ink-2);white-space:pre-wrap;word-break:break-word}", - ".wb-tab-title{display:inline-flex;align-items:center;gap:4px}", - ".wb-main-split{display:flex;flex-direction:row;height:100%;min-width:0}", - ".wb-main-native{flex:1 1 auto;min-width:560px;min-height:0;height:100%;display:flex;flex-direction:column}", - ".wb-main-resizer{flex:0 0 2px;position:relative;width:2px;cursor:col-resize;background:rgba(127,127,127,.18)}", - ".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-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() { - if (typeof document === "undefined" || !document || typeof document.createElement !== "function") return; - try { - var selector = "style[data-plugin-css=" + JSON.stringify(CSS_ID) + "]"; - if (typeof document.querySelector === "function" && document.querySelector(selector) !== null) return; - var tag = document.createElement("style"); - tag.dataset.plugin = "dsh-sansheng-liubu-workbench"; - tag.dataset.pluginCss = CSS_ID; - tag.textContent = CSS; - if (document.head && typeof document.head.appendChild === "function") document.head.appendChild(tag); - } catch (error) { - // 样式失败不阻断面板功能。 - } - } - - injectCss(); - - // --------------------------------------------------------------------- - // 纯 UI 小工具 - // --------------------------------------------------------------------- - - const BOUND_PROJECT_CACHE = new Map(); - - function readRailWidth() { - try { - var stored = Number(localStorage.getItem(RAIL_WIDTH_KEY)); - if (isFinite(stored) && stored > 0) return clamp(stored, RAIL_MIN, RAIL_MAX); - } catch (error) { - // localStorage 不可用时用默认值。 - } - return RAIL_DEFAULT; - } - - function saveRailWidth(width) { - try { - localStorage.setItem(RAIL_WIDTH_KEY, String(Math.round(clamp(width, RAIL_MIN, RAIL_MAX)))); - } catch (error) { - // 忽略。 - } - } - - function mainTakeoverEnabled() { - try { - return String(localStorage.getItem(MAIN_SWITCH_KEY) || "") !== "off"; - } catch (error) { - return true; - } - } - - function shortTime(value) { - if (!value) return ""; - var text = String(value); - return text.length >= 16 ? text.slice(0, 16).replace("T", " ") : text; - } - - function emptyTaskForm() { - return { title: "", objective: "", ownerRoleId: "lead" }; - } - - function seatsFor(data) { - var byId = {}; - var rows = data && Array.isArray(data.seats) ? data.seats : []; - for (var i = 0; i < rows.length; i++) { - if (rows[i] && rows[i].roleId) byId[rows[i].roleId] = rows[i]; - } - return ROLE_ORDER.map(function (roleId) { - if (byId[roleId]) return byId[roleId]; - var meta = ROLE_META[roleId]; - return { - roleId: roleId, - name: meta.name, - short: meta.name, - tier: meta.tier, - group: meta.group, - column: meta.column, - row: meta.row, - duty: meta.duty, - connected: false, - pending: true, - pendingLabel: "尚未接通", - activeTaskId: null, - binding: null, - config: null, - placeholder: true, - }; - }); - } - - function findResultForArtifact(results, artifact) { - if (!Array.isArray(results) || !artifact) return null; - if (artifact.sourceResultId) { - for (var i = 0; i < results.length; i++) { - if (results[i] && results[i].id === artifact.sourceResultId) return results[i]; - } - } - for (var j = 0; j < results.length; j++) { - var result = results[j]; - if (result && Array.isArray(result.artifactRefs) && result.artifactRefs.indexOf(artifact.id) >= 0) return result; - } - return null; - } - - // 成果存在性:missing 是宿主确认文件已不在;unknown 只表示没核验过, - // 绝不能当成“正常”,也不能用警告色吓人。 - function existenceLabel(existence) { - if (existence === "missing") return "文件已失效"; - if (existence === "unknown") return "位置未核验"; - 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; - revision = Math.floor(revision); - var text = "第 " + revision + " 版"; - if (revision > 1 && artifact && artifact.revisesArtifactId) { - text += " · 修订自上一版"; - } - return text; - } - - function taskKindLabel(task) { - 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; - var hasActiveTargets = activeTargets && typeof activeTargets.size === "number" && activeTargets.size > 0; - if (hasActiveTargets) return "active"; - if (!session.blank && !session.awaitingFirstTurn) return "active"; - if (session.running) return "active"; - return session.promptAttempted ? "engaging" : "blank"; - } - - function useBoundProject(ctx, sessionId) { - var state = React.useState(null); - var projectId = state[0]; - var setProjectId = state[1]; - - React.useEffect(function () { - if (!sessionId) { - setProjectId(null); - return undefined; - } - var cancelled = false; - findBoundProject(ctx, sessionId) - .then(function (found) { - if (!cancelled) setProjectId(found); - }) - .catch(function () { - if (!cancelled) setProjectId(null); - }); - return function () { - cancelled = true; - }; - }, [ctx, sessionId]); - - 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]; - var setWidth = state[1]; - var cleanupRef = React.useRef(null); - - React.useEffect(function () { - return function () { - if (cleanupRef.current) cleanupRef.current(); - }; - }, []); - - function onMouseDown(event) { - if (event && typeof event.preventDefault === "function") event.preventDefault(); - var session = { x: Number(event.clientX) || 0, width: width, last: width }; - function onMove(moveEvent) { - var next = clamp(session.width - ((Number(moveEvent.clientX) || 0) - session.x), RAIL_MIN, RAIL_MAX); - session.last = next; - setWidth(next); - } - function cleanup() { - if (typeof document !== "undefined" && document.removeEventListener) { - document.removeEventListener("mousemove", onMove); - document.removeEventListener("mouseup", onUp); - } - cleanupRef.current = null; - } - function onUp() { - cleanup(); - saveRailWidth(session.last); - } - if (typeof document !== "undefined" && document.addEventListener) { - document.addEventListener("mousemove", onMove); - document.addEventListener("mouseup", onUp); - cleanupRef.current = cleanup; - } - } - - function nudge(delta) { - var next = clamp(width + delta, RAIL_MIN, RAIL_MAX); - if (next === width) return; - setWidth(next); - saveRailWidth(next); - } - - return [width, onMouseDown, nudge]; - } - - // --------------------------------------------------------------------- - // 组件 - // --------------------------------------------------------------------- - - class PanelBoundary extends React.Component { - constructor(props) { - super(props); - this.state = { error: null }; - } - - static getDerivedStateFromError(error) { - return { error: error }; - } - - componentDidCatch(error) { - try { - console.error("[sansheng-workbench] 面板渲染失败", error); - } catch (ignored) { - // 忽略日志失败。 - } - } - - render() { - if (this.state.error) { - return h("div", { className: "wb-alert", role: "alert" }, [ - h("span", { className: "wb-alert-text" }, "工作台面板渲染失败:" + (this.state.error.message || String(this.state.error))), - ]); - } - return this.props.children; - } - } - - function SeatCard(props) { - var seat = props.seat; - var meta = ROLE_META[seat.roleId] || {}; - var binding = seat.binding || null; - var sessionId = binding && (binding.currentSessionId || binding.sessionId); - var status = seat.placeholder - ? "loading" - : (binding && binding.status) || (seat.connected ? "idle" : "uninitialized"); - var label = seat.placeholder ? "读取中…" : statusOf(status); - var name = seatDisplayName(seat); - var model = formatModelLine(seat.config); - var fullModel = modelTitle(seat.config); - var isLead = seat.roleId === "lead"; - var showConnect = !seat.placeholder && !seat.connected; - var classes = ["wb-card"]; - if (isLead) classes.push("is-lead"); - if (status === "running") classes.push("is-running"); - if (status === "needs_attention") classes.push("is-attention"); - if (status === "unavailable") classes.push("is-unavailable"); - if (showConnect) classes.push("has-connect"); - - function activate() { - if (props.onActivate) props.onActivate(seat); - } - - function onKeyDown(event) { - if (!event) return; - if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") { - if (typeof event.preventDefault === "function") event.preventDefault(); - activate(); - } - } - - var children = [ - h("span", { className: "wb-kicker", key: "kicker" }, meta.kicker || ""), - h("span", { className: "wb-name", key: "name" }, name), - h("span", { className: "wb-model", key: "model", title: fullModel }, model), - h("span", { className: "wb-status", key: "status" }, [ - h("span", { className: "wb-dot is-" + status, key: "dot" }), - h("span", { key: "label" }, label), - ]), - ]; - - if (showConnect) { - children.push(h("button", { - key: "connect", - type: "button", - className: "wb-connect", - disabled: Boolean(props.connecting), - onClick: function (event) { - if (event && typeof event.stopPropagation === "function") event.stopPropagation(); - if (props.onConnect) props.onConnect(seat); - }, - }, props.connecting ? "接通中…" : "接通")); - } - - return h("div", { - className: classes.join(" "), - ref: props.cardRef, - role: "button", - tabIndex: 0, - title: [seat.duty || meta.duty || "", fullModel].filter(Boolean).join(" · "), - "aria-label": (seat.name || name) + "," + label + (sessionId ? ",点击打开会话" : ""), - onClick: activate, - onKeyDown: onKeyDown, - }, children); - } - - function WorkbenchRail(props) { - var ctx = props.ctx; - var compact = props.compact !== false; - - var viewState = React.useState("court"); - var view = viewState[0]; - var setView = viewState[1]; - - var projectState = React.useState(props.projectId || null); - var projectId = projectState[0]; - var setProjectId = projectState[1]; - - var dataState = React.useState(null); - var data = dataState[0]; - var setData = dataState[1]; - - var errorState = React.useState(null); - var error = errorState[0]; - var setError = errorState[1]; - - var noticeState = React.useState(null); - 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]; - - var artifactState = React.useState(null); - var selectedArtifactId = artifactState[0]; - var setSelectedArtifactId = artifactState[1]; - - var formOpenState = React.useState(false); - var taskFormOpen = formOpenState[0]; - var setTaskFormOpen = formOpenState[1]; - - var formState = React.useState(emptyTaskForm()); - var taskForm = formState[0]; - var setTaskForm = formState[1]; - - var taskBusyState = React.useState(false); - 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]; - - var reviseTextState = React.useState(""); - var reviseText = reviseTextState[0]; - var setReviseText = reviseTextState[1]; - - // null | "draft" | "queued":标明正在提交哪个按钮,防止重复点。 - var reviseBusyState = React.useState(null); - var reviseBusy = reviseBusyState[0]; - var setReviseBusy = reviseBusyState[1]; - - var highlightTaskState = React.useState(null); - var highlightTaskId = highlightTaskState[0]; - var setHighlightTaskId = highlightTaskState[1]; - var highlightTimerRef = React.useRef(null); - - var reloadState = React.useState(0); - var reloadToken = reloadState[0]; - var setReloadToken = reloadState[1]; - - var projectIdRef = React.useRef(projectId); - var seqRef = React.useRef(0); - var hostRef = React.useRef(null); - var loadTokenRef = React.useRef(0); - var aliveRef = React.useRef(true); - var treeRef = React.useRef(null); - var leadRef = React.useRef(null); - var groupRef = React.useRef(null); - var sanRefs = React.useRef({}); - - // 首帧先给一份 400px 的几何连线,保证即使宿主/预览器不跑 effect 也能看见树; - // 真实浏览器随后用 getBoundingClientRect 校正到实际栏宽。 - var initialLayout = computeRailLayout(400); - var wireState = React.useState({ - width: initialLayout.width, - height: initialLayout.height, - paths: wirePathsFromLayout(initialLayout), - }); - var wires = wireState[0]; - var setWires = wireState[1]; - - projectIdRef.current = projectId; - - React.useEffect(function () { - aliveRef.current = true; - return function () { - aliveRef.current = false; - if (highlightTimerRef.current) { - clearTimeout(highlightTimerRef.current); - highlightTimerRef.current = null; - } - }; - }, []); - - function applyBootstrap(result, token) { - if (token !== undefined && token !== loadTokenRef.current) return; - if (!aliveRef.current) return; - projectIdRef.current = result.projectId; - seqRef.current = Number(result.value && result.value.eventSeq) || 0; - setProjectId(result.projectId); - setData(result.value); - } - - // 首屏 / 项目切换 / 手动重试:整树重取,绝不沿用上一个项目的 seats。 - React.useEffect(function () { - var cancelled = false; - var token = ++loadTokenRef.current; - setData(null); - setError(null); - setSelectedArtifactId(null); - setNotice(null); - hostRef.current = workspaceIdOf(ctx); - - var loading; - if (props.projectId) { - loading = apiGet("bootstrap", { projectId: props.projectId }).then(function (value) { - return { projectId: props.projectId, value: value }; - }); - } else { - loading = resolveWorkbenchProject(ctx); - } - - loading.then(function (result) { - if (cancelled) return; - applyBootstrap(result, token); - }).catch(function (failure) { - if (cancelled) return; - if (token !== loadTokenRef.current) return; - setError(describeError(failure)); - }); - - return function () { - cancelled = true; - }; - }, [ctx, props.projectId, reloadToken]); - - // 工作区切换:换项目就整树重取。 - React.useEffect(function () { - if (props.projectId) return undefined; - var workspace = ctx && ctx.uiWorkspace; - if (!workspace) return undefined; - var disposers = []; - var pendingToken = 0; - var cancelled = false; - - function check() { - var next = workspaceIdOf(ctx); - if (!next || next === hostRef.current) return; - hostRef.current = next; - var token = ++pendingToken; - var loadToken = ++loadTokenRef.current; - setData(null); - setSelectedArtifactId(null); - setNotice(null); - setError(null); - resolveWorkbenchProject(ctx).then(function (result) { - if (cancelled || token !== pendingToken) return; - applyBootstrap(result, loadToken); - }).catch(function (failure) { - if (cancelled || token !== pendingToken) return; - if (loadToken === loadTokenRef.current) setError(describeError(failure)); - }); - } - - var selection = workspace.selection; - if (selection && typeof selection.subscribe === "function") { - var off = selection.subscribe(check); - if (typeof off === "function") disposers.push(off); - } - if (typeof workspace.subscribe === "function") { - var offWorkspace = workspace.subscribe(check); - if (typeof offWorkspace === "function") disposers.push(offWorkspace); - } - if (typeof workspace.on === "function") { - var offEvent = workspace.on("change", check); - if (typeof offEvent === "function") disposers.push(offEvent); - } - - return function () { - cancelled = true; - for (var i = 0; i < disposers.length; i++) { - try { - disposers[i](); - } catch (ignored) { - // 忽略取消订阅失败。 - } - } - }; - }, [ctx, props.projectId]); - - // 长轮询:事件只作为“该刷新了”的信号,状态一律回读账本,绝不猜。 - React.useEffect(function () { - if (!projectId) return undefined; - var stopped = false; - var paused = false; - var inflight = false; - var timer = null; - var controller = null; - - function schedule(delay) { - if (stopped) return; - timer = setTimeout(run, delay); - } - - function refresh(mode) { - return apiGet("bootstrap", { projectId: projectId }).then(function (value) { - if (stopped || !aliveRef.current) return null; - if (projectIdRef.current !== projectId) return null; - var seq = Number(value && value.eventSeq); - if (isFinite(seq)) seqRef.current = Math.max(seqRef.current, seq); - setData(function (previous) { - if (!previous || previous.projectId !== value.projectId) return value; - if (mode === "seats") { - return assign({}, previous, { seats: value.seats, eventSeq: value.eventSeq }); - } - return assign({}, previous, { - seats: value.seats, - tasks: value.tasks, - artifacts: value.artifacts, - results: value.results, - project: value.project || previous.project, - projects: value.projects || previous.projects, - eventSeq: value.eventSeq, - }); - }); - return value; - }); - } - - function run() { - if (stopped || inflight) return; - timer = null; - if (paused) { - schedule(1500); - return; - } - inflight = true; - var localController = typeof AbortController === "function" ? new AbortController() : null; - controller = localController; - - apiGet("events", { projectId: projectId, since: seqRef.current }, { - signal: localController ? localController.signal : undefined, - }).then(function (result) { - if (stopped) return undefined; - var events = result && Array.isArray(result.events) ? result.events : []; - if (result && result.reset) { - seqRef.current = Number(result.seq) || 0; - return refresh("full").then(function () { - schedule(120); - }); - } - if (events.length > 0) { - var merged = mergeEvents([], events); - var maxSeq = Number(result.seq) || 0; - for (var i = 0; i < merged.length; i++) { - maxSeq = Math.max(maxSeq, Number(merged[i].seq) || 0); - } - seqRef.current = Math.max(seqRef.current, maxSeq); - var mode = isSeatOnlyEventBatch(merged) ? "seats" : "full"; - return refresh(mode).then(function () { - schedule(result.hasMore ? 0 : 120); - }); - } - var seq = Number(result && result.seq); - if (isFinite(seq)) seqRef.current = Math.max(seqRef.current, seq); - schedule(result && result.hasMore ? 0 : 250); - return undefined; - }).catch(function (failure) { - if (stopped) return; - if (failure && failure.name === "AbortError") return; - setNotice(describeError(failure)); - schedule(2500); - }).then(function () { - inflight = false; - controller = null; - }); - } - - function onVisibilityChange() { - if (typeof document !== "undefined" && document.hidden) { - paused = true; - if (timer) { - clearTimeout(timer); - timer = null; - } - if (controller) controller.abort(); - return; - } - paused = false; - if (!inflight) run(); - } - - if (typeof document !== "undefined" && document.addEventListener) { - document.addEventListener("visibilitychange", onVisibilityChange); - } - run(); - - return function () { - stopped = true; - if (timer) clearTimeout(timer); - if (controller) controller.abort(); - if (typeof document !== "undefined" && document.removeEventListener) { - document.removeEventListener("visibilitychange", onVisibilityChange); - } - }; - }, [projectId]); - - // 连线:每次渲染后按真实 rect 现算,窄栏/字体差异都不会错位。 - React.useEffect(function () { - if (view !== "court") return undefined; - var tree = treeRef.current; - if (!tree || typeof tree.getBoundingClientRect !== "function") return undefined; - - // 真实布局量不到时(离线预览替身 DOM、隐藏 tab 里 rect 全 0)的兜底: - // 用 computeRailLayout 的几何盒子算同一组贝塞尔,公式与真实测量完全一致。 - function fallbackWires(widthHint) { - var width = Number(widthHint) > 0 ? Number(widthHint) : 0; - if (!width) { - try { - width = tree.clientWidth || 0; - } catch (ignored) { - width = 0; - } - } - var layout = computeRailLayout(width || 400); - return { width: layout.width, height: layout.height, paths: wirePathsFromLayout(layout) }; - } - - function measure() { - var box = tree.getBoundingClientRect(); - if (!box || !box.width) { - setWires(fallbackWires(0)); - return; - } - - function rel(element) { - var rect = element.getBoundingClientRect(); - return { - top: rect.top - box.top, - bottom: rect.bottom - box.top, - left: rect.left - box.left, - cx: rect.left - box.left + rect.width / 2, - }; - } - - var paths = []; - var lead = leadRef.current; - if (lead) { - var leadRect = rel(lead); - var sanIds = ["zhongshu", "shangshu", "menxia"]; - for (var i = 0; i < sanIds.length; i++) { - var element = sanRefs.current[sanIds[i]]; - if (!element) continue; - var cardRect = rel(element); - var y0 = leadRect.bottom; - var y1 = cardRect.top; - if (!(y1 > y0)) continue; - paths.push({ - key: "lead-" + sanIds[i], - kind: "branch", - d: branchPathD(leadRect.cx, y0, cardRect.cx, y1), - }); - } - } - - var shangshu = sanRefs.current.shangshu; - var group = groupRef.current; - if (shangshu && group) { - var shangshuRect = rel(shangshu); - var groupRect = rel(group); - if (groupRect.top > shangshuRect.bottom) { - paths.push({ - key: "trunk", - kind: "trunk", - d: "M " + round(shangshuRect.cx) + " " + round(shangshuRect.bottom) + - " L " + round(shangshuRect.cx) + " " + round(groupRect.top), - }); - } - } - - if (paths.length === 0) { - // 关键 rect 全是 0(替身 DOM)时不能把 0 传给 。 - setWires(fallbackWires(box.width)); - return; - } - setWires({ width: Math.round(box.width), height: Math.round(box.height), paths: paths }); - } - - measure(); - var observer = null; - if (typeof ResizeObserver === "function") { - observer = new ResizeObserver(function () { - measure(); - }); - observer.observe(tree); - } - if (typeof window !== "undefined" && window.addEventListener) window.addEventListener("resize", measure); - - return function () { - if (observer) observer.disconnect(); - if (typeof window !== "undefined" && window.removeEventListener) window.removeEventListener("resize", measure); - }; - }, [view, data]); - - var seats = seatsFor(data); - var connectedCount = 0; - for (var seatIndex = 0; seatIndex < seats.length; seatIndex++) { - if (seats[seatIndex].connected) connectedCount += 1; - } - var metaText = "十席 · " + connectedCount + " 席已接通"; - - function activateSeat(seat) { - var binding = seat && seat.binding; - var sessionId = binding && (binding.currentSessionId || binding.sessionId); - if (!sessionId) return; - var failure = openSession(ctx, sessionId); - if (typeof failure === "string") setNotice("打开会话失败:" + failure); - } - - function connectSeat(seat) { - if (!projectId || connecting) return; - setConnecting(seat.roleId); - setNotice(null); - apiPost("connect", { projectId: projectId, roleId: seat.roleId }).then(function (result) { - var sessionId = result && ( - result.sessionId || - (result.seat && result.seat.binding && (result.seat.binding.currentSessionId || result.seat.binding.sessionId)) - ); - 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); - } - if (sessionId) { - var failure = openSession(ctx, sessionId); - if (typeof failure === "string") { - announce("已接通,但打开会话失败:" + failure, "error"); - } else { - announce("已接通。现在可以去任务页派工了。", "info"); - } - } else { - announce("已接通,但宿主没有返回会话号;请重试或检查宿主会话能力。", "error"); - } - }); - }).catch(function (failure) { - setNotice(describeError(failure)); - }).then(function () { - setConnecting(null); - }); - } - - function submitTask(event) { - if (event && typeof event.preventDefault === "function") event.preventDefault(); - if (!projectId) { - setNotice("还没有定位到工作台项目,无法新建任务。"); - return; - } - var title = String(taskForm.title || "").trim(); - var objective = String(taskForm.objective || "").trim(); - if (!title || !objective) { - setNotice("新建任务需要填写标题和目标。"); - return; - } - setTaskBusy(true); - setNotice(null); - apiPost("task", { - projectId: projectId, - title: title, - objective: objective, - ownerRoleId: taskForm.ownerRoleId || "lead", - sourceRoleId: "lead", - // 服务端 queued 要求该部门已接通会话;界面不替用户做这个决定,先存草稿。 - status: "draft", - }).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); - } - setTaskForm(emptyTaskForm()); - setTaskFormOpen(false); - announce("已存为草稿。去任务页点「派工」才会交给部门。", "info"); - }).catch(function (failure) { - setNotice(describeError(failure)); - }).then(function () { - setTaskBusy(false); - }); - } - - // 派工:把队列里的任务真正交给主责部门的会话。 - // 宿主的 /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) { - setNotice("还没有定位到工作台项目或成果,无法提交修订。"); - return; - } - var instruction = String(reviseText || "").trim(); - if (!instruction) { - setNotice("请先写清楚要主责部门改什么。"); - return; - } - if (reviseBusy) return; - var targetProjectId = projectId; - setReviseBusy(status); - setNotice(null); - apiPost("artifact/revision", { - projectId: targetProjectId, - artifactId: artifact.id, - instruction: instruction, - status: status, - }).then(function (value) { - var createdTaskId = value && value.task && value.task.id ? value.task.id : null; - return apiGet("bootstrap", { projectId: targetProjectId }).then(function (next) { - if (!aliveRef.current || projectIdRef.current !== targetProjectId) return; - seqRef.current = Math.max(seqRef.current, Number(next && next.eventSeq) || 0); - setData(next); - setReviseOpen(false); - setReviseText(""); - setSelectedArtifactId(null); - setView("tasks"); - if (createdTaskId) { - setHighlightTaskId(createdTaskId); - if (highlightTimerRef.current) clearTimeout(highlightTimerRef.current); - highlightTimerRef.current = setTimeout(function () { - highlightTimerRef.current = null; - if (aliveRef.current) setHighlightTaskId(null); - }, 2600); - } - }); - }).catch(function (failure) { - if (!aliveRef.current) return; - var message = describeError(failure); - // 服务端 INVALID_STATE 的原文就是「尚未接通会话」;这里补一句怎么解决。 - if (failure && (failure.code === "INVALID_STATE" || String(message).indexOf("尚未接通") >= 0)) { - message += " 请先在「朝堂」里接通主责部门,再点「直接派工」。"; - } - setNotice(message); - }).then(function () { - if (aliveRef.current) setReviseBusy(null); - }); - } - - function switchView(next) { - setView(next); - if (next !== "artifacts") { - setSelectedArtifactId(null); - setReviseOpen(false); - setReviseText(""); - setReviseBusy(null); - } - } - - function tabButton(key, label) { - var active = view === key; - return h("button", { - key: key, - type: "button", - role: "tab", - "aria-selected": active, - className: "wb-tab" + (active ? " is-active" : ""), - onClick: function () { - switchView(key); - }, - }, label); - } - - function renderCourt() { - var seatNodes = seats; - var byId = {}; - for (var i = 0; i < seatNodes.length; i++) byId[seatNodes[i].roleId] = seatNodes[i]; - - function cardRef(roleId) { - return function (element) { - if (roleId === "lead") leadRef.current = element; - if (roleId === "zhongshu" || roleId === "shangshu" || roleId === "menxia") { - sanRefs.current[roleId] = element; - } - }; - } - - function renderCard(roleId) { - var seat = byId[roleId]; - if (!seat) return null; - return h(SeatCard, { - key: roleId, - seat: seat, - cardRef: cardRef(roleId), - connecting: connecting === roleId, - onActivate: activateSeat, - onConnect: connectSeat, - }); - } - - var sanIds = ["zhongshu", "shangshu", "menxia"]; - var firstRow = ["libu", "hubu", "lipu"]; - var secondRow = ["bingbu", "xingbu", "gongbu"]; - - return h("div", { className: "wb-tree", ref: treeRef }, [ - h("svg", { - key: "wires", - className: "wb-wires", - width: wires.width || 0, - height: wires.height || 0, - "aria-hidden": "true", - }, wires.paths.map(function (wire) { - return h("path", { - key: wire.key, - className: wire.kind === "trunk" ? "wb-wire is-trunk" : "wb-wire", - d: wire.d, - }); - })), - h("div", { className: "wb-lead-row", key: "lead" }, [renderCard("lead")]), - h("div", { className: "wb-trio", key: "sansheng" }, sanIds.map(renderCard)), - h("div", { className: "wb-group", ref: groupRef, key: "ministries" }, [ - h("span", { className: "wb-group-label", key: "label" }, "六部 · 同级"), - h("div", { className: "wb-six", key: "six" }, firstRow.concat(secondRow).map(renderCard)), - ]), - ]); - } - - function renderTasks() { - var tasks = data && Array.isArray(data.tasks) ? data.tasks : []; - var ownerOptions = ROLE_ORDER.map(function (roleId) { - return h("option", { key: roleId, value: roleId }, ROLE_META[roleId].name); - }); - - return h("div", { className: "wb-list" }, [ - h("div", { className: "wb-list-head", key: "head" }, [ - h("span", { key: "count" }, "任务 · " + tasks.length), - h("button", { - key: "new", - type: "button", - className: "wb-small-btn", - onClick: function () { - setTaskFormOpen(!taskFormOpen); - }, - }, taskFormOpen ? "收起" : "新建"), - ]), - taskFormOpen ? h("form", { className: "wb-form", key: "form", onSubmit: submitTask }, [ - h("input", { - key: "title", - className: "wb-input", - placeholder: "标题", - value: taskForm.title, - onChange: function (event) { - setTaskForm(assign({}, taskForm, { title: event.target.value })); - }, - }), - h("textarea", { - key: "objective", - className: "wb-textarea", - placeholder: "目标(交给部门做什么)", - value: taskForm.objective, - onChange: function (event) { - setTaskForm(assign({}, taskForm, { objective: event.target.value })); - }, - }), - h("select", { - key: "owner", - className: "wb-select", - value: taskForm.ownerRoleId, - onChange: function (event) { - setTaskForm(assign({}, taskForm, { ownerRoleId: event.target.value })); - }, - }, ownerOptions), - h("div", { className: "wb-form-row", key: "actions" }, [ - h("button", { key: "submit", type: "submit", className: "wb-small-btn", disabled: taskBusy }, taskBusy ? "提交中…" : "存为草稿"), - ]), - ]) : null, - tasks.length === 0 ? h("p", { className: "wb-empty", key: "empty" }, "这个项目还没有任务。点「新建」先存一张草稿。") : null, - tasks.map(function (task) { - var owner = task.ownerRoleId && ROLE_META[task.ownerRoleId] ? ROLE_META[task.ownerRoleId].name : (task.ownerRoleId || "—"); - 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, - }, [ - h("div", { className: "wb-task-title", key: "title" }, kind - ? [h("span", { className: "wb-task-tag", key: "kind" }, kind), titleText] - : 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, - ]); - }), - ]); - } - - function renderArtifacts() { - var artifacts = data && Array.isArray(data.artifacts) ? data.artifacts : []; - return h("div", { className: "wb-list" }, [ - h("div", { className: "wb-list-head", key: "head" }, [ - h("span", { key: "count" }, "成果 · " + artifacts.length), - h("span", { key: "hint", style: { fontSize: "10px", color: "var(--wb-ink-3)" } }, "点一行看详情"), - ]), - artifacts.length === 0 ? h("p", { className: "wb-empty", key: "empty" }, "这个项目还没有登记成果。") : null, - artifacts.map(function (artifact) { - var owner = artifact.ownerRoleId && ROLE_META[artifact.ownerRoleId] ? ROLE_META[artifact.ownerRoleId].name : (artifact.ownerRoleId || "—"); - var verify = artifact.verification && artifact.verification.status ? artifact.verification.status : "unverified"; - var existence = artifact.existence; - var flag = existenceLabel(existence); - var missing = existence === "missing"; - var metaChildren = [owner + " · " + (artifact.mediaType || "未知类型") + " · " + verificationLabel(verify)]; - if (flag) { - metaChildren.push(h("span", { - className: "wb-artifact-flag" + (existence === "unknown" ? " is-unknown" : ""), - key: "existence", - }, " · " + flag)); - } - return h("button", { - key: artifact.id || artifact.fileRef, - type: "button", - className: "wb-artifact" + (missing ? " is-missing" : ""), - title: (artifact.displayName || artifact.fileRef || artifact.id) + - (artifact.fileRef && artifact.fileRef !== artifact.displayName ? " · " + artifact.fileRef : "") + - (flag ? " · " + flag : ""), - onClick: function () { - setSelectedArtifactId(artifact.id); - setReviseOpen(false); - setReviseText(""); - setReviseBusy(null); - setNotice(null); - }, - }, [ - h("span", { className: "wb-artifact-name", key: "name" }, artifact.displayName || artifact.fileRef || artifact.id), - h("span", { className: "wb-artifact-meta", key: "meta" }, metaChildren), - ]); - }), - ]); - } - - function renderDrawer() { - if (!selectedArtifactId) return null; - var artifacts = data && Array.isArray(data.artifacts) ? data.artifacts : []; - var artifact = null; - for (var i = 0; i < artifacts.length; i++) { - if (artifacts[i] && artifacts[i].id === selectedArtifactId) { - artifact = artifacts[i]; - break; - } - } - if (!artifact) return null; - var related = findResultForArtifact(data && data.results, artifact); - var owner = artifact.ownerRoleId && ROLE_META[artifact.ownerRoleId] ? ROLE_META[artifact.ownerRoleId].name : (artifact.ownerRoleId || "—"); - var verify = artifact.verification && artifact.verification.status ? artifact.verification.status : "unverified"; - - var reviseForm = reviseOpen ? h("form", { - className: "wb-form", - key: "revise-form", - onSubmit: function (event) { - if (event && typeof event.preventDefault === "function") event.preventDefault(); - submitRevision(artifact, "draft"); - }, - }, [ - h("textarea", { - key: "text", - className: "wb-textarea", - placeholder: "要改什么?写清楚交给主责部门。", - value: reviseText, - onChange: function (event) { - setReviseText(event.target.value); - }, - }), - h("div", { className: "wb-form-row", key: "actions" }, [ - h("button", { - key: "draft", - type: "submit", - className: "wb-small-btn", - disabled: Boolean(reviseBusy), - }, reviseBusy === "draft" ? "保存中…" : "存为草稿"), - h("button", { - key: "queue", - type: "button", - className: "wb-small-btn", - disabled: Boolean(reviseBusy), - onClick: function () { - submitRevision(artifact, "queued"); - }, - }, reviseBusy === "queued" ? "派工中…" : "直接派工"), - ]), - ]) : null; - - return h("aside", { className: "wb-drawer", role: "dialog", "aria-label": "成果详情" }, [ - h("div", { className: "wb-drawer-head", key: "head" }, [ - h("span", { className: "wb-drawer-title", key: "title" }, "成果"), - h("button", { - key: "close", - type: "button", - className: "wb-icon-btn", - "aria-label": "关闭", - onClick: function () { - setSelectedArtifactId(null); - setReviseOpen(false); - setReviseText(""); - setReviseBusy(null); - }, - }, "×"), - ]), - h("div", { className: "wb-field", key: "revision" }, [ - h("span", { className: "wb-field-label", key: "label" }, "版本"), - h("span", { className: "wb-field-value", key: "value" }, revisionLabel(artifact)), - ]), - artifact.existence === "missing" ? h("p", { className: "wb-missing-note", key: "missing" }, - "这份文件在磁盘上找不到了,记录还在,可以重新登记或找主责部门补一份。") : null, - h("div", { className: "wb-field", key: "name" }, [ - h("span", { className: "wb-field-label", key: "label" }, "名称"), - h("span", { className: "wb-field-value", key: "value" }, artifact.displayName || "(未命名)"), - ]), - h("div", { className: "wb-field", key: "owner" }, [ - h("span", { className: "wb-field-label", key: "label" }, "部门 / 任务"), - h("span", { className: "wb-field-value", key: "value" }, owner + " · " + (artifact.taskId || "未关联任务")), - ]), - h("div", { className: "wb-field", key: "file" }, [ - h("span", { className: "wb-field-label", key: "label" }, "文件引用"), - h("span", { className: "wb-field-value", key: "value" }, artifact.fileRef || "—"), - ]), - h("div", { className: "wb-field", key: "verify" }, [ - h("span", { className: "wb-field-label", key: "label" }, "校验状态"), - h("span", { className: "wb-field-value", key: "value" }, verify), - ]), - h("div", { className: "wb-field", key: "summary" }, [ - h("span", { className: "wb-field-label", key: "label" }, "摘要"), - h("p", { className: "wb-drawer-body", key: "value" }, related && related.summary - ? related.summary - : "账本里这条成果没有关联的结案摘要。"), - ]), - h("div", { className: "wb-field", key: "revise" }, [ - h("button", { - key: "toggle", - type: "button", - className: "wb-small-btn", - onClick: function () { - setReviseOpen(!reviseOpen); - if (reviseOpen) setReviseText(""); - setNotice(null); - }, - }, reviseOpen ? "收起修改请求" : "找主责部门修改"), - reviseForm, - ]), - ]); - } - - var alert = null; - if (error) { - alert = h("div", { className: "wb-alert", role: "alert", key: "error" }, [ - h("span", { className: "wb-alert-text", key: "text" }, error), - h("button", { - key: "retry", - type: "button", - onClick: function () { - setReloadToken(reloadToken + 1); - }, - }, "重试"), - ]); - } else if (notice) { - alert = h("div", { className: "wb-alert is-" + noticeTone, role: "alert", key: "notice" }, [ - h("span", { className: "wb-alert-text", key: "text" }, notice), - ]); - } - - var content; - if (view === "tasks") content = renderTasks(); - else if (view === "artifacts") content = renderArtifacts(); - else content = renderCourt(); - - return h("div", { className: "wb-rail" + (compact ? " is-compact" : "") }, [ - h("div", { className: "wb-head", key: "head" }, [ - h("span", { className: "wb-title", key: "title" }, "三省六部"), - h("span", { className: "wb-meta", key: "meta" }, metaText), - ]), - h("div", { className: "wb-tabs", role: "tablist", key: "tabs" }, [ - tabButton("court", "朝堂"), - tabButton("tasks", "任务"), - tabButton("artifacts", "成果"), - ]), - alert, - h("div", { className: "wb-scroll", key: "scroll" }, [content]), - renderDrawer(), - ]); - } - - function WorkbenchPanel(props) { - return h(PanelBoundary, null, h(WorkbenchRail, { ctx: props.ctx, compact: true })); - } - - /** - * main.conversation 的接管组件。 - * 逃生开关:localStorage["sansheng.workbench.main"] === "off" 时不注册这个槽, - * 只保留右侧栏「朝堂」页签版,普通聊天完全不受影响。 - */ - function createConversationMain(ctx) { - return function SanshengConversationMain(props) { - var input = props || {}; - var sessionId = input.sessionId; - var useSession = input.useSession; - var useSessions = input.useSessions; - var useConversation = input.useConversation; - var renderSlot = input.renderSlot; - var renderFactorySlot = input.renderFactorySlot; - - // 宿主自己的 header + content:组件体内任何一步炸掉都回退到这里,中央聊天不白屏。 - function renderNative(phaseValue, heroValue) { - return h("div", { className: "wb-main-native", "data-phase": phaseValue }, [ - typeof renderSlot === "function" ? renderSlot("conversation.header", {}) : null, - typeof renderFactorySlot === "function" - ? renderFactorySlot( - "conversation.content", - { variant: "main", phase: phaseValue, hero: heroValue }, - { slots: { widthControls: input.widthControls || {} } }, - ) - : null, - ]); - } - - try { - var session = typeof useSession === "function" ? useSession(function (value) { return value; }) : undefined; - var conversation = typeof useConversation === "function" ? useConversation(function (value) { return value; }) : undefined; - var summaryBlank = typeof useSessions === "function" - ? useSessions(function (state) { - if (sessionId === undefined || !state) return undefined; - var summary = state.byId && state.byId[sessionId]; - return summary ? summary.blank : undefined; - }) - : undefined; - - var shellPhase = session === undefined || conversation === undefined - ? "blank" - : conversationPhase(session, conversation); - var openState = session && session.openState; - var subagent = session && session.subagent; - var address = subagent && subagent.address; - var parentAvailabilityPending = Boolean(address) && - address.mode === "continuable" && - subagent.parentAvailable === undefined; - var settling = sessionId !== undefined && ( - (shellPhase === "blank" && openState === "loading" && summaryBlank !== true) || - parentAvailabilityPending - ); - var hero = sessionId === undefined || - (shellPhase === "blank" && (openState === "open" || summaryBlank === true)); - var phase = settling ? "settling" : hero ? "hero" : "active"; - - var railProjectId = useBoundProject(ctx, sessionId); - var widthState = useRailWidth(); - var railWidth = widthState[0]; - var onResizeStart = widthState[1]; - var nudgeRail = widthState[2]; - - var native = renderNative(phase, hero); - - // 不是本工作台已绑定的部门会话:只渲染原生会话,与宿主原行为一致,不加任何东西。 - if (!sessionId || !railProjectId) return native; - - return h("div", { className: "wb-main-split" }, [ - native, - h("div", { - className: "wb-main-resizer", - key: "resizer", - role: "separator", - "aria-orientation": "vertical", - "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", - key: "rail", - style: { width: railWidth + "px" }, - }, h(PanelBoundary, null, - h(WorkbenchRail, { ctx: ctx, projectId: railProjectId, compact: false }))), - ]); - } catch (error) { - // 保险:接管逻辑出错时退回宿主原生会话,绝不把中央聊天拖成白屏。 - try { - console.warn("[sansheng-workbench] 接管失败,回退原生会话:", error); - } catch (ignored) { - // 连日志都失败时也要继续回退。 - } - return renderNative(sessionId === undefined ? "hero" : "active", sessionId === undefined); - } - }; - } - - // --------------------------------------------------------------------- - // 注册 - // --------------------------------------------------------------------- - - function apply(ctx) { - if (!ctx) throw new Error("三省六部工作台需要宿主上下文"); - - // 1) 右侧栏页签「朝堂」:优先 better-sidebar 的 registerTab。 - var better = betterSidebarOf(ctx); - if (better) { - effectOf(ctx, function () { - return better.registerTab({ - id: TAB_ID, - title: "朝堂", - description: "三省六部 · 十席部门树", - order: 5, - single: true, - component: function (props) { - return h(WorkbenchPanel, { ctx: ctx, scope: props && props.scope }); - }, - }); - }, "三省六部工作台:better-sidebar 页签"); - } else { - var tabs = sidebarRightTabsOf(ctx); - if (tabs) { - effectOf(ctx, function () { - return tabs.register({ - id: TAB_ID, - kind: TAB_KIND, - priority: "builtin", - title: function () { - return "朝堂"; - }, - }); - }, "三省六部工作台:右侧栏页签"); - } else { - console.warn("[sansheng-workbench] 宿主没有 betterSidebar / sidebarRightTabs,页签可能无法停靠;pane 槽仍会注册。"); - } - } - - // 2) 页签内容 + 标题:即使上面没有服务也注册,宿主若按槽渲染仍可用。 - if (ctx.slots && typeof ctx.slots.inject === "function") { - ctx.slots.inject("sidebar.right.pane.tab", function () { - return ctx.slots.register({ name: "sidebar.right.pane.tab", key: TAB_ID }, function (props) { - return h(WorkbenchPanel, { ctx: ctx, props: props }); - }); - }); - ctx.slots.inject("sidebar.right.pane.tab.title", function () { - return ctx.slots.register({ name: "sidebar.right.pane.tab.title", key: TAB_ID }, function () { - return h("span", { className: "wb-tab-title" }, "朝堂"); - }); - }); - } - - // 3) 中央主区接管:priority -1 抢在宿主默认 0 之前;原生会话内容原样透传。 - // 逃生开关:localStorage["sansheng.workbench.main"] = "off" 时跳过本段。 - if (mainTakeoverEnabled() && ctx.slots && typeof ctx.slots.inject === "function") { - ctx.slots.inject("main.conversation", function () { - return ctx.slots.register({ - name: "main.conversation", - priority: -1, - children: { - "conversation.header": { kind: "single", scope: "session-maybe" }, - }, - }, createConversationMain(ctx)); - }); - } - } - - exports.inject = ["slots", "sessions", "uiWorkspace", "uiConversation"]; - exports.apply = apply; - exports.WorkbenchRail = WorkbenchRail; - exports.WorkbenchPanel = WorkbenchPanel; - exports.__test = { - computeRailLayout: computeRailLayout, - railResizeTarget: railResizeTarget, - statusOf: statusOf, - mergeEvents: mergeEvents, - apiPath: apiPath, - pickProjectId: pickProjectId, - formatModelLine: formatModelLine, - seatDisplayName: seatDisplayName, - modelTitle: modelTitle, - existenceLabel: existenceLabel, - verificationLabel: verificationLabel, - revisionLabel: revisionLabel, - taskKindLabel: taskKindLabel, - taskActionKeys: taskActionKeys, - wirePathsFromLayout: wirePathsFromLayout, - ROLE_META: ROLE_META, - }; - - return module.exports; - }, -}); diff --git a/workbench/panel/package.json b/workbench/panel/package.json deleted file mode 100644 index 64893a0..0000000 --- a/workbench/panel/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "dsh-sansheng-liubu-workbench", - "version": "0.1.0", - "private": true, - "description": "三省六部工作台:右侧朝堂部门树、任务与成果", - "type": "module", - "exports": { - "./client": "./lib/client.js" - }, - "files": [ - "lib/**" - ], - "dsh": { - "client": { - "platform": "web", - "inject": [ - "@deepseek-ai/dsh-api-session-controller", - "@deepseek-ai/dsh-client-ui-workspace", - "@deepseek-ai/dsh-client-ui-primitives" - ] - } - }, - "peerDependencies": { - "@deepseek-ai/cordis": "~4.0.5" - } -} diff --git a/workbench/panel/test/client.test.mjs b/workbench/panel/test/client.test.mjs deleted file mode 100644 index a71679a..0000000 --- a/workbench/panel/test/client.test.mjs +++ /dev/null @@ -1,566 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import vm from "node:vm"; - -const CLIENT_PATH = fileURLToPath(new URL("../lib/client.js", import.meta.url)); -const SOURCE = readFileSync(CLIENT_PATH, "utf8"); - -function createStorage(initial) { - const map = new Map(Object.entries(initial || {})); - return { - getItem(key) { - return map.has(key) ? map.get(key) : null; - }, - setItem(key, value) { - map.set(key, String(value)); - }, - removeItem(key) { - map.delete(key); - }, - }; -} - -function createReact() { - function createElement(type, props) { - const children = Array.prototype.slice.call(arguments, 2); - return { type: type, props: props || {}, children: children }; - } - - class Component { - constructor(props) { - this.props = props; - this.state = {}; - } - } - - return { - createElement: createElement, - Component: Component, - useState: function (initial) { - return [initial, function () {}]; - }, - useRef: function (initial) { - return { current: initial }; - }, - useEffect: function () {}, - useCallback: function (fn) { - return fn; - }, - useMemo: function (fn) { - return fn(); - }, - useContext: function () { - return null; - }, - createContext: function (value) { - return { _value: value }; - }, - Fragment: "Fragment", - }; -} - -function createDocument() { - const appended = []; - return { - appended: appended, - hidden: false, - head: { - appendChild: function (node) { - appended.push(node); - }, - }, - body: {}, - querySelector: function () { - return null; - }, - createElement: function (tagName) { - return { - tagName: tagName, - dataset: {}, - textContent: "", - appendChild: function () {}, - setAttribute: function () {}, - }; - }, - addEventListener: function () {}, - removeEventListener: function () {}, - }; -} - -function loadPlugin(options) { - options = options || {}; - const storage = createStorage(options.storage); - const document = createDocument(); - const react = createReact(); - let definition = null; - - const window = { - __ModuleLoader__: { - load: function (loaded) { - definition = loaded; - }, - }, - }; - - const sandbox = { - window: window, - document: document, - console: console, - URL: URL, - Map: Map, - Set: Set, - WeakMap: WeakMap, - Promise: Promise, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - localStorage: storage, - Symbol: Symbol, - }; - - vm.runInNewContext(SOURCE, sandbox, { filename: CLIENT_PATH }); - assert.ok(definition, "bundle 应该调用 window.__ModuleLoader__.load"); - assert.equal(definition.id, "dsh-sansheng-liubu-workbench", "bundle id 必须是包名"); - - const exports = definition.factory(function (id) { - if (id === "react") return react; - throw new Error("unexpected require: " + id); - }); - - return { exports: exports, react: react, storage: storage, document: document, definition: definition }; -} - -function createCtx(options) { - options = options || {}; - const registrations = []; - const injections = []; - const tabs = []; - const effects = []; - - const ctx = { - slots: { - inject: function (name, factory) { - injections.push(name); - const value = factory(); - if (value !== undefined) registrations.push(value); - return function () {}; - }, - register: function (spec, component) { - const registration = { spec: spec, component: component }; - registrations.push(registration); - return registration; - }, - }, - effect: function (factory, label) { - effects.push(label); - const value = factory(); - return typeof value === "function" ? value : function () {}; - }, - get: function (name) { - return options.services ? options.services[name] : undefined; - }, - uiWorkspace: { - currentWorkspaceId: options.workspaceId || "ws-1", - openSession: function () {}, - }, - }; - - if (!options.noTabs) { - ctx.sidebarRightTabs = { - register: function (spec) { - tabs.push(spec); - return function () {}; - }, - }; - } - - return { ctx: ctx, registrations: registrations, injections: injections, tabs: tabs, effects: effects }; -} - -test("bundle 契约:id、inject 与纯函数导出", function () { - const plugin = loadPlugin(); - const api = plugin.exports; - - assert.deepEqual(Array.from(api.inject), ["slots", "sessions", "uiWorkspace", "uiConversation"]); - assert.equal(typeof api.apply, "function"); - assert.equal(typeof api.WorkbenchRail, "function"); - assert.equal(typeof api.__test, "object"); - - const expected = ["computeRailLayout", "statusOf", "mergeEvents", "apiPath", "pickProjectId", "formatModelLine", "ROLE_META"]; - for (const key of expected) assert.ok(key in api.__test, "__test 缺少 " + key); - assert.equal(Object.keys(api.__test.ROLE_META).length, 10); - assert.deepEqual(Object.keys(api.__test.ROLE_META).slice(0, 4), ["lead", "zhongshu", "shangshu", "menxia"]); -}); - -test("computeRailLayout:丞相跨三列居中、三省一列、六部 3×2", function () { - const layout = loadPlugin().exports.__test.computeRailLayout(400); - - assert.equal(layout.width, 400); - assert.equal(layout.nodes.length, 10); - - const byId = {}; - for (const node of layout.nodes) { - assert.equal(typeof node.id, "string"); - assert.equal(typeof node.x, "number"); - assert.equal(typeof node.y, "number"); - assert.equal(typeof node.col, "number"); - assert.equal(typeof node.row, "number"); - byId[node.id] = node; - } - - const lead = byId.lead; - assert.equal(lead.col, 1); - assert.equal(lead.span, 3); - assert.ok(Math.abs(lead.x + lead.w / 2 - 200) < 0.001, "丞相应水平居中"); - assert.ok(Math.abs(lead.x - (400 - lead.w) / 2) < 0.001); - - const san = ["zhongshu", "shangshu", "menxia"].map((id) => byId[id]); - assert.deepEqual(Array.from(san, (node) => node.col), [0, 1, 2]); - assert.deepEqual(Array.from(san, (node) => node.row), [1, 1, 1]); - assert.equal(new Set(Array.from(san, (node) => node.y)).size, 1, "三省应在同一行"); - assert.ok(san[0].x < san[1].x && san[1].x < san[2].x, "三省 x 必须递增"); - - const six = layout.nodes.filter((node) => node.row >= 2); - assert.equal(six.length, 6); - assert.deepEqual(Array.from(six, (node) => node.id), ["libu", "hubu", "lipu", "bingbu", "xingbu", "gongbu"]); - assert.equal(six[5].id, "gongbu", "第 6 个是工部"); - assert.deepEqual(Array.from(six, (node) => node.col), [0, 1, 2, 0, 1, 2]); - assert.deepEqual(Array.from(six, (node) => node.row), [2, 2, 2, 3, 3, 3]); - - assert.ok(layout.groups.ministries.y > layout.groups.sansheng.y + layout.groups.sansheng.h); - assert.ok(layout.height > 0); -}); - -test("computeRailLayout:窄栏仍是三列且不出现负宽度", function () { - const layout = loadPlugin().exports.__test.computeRailLayout(340); - assert.equal(layout.nodes.length, 10); - assert.equal(new Set(Array.from(layout.nodes, (node) => node.col)).size, 3); - for (const node of layout.nodes) assert.ok(node.w > 0, node.id + " 宽度必须为正"); - assert.ok(layout.leadWidth <= 184); -}); - -test("statusOf:六种部门状态与未知值兜底", function () { - const { statusOf } = loadPlugin().exports.__test; - assert.equal(statusOf("uninitialized"), "未接通"); - assert.equal(statusOf("idle"), "空闲"); - assert.equal(statusOf("queued"), "排队"); - assert.equal(statusOf("running"), "正在运行"); - assert.equal(statusOf("unavailable"), "不可用"); - assert.equal(statusOf("needs_attention"), "需人处理"); - assert.equal(statusOf("something-new"), "未知"); - assert.equal(statusOf(null), "未接通"); - assert.equal(statusOf(""), "未接通"); -}); - -test("mergeEvents:按 eventId 去重、按 seq 升序、忽略乱序重复", function () { - const { mergeEvents } = loadPlugin().exports.__test; - const merged = mergeEvents( - [{ eventId: "a", seq: 3 }, { eventId: "b", seq: 1 }], - [{ eventId: "b", seq: 1 }, { eventId: "c", seq: 2 }, { eventId: "a", seq: 3 }], - ); - - assert.equal(merged.length, 3); - assert.deepEqual(Array.from(merged, (event) => event.eventId), ["b", "c", "a"]); - assert.deepEqual(Array.from(merged, (event) => event.seq), [1, 2, 3]); - - const again = mergeEvents(merged, []); - assert.deepEqual(Array.from(again, (event) => event.eventId), ["b", "c", "a"]); - assert.deepEqual(Array.from(mergeEvents([], [])), []); -}); - -test("formatModelLine:无配置跟随宿主,有配置拼 provider/model · effort", function () { - const { formatModelLine } = loadPlugin().exports.__test; - assert.equal(formatModelLine(null), "跟随宿主"); - assert.equal(formatModelLine(undefined), "跟随宿主"); - assert.equal(formatModelLine({}), "跟随宿主"); - assert.equal(formatModelLine({ provider: "", model: "" }), "跟随宿主"); - assert.equal(formatModelLine({ provider: "deepseek", model: "", reasoningEffort: "high" }), "跟随宿主"); - assert.equal(formatModelLine({ provider: "deepseek", model: "deepseek-v4", reasoningEffort: "high" }), "deepseek/deepseek-v4 · 高"); - assert.equal(formatModelLine({ provider: "deepseek", model: "deepseek-v4" }), "deepseek/deepseek-v4"); - assert.equal(formatModelLine({ provider: "deepseek", model: "deepseek-v4", reasoningEffort: "custom" }), "deepseek/deepseek-v4 · custom"); - // model 自带 provider 前缀时只留最后一段,完整路径放 title。 - assert.equal( - formatModelLine({ provider: "magpie", model: "workbuddy/deepseek-v4", reasoningEffort: "high" }), - "deepseek-v4 · 高", - ); -}); - -test("seatDisplayName:name 与 short 同时存在时必须用完整名", function () { - const { seatDisplayName, modelTitle } = loadPlugin().exports.__test; - - assert.equal(seatDisplayName({ roleId: "lead", name: "丞相", short: "丞" }), "丞相"); - assert.equal(seatDisplayName({ roleId: "zhongshu", name: "中书", short: "中" }), "中书"); - assert.equal(seatDisplayName({ roleId: "lead" }), "丞相", "缺 name 时回落到 ROLE_META 的完整名"); - assert.equal(seatDisplayName({ roleId: "lead", short: "丞" }), "丞相", "short 不能优先于 ROLE_META 的完整名"); - assert.equal(seatDisplayName({ name: "", roleId: "unknown" }), "unknown"); - - assert.equal(modelTitle(null), "跟随宿主(未单独配置模型)"); - assert.equal( - modelTitle({ provider: "magpie", model: "workbuddy/deepseek-v4", reasoningEffort: "high" }), - "magpie/workbuddy/deepseek-v4 · 高", - ); -}); - -test("wirePathsFromLayout:量不到 DOM 时仍能生成三支 + 主干连线", function () { - const { computeRailLayout, wirePathsFromLayout } = loadPlugin().exports.__test; - const layout = computeRailLayout(400); - const paths = wirePathsFromLayout(layout); - - assert.equal(paths.length, 4, "三省三支 + 尚书到六部一条主干"); - const branch = paths.filter((item) => item.kind === "branch"); - const trunk = paths.filter((item) => item.kind === "trunk"); - assert.equal(branch.length, 3); - assert.equal(trunk.length, 1); - assert.deepEqual(Array.from(branch).map((item) => item.key), ["lead-zhongshu", "lead-shangshu", "lead-menxia"]); - for (const item of branch) { - const id = item.key.replace(/^lead-/, ""); - const card = layout.sansheng.find((node) => node.id === id); - assert.ok(item.d.includes(" C "), "分支必须用三次贝塞尔收口,垂直进入卡片顶边"); - assert.ok(!item.d.includes(" Q "), "不要退回二次贝塞尔(会在卡片顶边上方擦成一条横线)"); - const tail = item.d.match(/ C [0-9.]+ [0-9.]+ [0-9.]+ [0-9.]+ ([0-9.]+) ([0-9.]+)$/); - assert.ok(tail, "分支末尾应是第二个控制点 + 终点"); - assert.ok(Math.abs(Number(tail[1]) - card.cx) < 0.06, "终点 x 应等于卡片顶边中点"); - assert.equal(Number(tail[2]), card.y, "终点 y 应落在卡片顶边"); - } - const shangshu = layout.sansheng.find((node) => node.id === "shangshu"); - assert.equal(trunk[0].d, "M 200 " + (shangshu.y + shangshu.h) + " L 200 " + layout.groups.ministries.y); -}); - -test("apiPath:拼出同源工作台路径并编码查询串", function () { - const { apiPath } = loadPlugin().exports.__test; - assert.equal(apiPath("bootstrap"), "/sansheng/workbench/bootstrap"); - assert.equal(apiPath("/connect"), "/sansheng/workbench/connect"); - assert.equal(apiPath("events", { projectId: "p-1", since: 7 }), "/sansheng/workbench/events?projectId=p-1&since=7"); - assert.equal(apiPath("events", { projectId: "p 1", since: undefined }), "/sansheng/workbench/events?projectId=p%201"); - assert.equal(apiPath("bootstrap", {}), "/sansheng/workbench/bootstrap"); -}); - -test("pickProjectId:优先当前工作区,其次 bootstrap 默认项目", function () { - const { pickProjectId } = loadPlugin().exports.__test; - const data = { - projectId: "p-default", - projects: [ - { id: "p-other", hostWorkspaceId: "ws-other" }, - { id: "p-mine", hostWorkspaceId: "ws-mine" }, - ], - }; - assert.equal(pickProjectId(data, "ws-mine"), "p-mine"); - assert.equal(pickProjectId(data, "ws-missing"), null); - assert.equal(pickProjectId(data), "p-default"); - assert.equal(pickProjectId({ projects: [{ id: "p-only" }] }), "p-only"); - assert.equal(pickProjectId({ projects: [] }), null); -}); - -test("apply:注册朝堂页签、pane 槽与 priority -1 的 main.conversation", function () { - const plugin = loadPlugin(); - const mock = createCtx(); - plugin.exports.apply(mock.ctx); - - assert.ok(mock.injections.includes("sidebar.right.pane.tab")); - assert.ok(mock.injections.includes("sidebar.right.pane.tab.title")); - assert.ok(mock.injections.includes("main.conversation")); - - assert.equal(mock.tabs.length, 1); - assert.equal(mock.tabs[0].id, "sansheng-liubu-workbench"); - assert.equal(mock.tabs[0].priority, "builtin"); - assert.equal(mock.tabs[0].title(), "朝堂"); - - const main = mock.registrations.find((entry) => entry.spec && entry.spec.name === "main.conversation"); - assert.ok(main, "必须注册 main.conversation"); - assert.equal(main.spec.priority, -1); - assert.deepEqual(Array.from(Object.keys(main.spec.children)), ["conversation.header"]); -}); - -test("apply:localStorage 逃生开关 sansheng.workbench.main=off 时不接管主区", function () { - const plugin = loadPlugin({ storage: { "sansheng.workbench.main": "off" } }); - const mock = createCtx(); - plugin.exports.apply(mock.ctx); - - assert.equal(mock.injections.includes("main.conversation"), false); - assert.ok(mock.injections.includes("sidebar.right.pane.tab")); -}); - -test("main.conversation:非绑定会话只透传原生 header/content,不加右栏", function () { - const plugin = loadPlugin(); - const mock = createCtx(); - plugin.exports.apply(mock.ctx); - - const main = mock.registrations.find((entry) => entry.spec && entry.spec.name === "main.conversation"); - const tree = main.component({ - sessionId: "session-1", - useSession: function () { - return { openState: "open", blank: true, running: false, promptAttempted: false }; - }, - useSessions: function (select) { - return select({ byId: { "session-1": { blank: true } } }); - }, - useConversation: function () { - return { activeTargets: new Set() }; - }, - renderSlot: function (name) { - return { type: "header-slot", name: name }; - }, - renderFactorySlot: function (name, params) { - return { type: "content-slot", name: name, params: params }; - }, - widthControls: { width: 900 }, - }); - - assert.equal(tree.props.className, "wb-main-native"); - const children = tree.children[0]; - assert.equal(children[0].type, "header-slot"); - assert.equal(children[1].type, "content-slot"); - assert.equal(children[1].params.phase, "hero"); - assert.deepEqual(children[1].params.hero, true); - assert.ok(!JSON.stringify(tree).includes("wb-main-rail"), "非工作台会话不能出现右栏"); -}); - -test("WorkbenchRail:无数据时也渲染完整骨架与三个内部页签", function () { - const plugin = loadPlugin(); - const mock = createCtx(); - const tree = plugin.exports.WorkbenchRail({ ctx: mock.ctx, compact: true }); - - assert.ok(tree.props.className.includes("wb-rail")); - assert.ok(tree.props.className.includes("is-compact")); - const serialized = JSON.stringify(tree); - assert.ok(serialized.includes("三省六部")); - assert.ok(serialized.includes("朝堂")); - assert.ok(serialized.includes("任务")); - assert.ok(serialized.includes("成果")); - assert.ok(serialized.includes("十席 · 0 席已接通")); - assert.ok(serialized.includes("六部 · 同级")); - assert.ok(serialized.includes("正在读取") === false); -}); - -test("main.conversation:接管逻辑抛错时回退原生会话,不白屏", function () { - const plugin = loadPlugin(); - const mock = createCtx(); - plugin.exports.apply(mock.ctx); - - const main = mock.registrations.find((entry) => entry.spec && entry.spec.name === "main.conversation"); - const warnings = []; - const originalWarn = console.warn; - console.warn = function () { - warnings.push(Array.from(arguments)); - }; - try { - const tree = main.component({ - sessionId: "session-1", - useSession: function () { - // 模拟接管逻辑在渲染途中抛异常(理论上不应发生,但必须兜住)。 - throw new Error("boom"); - }, - useSessions: function () { - return undefined; - }, - useConversation: function () { - return { activeTargets: new Set() }; - }, - renderSlot: function (name) { - return { type: "header-slot", name: name }; - }, - renderFactorySlot: function (name, params) { - return { type: "content-slot", name: name, params: params }; - }, - }); - - assert.equal(tree.props.className, "wb-main-native"); - assert.equal(tree.children[0][0].type, "header-slot"); - assert.equal(tree.children[0][1].type, "content-slot"); - assert.ok(!JSON.stringify(tree).includes("wb-main-split"), "回退时不能拼右栏"); - assert.ok(!JSON.stringify(tree).includes("wb-main-resizer"), "回退时不能拼分隔条"); - assert.ok( - warnings.some((args) => String(args[0]).includes("接管失败")), - "回退时要留下可诊断的 console.warn", - ); - } finally { - console.warn = originalWarn; - } -}); - -test("existenceLabel:missing / unknown / ok 三态,unknown 不能被当成正常", function () { - const plugin = loadPlugin(); - const { existenceLabel } = plugin.exports.__test; - - assert.equal(existenceLabel("missing"), "文件已失效"); - assert.equal(existenceLabel("unknown"), "位置未核验"); - assert.equal(existenceLabel("ok"), ""); - assert.equal(existenceLabel(undefined), ""); - assert.notEqual(existenceLabel("unknown"), ""); - assert.ok(!existenceLabel("unknown").includes("正常"), "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; - - assert.equal(revisionLabel({ revision: 1, revisesArtifactId: "art-0" }), "第 1 版"); - assert.ok(!revisionLabel({ revision: 1, revisesArtifactId: "art-0" }).includes("修订自")); - assert.equal(revisionLabel({ revision: 2, revisesArtifactId: "art-0" }), "第 2 版 · 修订自上一版"); - assert.equal(revisionLabel({ revision: 3, revisesArtifactId: null }), "第 3 版"); - assert.equal(revisionLabel({}), "第 1 版"); - assert.equal(revisionLabel(null), "第 1 版"); -}); - -test("taskKindLabel:只给 kind=revision 加「修订」标签", function () { - const plugin = loadPlugin(); - const { taskKindLabel } = plugin.exports.__test; - - assert.equal(taskKindLabel({ kind: "revision" }), "修订"); - assert.equal(taskKindLabel({ kind: "normal" }), ""); - 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(","), ''); -}); diff --git a/workbench/test/acceptance-extra.test.mjs b/workbench/test/acceptance-extra.test.mjs deleted file mode 100644 index ed1dd4e..0000000 --- a/workbench/test/acceptance-extra.test.mjs +++ /dev/null @@ -1,251 +0,0 @@ -// A09 / A17 / A19 的补强验收:附件级材料引用、宿主重启后的账本恢复、项目间材料隔离。 - -import test from 'node:test' -import assert from 'node:assert/strict' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -import { WorkbenchStore } from '../core/store.mjs' -import { createWorkbenchService } from '../host/service.mjs' -import { buildDispatchText, describeMaterialRef } from '../host/session-adapter.mjs' - -const clock = () => 1700000000000 - -function memoryStore() { - return new WorkbenchStore({ file: null, clock }) -} - -function seed(service, hostWorkspaceId) { - const project = service.registerProject({ hostWorkspaceId, displayNameCache: hostWorkspaceId }).project - const binding = service.bindDepartmentSession({ projectId: project.id, roleId: 'gongbu', sessionId: `ses_${hostWorkspaceId}` }) - return { project, generation: binding.binding.bindingGeneration } -} - -test('A09 交接材料:附件引用原样进 packet,成果引用带版本,文本里可读', () => { - const store = memoryStore() - const service = createWorkbenchService({ store, clock }) - const { project, generation } = seed(service, 'ws-a') - const task = service.createTask({ - projectId: project.id, - ownerRoleId: 'gongbu', - sourceRoleId: 'lead', - title: '按预算出方案', - objective: 'o', - status: 'queued', - }).task - const artifact = service.registerArtifact({ - projectId: project.id, - ownerRoleId: 'gongbu', - taskId: task.id, - displayName: '预算表', - fileRef: 'C:/work/预算.xlsx', - kind: 'spreadsheet', - }).artifact - - const dispatched = service.dispatchTask({ - projectId: project.id, - taskId: task.id, - idempotencyKey: 'k-material', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-a', - bindingGeneration: generation, - packet: { - materialRefs: [ - { artifactId: artifact.id }, - { attachmentId: 'att_abc', name: '预算.xlsx', mime: 'application/vnd.ms-excel', size: 2048 }, - '聊天里贴过的那段口径', - ], - }, - }) - - const refs = dispatched.contextPacket.materialRefs - assert.deepEqual(refs[0], { artifactId: artifact.id, revision: 1, title: '预算表' }) - assert.deepEqual(refs[1], { attachmentId: 'att_abc', name: '预算.xlsx', mime: 'application/vnd.ms-excel', size: 2048 }) - assert.equal(refs[2], '聊天里贴过的那段口径') - - // 派发文本必须把材料写成能读的一行,并保留可追溯 ID。 - const text = buildDispatchText({ task, packet: dispatched.contextPacket, contractGuide: 'G', roleName: '工部' }) - assert.ok(text.includes(`成果 预算表 ${artifact.id}(第 1 版)`)) - assert.match(text, /附件 att_abc(预算\.xlsx · application\/vnd\.ms-excel · 2048 字节)/) - assert.match(text, /聊天里贴过的那段口径/) - - // 纯函数本身也单独锁一下:非对象、空串、缺 ID 都不该糊过去。 - assert.equal(describeMaterialRef(null), 'null') - assert.equal(describeMaterialRef('a.xlsx'), 'a.xlsx') -}) - -test('A09/A19 交接材料不能越权:别的项目的成果引用直接拒绝,且不泄露归属', () => { - const store = memoryStore() - const service = createWorkbenchService({ store, clock }) - const a = seed(service, 'ws-a') - const b = seed(service, 'ws-b') - const taskA = service.createTask({ - projectId: a.project.id, - ownerRoleId: 'gongbu', - sourceRoleId: 'lead', - title: 'A 的任务', - objective: 'o', - status: 'queued', - }).task - const artifact = service.registerArtifact({ - projectId: a.project.id, - ownerRoleId: 'gongbu', - taskId: taskA.id, - title: 'A 的成果', - fileRef: 'C:/work/a.xlsx', - }).artifact - const task = service.createTask({ - projectId: b.project.id, - ownerRoleId: 'gongbu', - sourceRoleId: 'lead', - title: 'B 的任务', - objective: 'o', - status: 'queued', - }).task - - assert.throws( - () => - service.dispatchTask({ - projectId: b.project.id, - taskId: task.id, - idempotencyKey: 'k-cross', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-b', - bindingGeneration: b.generation, - packet: { materialRefs: [{ artifactId: artifact.id }] }, - }), - (error) => error.code === 'CROSS_PROJECT' && !JSON.stringify(error.details ?? {}).includes(a.project.id), - ) - - // 正常派发:B 的上下文包里只有自己的东西,绝不自动继承 A 的材料。 - const dispatched = service.dispatchTask({ - projectId: b.project.id, - taskId: task.id, - idempotencyKey: 'k-own', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-b', - bindingGeneration: b.generation, - }) - assert.deepEqual(dispatched.contextPacket.materialRefs, []) - - // 缺 ID 的引用、空字符串都要明确报错,而不是“尽力猜”。 - assert.throws( - () => - service.dispatchTask({ - projectId: b.project.id, - taskId: task.id, - idempotencyKey: 'k-bad', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-b', - bindingGeneration: b.generation, - packet: { materialRefs: [{ name: '没有 ID 的东西' }] }, - }), - (error) => error.code === 'INVALID_INPUT', - ) -}) - -test('A17 宿主重启:账本重开后项目/绑定/配置/任务/派发都还在,换绑代号不回退', () => { - const dir = mkdtempSync(join(tmpdir(), 'wb-restart-')) - const file = join(dir, 'workbench.json') - try { - const first = new WorkbenchStore({ file, clock }) - first.load() - const service = createWorkbenchService({ store: first, clock }) - const { project, generation } = seed(service, 'ws-restart') - service.saveDepartmentConfig({ projectId: project.id, roleId: 'gongbu', provider: 'magpie', model: 'workbuddy/deepseek-v4.1-flash', expectedRevision: 0 }) - const task = service.createTask({ - projectId: project.id, - ownerRoleId: 'gongbu', - sourceRoleId: 'lead', - title: '重启前建的任务', - objective: 'o', - status: 'queued', - }).task - const dispatched = service.dispatchTask({ - projectId: project.id, - taskId: task.id, - idempotencyKey: 'k-restart', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-restart', - bindingGeneration: generation, - }) - assert.equal(dispatched.dispatch.idempotencyKey, 'k-restart') - - // —— 模拟宿主重启:新建 store 从同一文件重开 —— - const second = new WorkbenchStore({ file, clock }) - second.load() - const revived = createWorkbenchService({ store: second, clock }) - - const projects = revived.listProjects() - assert.equal(projects.length, 1) - assert.equal(projects[0].hostWorkspaceId, 'ws-restart') - - const seats = revived.listSeats(project.id) - const gongbu = seats.find((seat) => seat.roleId === 'gongbu') - assert.equal(gongbu.connected, true) - assert.equal(gongbu.config.model, 'workbuddy/deepseek-v4.1-flash') - assert.equal(gongbu.config.configRevision, 1) - - const revivedTask = revived.getTask(project.id, task.id) - assert.equal(revivedTask.title, '重启前建的任务') - - // 幂等键跨重启仍有效:再点一次不会重复投递。 - const again = revived.dispatchTask({ - projectId: project.id, - taskId: task.id, - idempotencyKey: 'k-restart', - targetRoleId: 'gongbu', - targetSessionId: 'ses_ws-restart', - bindingGeneration: generation, - }) - assert.equal(again.duplicate, true) - assert.equal(again.dispatch.id, dispatched.dispatch.id) - } finally { - 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) -}) diff --git a/workbench/test/assembly.test.mjs b/workbench/test/assembly.test.mjs deleted file mode 100644 index 8069494..0000000 --- a/workbench/test/assembly.test.mjs +++ /dev/null @@ -1,275 +0,0 @@ -// 装配层测试:index.mjs 把 store / service / 会话层 / HTTP 路由拼在一起的那一层。 -// 这里专门验「宿主稍后才给 sessionController」这条真实时序——它决定用户要不要多重启一次。 - -import test from 'node:test' -import assert from 'node:assert/strict' -import { Readable } from 'node:stream' - -import { createWorkbenchHost } from '../host/index.mjs' -import { WorkbenchStore } from '../core/store.mjs' - -const clock = () => 1700000000000 -const WS = 'ws_demo' - -/** 最小 webServer 替身:记下注册的路由,卸载时清掉。 */ -function fakeWebServer() { - const routes = new Map() - return { - routes, - register(route) { - routes.set(route.path, route) - return () => routes.delete(route.path) - }, - } -} - -/** 最小 cordis 替身:inject 只把回调存起来,测试手动触发「依赖出现」。 */ -function fakeCtx({ webServer = null, controller = null } = {}) { - const pending = [] - return { - webServer, - sessionController: controller, - get: () => undefined, - inject(deps, callback) { - pending.push({ deps, callback }) - return { dispose() {} } - }, - fire(dep, scoped) { - const hit = pending.filter((row) => row.deps.includes(dep)) - for (const row of hit) row.callback(scoped) - return hit.length - }, - pending, - } -} - -function fakeRes() { - const res = { - statusCode: 0, - headers: {}, - body: '', - writableEnded: false, - headersSent: false, - setHeader(name, value) { - this.headers[String(name).toLowerCase()] = value - return this - }, - writeHead(status, headers) { - this.statusCode = status - for (const [name, value] of Object.entries(headers ?? {})) this.headers[String(name).toLowerCase()] = value - this.headersSent = true - return this - }, - end(chunk) { - if (chunk !== undefined) this.body += String(chunk) - this.writableEnded = true - return this - }, - get json() { - return this.body === '' ? null : JSON.parse(this.body) - }, - } - return res -} - -function fakeReq(method, url, body) { - const text = body === undefined ? '' : JSON.stringify(body) - const stream = Readable.from(body === undefined ? [] : [Buffer.from(text, 'utf8')]) - stream.method = method - stream.url = url - stream.headers = { 'content-type': 'application/json' } - return stream -} - -async function callRoute(webServer, suffix, method, body) { - const route = [...webServer.routes.values()].find((item) => String(item.path).endsWith(suffix)) - assert.notEqual(route, undefined, `未注册路由:${suffix}`) - const res = fakeRes() - await route.handler(fakeReq(method, route.path, body), res) - return res.json -} - -/** 所有测试都用内存账本,绝不碰 %DSH_HOME% 下的真账本。 */ -function memoryStore() { - return new WorkbenchStore({ file: null, clock }) -} - -function tinyController(seed = ['ses_gongbu']) { - const sessions = new Map() - const prompts = [] - for (const sessionId of seed) { - sessions.set(sessionId, { sessionId, workspaceId: WS, running: false, accepted: new Set() }) - } - return { - prompts, - sessions, - async create(request) { - const sessionId = request.sessionId ?? 'ses_auto' - sessions.set(sessionId, { sessionId, workspaceId: request.workspaceId ?? WS, running: false, accepted: new Set() }) - return { sessionId } - }, - async prompt(request) { - prompts.push(request) - const row = sessions.get(request.sessionId) - if (row === undefined || !row.accepted) throw Object.assign(new Error('no session'), { code: 'session/conflict' }) - row.accepted.add(request.requestId) - return { accepted: true } - }, - cancel() { - return { accepted: true } - }, - } -} - -test('装配层:宿主先有 webServer、后有 sessionController 时,派发从“只落账”升级为真投递', async () => { - const store = memoryStore() - const webServer = fakeWebServer() - const ctx = fakeCtx({ webServer }) - - const host = createWorkbenchHost(ctx, { store, startReconciler: false }) - assert.equal(host.store, store) - assert.equal(host.registered, true) - assert.equal(webServer.routes.size, 13) - assert.equal(host.hasSessions, false) - - const project = host.service.registerProject({ hostWorkspaceId: WS }).project - const bound = host.service.bindDepartmentSession({ projectId: project.id, roleId: 'gongbu', sessionId: 'ses_gongbu' }) - const generation = bound.binding.bindingGeneration - const task = host.service.createTask({ - projectId: project.id, - ownerRoleId: 'gongbu', - sourceRoleId: 'lead', - title: '接线后派发', - objective: 'o', - status: 'queued', - }).task - - // 还没有会话层:路由只落账,状态停在 prepared,不伪装成已发送。 - const before = await callRoute(webServer, '/dispatch', 'POST', { - projectId: project.id, - taskId: task.id, - idempotencyKey: 'k-ledger', - targetRoleId: 'gongbu', - targetSessionId: 'ses_gongbu', - bindingGeneration: generation, - }) - assert.equal(before.ok, true) - assert.equal(before.value.dispatch.status, 'prepared') - - // 宿主晚到:装配层自己把会话层补挂上,不需要重建工作台、也不需要多重启一次。 - const controller = tinyController() - assert.equal(ctx.fire('sessionController', { sessionController: controller }), 1) - assert.equal(host.hasSessions, true) - assert.notEqual(host.dispatchService, null) - assert.notEqual(host.reconciler, null) - - // 同一份账本、同一张任务,换新的幂等键再派一次:这次真的投递到会话。 - const after = await callRoute(webServer, '/dispatch', 'POST', { - projectId: project.id, - taskId: task.id, - idempotencyKey: 'k-live', - targetRoleId: 'gongbu', - targetSessionId: 'ses_gongbu', - bindingGeneration: generation, - }) - assert.equal(after.ok, true) - assert.equal(after.value.dispatch.state ?? after.value.dispatch.status, 'accepted') - assert.equal(controller.prompts.length, 1) - - host.dispose() - assert.equal(webServer.routes.size, 0) -}) - -test('装配层:重复挂载会话层是幂等的,不会把已挂上的换掉', () => { - const store = memoryStore() - const ctx = fakeCtx({ webServer: fakeWebServer() }) - const host = createWorkbenchHost(ctx, { store, startReconciler: false }) - assert.equal(host.hasSessions, false) - - assert.equal(host.attachSessions(tinyController()), true) - const first = host.sessions - assert.equal(host.attachSessions(tinyController()), true) - assert.equal(host.sessions, first) - host.dispose() -}) - -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') -}); diff --git a/workbench/test/host.test.mjs b/workbench/test/host.test.mjs deleted file mode 100644 index fb1c80c..0000000 --- a/workbench/test/host.test.mjs +++ /dev/null @@ -1,357 +0,0 @@ -// Host 层测试:契约解析、会话适配、派发幂等、对账与工作台外壳。 -// 全部用假 SessionController(与 P0 记录的签名同形)驱动,不连真宿主, -// 这样“首次派发 / 重复点击 / 超时未知 / 宿主重启后对账”都能确定性地复现。 - -import test from 'node:test' -import assert from 'node:assert/strict' - -import { WorkbenchStore } from '../core/store.mjs' -import { createWorkbenchService } from '../host/service.mjs' -import { - CONTRACT_ACTION_PREFIX, - parseContractLines, - validateContractCall, - describeContract, -} from '../host/contract.mjs' -import { buildDispatchText, classifyHostError, createSessionAdapter } from '../host/session-adapter.mjs' -import { createDispatchService } from '../host/dispatch-service.mjs' -import { createReconciler } from '../host/reconciler.mjs' -import { createWorkbenchHost } from '../host/workbench-host.mjs' - -const clock = () => 1700000000000 -const WS = 'ws_demo' - -/** 假宿主:行为可控,记录每次 create/prompt/cancel,便于断言“没重发”。 */ -function fakeController(behaviour = {}) { - const calls = { create: [], prompt: [], cancel: [], selectModel: [], inspect: [], list: 0 } - const sessions = new Map() - let next = 1 - const controller = { - calls, - sessions, - async create(request) { - calls.create.push(request) - const existing = [...sessions.values()].find((row) => row.workspaceId === request.workspaceId) - if (existing !== undefined && request.sessionId === undefined) return { sessionId: existing.sessionId } - const sessionId = request.sessionId ?? `ses_${next++}` - sessions.set(sessionId, { sessionId, workspaceId: request.workspaceId ?? 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' }) - if (behaviour.promptFails === 'timeout') throw Object.assign(new Error('timeout picking up request'), { code: 'ETIMEDOUT' }) - if (behaviour.promptFails === 'busy') throw Object.assign(new Error('agent busy'), { code: 'session/agent-busy' }) - if (row.accepted.has(request.requestId)) return { accepted: true } - row.accepted.add(request.requestId) - row.running = behaviour.staysRunning !== false - 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) - if (behaviour.selectModelFails === true) { - throw Object.assign(new Error('model unavailable'), { code: 'session/model-unavailable' }) - } - return { selected: { provider: request.provider, model: request.model } } - }, - async list() { - calls.list += 1 - return { - items: [...sessions.values()].map((row) => ({ sessionId: row.sessionId, running: row.running, agentAvailable: true, updatedAt: '', blank: false })), - } - }, - } - return controller -} - -function freshWorkbench(behaviour = {}) { - const store = new WorkbenchStore({ file: null, clock, env: { DSH_HOME: '/tmp/never-used' } }) - const service = createWorkbenchService({ store, clock }) - const controller = fakeController(behaviour) - const sessions = createSessionAdapter({ sessionController: controller }) - const dispatch = createDispatchService({ store, service, sessions }) - const reconciler = createReconciler({ store, service, sessions, clock }) - const project = service.registerProject({ hostWorkspaceId: WS, displayNameCache: '演示项目' }).project - // 接通丞相与工部两个会话(首版两席闭环)。 - for (const roleId of ['lead', 'gongbu']) { - const sessionId = roleId === 'lead' ? 'ses_lead' : 'ses_gongbu' - controller.sessions.set(sessionId, { sessionId, workspaceId: WS, running: false, accepted: new Set() }) - service.bindDepartmentSession({ projectId: project.id, roleId, sessionId, allowReplace: false }) - } - service.saveDepartmentConfig({ - projectId: project.id, - roleId: 'gongbu', - provider: 'magpie', - model: 'workbuddy/deepseek-v4.1-flash', - expectedRevision: 0, - }) - return { store, service, controller, sessions, dispatch, reconciler, projectId: project.id } -} - -// ---------- 契约 ---------- - -test('契约解析只认四动作,坏 JSON 与未知动作都不改状态', () => { - const text = [ - '普通正文,不含指令。', - `${CONTRACT_ACTION_PREFIX}{"action":"reportTaskResult","taskId":"task_1","attemptId":"att_1","summary":"完成"}`, - `${CONTRACT_ACTION_PREFIX}{"action":"finalizeEverything","taskId":"task_1"}`, - `${CONTRACT_ACTION_PREFIX}{不是 JSON}`, - '我已经完成了。', - ].join('\n') - const { calls, invalid } = parseContractLines(text) - assert.equal(calls.length, 1) - assert.equal(calls[0].action, 'reportTaskResult') - assert.equal(invalid.length, 2) - assert.match(invalid[0].reason, /未知动作/) - assert.match(invalid[1].reason, /JSON/) - // 纯文本“已完成”不产生任何调用:这是方案明令禁止的推断路径。 - assert.deepEqual(parseContractLines('任务已完成,请查收').calls, []) - assert.deepEqual(parseContractLines(null), { calls: [], invalid: [] }) -}) - -test('validateContractCall 拦住缺幂等键/缺摘要的调用', () => { - assert.deepEqual(validateContractCall({ action: 'dispatchTask', payload: { taskId: 'task_1', idempotencyKey: 'k' } }), []) - assert.deepEqual(validateContractCall({ action: 'reportTaskResult', payload: { taskId: 'task_1', attemptId: 'att_1', summary: 's' } }), []) - assert.match(validateContractCall({ action: 'dispatchTask', payload: { taskId: 'task_1' } })[0], /idempotencyKey/) - assert.match(validateContractCall({ action: 'reportTaskResult', payload: { taskId: 't' } }).join(';'), /attemptId/) - assert.match(validateContractCall({ action: 'requestTaskInput', payload: { taskId: 't', attemptId: 'a' } }).join(';'), /reason/) - assert.match(validateContractCall({ action: 'syncDecision', payload: { taskId: 't' } }).join(';'), /decision/) - assert.match(describeContract(), /reportTaskResult/) -}) - -// ---------- 会话适配 ---------- - -test('会话适配:缺 sessionId 时按 workspace 建会话且不重复建', async () => { - const controller = fakeController() - const sessions = createSessionAdapter({ sessionController: controller }) - const first = await sessions.ensureSession({ workspaceId: WS, agentPreset: 'sansheng-liubu' }) - const second = await sessions.ensureSession({ workspaceId: WS, agentPreset: 'sansheng-liubu' }) - assert.equal(first.created, true) - assert.equal(first.sessionId, second.sessionId, '同一 workspace 不能建出第二个会话') - assert.equal(controller.calls.create.length, 2) - await assert.rejects(() => sessions.ensureSession({}), /workspaceId/) -}) - -test('会话适配:prompt 必须带 requestId,错误分类可区分可重试与必失败', async () => { - const controller = fakeController() - const sessions = createSessionAdapter({ sessionController: controller }) - await assert.rejects(() => sessions.sendPrompt({ sessionId: 'ses_1', text: 'hi' }), /requestId/) - await assert.rejects(() => sessions.sendPrompt({ sessionId: 'ses_1', requestId: 'r1', text: ' ' }), /为空/) - assert.equal(classifyHostError(Object.assign(new Error('x'), { code: 'session/conflict' })), 'conflict') - assert.equal(classifyHostError(Object.assign(new Error('x'), { code: 'session/model-unavailable' })), 'model_unavailable') - assert.equal(classifyHostError(new Error('request timeout')), 'transient') - assert.equal(classifyHostError(new Error('随便什么')), 'unknown') -}) - -test('派发提示词只写事实,不给“已完成”下定义', () => { - const text = buildDispatchText({ - task: { id: 'task_1', title: '整理报表', objective: '合并三张表', acceptance: ['口径一致'], constraints: ['只读源文件'] }, - packet: { materialRefs: ['a.xlsx'] }, - contractGuide: '(结构化回传说明)', - roleName: '工部', - }) - assert.match(text, /任务单 task_1/) - assert.match(text, /口径一致/) - assert.match(text, /a\.xlsx/) - assert.match(text, /不要只在正文里说“已完成”/) -}) - -// ---------- 派发 ---------- - -test('首次派发:固定模型快照 → prompt 用 attemptId 作幂等键 → dispatch accepted', async () => { - const { store, service, controller, dispatch, projectId } = freshWorkbench() - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: '导出报表', objective: '按模板导出' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k1' }) - assert.equal(result.outcome, 'accepted') - assert.equal(result.duplicate, false) - const attempt = store.getAttempt(result.attempt.id) - assert.equal(attempt.state, 'running') - // 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') -}) - -test('重复点击同一幂等键:不重复投递、返回既有结论', async () => { - const { service, controller, dispatch, projectId } = freshWorkbench() - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const first = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'same' }) - const second = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'same' }) - assert.equal(second.duplicate, true) - assert.equal(second.dispatch.id, first.dispatch.id) - assert.equal(controller.calls.prompt.length, 1, '第二次点击不能再发一条消息') -}) - -test('投递超时:dispatch 记 unknown,不自动重发', async () => { - const { store, service, controller, dispatch, projectId } = freshWorkbench({ promptFails: 'timeout' }) - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k-timeout' }) - assert.equal(result.outcome, 'unknown') - assert.equal(store.getDispatch(result.dispatch.id).state, 'unknown') - assert.equal(store.getAttempt(result.attempt.id).state, 'unknown') - assert.equal(controller.calls.prompt.length, 1) - // 再点一次同一幂等键:仍是 unknown,不会再发第二遍 - const again = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k-timeout' }) - assert.equal(again.duplicate, true) - assert.equal(controller.calls.prompt.length, 1) - // 查证:会话确实存在 → 收口为 accepted - const verified = await dispatch.verifyUnknown(result.dispatch.id) - assert.equal(verified.outcome, 'accepted') - assert.equal(store.getAttempt(result.attempt.id).state, 'running') -}) - -test('部门未接通时派发被拒,任务留在账上而不是变成失败', async () => { - const { store, service, dispatch, projectId } = freshWorkbench() - // 户部没有接通会话:只能先存草稿,入队会被明确拒绝(派给没会话的部门只会在投递阶段撞 unknown)。 - const task = service.createTask({ projectId, ownerRoleId: 'hubu', sourceRoleId: 'lead', title: 't', objective: 'o', status: 'draft' }).task - await assert.rejects( - () => dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k' }), - (error) => error.code === 'INVALID_STATE', - ) - assert.equal(store.getTask(task.id).status, 'draft', '被拒的派发不改任务状态') -}) - -// ---------- 对账 ---------- - -test('对账:宿主还在跑只推进 running,不判完成', async () => { - const { store, service, dispatch, reconciler, projectId } = freshWorkbench({ staysRunning: true }) - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k' }) - const outcome = await reconciler.reconcileOnce() - assert.equal(outcome.checked >= 1, true) - assert.equal(store.getTask(task.id).status, 'running', '还在跑就不是完成') - assert.equal(store.getAttempt(result.attempt.id).state, 'running') -}) - -test('对账:运行结束但无报告 → needs_attention,而不是 completed', async () => { - const { store, service, controller, dispatch, reconciler, projectId } = freshWorkbench() - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k' }) - controller.sessions.get('ses_gongbu').running = false - await reconciler.reconcileOnce() - assert.equal(store.getAttempt(result.attempt.id).state, 'succeeded') - assert.equal(store.getTask(task.id).status, 'needs_attention') - assert.match(store.getTask(task.id).needsAttentionReason, /结构化报告/) -}) - -test('对账:取消请求后宿主停跑 → attempt cancelled、任务 cancelled', async () => { - const { store, service, controller, dispatch, reconciler, sessions, projectId } = freshWorkbench() - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k' }) - // 只发停止请求:cancel() 是同步 accepted,不等于已停,此时尝试仍停在 running。 - sessions.requestCancel('ses_gongbu') - controller.sessions.get('ses_gongbu').running = false - await reconciler.reconcileOnce() - assert.equal(store.getAttempt(result.attempt.id).state, 'cancelled') - assert.equal(store.getTask(task.id).status, 'cancelled') -}) - -test('对账:宿主重启后查不到会话时不猜,保持原状', async () => { - const { store, service, controller, dispatch, reconciler, projectId } = freshWorkbench() - const task = service.createTask({ projectId, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o' }).task - const result = await dispatch.dispatch({ projectId, taskId: task.id, idempotencyKey: 'k' }) - // 让 list 抛错:问不到 = null - controller.list = async () => { - throw new Error('host restarting') - } - const outcome = await reconciler.reconcileOnce() - assert.equal(outcome.changed.length, 0) - assert.equal(store.getAttempt(result.attempt.id).state, 'running') -}) - -// ---------- 工作台外壳 ---------- - -test('工作台外壳:浏览器侧/无会话能力时降级为只读账本', async () => { - const store = new WorkbenchStore({ file: null, clock }) - const host = createWorkbenchHost({}, { store }) - assert.equal(host.hasSessions, false) - const project = host.service.registerProject({ hostWorkspaceId: WS }).project - const bootstrap = host.bootstrap(project.id) - assert.equal(bootstrap.seats.length, 10) - assert.equal(bootstrap.seats.filter((seat) => seat.connected).length, 0) - assert.equal(bootstrap.seats[0].pendingLabel, '尚未接通') - const dispatched = await host.dispatchTask({ projectId: project.id, taskId: 'task_x', idempotencyKey: 'k' }) - assert.equal(dispatched.ok, false) - assert.equal(dispatched.code, 'NO_SESSION_CONTROLLER') -}) - -test('工作台外壳:接通部门写出绑定,且同一会话不能同时属于两个部门', async () => { - const store = new WorkbenchStore({ file: null, clock }) - const controller = fakeController() - const host = createWorkbenchHost({ sessionController: controller }, { store }) - const project = host.service.registerProject({ hostWorkspaceId: WS }).project - const gongbu = await host.connectDepartment({ projectId: project.id, roleId: 'gongbu' }) - assert.equal(gongbu.created, true) - assert.equal(gongbu.seat.connected, true) - // 把工部已在用的会话硬塞给户部:store 必须拒绝(会话独占) - await assert.rejects( - () => host.connectDepartment({ projectId: project.id, roleId: 'hubu', sessionId: gongbu.sessionId }), - (error) => error.code === 'SESSION_CONFLICT', - ) - const seats = host.bootstrap(project.id).seats - assert.equal(seats.find((seat) => seat.roleId === 'gongbu').connected, true) - assert.equal(seats.find((seat) => seat.roleId === 'hubu').connected, false) -}) - -test('工作台外壳:ingestAgentOutput 只应用可解析的契约行', () => { - const store = new WorkbenchStore({ file: null, clock }) - const host = createWorkbenchHost({}, { store }) - const project = host.service.registerProject({ hostWorkspaceId: WS }).project - // 无会话能力的外壳里工部未接通,只能建草稿;这里要验的是契约解析,不是入队资格。 - const task = host.service.createTask({ projectId: project.id, ownerRoleId: 'gongbu', sourceRoleId: 'lead', title: 't', objective: 'o', status: 'draft' }).task - // 草稿要先入队,才谈得上 waiting_input。 - store.updateTask({ ...store.getTask(task.id), status: 'queued' }) - const text = [ - '正文里说一句“已完成”,不算数。', - `${CONTRACT_ACTION_PREFIX}${JSON.stringify({ action: 'requestTaskInput', taskId: task.id, reason: '缺口径' })}`, - ].join('\n') - const out = host.ingestAgentOutput({ projectId: project.id, roleId: 'gongbu', text }) - assert.equal(out.applied.length, 1) - assert.equal(out.failed.length, 0) - assert.equal(store.getTask(task.id).status, 'waiting_input') -}) - -test('工作台外壳:sessionController 晚到后仍能补挂会话层(不必多重启一次)', async () => { - const store = new WorkbenchStore({ file: null, clock }) - // 模拟 apply 那一刻宿主还没装好 sessionController。 - const host = createWorkbenchHost({}, { store }) - const project = host.service.registerProject({ hostWorkspaceId: WS }).project - assert.equal(host.hasSessions, false) - const refused = await host.dispatchTask({ projectId: project.id, taskId: 'task_x', idempotencyKey: 'k1', sourceRoleId: 'lead', targetRoleId: 'gongbu', targetSessionId: 'ses_gongbu', bindingGeneration: 0 }) - assert.equal(refused.ok, false) - assert.equal(refused.code, 'NO_SESSION_CONTROLLER') - - // 宿主稍后把会话控制器交过来:同一实例直接挂上,不需要重建工作台。 - const controller = fakeController() - assert.equal(host.attachSessions(controller), true) - assert.equal(host.hasSessions, true) - assert.notEqual(host.sessions, null) - assert.notEqual(host.dispatchService, null) - assert.notEqual(host.reconciler, null) - - // 重复挂载必须幂等:不能把已有会话层换掉。 - const first = host.sessions - assert.equal(host.attachSessions(fakeController()), true) - assert.equal(host.sessions, first) - - // 挂上之后「接通部门」才真正建会话并登记到账本。 - const connected = await host.connectDepartment({ projectId: project.id, roleId: 'gongbu' }) - assert.equal(connected.sessionId, 'ses_gongbu'.replace('ses_gongbu', connected.sessionId)) - assert.equal(store.getBinding(project.id, 'gongbu').currentSessionId, connected.sessionId) -}) diff --git a/workbench/test/ids.test.mjs b/workbench/test/ids.test.mjs deleted file mode 100644 index 19d61b1..0000000 --- a/workbench/test/ids.test.mjs +++ /dev/null @@ -1,58 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { - createIdFactory, - ID_ENTITIES, - ID_PREFIXES, - cryptoRandom, - isIdOf, - newId, -} from '../core/ids.mjs' - -test('every entity prefix appears in the plan and generated ids round-trip', () => { - for (const entity of ID_ENTITIES) { - const id = newId(entity, { random: () => 0 }) - assert.match(id, new RegExp(`^${ID_PREFIXES[entity]}_[0-9a-z]{12}$`), `${entity} 前缀正确`) - assert.equal(isIdOf(entity, id), true) - } - // 前缀本身也能直接使用,方便调用方不想记实体名的场景。 - assert.match(newId('task', { random: () => 3 }), /^task_3{12}$/) -}) - -test('prefixes stay unique so ids cannot be confused across entities', () => { - const prefixes = Object.values(ID_PREFIXES) - assert.equal(new Set(prefixes).size, prefixes.length) - assert.deepEqual(prefixes.slice(0, 3), ['proj', 'bind', 'cfg']) -}) - -test('injected random source makes ids reproducible', () => { - const seq = (limit) => { - let index = 0 - return () => index++ % limit - } - assert.equal(newId('project', { random: seq(36), length: 6 }), 'proj_012345') - const a = createIdFactory({ random: () => 1, length: 4 }) - const b = createIdFactory({ random: () => 1, length: 4 }) - for (const entity of ID_ENTITIES) { - assert.equal(a[entity](), b[entity]()) - assert.match(a[entity](), new RegExp(`^${ID_PREFIXES[entity]}_`)) - } -}) - -test('character alphabet values are accepted and unknown prefixes rejected', () => { - assert.equal(newId('result', { random: (i) => ['a', 'b', 'c', 'd'][i], length: 4 }), 'res_abcd') - assert.throws(() => newId('nope', { random: () => 0 }), /未知 ID 前缀/) - assert.throws(() => newId('task', { random: () => 'Z', length: 4 }), /字母表外/) - assert.throws(() => newId('task', { random: () => 1.5, length: 4 }), /整数/) - assert.throws(() => newId('task', { random: () => 0, length: 2 }), /4..64/) - assert.equal(isIdOf('task', 'dsp_abc'), false) - assert.equal(isIdOf('task', 'task_'), false) - assert.equal(isIdOf('task', undefined), false) -}) - -test('default crypto source produces distinct ids', () => { - if (typeof globalThis.crypto?.getRandomValues !== 'function') return - assert.match(cryptoRandom(), /^[0-9a-z]$/) - const ids = new Set(Array.from({ length: 50 }, () => newId('task'))) - assert.ok(ids.size >= 45, '随机 ID 冲突率应很低') -}) diff --git a/workbench/test/panel-contract.test.mjs b/workbench/test/panel-contract.test.mjs deleted file mode 100644 index a405b22..0000000 --- a/workbench/test/panel-contract.test.mjs +++ /dev/null @@ -1,68 +0,0 @@ -// 前端与 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/roles.test.mjs b/workbench/test/roles.test.mjs deleted file mode 100644 index 6def71a..0000000 --- a/workbench/test/roles.test.mjs +++ /dev/null @@ -1,123 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { - LAYOUT_ORDER, - LEADERS, - MINISTRIES, - ROLE_IDS, - ROLE_NAMES, - ROLE_NAME_ALIASES, - ROLES, - canDispatch, - getRole, - initialSeats, - isRoleId, - layoutGroups, - requireRole, -} from '../core/roles.mjs' - -test('ten seats keep the plan roleIds in the plan order', () => { - assert.deepEqual([...ROLE_IDS], ['lead', 'zhongshu', 'shangshu', 'menxia', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) - assert.deepEqual(ROLES.map((seat) => seat.id), [...ROLE_IDS], '导出数组即布局顺序') - assert.equal(ROLES.length, 10) - // 吏部与礼部不可混用:名称、ID、位置都不同。 - assert.equal(ROLE_NAMES.libu, '吏部') - assert.equal(ROLE_NAMES.lipu, '礼部') -}) - -test('seat names and duties match the plan table', () => { - const expected = { - lead: '丞相', - zhongshu: '中书', - shangshu: '尚书', - menxia: '门下', - libu: '吏部', - hubu: '户部', - lipu: '礼部', - bingbu: '兵部', - xingbu: '刑部', - gongbu: '工部', - } - for (const [id, name] of Object.entries(expected)) { - assert.equal(ROLE_NAMES[id], name) - assert.ok(getRole(id).duty.length > 0, `${id} 有职责描述`) - assert.ok(getRole(id).responsibility.length > 10, `${id} 有较完整职责说明`) - } - assert.equal(getRole('lead').duty, '接需求、分流、协调、汇报') - assert.equal(getRole('gongbu').duty, '代码实现与工程产出') -}) - -test('tiers split the chancellery from the six ministries', () => { - assert.deepEqual([...LEADERS], ['lead', 'zhongshu', 'shangshu', 'menxia']) - assert.deepEqual([...MINISTRIES], ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) - assert.equal(getRole('lead').tier, 'leaders') - assert.equal(getRole('shangshu').tier, 'leaders') - assert.equal(getRole('gongbu').tier, 'ministries') -}) - -test('layout is three columns with the chancellor centred on top', () => { - assert.deepEqual( - { row: getRole('lead').row, column: getRole('lead').column }, - { row: 0, column: 'span' }, - '丞相跨三列居中', - ) - const sansheng = ['zhongshu', 'shangshu', 'menxia'].map((id) => getRole(id)) - assert.deepEqual(sansheng.map((seat) => seat.column), ['left', 'center', 'right']) - assert.ok(sansheng.every((seat) => seat.row === 1)) - // 六部两排:吏户礼 / 兵刑工 - assert.deepEqual( - ['libu', 'hubu', 'lipu'].map((id) => getRole(id).column), - ['left', 'center', 'right'], - ) - assert.deepEqual( - ['bingbu', 'xingbu', 'gongbu'].map((id) => getRole(id).column), - ['left', 'center', 'right'], - ) - assert.ok(['libu', 'hubu', 'lipu'].every((id) => getRole(id).row === 2)) - assert.ok(['bingbu', 'xingbu', 'gongbu'].every((id) => getRole(id).row === 3)) - // 六部同属一个分组,连线不画成吏部下辖兵部。 - assert.equal(new Set(MINISTRIES.map((id) => getRole(id).group)).size, 1) -}) - -test('layoutGroups renders three tiers without inventing parent links', () => { - assert.deepEqual(layoutGroups().lead, ['lead']) - assert.deepEqual(layoutGroups().sansheng, ['zhongshu', 'shangshu', 'menxia']) - assert.deepEqual(layoutGroups().ministries, [['libu', 'hubu', 'lipu'], ['bingbu', 'xingbu', 'gongbu']]) -}) - -test('role lookups reject unknown ids and keep legacy name aliases', () => { - assert.equal(isRoleId('gongbu'), true) - assert.equal(isRoleId('xingbu'), true) - assert.equal(isRoleId('兵部'), false) - assert.equal(isRoleId(undefined), false) - assert.equal(getRole('unknown'), undefined) - assert.throws(() => requireRole('hufu'), /未知角色/) - assert.deepEqual([...ROLE_NAME_ALIASES.zhongshu], ['中书省']) - assert.equal(ROLE_NAME_ALIASES.libu, undefined, '吏部没有旧名别名,防止与礼部混淆') -}) - -test('only the chancellor and shangshu may dispatch by default', () => { - assert.equal(canDispatch('lead'), true) - assert.equal(canDispatch('shangshu'), true) - for (const id of ROLE_IDS.filter((role) => role !== 'lead' && role !== 'shangshu')) { - assert.equal(canDispatch(id), false, `${id} 不自主派工`) - } -}) - -test('initial seats describe configuration rows without creating sessions', () => { - const seats = initialSeats() - assert.equal(seats.length, 10) - assert.deepEqual(seats[0], { roleId: 'lead', name: '丞相', tier: 'leaders' }) - assert.deepEqual(Object.keys(seats[0]).sort(), ['name', 'roleId', 'tier']) -}) - -test('LAYOUT_ORDER 是按布局排序的数组,可直接给 UI 渲染', () => { - assert.deepEqual( - [...LAYOUT_ORDER], - ['lead', 'zhongshu', 'shangshu', 'menxia', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'], - ) - assert.equal(LAYOUT_ORDER.length, ROLE_IDS.length) - // 每席的 row/column 沿数组单调排列,UI 直接按顺序铺即可 - const rows = LAYOUT_ORDER.map((id) => getRole(id).row) - assert.deepEqual(rows, [...rows].sort((a, b) => a - b)) -}) diff --git a/workbench/test/routes.test.mjs b/workbench/test/routes.test.mjs deleted file mode 100644 index 743f423..0000000 --- a/workbench/test/routes.test.mjs +++ /dev/null @@ -1,587 +0,0 @@ -// 工作台 HTTP 路由测试:用假的 ctx / req / res 直接驱动 handler。 -// 这里不启真服务器:路由层要验的是契约(方法、状态码、包装、上限、长轮询语义), -// 起服务器只会把测试变慢而不多验到东西。 -// -// 长轮询只测“等待”这一侧的时序,所以 options 里把 longPollMs / pollIntervalMs 压到毫秒级; -// 25 秒是生产默认值,由 DEFAULT_LONG_POLL_MS 保证,这里断言常量本身而不是等它。 - -import test from 'node:test' -import assert from 'node:assert/strict' -import { Readable } from 'node:stream' -import { WorkbenchStore } from '../core/store.mjs' -import { createWorkbenchService } from '../host/service.mjs' -import { - MAX_BODY_BYTES, - ROUTE_PREFIX, - buildRouteTable, - listWorkbenchRoutes, - registerWorkbenchRoutes, -} from '../host/routes.mjs' - -const FIXED_NOW = Date.parse('2026-11-09T12:00:00.000Z') - -function makeService() { - let counter = 0 - const random = () => Math.imul(counter++, 2654435761) >>> 0 - const store = new WorkbenchStore({ file: null, clock: () => FIXED_NOW, random }) - const service = createWorkbenchService({ store, clock: () => FIXED_NOW }) - return { store, service } -} - -/** 假 res:只记录 writeHead/end,够断言状态码、头与体。 */ -function fakeRes() { - const res = { - statusCode: 0, - headers: {}, - body: '', - writableEnded: false, - destroyed: false, - headersSent: false, - setHeader(name, value) { - this.headers[String(name).toLowerCase()] = value - return this - }, - writeHead(status, headers) { - this.statusCode = status - for (const [name, value] of Object.entries(headers ?? {})) this.headers[String(name).toLowerCase()] = value - this.headersSent = true - return this - }, - end(chunk) { - if (chunk !== undefined) this.body += String(chunk) - this.writableEnded = true - return this - }, - get json() { - return this.body === '' ? null : JSON.parse(this.body) - }, - } - return res -} - -function fakeReq(method, url, body = undefined) { - const hasBody = body !== undefined - const text = hasBody === false ? '' : (typeof body === 'string' ? body : JSON.stringify(body)) - const stream = Readable.from(hasBody ? [Buffer.from(text, 'utf8')] : []) - stream.method = method - stream.url = url - stream.headers = { 'content-type': 'application/json' } - return stream -} - -/** 装一套路由,返回 { ctx, routes: Map, dispose, options }。 */ -function mount(service, options = {}) { - const registered = new Map() - const disposed = [] - const ctx = { - webServer: { - register(route) { - registered.set(route.path, route) - const off = () => disposed.push(route.path) - return off - }, - }, - } - const dispose = registerWorkbenchRoutes(ctx, service, { longPollMs: 30, pollIntervalMs: 5, ...options }) - const call = async (method, url, body) => { - // 注册表按“不含查询串”的精确路径索引;带 ?since= 的调用要先把查询串切掉再查。 - const path = url.search(/[?#]/) < 0 ? url : url.slice(0, url.search(/[?#]/)) - const route = registered.get(path) - assert.ok(route !== undefined, `未注册路由: ${path}`) - assert.equal(route.kind, 'exact') - const res = fakeRes() - await route.handler(fakeReq(method, url, body), res) - return res - } - return { ctx, registered, disposed, dispose, call } -} - -function seedService(service) { - const a = service.registerProject({ hostWorkspaceId: 'ws-a', displayNameCache: '项目A' }).project - const b = service.registerProject({ hostWorkspaceId: 'ws-b', displayNameCache: '项目B' }).project - service.bindDepartmentSession({ projectId: a.id, roleId: 'libu', sessionId: 'sess-a-libu' }) - service.bindDepartmentSession({ projectId: b.id, roleId: 'libu', sessionId: 'sess-b-libu' }) - return { a, b } -} - -// ---------- 注册与降级 ---------- - -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`, - `${ROUTE_PREFIX}/config`, - `${ROUTE_PREFIX}/connect`, - `${ROUTE_PREFIX}/dispatch`, - `${ROUTE_PREFIX}/events`, - `${ROUTE_PREFIX}/ingest`, - `${ROUTE_PREFIX}/project`, - `${ROUTE_PREFIX}/result`, - `${ROUTE_PREFIX}/task`, - `${ROUTE_PREFIX}/task/cancel`, - ]) - assert.equal(dispose.registered, true) - assert.equal(dispose.paths.length, 13) - dispose() - dispose() - assert.equal(disposed.length, 13, '十三条路由各卸载一次,重复调用不再卸载') -}) - -test('注册:宿主没有 webServer 时降级为 no-op,不抛', () => { - const { service } = makeService() - for (const ctx of [undefined, null, {}, { webServer: {} }, { webServer: { register: 1 } }]) { - const dispose = registerWorkbenchRoutes(ctx, service, {}) - assert.equal(typeof dispose, 'function') - assert.equal(dispose.registered, false) - assert.match(dispose.reason, /webServer/) - dispose() - } -}) - -test('注册:中途失败会回滚已注册的路由', () => { - const { service } = makeService() - let calls = 0 - const offs = [] - const ctx = { - webServer: { - register() { - calls += 1 - if (calls === 3) throw new Error('宿主拒绝注册') - const off = () => offs.push(calls) - return off - }, - }, - } - assert.throws(() => registerWorkbenchRoutes(ctx, service, {}), /宿主拒绝注册/) - assert.equal(offs.length, 2, '两条已注册的回滚') -}) - -test('listWorkbenchRoutes 列出端点与方法', () => { - const rows = listWorkbenchRoutes() - assert.equal(rows.length, 13) - assert.deepEqual(rows.find((row) => row.path.endsWith('/bootstrap')), { - path: `${ROUTE_PREFIX}/bootstrap`, - method: 'GET', - }) - assert.equal(rows.filter((row) => row.method === 'GET').length, 2) -}) - -// ---------- 方法与包装 ---------- - -test('方法:POST 路由被 GET 调用返回 405 且带 Allow', async () => { - const { service } = makeService() - const { call } = mount(service) - for (const path of Object.keys(buildRouteTable(service, {}))) { - if (path.endsWith('/bootstrap') || path.endsWith('/events')) continue - const res = await call('GET', path) - assert.equal(res.statusCode, 405, `${path} 应 405`) - assert.equal(res.headers.allow, 'POST') - assert.equal(res.json.ok, false) - assert.equal(res.json.error.code, 'METHOD_NOT_ALLOWED') - } -}) - -test('方法:GET 路由被 POST 调用返回 405 且带 Allow', async () => { - const { service } = makeService() - const { call } = mount(service) - for (const path of [`${ROUTE_PREFIX}/bootstrap`, `${ROUTE_PREFIX}/events`]) { - const res = await call('POST', path, {}) - assert.equal(res.statusCode, 405) - assert.equal(res.headers.allow, 'GET') - } -}) - -test('方法:PUT/DELETE 一律 405', async () => { - const { service } = makeService() - const { call } = mount(service) - for (const method of ['PUT', 'DELETE', 'PATCH']) { - const res = await call(method, `${ROUTE_PREFIX}/task`, { projectId: 'proj_x' }) - assert.equal(res.statusCode, 405, `${method} 应 405`) - } -}) - -test('响应头:JSON + charset、no-store、Content-Length 与实际字节一致', async () => { - const { service } = makeService() - const { call } = mount(service) - const res = await call('POST', `${ROUTE_PREFIX}/project`, { hostWorkspaceId: 'ws-a', displayNameCache: '中文项目' }) - assert.equal(res.statusCode, 200) - assert.equal(res.headers['content-type'], 'application/json; charset=utf-8') - assert.equal(res.headers['cache-control'], 'no-store') - assert.equal(res.headers['content-length'], Buffer.byteLength(res.body)) - assert.equal(res.json.ok, true) - assert.ok(res.json.value.project.id.startsWith('proj_')) -}) - -test('未实现路径:不在表里就没有路由,表本身不含其它前缀', () => { - const { service } = makeService() - const table = buildRouteTable(service, {}) - assert.equal(Object.keys(table).some((path) => path === `${ROUTE_PREFIX}/unknown`), false) - assert.equal(Object.keys(table).every((path) => path.startsWith(`${ROUTE_PREFIX}/`)), true) - // 前缀只登记 exact:绝不允许 kind='prefix' 把整棵子树交给某个 handler。 - const { registered } = mount(service) - for (const route of registered.values()) assert.equal(route.kind, 'exact') -}) - -// ---------- 请求体 ---------- - -test('请求体:非法 JSON 返回 400 INVALID_INPUT', async () => { - const { service } = makeService() - const { call } = mount(service) - const res = await call('POST', `${ROUTE_PREFIX}/project`, '{这不是 JSON') - assert.equal(res.statusCode, 400) - assert.equal(res.json.ok, false) - assert.equal(res.json.error.code, 'INVALID_INPUT') -}) - -test('请求体:JSON 数组 / null / 标量都拒绝', async () => { - const { service } = makeService() - const { call } = mount(service) - for (const raw of ['[]', 'null', '42', '"字符串"']) { - const res = await call('POST', `${ROUTE_PREFIX}/project`, raw) - assert.equal(res.statusCode, 400, `${raw} 应 400`) - assert.equal(res.json.error.code, 'INVALID_INPUT') - } -}) - -test('请求体:空体按 {} 处理,交给服务层报缺参', async () => { - const { service } = makeService() - const { call } = mount(service) - const res = await call('POST', `${ROUTE_PREFIX}/task`, undefined) - assert.equal(res.statusCode, 400) - // 路由层不替业务决定“先报哪个缺参”:服务层先校验角色,所以这里是 INVALID_ROLE。 - assert.equal(res.json.error.code, 'INVALID_ROLE') - assert.equal(res.json.error.details.field, 'ownerRoleId') -}) - -test('请求体:超过 256 KB 返回 413', async () => { - const { service } = makeService() - const { call } = mount(service) - const big = JSON.stringify({ projectId: 'proj_x', pad: 'x'.repeat(MAX_BODY_BYTES) }) - assert.ok(Buffer.byteLength(big) > MAX_BODY_BYTES) - const res = await call('POST', `${ROUTE_PREFIX}/task`, big) - assert.equal(res.statusCode, 413) - assert.equal(res.json.ok, false) - assert.equal(res.json.error.code, 'INVALID_INPUT') - assert.equal(res.json.error.details.limit, MAX_BODY_BYTES) -}) - -test('请求体:刚好等于上限不拦,超过上限 1 字节就拦', async () => { - const { service } = makeService() - const { call } = mount(service, { maxBodyBytes: 64 }) - const okBody = JSON.stringify({ pad: 'y'.repeat(64 - '{"pad":""}'.length) }) - assert.equal(Buffer.byteLength(okBody), 64) - const ok = await call('POST', `${ROUTE_PREFIX}/project`, okBody) - assert.equal(ok.statusCode, 400, '体本身合法,但缺 hostWorkspaceId → 业务 400,不是 413') - assert.notEqual(ok.statusCode, 413) - - const over = JSON.stringify({ pad: 'y'.repeat(65 - '{"pad":""}'.length) }) - assert.equal(Buffer.byteLength(over), 65) - const res = await call('POST', `${ROUTE_PREFIX}/project`, over) - assert.equal(res.statusCode, 413) -}) - -// ---------- 业务错误映射 ---------- - -test('错误映射:NOT_FOUND→404、CROSS_PROJECT→409、CONFIG_CONFLICT→409', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a, b } = seedService(service) - - const missing = await call('POST', `${ROUTE_PREFIX}/task/cancel`, { projectId: a.id, taskId: 'task_notexist001' }) - assert.equal(missing.statusCode, 404) - assert.equal(missing.json.error.code, 'NOT_FOUND') - - const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - const cross = await call('POST', `${ROUTE_PREFIX}/task/cancel`, { projectId: b.id, taskId: task.id }) - assert.equal(cross.statusCode, 409) - assert.equal(cross.json.error.code, 'CROSS_PROJECT') - assert.equal(cross.body.includes(a.id), false, '不得回显另一个项目的真实 ID') - - const config = await call('POST', `${ROUTE_PREFIX}/config`, { - projectId: a.id, - roleId: 'libu', - provider: 'anthropic', - model: 'claude', - expectedRevision: 7, - }) - assert.equal(config.statusCode, 409) - assert.equal(config.json.error.code, 'CONFIG_CONFLICT') - assert.equal(config.json.error.details.currentRevision, 0) -}) - -test('错误:details 原样透出(CAS 冲突带回当前值)', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a } = seedService(service) - const saved = service.saveDepartmentConfig({ - projectId: a.id, - roleId: 'libu', - provider: 'anthropic', - model: 'claude-sonnet', - reasoningEffort: 'high', - expectedRevision: 0, - }) - const res = await call('POST', `${ROUTE_PREFIX}/config`, { - projectId: a.id, - roleId: 'libu', - provider: 'openai', - model: 'gpt', - expectedRevision: saved.config.configRevision, - }) - assert.equal(res.statusCode, 200) - assert.equal(res.json.value.config.model, 'gpt') -}) - -test('错误:未知 roleId → 400 INVALID_ROLE', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a } = seedService(service) - const res = await call('POST', `${ROUTE_PREFIX}/bind`, { projectId: a.id, roleId: 'libbu', sessionId: 'sess-x' }) - assert.equal(res.statusCode, 400) - assert.equal(res.json.error.code, 'INVALID_ROLE') -}) - -// ---------- 成功路径 ---------- - -test('bootstrap:一次拿全,且只含选中项目', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a, b } = seedService(service) - service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }) - service.createTask({ projectId: b.id, title: '乙', objective: '乙', ownerRoleId: 'libu' }) - - const res = await call('GET', `${ROUTE_PREFIX}/bootstrap?projectId=${encodeURIComponent(a.id)}`) - assert.equal(res.statusCode, 200) - const value = res.json.value - assert.equal(value.projectId, a.id) - assert.equal(value.projects.length, 2, '项目列表含全部项目(切换器要用)') - assert.equal(value.seats.length, 10) - assert.deepEqual(value.tasks.map((task) => task.title), ['甲']) - // 布局只给角色 ID:前端按 ROLES 拿名字,避免同一份数据两处维护。 - assert.deepEqual(value.layout.lead, ['lead']) -}) - -test('bootstrap:不传 projectId 时选中第一个项目', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a } = seedService(service) - const res = await call('GET', `${ROUTE_PREFIX}/bootstrap`) - assert.equal(res.statusCode, 200) - assert.equal(res.json.value.projectId, a.id) -}) - -test('bootstrap:伪造 projectId 返回 404,不泄露存在性', async () => { - const { service } = makeService() - const { call } = mount(service) - const { b } = seedService(service) - const res = await call('GET', `${ROUTE_PREFIX}/bootstrap?projectId=proj_zzzzzzzzzzzz`) - assert.equal(res.statusCode, 404) - assert.equal(res.json.error.code, 'NOT_FOUND') - assert.equal(res.body.includes(b.id), false) -}) - -test('project / bind / config / task 四个 POST 串起来走通', async () => { - const { service } = makeService() - const { call } = mount(service) - const created = await call('POST', `${ROUTE_PREFIX}/project`, { hostWorkspaceId: 'ws-z', displayNameCache: '项目Z' }) - const projectId = created.json.value.project.id - - const bound = await call('POST', `${ROUTE_PREFIX}/bind`, { projectId, roleId: 'libu', sessionId: 'sess-z' }) - assert.equal(bound.statusCode, 200) - assert.equal(bound.json.value.seat.connected, true) - - const configured = await call('POST', `${ROUTE_PREFIX}/config`, { - projectId, - roleId: 'libu', - provider: 'anthropic', - model: 'claude', - reasoningEffort: 'medium', - expectedRevision: 0, - }) - assert.equal(configured.statusCode, 200) - assert.equal(configured.json.value.config.reasoningEffort, 'medium') - - const task = await call('POST', `${ROUTE_PREFIX}/task`, { - projectId, - title: '写一份摘要', - objective: '摘要', - ownerRoleId: 'libu', - }) - assert.equal(task.statusCode, 200) - 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) - const { a } = seedService(service) - const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - - const first = await call('POST', `${ROUTE_PREFIX}/dispatch`, { - projectId: a.id, - taskId: task.id, - idempotencyKey: 'route-key-1', - packet: { excerpts: ['需求'] }, - }) - assert.equal(first.statusCode, 200) - assert.equal(first.json.value.duplicate, false) - const again = await call('POST', `${ROUTE_PREFIX}/dispatch`, { - projectId: a.id, - taskId: task.id, - idempotencyKey: 'route-key-1', - }) - assert.equal(again.json.value.duplicate, true) - assert.equal(again.json.value.dispatch.id, first.json.value.dispatch.id) - - const started = service.startAttempt({ projectId: a.id, attemptId: first.json.value.attempt.id }) - const result = await call('POST', `${ROUTE_PREFIX}/result`, { - projectId: a.id, - taskId: task.id, - attemptId: started.attempt.id, - report: { summary: '做完了', checks: [] }, - runTerminal: 'succeeded', - }) - assert.equal(result.statusCode, 200) - assert.equal(result.json.value.task.status, 'completed') - - const other = service.createTask({ projectId: a.id, title: '乙', objective: '乙', ownerRoleId: 'libu' }).task - const cancelled = await call('POST', `${ROUTE_PREFIX}/task/cancel`, { projectId: a.id, taskId: other.id, reason: '不做了' }) - assert.equal(cancelled.statusCode, 200) - assert.equal(cancelled.json.value.task.status, 'cancelled') -}) - -// ---------- 事件 ---------- - -test('events:since 之后只给新事件,游标可重放(多标签页共用一条日志)', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a } = seedService(service) - const head = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=0&wait=0`) - assert.equal(head.statusCode, 200) - const cursor = head.json.value.seq - assert.ok(cursor >= 1) - // since=0 会补齐历史(建项目/绑定的那些事件),游标之后的才算“新”。 - for (const event of head.json.value.events) assert.ok(event.seq <= cursor) - - const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - const after = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=${cursor}&wait=0`) - assert.ok(after.json.value.events.length >= 1) - for (const event of after.json.value.events) { - assert.ok(event.seq > cursor, '只返回 since 之后的事件') - assert.equal(event.projectId, a.id) - } - - // 重放同一个 since 必须拿到同一批事件:事件日志是只读游标,不是"读一次就消失"的队列, - // 否则开两个标签页就会互相偷事件。 - const replay = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=${cursor}&wait=0`) - assert.deepEqual( - replay.json.value.events.map((event) => event.eventId), - after.json.value.events.map((event) => event.eventId), - ) - assert.ok(task.id.startsWith('task_')) -}) - -test('events:since 越界(大于当前 seq)返回 reset 让前端整体重拉', async () => { - const { service } = makeService() - const { call } = mount(service) - const { a } = seedService(service) - const res = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=999999&wait=0`) - assert.equal(res.statusCode, 200) - assert.equal(res.json.value.reset, true) - assert.equal(res.json.value.events.length, 0) -}) - -test('events:since 不是数字 → 400', async () => { - const { service } = makeService() - const { call } = mount(service) - const res = await call('GET', `${ROUTE_PREFIX}/events?since=abc&wait=0`) - assert.equal(res.statusCode, 400) - assert.equal(res.json.error.code, 'INVALID_INPUT') -}) - -test('events:长轮询等到新事件立刻返回,不等满窗口', async () => { - const { service } = makeService() - const { call } = mount(service, { longPollMs: 5_000, pollIntervalMs: 5 }) - const { a } = seedService(service) - const head = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=0&wait=0`) - const cursor = head.json.value.seq - - const startedAt = Date.now() - const pending = call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=${cursor}`) - await new Promise((resolve) => setTimeout(resolve, 20)) - service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }) - const res = await pending - const elapsed = Date.now() - startedAt - assert.equal(res.statusCode, 200) - assert.ok(res.json.value.events.length >= 1, '有新事件就返回') - assert.ok(elapsed < 2_000, `应在窗口耗尽前返回,实际 ${elapsed}ms`) -}) - -test('events:没有新事件时挂满窗口后返回空列表 + 当前 seq', async () => { - const { service } = makeService() - const { call } = mount(service, { longPollMs: 40, pollIntervalMs: 5 }) - const { a } = seedService(service) - const head = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=0&wait=0`) - const cursor = head.json.value.seq - const startedAt = Date.now() - const res = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=${cursor}`) - const elapsed = Date.now() - startedAt - assert.equal(res.statusCode, 200) - assert.deepEqual(res.json.value.events, []) - assert.equal(res.json.value.seq, cursor) - assert.ok(elapsed >= 35, `应至少挂到窗口尾,实际 ${elapsed}ms`) -}) - -test('events:longPollMs=0 时退化为立即返回', async () => { - const { service } = makeService() - const { call } = mount(service, { longPollMs: 0 }) - const { a } = seedService(service) - const startedAt = Date.now() - const res = await call('GET', `${ROUTE_PREFIX}/events?projectId=${encodeURIComponent(a.id)}&since=0`) - assert.equal(res.statusCode, 200) - assert.ok(Date.now() - startedAt < 500) -}) - -test('events:伪造 projectId 返回 404', async () => { - const { service } = makeService() - const { call } = mount(service) - seedService(service) - const res = await call('GET', `${ROUTE_PREFIX}/events?projectId=proj_zzzzzzzzzzzz&since=0&wait=0`) - assert.equal(res.statusCode, 404) - assert.equal(res.json.error.code, 'NOT_FOUND') -}) diff --git a/workbench/test/service.test.mjs b/workbench/test/service.test.mjs deleted file mode 100644 index 76906eb..0000000 --- a/workbench/test/service.test.mjs +++ /dev/null @@ -1,699 +0,0 @@ -// Host 侧业务服务测试:项目隔离、CAS、幂等派发、结果去重、完成判定三分支。 -// 全部用真实 WorkbenchStore(内存账本),不 mock 数据层——幂等与状态机就在那一层, -// 换成假 store 会把要验的东西验掉。 - -import testDefault from 'node:test' -import assert from 'node:assert/strict' -import { WorkbenchStore } from '../core/store.mjs' -import { createWorkbenchService, ServiceError } from '../host/service.mjs' - -const FIXED_NOW = Date.parse('2026-11-09T12:00:00.000Z') - -/** - * 固定时钟 + 可复现随机源:ID 可复现且互不相同,便于断言“只生成了一条”。 - * 种子来自当前用例名,这样每个用例都从同一条 ID 序列开头跑: - * 不会因为别的用例多写了几条记录,就把这里的 ID 推到别处去。 - */ -function makeService(seed = 'default') { - // 单调递增计数器 + 奇数乘法打散:每次 pick 都取一个新的 32 位整数。 - // 直接返回 counter++ 会和字母表长度 36 同周期(12 位 ID 每 36 步就重演同一串, - // 于是「同一次运行里先建任务甲、再建任务乙」可能拿到同一个 ID); - // 乘一个奇数再取 32 位无符号,保证整数性、单调可复现,且不落在 36 的周期上。 - let counter = hashSeed(seed) - const random = () => Math.imul(counter++, 2654435761) >>> 0 - const store = new WorkbenchStore({ - file: null, - clock: () => FIXED_NOW, - random, - }) - const service = createWorkbenchService({ store, clock: () => FIXED_NOW }) - return { store, service } -} - -/** 当前用例名:随机种子取自它,保证每个用例的 ID 序列彼此独立。 */ -let currentTest = 'seed' - -/** 包一层 node:test:进入用例时记下名字,供 makeService 取种子。 */ -function test(name, fn) { - return testDefault(name, (t) => { - currentTest = name - return fn(t) - }) -} - -/** 把用例名里的 ID 前缀说明清掉,只留可哈希的字符。 */ -function seedOfCurrent() { - return currentTest -} -function hashSeed(text) { - let hash = 2166136261 - for (let index = 0; index < text.length; index += 1) { - hash ^= text.charCodeAt(index) - hash = Math.imul(hash, 16777619) - } - return Math.abs(hash) % 100000 -} - -/** 建两个项目,各自把一个部门接通,返回常用 ID。 */ -function seed() { - const { store, service } = makeService(seedOfCurrent()) - const a = service.registerProject({ hostWorkspaceId: 'ws-a', displayNameCache: '项目A' }).project - const b = service.registerProject({ hostWorkspaceId: 'ws-b', displayNameCache: '项目B' }).project - service.bindDepartmentSession({ projectId: a.id, roleId: 'libu', sessionId: 'sess-a-libu' }) - service.bindDepartmentSession({ projectId: b.id, roleId: 'libu', sessionId: 'sess-b-libu' }) - return { store, service, a, b } -} - -function expectCode(fn, code) { - let caught = null - try { - fn() - } catch (error) { - caught = error - } - assert.ok(caught !== null, `期望抛出 ${code},实际没抛`) - assert.ok(caught instanceof ServiceError, `期望 ServiceError,实际 ${caught?.name}`) - assert.equal(caught.code, code, `错误码不符:${caught.code} / ${caught.message}`) - return caught -} - -// ---------- 项目 ---------- - -test('registerProject 同一工作区只建一个项目', () => { - const { service } = makeService(seedOfCurrent()) - const first = service.registerProject({ hostWorkspaceId: 'ws-a', displayNameCache: '甲' }) - assert.equal(first.duplicate, false) - const again = service.registerProject({ hostWorkspaceId: 'ws-a', displayNameCache: '甲改名' }) - assert.equal(again.duplicate, true) - assert.equal(again.project.id, first.project.id, '重复登记不换 projectId') - assert.equal(again.project.displayNameCache, '甲改名', '名称可更新') - assert.equal(service.listProjects().length, 1) - assert.equal(service.listProjects()[0].seatCount, 10) -}) - -test('listSeats 十席布局:未接通时 pending,接通后 connected', () => { - const { service, a } = seed() - const seats = service.listSeats(a.id) - assert.equal(seats.length, 10) - assert.deepEqual(seats.map((seat) => seat.roleId), [ - 'lead', 'zhongshu', 'shangshu', 'menxia', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu', - ]) - const libu = seats.find((seat) => seat.roleId === 'libu') - assert.equal(libu.connected, true) - assert.equal(libu.pending, false) - assert.equal(libu.binding.currentSessionId, 'sess-a-libu') - assert.equal(libu.binding.bindingGeneration, 1) - const hubu = seats.find((seat) => seat.roleId === 'hubu') - assert.equal(hubu.connected, false) - assert.equal(hubu.pending, true) - assert.equal(hubu.pendingLabel, '尚未接通') - // 只暴露 provider/model 名字,不含任何凭据字段 - for (const seat of seats) { - assert.deepEqual(Object.keys(seat.config).sort(), ['configRevision', 'configured', 'model', 'provider', 'reasoningEffort']) - } - assert.equal(service.layout().ministries.length, 2) -}) - -// ---------- 项目隔离 ---------- - -test('项目隔离:A 的 taskId 在 B 上被拒为 CROSS_PROJECT', () => { - const { service, a, b } = seed() - const task = service.createTask({ projectId: a.id, title: '甲任务', objective: '做甲事', ownerRoleId: 'libu' }).task - expectCode(() => service.getTask(b.id, task.id), 'CROSS_PROJECT') - expectCode(() => service.cancelTask({ projectId: b.id, taskId: task.id }), 'CROSS_PROJECT') - expectCode(() => service.dispatchTask({ - projectId: b.id, - taskId: task.id, - idempotencyKey: 'k1', - }), 'CROSS_PROJECT') - expectCode(() => service.requestTaskInput({ projectId: b.id, taskId: task.id, reason: '要资料' }), 'CROSS_PROJECT') -}) - -test('项目隔离:伪造/不存在的 ID 一律 NOT_FOUND,且不泄露归属', () => { - const { service, a } = seed() - // 形状合法但不存在 - const fakeTask = expectCode(() => service.getTask(a.id, 'task_doesnotexist'), 'NOT_FOUND') - assert.ok(!JSON.stringify(fakeTask).includes('proj_'), '错误里不带任何项目 ID') - // 形状非法 - expectCode(() => service.getTask(a.id, 'not-a-task-id'), 'NOT_FOUND') - // 不存在的项目 - expectCode(() => service.listSeats('proj_ghost'), 'NOT_FOUND') - expectCode(() => service.registerProject({ hostWorkspaceId: '' }), 'INVALID_INPUT') - // 项目 A 的会话绑不到项目 B 之外的地方时不会串项目 - const conflict = expectCode(() => service.bindDepartmentSession({ - projectId: a.id, - roleId: 'hubu', - sessionId: 'sess-b-libu', - }), 'SESSION_CONFLICT') - assert.equal(conflict.details.heldBy.projectId, b_idOf(service), 'heldBy 指向真实持有者,便于 UI 解释') -}) - -/** 找项目 B 的 id(测试里只为了断言 heldBy,不参与业务)。 */ -function b_idOf(service) { - return service.listProjects().find((row) => row.hostWorkspaceId === 'ws-b').id -} - -test('项目隔离:跨项目成果引用与尝试引用被拒', () => { - const { store, service, a, b } = seed() - const taskA = service.createTask({ projectId: a.id, title: '甲', objective: '甲目标', ownerRoleId: 'libu' }).task - const taskB = service.createTask({ projectId: b.id, title: '乙', objective: '乙目标', ownerRoleId: 'libu' }).task - const artB = service.registerArtifact({ projectId: b.id, taskId: taskB.id, displayName: '乙成果' }).artifact - const dispatched = service.dispatchTask({ projectId: a.id, taskId: taskA.id, idempotencyKey: 'd-a' }) - // 用 B 的成果引用给 A 的任务交报告:拒绝 - const err = expectCode(() => service.reportTaskResult({ - projectId: a.id, - taskId: taskA.id, - attemptId: dispatched.attempt.id, - report: { summary: '做完了', artifactRefs: [artB.id] }, - runTerminal: 'succeeded', - }), 'CROSS_PROJECT') - assert.ok(!JSON.stringify(err).includes(taskB.id), '不泄露另一项目的任务 ID') - // 用 B 的尝试给 A 的任务报结果:CROSS_PROJECT - assert.ok(store.getTask(taskB.id) !== undefined) -}) - -test('项目隔离:另一项目的 attemptId 报结果被拒', () => { - const { service, a, b } = seed() - const taskA = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - const taskB = service.createTask({ projectId: b.id, title: '乙', objective: '乙', ownerRoleId: 'libu' }).task - const dispB = service.dispatchTask({ projectId: b.id, taskId: taskB.id, idempotencyKey: 'kb' }) - expectCode(() => service.reportTaskResult({ - projectId: a.id, - taskId: taskA.id, - attemptId: dispB.attempt.id, - report: { summary: '串了' }, - runTerminal: 'succeeded', - }), 'CROSS_PROJECT') -}) - -// ---------- 配置 CAS ---------- - -test('saveDepartmentConfig 走 CAS:旧 revision 冲突并带回当前值', () => { - const { service, a } = seed() - const first = service.saveDepartmentConfig({ - projectId: a.id, - roleId: 'libu', - provider: 'deepseek', - model: 'v4', - reasoningEffort: 'high', - expectedRevision: 0, - }) - assert.equal(first.configRevision, 1) - const conflict = expectCode(() => service.saveDepartmentConfig({ - projectId: a.id, - roleId: 'libu', - provider: 'openai', - model: 'gpt', - expectedRevision: 0, - }), 'CONFIG_CONFLICT') - assert.equal(conflict.details.expectedRevision, 0) - assert.equal(conflict.details.currentRevision, 1) - assert.deepEqual(conflict.details.current, { provider: 'deepseek', model: 'v4', reasoningEffort: 'high' }) - // 读回新 revision 后可以成功 - const ok = service.saveDepartmentConfig({ - projectId: a.id, - roleId: 'libu', - provider: 'openai', - model: 'gpt', - expectedRevision: conflict.details.currentRevision, - }) - assert.equal(ok.configRevision, 2) - expectCode(() => service.saveDepartmentConfig({ - projectId: a.id, - roleId: 'libu', - provider: 'x', - model: 'y', - expectedRevision: '1', - }), 'INVALID_INPUT') -}) - -test('绑定:同一会话被别处持有 → SESSION_CONFLICT;换绑需 allowReplace', () => { - const { service, a } = seed() - const bound = service.bindDepartmentSession({ projectId: a.id, roleId: 'hubu', sessionId: 'sess-hubu-1' }) - assert.equal(bound.seat.connected, true) - const conflict = expectCode(() => service.bindDepartmentSession({ - projectId: a.id, - roleId: 'hubu', - sessionId: 'sess-hubu-2', - }), 'SESSION_CONFLICT') - assert.equal(conflict.details.currentSessionId, 'sess-hubu-1') - const replaced = service.bindDepartmentSession({ - projectId: a.id, - roleId: 'hubu', - sessionId: 'sess-hubu-2', - allowReplace: true, - }) - assert.equal(replaced.binding.bindingGeneration, 2) - assert.equal(replaced.binding.historySessionRefs.length, 1, '旧会话进历史,不删除') -}) - -// ---------- 派发 ---------- - -test('dispatchTask 写 dispatch+contextPacket+attempt,同幂等键只一条', () => { - const { store, service, a } = seed() - const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲目标', ownerRoleId: 'libu' }).task - const first = service.dispatchTask({ - projectId: a.id, - taskId: task.id, - idempotencyKey: 'idem-1', - packet: { excerpts: ['原始需求'], expectedOutputs: ['报告'] }, - }) - assert.equal(first.duplicate, false) - assert.equal(first.dispatch.status, 'prepared') - assert.equal(first.attempt.state, 'queued') - assert.equal(first.attempt.sessionId, 'sess-a-libu') - assert.equal(first.attempt.effectiveConfigSnapshot.provider, null) - assert.equal(first.contextPacket.version, 1) - assert.deepEqual(first.contextPacket.excerpts, ['原始需求']) - - const again = service.dispatchTask({ projectId: a.id, taskId: task.id, idempotencyKey: 'idem-1' }) - assert.equal(again.duplicate, true) - assert.equal(again.dispatch.id, first.dispatch.id, '幂等命中返回原派发') - assert.equal(again.attempt.id, first.attempt.id) - assert.equal(store.state.dispatches.size, 1, '账本里只有一条派发') - assert.equal(store.state.attempts.size, 1, '也为幂等,只有一条尝试') - - // 换个键:新派发,上下文包版本递增 - const second = service.dispatchTask({ projectId: a.id, taskId: task.id, idempotencyKey: 'idem-2' }) - assert.equal(second.duplicate, false) - assert.equal(second.contextPacket.version, 2) - assert.equal(store.state.dispatches.size, 2) -}) - -test('dispatchTask:未接通、已终态、目标与主责不一致都拒绝', () => { - const { service, a } = seed() - // 未接通会话的部门不能直接入队(默认 queued),只能先存草稿 - expectCode(() => service.createTask({ projectId: a.id, title: '丙', objective: '丙', ownerRoleId: 'hubu' }), 'INVALID_STATE') - const task = service.createTask({ projectId: a.id, title: '甲', objective: '甲', ownerRoleId: 'hubu', status: 'draft' }).task - expectCode(() => service.dispatchTask({ projectId: a.id, taskId: task.id, idempotencyKey: 'k' }), 'INVALID_STATE') - const queued = service.createTask({ projectId: a.id, title: '乙', objective: '乙', ownerRoleId: 'libu' }).task - expectCode(() => service.dispatchTask({ - projectId: a.id, - taskId: queued.id, - idempotencyKey: 'k2', - targetRoleId: 'hubu', - }), 'DISPATCH_INVALID') - // 换绑后旧 bindingGeneration 派发失败 - const first = service.bindDepartmentSession({ projectId: a.id, roleId: 'hubu', sessionId: 'sess-hubu' }) - const fresh = service.createTask({ projectId: a.id, title: '丁', objective: '丁', ownerRoleId: 'hubu' }).task - service.bindDepartmentSession({ projectId: a.id, roleId: 'hubu', sessionId: 'sess-hubu-2', allowReplace: true }) - const staleGeneration = first.binding.bindingGeneration - expectCode(() => service.dispatchTask({ - projectId: a.id, - taskId: fresh.id, - idempotencyKey: 'k3', - bindingGeneration: staleGeneration, - }), 'SESSION_CONFLICT') -}) - -// ---------- 结果与完成判定 ---------- - -/** 建任务 → 派发 → 让任务进入 running,返回三件套。 */ -function runningTask(ctx, projectId = ctx.a.id) { - const task = ctx.service.createTask({ projectId, title: '任务', objective: '目标', ownerRoleId: 'libu' }).task - const dispatched = ctx.service.dispatchTask({ projectId, taskId: task.id, idempotencyKey: `key-${task.id}` }) - const started = ctx.service.startAttempt({ - projectId, - taskId: task.id, - attemptId: dispatched.attempt.id, - hostRunId: 'run-1', - }) - return { task: started.task, attempt: dispatched.attempt, dispatch: dispatched.dispatch } -} - -test('完成判定分支一:报告+终态成功+成果有效 → completed', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - const artifact = ctx.service.registerArtifact({ projectId: ctx.a.id, taskId: task.id, displayName: 'report.md' }).artifact - const out = ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '已完成分析', artifactRefs: [artifact.id], checks: [{ name: '自检', ok: true }] }, - runTerminal: 'succeeded', - sourceMessageRef: 'msg-1', - }) - assert.equal(out.duplicate, false) - assert.equal(out.decision.applied, true) - assert.equal(out.decision.status, 'completed') - assert.equal(out.task.status, 'completed') - assert.ok(out.task.reportReceivedAt !== null) - assert.ok(out.task.endedAt !== null) -}) - -test('完成判定分支二:终态成功但报告不可信 → needs_attention', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - const out = ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '看起来完成了', blockedReason: '缺少关键数据' }, - runTerminal: 'succeeded', - }) - assert.equal(out.decision.status, 'needs_attention') - assert.equal(out.task.status, 'needs_attention') - assert.match(out.task.needsAttentionReason, /有效/) - // needs_attention 不是完成:没有 completed 时间 - assert.equal(out.task.endedAt, null) -}) - -test('完成判定分支三:报告先到、宿主未结束 → 登记但不完成,终态后补齐', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - const first = ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '分析完成,等运行收尾' }, - runTerminal: 'running', - }) - // 报告本身写进了账(status 不是 completed 就是证据),但任务没被判完成 - assert.equal(first.decision.status, 'running', '运行未结束不判完成') - assert.equal(first.task.status, 'running') - assert.ok(first.task.reportReceivedAt !== null, '报告先到时先登记报告时间(候选)') - assert.ok(first.result.id.startsWith('res_'), '结果已登记为候选') - // 终态后到:reportRunTerminal 把它推进到 completed - const second = ctx.service.reportRunTerminal({ projectId: ctx.a.id, taskId: task.id, runTerminal: 'succeeded' }) - assert.equal(second.task.status, 'completed') - assert.equal(second.decision.applied, true) -}) - -test('结果去重:同 (attemptId, reportVersion) 与同 sourceMessageRef 只登记一次', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - const payload = { - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '第一次提交' }, - runTerminal: 'succeeded', - sourceMessageRef: 'msg-9', - } - const first = ctx.service.reportTaskResult(payload) - assert.equal(first.duplicate, false) - const revision = ctx.store.getTask(task.id).revision - const second = ctx.service.reportTaskResult(payload) - assert.equal(second.duplicate, true) - assert.equal(second.result.id, first.result.id) - assert.equal(second.decision.applied, false) - assert.equal(ctx.store.getTask(task.id).revision, revision, '重复事件不改任务 revision') - // 换 reportVersion 但同 sourceMessageRef:仍算重复 - const third = ctx.service.reportTaskResult({ ...payload, reportVersion: 2 }) - assert.equal(third.duplicate, true) - assert.equal(ctx.store.listResults(undefined).filter((row) => row.taskId === task.id).length, 1) -}) - -test('结果:伪造成果引用被拒,不留半条结果', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - expectCode(() => ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '带假附件', artifactRefs: ['art_fake123'] }, - runTerminal: 'succeeded', - }), 'NOT_FOUND') - assert.equal(ctx.store.listResults(undefined).length, 0) - expectCode(() => ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: ' ' }, - }), 'INVALID_INPUT') - expectCode(() => ctx.service.reportTaskResult({ - projectId: ctx.a.id, - taskId: task.id, - attemptId: attempt.id, - report: { summary: '好' }, - runTerminal: 'done', - }), 'INVALID_INPUT') -}) - -test('cancelTask:业务落 cancelled,运行中的尝试只到 cancel_requested', () => { - const ctx = seed() - const { task, attempt } = runningTask(ctx) - const out = ctx.service.cancelTask({ projectId: ctx.a.id, taskId: task.id, reason: '不再需要' }) - assert.equal(out.task.status, 'cancelled') - assert.equal(out.task.cancelReason, '不再需要') - assert.equal(out.attempt.state, 'cancel_requested') - assert.equal(out.cancelRequest.attemptId, attempt.id) - assert.equal(out.cancelRequest.hostRunId, 'run-1') - // 已终态再取消:applied=false,状态不变 - const again = ctx.service.cancelTask({ projectId: ctx.a.id, taskId: task.id }) - assert.equal(again.applied, false) - assert.equal(again.task.status, 'cancelled') -}) - -test('requestTaskInput 进入 waiting_input,supplyTaskInput 回到 running', () => { - const ctx = seed() - const { task } = runningTask(ctx) - const asked = ctx.service.requestTaskInput({ - projectId: ctx.a.id, - taskId: task.id, - reason: '缺少原始数据', - missingItems: ['数据文件'], - }) - assert.equal(asked.task.status, 'waiting_input') - assert.equal(asked.task.waitingReason, '缺少原始数据') - assert.deepEqual(asked.missingItems, ['数据文件']) - const supplied = ctx.service.supplyTaskInput({ projectId: ctx.a.id, taskId: task.id }) - assert.equal(supplied.task.status, 'running') -}) - -test('syncDecision 只登记带来源的决定事件,不广播', () => { - const ctx = seed() - const { task } = runningTask(ctx) - const out = ctx.service.syncDecision({ - projectId: ctx.a.id, - taskId: task.id, - content: '同意按方案 B 执行', - sourceSessionId: 'sess-lead', - roleId: 'lead', - }) - assert.equal(out.event.type, 'decision.synced') - assert.equal(out.event.payload.content, '同意按方案 B 执行') - assert.equal(out.event.payload.sourceSessionId, 'sess-lead') - assert.equal(out.task.id, task.id) - expectCode(() => ctx.service.syncDecision({ projectId: ctx.a.id, content: ' ' }), 'INVALID_INPUT') -}) - -// ---------- 投影与事件 ---------- - -test('bootstrap 一次拿全且只含选中项目的数据', () => { - const ctx = seed() - const taskA = ctx.service.createTask({ projectId: ctx.a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - const taskB = ctx.service.createTask({ projectId: ctx.b.id, title: '乙', objective: '乙', ownerRoleId: 'libu' }).task - const view = ctx.service.bootstrap(ctx.a.id) - assert.equal(view.projectId, ctx.a.id) - assert.equal(view.projects.length, 2) - assert.equal(view.seats.length, 10) - assert.deepEqual(view.tasks.map((row) => row.id), [taskA.id]) - assert.ok(!view.tasks.some((row) => row.id === taskB.id), '不串项目任务') - assert.equal(view.eventSeq, ctx.store.eventSeq) - // 不传 projectId 时取第一个项目 - const fallback = ctx.service.bootstrap() - assert.equal(fallback.projectId, view.projects[0].id) - expectCode(() => ctx.service.bootstrap('proj_ghost'), 'NOT_FOUND') -}) - -test('listEvents since 语义:只给新事件,越界给 reset', () => { - const ctx = seed() - const before = ctx.service.listEvents(ctx.a.id, 0) - assert.ok(before.events.length > 0) - assert.ok(before.events.every((row) => row.projectId === ctx.a.id), '只返回本项目事件') - const last = before.seq - const empty = ctx.service.listEvents(ctx.a.id, last) - assert.equal(empty.events.length, 0) - assert.equal(empty.seq, last) - // 产生一条新事件,且只属于项目 A(项目 B 的事件不该出现在 A 的游标里) - ctx.service.createTask({ projectId: ctx.a.id, title: '新', objective: '新', ownerRoleId: 'libu' }) - const mine = ctx.store.listEvents(ctx.a.id).filter((row) => row.seq > last) - const after = ctx.service.listEvents(ctx.a.id, last) - if (mine.length > 0) { - assert.equal(after.events.length, mine.length) - assert.deepEqual(after.events.map((row) => row.seq), mine.map((row) => row.seq)) - } else { - assert.equal(after.events.length, 0) - } - assert.ok(after.events.every((row) => row.projectId === ctx.a.id)) - // 用当前 seq 当游标再问一次必须为空(since 语义是“严格大于”) - assert.equal(ctx.service.listEvents(ctx.a.id, after.seq).events.length, 0) - // since 超过当前 seq:账本被替换/回滚,前端应全量重拉 - const reset = ctx.service.listEvents(ctx.a.id, last + 9999) - assert.equal(reset.reset, true) -}) - -test('成果登记与查询同样受项目隔离', () => { - const ctx = seed() - const task = ctx.service.createTask({ projectId: ctx.a.id, title: '甲', objective: '甲', ownerRoleId: 'libu' }).task - const art = ctx.service.registerArtifact({ - projectId: ctx.a.id, - taskId: task.id, - displayName: '交付物', - verification: { status: 'verified' }, - }).artifact - assert.equal(ctx.service.getArtifact(ctx.a.id, art.id).displayName, '交付物') - expectCode(() => ctx.service.getArtifact(ctx.b.id, art.id), 'CROSS_PROJECT') - assert.equal(ctx.service.listArtifacts(ctx.b.id).length, 0) -}) - -test('未知部门与缺参数走 INVALID_ROLE / INVALID_INPUT', () => { - const ctx = seed() - expectCode(() => ctx.service.listTasks(ctx.a.id, { ownerRoleId: 'unknown' }), 'INVALID_ROLE') - expectCode(() => ctx.service.createTask({ projectId: ctx.a.id, objective: 'x', ownerRoleId: 'libu' }), 'INVALID_INPUT') - expectCode(() => ctx.service.createTask({ projectId: ctx.a.id, title: 'x', objective: 'y', ownerRoleId: 'hufu' }), 'INVALID_ROLE') - expectCode(() => ctx.service.bindDepartmentSession({ projectId: ctx.a.id, roleId: 'libu', sessionId: '' }), 'INVALID_INPUT') -}) - -// ---------- A20:目录冲突 ---------- - -test('A20 同目录/父子目录登记成另一个项目时明确报冲突,不宣称隔离', () => { - const { service } = makeService(seedOfCurrent()) - service.registerProject({ hostWorkspaceId: 'ws-a', canonicalRoot: 'C:\\work\\alpha' }) - // 大小写、分隔符、末尾斜杠都算同一目录 - const same = expectCode( - () => service.registerProject({ hostWorkspaceId: 'ws-b', canonicalRoot: 'c:/work/alpha/' }), - 'DUPLICATE_PROJECT', - ) - assert.equal(same.details.relation, 'same') - assert.equal(same.details.otherHostWorkspaceId, 'ws-a') - assert.equal(same.details.hint, 'allowSharedRoot') - - const nested = expectCode( - () => service.registerProject({ hostWorkspaceId: 'ws-c', canonicalRoot: 'C:\\work\\alpha\\sub' }), - 'DUPLICATE_PROJECT', - ) - assert.equal(nested.details.relation, 'nested') - - // 显式放行:仍然登记,但把识别到的关系带回去,让 UI 有话说 - const shared = service.registerProject({ - hostWorkspaceId: 'ws-d', - canonicalRoot: 'C:\\work\\alpha', - allowSharedRoot: true, - }) - assert.equal(shared.duplicate, false) - assert.equal(shared.sharedRoot.relation, 'same') - - // 不同目录互不干扰 - const other = service.registerProject({ hostWorkspaceId: 'ws-e', canonicalRoot: 'D:\\other' }) - assert.equal(other.duplicate, false) - assert.equal(other.sharedRoot, null) - // 无关目录不该被误判为同一个:alpha 与 alphabeta 是不同目录 - const notPrefix = service.registerProject({ hostWorkspaceId: 'ws-f', canonicalRoot: 'C:\\work\\alphabeta' }) - assert.equal(notPrefix.duplicate, false) -}) - -// ---------- A22 / A23:成果修订与失效显示 ---------- - -test('A22 成果修订只开一条修订任务给原主责部门,派发自带原成果引用', () => { - const ctx = seed() - const task = ctx.service.createTask({ - projectId: ctx.a.id, ownerRoleId: 'libu', title: '写报告', objective: '产出报告', - }).task - const artifact = ctx.service.registerArtifact({ - projectId: ctx.a.id, taskId: task.id, fileRef: 'C:/work/a/report.md', displayName: '报告', - }).artifact - assert.equal(artifact.revision, 1) - - const revised = ctx.service.requestArtifactRevision({ - projectId: ctx.a.id, artifactId: artifact.id, instruction: '只改第三节的结论', - }) - assert.equal(revised.task.kind, 'revision') - assert.equal(revised.task.ownerRoleId, 'libu', '仍归原主责部门,不重跑整套三省') - assert.equal(revised.task.sourceRoleId, 'lead') - assert.equal(revised.task.reviseOfArtifactId, artifact.id) - assert.equal(revised.task.artifactRevision, 1) - assert.equal(revised.task.scope.kind, 'artifact-revision') - assert.equal(revised.task.objective, '只改第三节的结论') - assert.equal(revised.task.status, 'draft', '默认草稿:不替用户立刻派工') - - // 派发时若没显式给 materialRefs,自动带上「哪份成果的哪一版」 - const dispatched = ctx.service.dispatchTask({ - projectId: ctx.a.id, taskId: revised.task.id, targetRoleId: 'libu', idempotencyKey: 'rev-1', - }) - assert.deepEqual(dispatched.contextPacket.materialRefs, [{ artifactId: artifact.id, revision: 1, title: "报告" }]) - - // 新成果接到旧成果上:版本 +1,且跨项目修订被拒 - const next = ctx.service.registerArtifact({ - projectId: ctx.a.id, taskId: revised.task.id, fileRef: 'C:/work/a/report-v2.md', - displayName: '报告 v2', revisesArtifactId: artifact.id, - }).artifact - assert.equal(next.revision, 2) - assert.equal(next.revisesArtifactId, artifact.id) - - const bTask = ctx.service.createTask({ projectId: ctx.b.id, ownerRoleId: 'libu', title: 'b', objective: 'b' }).task - const foreign = ctx.service.registerArtifact({ projectId: ctx.b.id, taskId: bTask.id }).artifact - expectCode( - () => ctx.service.registerArtifact({ projectId: ctx.a.id, taskId: task.id, revisesArtifactId: foreign.id }), - 'CROSS_PROJECT', - ) -}) - -test('A23 成果文件不见了显示 missing,探不了就是 unknown,绝不猜成 ok', () => { - const { store } = makeService(seedOfCurrent()) - // 文件系统由宿主注入:这里只验投影怎么读结论 - const existing = new Set(['C:/work/keep.md']) - const service = createWorkbenchService({ - store, clock: () => FIXED_NOW, fileExists: (path) => existing.has(path), - }) - const project = service.registerProject({ hostWorkspaceId: 'ws-a' }).project - service.bindDepartmentSession({ projectId: project.id, roleId: 'libu', sessionId: 'sess-a-libu' }) - const task = service.createTask({ projectId: project.id, ownerRoleId: 'libu', title: 't', objective: 'o' }).task - const kept = service.registerArtifact({ projectId: project.id, taskId: task.id, fileRef: 'C:/work/keep.md' }).artifact - const gone = service.registerArtifact({ projectId: project.id, taskId: task.id, fileRef: 'C:/work/gone.md' }).artifact - const remote = service.registerArtifact({ projectId: project.id, taskId: task.id, fileRef: null }).artifact - - assert.equal(kept.existence, 'ok') - assert.equal(gone.existence, 'missing') - assert.equal(remote.existence, 'unknown', '没有本地路径就不下结论') - - const boot = service.bootstrap(project.id) - assert.deepEqual(boot.artifacts.map((row) => row.existence), ['ok', '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) -}) diff --git a/workbench/test/states.test.mjs b/workbench/test/states.test.mjs deleted file mode 100644 index a3f18fd..0000000 --- a/workbench/test/states.test.mjs +++ /dev/null @@ -1,127 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { - ATTEMPT_STATES, - DEPARTMENT_STATES, - DISPATCH_STATES, - STATE_MACHINES, - TASK_STATES, - TERMINAL_STATES, - allowedTransitions, - assertTransition, - canTransition, - isState, - isTerminal, - statesOf, -} from '../core/states.mjs' - -test('every machine lists the plan states verbatim', () => { - assert.deepEqual([...TASK_STATES], [ - 'draft', - 'queued', - 'running', - 'waiting_input', - 'needs_attention', - 'completed', - 'failed', - 'cancelled', - ]) - assert.deepEqual([...DISPATCH_STATES], ['prepared', 'sending', 'accepted', 'unknown', 'rejected']) - assert.deepEqual([...ATTEMPT_STATES], [ - 'queued', - 'running', - 'succeeded', - 'failed', - 'cancel_requested', - 'cancelled', - 'unknown', - ]) - assert.deepEqual([...DEPARTMENT_STATES], ['uninitialized', 'idle', 'queued', 'running', 'unavailable']) - assert.equal(Object.keys(STATE_MACHINES).length, 4) -}) - -test('state queries validate the machine name', () => { - assert.equal(isState('task', 'draft'), true) - assert.equal(isState('task', 'pending'), false, '旧 pending/in_progress 不属于新状态机') - assert.equal(isState('attempt', 'cancel_requested'), true) - assert.deepEqual(statesOf('department'), DEPARTMENT_STATES) - assert.throws(() => statesOf('nope'), /未知状态机/) - assert.throws(() => allowedTransitions('task', 'pending'), /未知状态/) -}) - -test('task happy path and legal detours', () => { - assert.deepEqual([...allowedTransitions('task', 'draft')], ['queued', 'cancelled']) - assert.equal(canTransition('task', 'draft', 'queued'), true) - assert.equal(canTransition('task', 'queued', 'running'), true) - assert.equal(canTransition('task', 'running', 'completed'), true) - assert.equal(canTransition('task', 'running', 'waiting_input'), true) - assert.equal(canTransition('task', 'waiting_input', 'queued'), true) - assert.equal(canTransition('task', 'needs_attention', 'completed'), true, '补报后可完成') - assert.equal(canTransition('task', 'running', 'draft'), false) - assert.equal(canTransition('task', 'completed', 'running'), false, '终态不回退') - assert.equal(canTransition('task', 'failed', 'running'), false) - assert.equal(canTransition('task', 'cancelled', 'queued'), false) - assert.equal(canTransition('task', 'running', 'running'), true, '同状态重复写入视为幂等') -}) - -test('dispatch states separate sending from accepted', () => { - assert.equal(canTransition('dispatch', 'prepared', 'sending'), true) - assert.equal(canTransition('dispatch', 'sending', 'accepted'), true) - assert.equal(canTransition('dispatch', 'sending', 'unknown'), true, '回执超时进入 unknown') - assert.equal(canTransition('dispatch', 'unknown', 'accepted'), true, '对账后可确认已接收') - assert.equal(canTransition('dispatch', 'unknown', 'rejected'), true) - assert.equal(canTransition('dispatch', 'accepted', 'unknown'), false) - assert.equal(canTransition('dispatch', 'rejected', 'sending'), false) - assert.equal(canTransition('dispatch', 'prepared', 'accepted'), false, '不能跳过发送直接接收') -}) - -test('attempt states keep cancel requests separate from cancellation', () => { - assert.equal(canTransition('attempt', 'queued', 'running'), true) - assert.equal(canTransition('attempt', 'running', 'cancel_requested'), true) - assert.equal(canTransition('attempt', 'cancel_requested', 'cancelled'), true) - assert.equal(canTransition('attempt', 'cancel_requested', 'succeeded'), true, '取消与成功竞争照常落终态') - assert.equal(canTransition('attempt', 'cancelled', 'running'), false) - assert.equal(canTransition('attempt', 'unknown', 'running'), true, '对账发现仍在跑') - assert.equal(canTransition('attempt', 'succeeded', 'failed'), false) -}) - -test('department states describe the session, not the task', () => { - assert.equal(canTransition('department', 'uninitialized', 'queued'), true) - assert.equal(canTransition('department', 'running', 'unavailable'), true) - assert.equal(canTransition('department', 'unavailable', 'idle'), true) - assert.equal(canTransition('department', 'idle', 'completed'), false, '部门没有完成态') -}) - -test('assertTransition throws readable errors and returns the target', () => { - assert.equal(assertTransition('task', 'draft', 'queued'), 'queued') - assert.equal(assertTransition('task', 'queued', 'queued'), 'queued') - assert.throws(() => assertTransition('task', 'completed', 'running'), /Task 不允许从 completed 迁移到 running/) - assert.throws(() => assertTransition('task', 'bogus', 'running'), /当前状态非法/) - assert.throws(() => assertTransition('task', 'draft', 'bogus'), /目标状态非法/) - assert.throws(() => assertTransition('nope', 'draft', 'queued'), /未知状态机/) -}) - -test('terminal states are explicit per machine', () => { - assert.equal(isTerminal('task', 'completed'), true) - assert.equal(isTerminal('task', 'needs_attention'), false, '待核不算完成') - assert.equal(isTerminal('dispatch', 'accepted'), true) - assert.equal(isTerminal('dispatch', 'unknown'), false, 'unknown 必须对账') - assert.equal(isTerminal('attempt', 'cancel_requested'), false) - assert.equal(isTerminal('attempt', 'cancelled'), true) - assert.equal(isTerminal('department', 'unavailable'), false) - assert.throws(() => isTerminal('nope', 'x'), /未知状态机/) -}) - -test('terminal state sets match the machines', () => { - assert.deepEqual([...TERMINAL_STATES.task], ['completed', 'failed', 'cancelled']) - assert.deepEqual([...TERMINAL_STATES.dispatch], ['accepted', 'rejected']) - assert.deepEqual([...TERMINAL_STATES.attempt], ['succeeded', 'failed', 'cancelled']) - // 部门不是业务流程,没有“完成”概念 - assert.deepEqual([...TERMINAL_STATES.department], []) - for (const key of Object.keys(TERMINAL_STATES)) { - for (const state of TERMINAL_STATES[key]) { - assert.equal(isTerminal(key, state), true, ) - assert.deepEqual(allowedTransitions(key, state), [], ) - } - } -}) diff --git a/workbench/test/store.test.mjs b/workbench/test/store.test.mjs deleted file mode 100644 index b97eb07..0000000 --- a/workbench/test/store.test.mjs +++ /dev/null @@ -1,368 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { SCHEMA_VERSION, StoreError, WorkbenchStore, defaultStorePath, entityOf } from '../core/store.mjs' -import { createIdFactory } from '../core/ids.mjs' - -/** 固定随机源和时钟:随机源按调用递增,保证 ID 可复现且互不相同。 */ -function makeStore(file = null) { - let cursor = 0 - return new WorkbenchStore({ - file, - clock: () => Date.parse('2026-11-09T12:00:00.000Z'), - random: () => cursor++, - }) -} - -function mkStore() { - const store = makeStore() - const a = store.createProject({ hostWorkspaceId: 'ws-a', displayNameCache: '项目A' }) - const b = store.createProject({ hostWorkspaceId: 'ws-b', displayNameCache: '项目B' }) - return { store, a, b } -} - -test('createProject seeds ten empty seats without sessions', () => { - const { store, a } = mkStore() - assert.match(a, /^proj_/) - assert.equal(store.listProjects().length, 2) - const bindings = store.listBindings(a) - assert.equal(bindings.length, 10) - assert.ok(bindings.every((row) => row.currentSessionId === null && row.status === 'uninitialized')) - assert.ok(store.listConfigs(a).every((row) => row.providerId === null && row.configRevision === 0)) - assert.equal(store.revision, 2, '每次提交递增 revision') - assert.equal(store.eventSeq, 2, '事件日志追加 seq') - assert.deepEqual(store.listEvents(a).map((row) => row.type), ['project.created']) - assert.throws(() => store.createProject({ hostWorkspaceId: 'ws-a' }), /已登记/) - assert.throws(() => store.createProject({ hostWorkspaceId: ' ' }), /非空字符串/) - assert.throws(() => store.bindSession(a, 'hufu', 's1'), /未知角色/) -}) - -test('one active binding per (projectId, roleId)', () => { - const { store, a } = mkStore() - const bound = store.bindSession(a, 'gongbu', 'sess-1') - assert.equal(bound.bindingGeneration, 1) - assert.equal(bound.currentSessionId, 'sess-1') - assert.equal(store.getBinding(a, 'gongbu').currentSessionId, 'sess-1') - // 同一 (project, role) 的两个绑定行不可能同时存在:键就是 (projectId, roleId)。 - const rows = store.listBindings(a).filter((row) => row.roleId === 'gongbu') - assert.equal(rows.length, 1) - // 同一部门换绑走 releaseBinding,旧会话进历史而不是悄悄被覆盖。 - const rebound = store.bindSession(a, 'gongbu', 'sess-2', { allowReplace: true }) - assert.equal(rebound.currentSessionId, 'sess-2') - assert.equal(rebound.bindingGeneration, 2) - assert.deepEqual(rebound.historySessionRefs.map((row) => row.sessionId), ['sess-1']) -}) - -test('binding requires the old session to be released before it is reused', () => { - const { store, a } = mkStore() - store.bindSession(a, 'gongbu', 'sess-1') - assert.throws(() => store.bindSession(a, 'gongbu', 'sess-1'), /无需重复绑定/) - assert.equal(store.getBinding(a, 'gongbu').bindingGeneration, 1) -}) - -test('a session id cannot be bound to two different (projectId, roleId)', () => { - const { store, a, b } = mkStore() - store.bindSession(a, 'gongbu', 'sess-1') - assert.throws(() => store.bindSession(a, 'libu', 'sess-1'), /SESSION_CONFLICT|已绑定/) - assert.throws(() => store.bindSession(b, 'gongbu', 'sess-1'), /已绑定/) - // 释放后旧会话进入 historySessionRefs,不删除历史,且可绑定到别处。 - const released = store.releaseBinding(a, 'gongbu') - assert.equal(released.currentSessionId, null) - assert.equal(released.historySessionRefs.length, 1) - assert.equal(released.historySessionRefs[0].sessionId, 'sess-1') - const moved = store.bindSession(b, 'gongbu', 'sess-1') - assert.equal(moved.currentSessionId, 'sess-1') - assert.equal(moved.bindingGeneration, 1) -}) - -test('rebinding bumps bindingGeneration so old dispatches stay pinned', () => { - const { store, a } = mkStore() - store.bindSession(a, 'gongbu', 'sess-1') - store.releaseBinding(a, 'gongbu') - const next = store.bindSession(a, 'gongbu', 'sess-2') - assert.equal(next.bindingGeneration, 2) - assert.deepEqual(store.getBinding(a, 'gongbu').historySessionRefs.map((row) => row.sessionId), ['sess-1']) - assert.throws(() => store.setBindingStatus(a, 'gongbu', 'completed'), /目标状态非法/) - assert.equal(store.setBindingStatus(a, 'gongbu', 'unavailable').status, 'unavailable') -}) - -test('configuration CAS rejects stale writers and returns the current value', () => { - const { store, a, b } = mkStore() - const first = store.saveConfig(a, 'gongbu', { provider: 'deepseek', model: 'chat', reasoningEffort: 'high' }, 0) - assert.equal(first.configRevision, 1) - assert.equal(first.providerId, 'deepseek') - assert.throws( - () => store.saveConfig(a, 'gongbu', { provider: 'openai', model: 'gpt', reasoningEffort: null }, 0), - (error) => { - assert.equal(error.code, 'CAS_CONFLICT') - assert.equal(error.details.currentRevision, 1) - assert.deepEqual(error.details.current, { provider: 'deepseek', model: 'chat', reasoningEffort: 'high' }) - return true - }, - ) - // 冲突不写账:revision 与配置保持原样 - assert.equal(store.getConfig(a, 'gongbu').providerId, 'deepseek') - // 另一项目另一部门互不影响 - assert.equal(store.getConfig(b, 'gongbu').configRevision, 0) - const second = store.saveConfig(a, 'gongbu', { provider: 'openai', model: 'gpt' }, 1) - assert.equal(second.configRevision, 2) - assert.equal(second.reasoningEffort, null, '缺省 effort 落 null,不透传 undefined') - assert.throws(() => store.saveConfig(a, 'gongbu', { provider: 'x', model: 'y' }, '1'), /expectedRevision/) - assert.throws(() => store.saveConfig(a, 'gongbu', { provider: 'x' }, 2), /model/) -}) - -test('dispatch idempotency key returns the existing record', () => { - const { store, a } = mkStore() - const first = store.recordDispatch({ projectId: a, idempotencyKey: 'k-1', taskId: null }) - assert.equal(first.duplicate, false) - assert.match(first.dispatch.id, /^dsp_/) - const again = store.recordDispatch({ projectId: a, idempotencyKey: 'k-1' }) - assert.equal(again.duplicate, true) - assert.equal(again.dispatch.id, first.dispatch.id) - assert.equal([...store.state.dispatches.values()].length, 1, '重复点击只留一条派发') - // 幂等键按项目隔离:另一项目同键是另一件事。 - const { b } = { b: store.listProjects()[1].id } - assert.equal(store.recordDispatch({ projectId: b, idempotencyKey: 'k-1' }).duplicate, false) - // 状态推进走状态机 - const accepted = store.updateDispatch(first.dispatch.id, { status: 'sending' }) - assert.equal(accepted.status, 'sending') - assert.throws(() => store.updateDispatch(first.dispatch.id, { status: 'proposed' }), /目标状态非法/) - assert.throws(() => store.updateDispatch(first.dispatch.id, { status: 'prepared' }), /不允许/) -}) - -test('recordResult deduplicates duplicate completion events', () => { - const { store, a } = mkStore() - const task = store.insertTask({ projectId: a, ownerRoleId: 'gongbu', sourceRoleId: 'lead', status: 'draft' }) - const attempt = store.insertAttempt({ projectId: a, taskId: task.id, state: 'running' }) - const base = { projectId: a, taskId: task.id, attemptId: attempt.id, summary: '完成', reportVersion: 1 } - const first = store.recordResult(base) - assert.equal(first.duplicate, false) - assert.match(first.result.id, /^res_/) - const dupVersion = store.recordResult(base) - assert.equal(dupVersion.duplicate, true) - assert.equal(dupVersion.result.id, first.result.id) - // 同一源消息的重复事件同样只登记一次 - const dupMessage = store.recordResult({ ...base, reportVersion: 2, sourceMessageRef: 'msg-1' }) - assert.equal(dupMessage.duplicate, false) - const dupMessageAgain = store.recordResult({ ...base, reportVersion: 3, sourceMessageRef: 'msg-1' }) - assert.equal(dupMessageAgain.duplicate, true) - assert.equal(store.listResults(task.id).length, 2) -}) - -test('cross-project references are rejected on write', () => { - const { store, a, b } = mkStore() - const taskA = store.insertTask({ projectId: a, ownerRoleId: 'gongbu', sourceRoleId: 'lead', status: 'draft' }) - assert.throws( - () => store.insertAttempt({ projectId: b, taskId: taskA.id, state: 'queued' }), - (error) => error.code === 'CROSS_PROJECT', - ) - const attemptA = store.insertAttempt({ projectId: a, taskId: taskA.id, state: 'running' }) - assert.throws( - () => store.recordResult({ projectId: b, taskId: null, attemptId: attemptA.id, summary: 'x' }), - (error) => error.code === 'CROSS_PROJECT', - ) - assert.equal(store.listResults().length, 0, '被拒绝的写入不落账') -}) - -test('cross-project recordResult and artifacts are refused', () => { - const { store, a, b } = mkStore() - const taskA = store.insertTask({ projectId: a, ownerRoleId: 'gongbu', sourceRoleId: 'lead', status: 'draft' }) - const attemptA = store.insertAttempt({ projectId: a, taskId: taskA.id, state: 'running' }) - assert.throws( - () => store.recordResult({ projectId: b, attemptId: attemptA.id, summary: 'x' }), - (error) => error.code === 'CROSS_PROJECT', - ) - const resultA = store.recordResult({ projectId: a, taskId: taskA.id, attemptId: attemptA.id, summary: 'ok' }) - assert.throws( - () => store.recordArtifact({ projectId: b, taskId: taskA.id, ownerRoleId: 'gongbu', sourceResultId: resultA.result.id }), - (error) => error.code === 'CROSS_PROJECT', - ) - const artifact = store.recordArtifact({ projectId: a, taskId: taskA.id, ownerRoleId: 'gongbu', sourceResultId: resultA.result.id }) - assert.match(artifact.id, /^art_/) - assert.throws(() => store.insertContextPacket({ projectId: b, taskId: taskA.id }), /CROSS_PROJECT|跨项目/) - assert.throws(() => store.assertProjectOwns(b, 'tasks', taskA.id), /不属于项目/) - assert.throws(() => store.assertProjectOwns(a, 'tasks', 'task_missing'), /不存在/) - assert.equal(store.assertProjectOwns(a, 'tasks', taskA.id).id, taskA.id) - assert.throws(() => store.insertTask({ projectId: 'proj_nope', ownerRoleId: 'gongbu', sourceRoleId: 'lead', status: 'draft' }), /项目不存在/) - // 先校验角色,未知部门在建立任务时就拒绝 - const fresh = new WorkbenchStore({ file: null, clock: () => 1700000000000, random: () => 7 }) - const fa = fresh.createProject({ hostWorkspaceId: 'ws-a' }) - assert.throws(() => fresh.insertTask({ projectId: fa, ownerRoleId: 'hufu', sourceRoleId: 'lead', status: 'draft' }), /未知主责部门/) - assert.throws(() => store.recordArtifact({ projectId: a, taskId: taskA.id, ownerRoleId: 'hufu' }), /未知主责部门/) -}) - -test('task writes cannot skip the state machine or rewrite project', () => { - const { store, a, b } = mkStore() - const task = store.insertTask({ projectId: a, ownerRoleId: 'gongbu', sourceRoleId: 'lead', status: 'draft' }) - assert.equal(task.revision, 1) - const queued = store.updateTask({ ...task, status: 'queued' }) - assert.equal(queued.revision, 2) - assert.throws(() => store.updateTask({ ...task, status: 'completed' }), /不允许/) - assert.throws(() => store.updateTask({ ...task, projectId: b, status: 'queued' }), /不能被改写/) - assert.throws(() => store.insertTask({ ...task }), /任务已存在/) -}) - -test('markEventDelivered acks the outbox without deleting events', () => { - const { store, a, b } = mkStore() - const first = store.appendEvent({ type: 'ping', projectId: a }) - const second = store.appendEvent({ type: 'ping', projectId: a }) - const other = store.appendEvent({ type: 'ping', projectId: b }) - assert.equal(store.listPendingEvents(a).length, 3, '项目 a:建项目 1 条 + 两条 ping') - - const revision = store.revision - assert.deepEqual(store.markEventDelivered(a, [first.eventId]), { delivered: 1 }) - assert.equal(store.revision, revision + 1, '标记走同一条提交路径,递增 revision') - // 幂等:重复 ack 不报错、不重复计数,也不白增 revision - const revision2 = store.revision - assert.deepEqual(store.markEventDelivered(a, [first.eventId]), { delivered: 0 }) - assert.equal(store.revision, revision2, '空操作不递增 revision') - // 未知 id 静默忽略 - assert.deepEqual(store.markEventDelivered(a, ['evt_missing', 'not-an-id']), { delivered: 0 }) - // 跨项目 id 忽略:既不是错误,也不会写到别的项目 - assert.deepEqual(store.markEventDelivered(a, [other.eventId]), { delivered: 0 }) - assert.equal(store.listPendingEvents(b).length, 2, '项目 b 的事件不受影响') - // 标记后不再出现在 pending,但事件仍可通过 listEvents 审计看到 - assert.deepEqual( - store.listPendingEvents(a).map((row) => row.eventId), - [store.listEvents(a)[0].eventId, second.eventId], - '只剩项目创建事件与第二条 ping', - ) - const acks = store.listEvents(a).find((row) => row.eventId === first.eventId) - assert.ok(acks.deliveredAt !== null, '已投递事件保留记录并写时间戳') - assert.equal(store.listEvents(a).length, 3) - // 项目不存在与其它方法一致抛 StoreError - assert.throws( - () => store.markEventDelivered('proj_nope', [first.eventId]), - (error) => error instanceof StoreError && error.code === 'NOT_FOUND', - ) -}) - -test('listPendingEvents honours limit and keeps seq order', () => { - const { store, a } = mkStore() - // mkStore 先建了两个项目,项目 a 的 project.created 是第 1 条事件 - const created = store.listEvents(a)[0] - const first = store.appendEvent({ type: 'ping', projectId: a }) - const second = store.appendEvent({ type: 'ping', projectId: a }) - const third = store.appendEvent({ type: 'ping', projectId: a }) - assert.deepEqual(store.listPendingEvents(a).map((row) => row.seq), [created.seq, first.seq, second.seq, third.seq]) - assert.deepEqual(store.listPendingEvents(a, { limit: 2 }).map((row) => row.seq), [created.seq, first.seq]) - // 非正整数 limit 视为不传,行为与旧接口一致 - assert.equal(store.listPendingEvents(a, { limit: 0 }).length, 4) - assert.equal(store.listPendingEvents(a, { limit: -1 }).length, 4) - assert.equal(store.listPendingEvents(a, {}).length, 4) - // limit 与 ack 组合:已投递的不占额度 - assert.deepEqual(store.markEventDelivered(a, [created.eventId, first.eventId]), { delivered: 2 }) - assert.equal(store.listPendingEvents(a).length, 2) - assert.deepEqual(store.listPendingEvents(a, { limit: 1 }).map((row) => row.seq), [second.seq]) - assert.deepEqual(store.listPendingEvents(a, { limit: 2 }).map((row) => row.seq), [second.seq, third.seq]) -}) - -test('event log keeps monotonic seq and rejects duplicate eventId', () => { - const { store, a } = mkStore() - const first = store.appendEvent({ type: 'ping', projectId: a }) - const second = store.appendEvent({ type: 'ping', projectId: a }) - assert.ok(second.seq > first.seq) - assert.equal(store.listPendingEvents().length, 4, '两个项目创建 + 两条 ping 都待处理') - assert.deepEqual(store.listPendingEvents().slice(-2).map((row) => row.type), ['ping', 'ping']) - assert.equal(store.listEvents(a).length, 3) - assert.throws(() => store.appendEvent({ type: 'ping', projectId: a, eventId: first.eventId }), /事件已登记/) - assert.throws(() => store.appendEvent({ projectId: a }), /event.type/) -}) - -test('failed writes roll back memory and leave no ghost rows', () => { - const { store, a } = mkStore() - const revision = store.revision - const events = store.eventSeq - assert.throws(() => store.recordDispatch({ projectId: a, idempotencyKey: 'k', status: 'proposed' }), /未知派发状态/) - assert.equal([...store.state.dispatches.values()].length, 0) - assert.equal(store.revision, revision, '失败不递增 revision') - assert.equal(store.eventSeq, events, '失败不留下半截事件') -}) - -test('file persistence round-trips and writes atomically', () => { - const dir = mkdtempSync(join(tmpdir(), 'sansheng-store-')) - try { - const file = join(dir, 'nested', 'workbench.json') - const store = makeStore(file) - const a = store.createProject({ hostWorkspaceId: 'ws-a', displayNameCache: '项目A' }) - store.bindSession(a, 'gongbu', 'sess-1') - store.saveConfig(a, 'gongbu', { provider: 'p', model: 'm', reasoningEffort: 'low' }, 0) - store.recordDispatch({ projectId: a, idempotencyKey: 'k-1' }) - store.appendEvent({ type: 'test.event', projectId: a }) - assert.equal(existsSync(file), true) - // 原子写:目录里只剩目标文件,没有残留 .tmp - assert.deepEqual(readdirSync(dirname(file)), ['workbench.json']) - const raw = JSON.parse(readFileSync(file, 'utf8')) - assert.equal(raw.schemaVersion, 1) - assert.equal(raw.revision, store.revision) - - const reloaded = makeStore(file) - assert.equal(reloaded.load(), true) - assert.equal(reloaded.revision, store.revision) - assert.equal(reloaded.getBinding(a, 'gongbu').currentSessionId, 'sess-1') - assert.equal(reloaded.getConfig(a, 'gongbu').configRevision, 1) - assert.equal(reloaded.listEvents(a).length, store.listEvents(a).length) - assert.deepEqual(reloaded.snapshot().projects, store.snapshot().projects) - // 重新载入后仍能继续写,且唯一性约束照样生效 - assert.throws(() => reloaded.bindSession(a, 'libu', 'sess-1'), /已绑定/) - assert.equal(reloaded.recordDispatch({ projectId: a, idempotencyKey: 'k-1' }).duplicate, true) - - // 缺省路径:%DSH_HOME%\sansheng-liubu\workbench.json,未设置时落 ~/.dsh - const sep = String.fromCharCode(92) - const winPath = defaultStorePath({ DSH_HOME: 'C:' + sep + 'dsh-home' }).split(sep).join('/') - assert.equal(winPath, 'C:/dsh-home/sansheng-liubu/workbench.json') - assert.equal(makeStore(null).save(), false, '纯内存模式不落盘') - } finally { - rmSync(dir, { recursive: true, force: true }) - } -}) - -test('load rejects unknown schema versions instead of guessing', () => { - const dir = mkdtempSync(join(tmpdir(), 'sansheng-schema-')) - try { - const file = join(dir, 'workbench.json') - const store = makeStore(file) - store.createProject({ hostWorkspaceId: 'ws-a' }) - const raw = JSON.parse(readFileSync(file, 'utf8')) - raw.schemaVersion = 99 - writeFileSync(file, JSON.stringify(raw)) - const other = makeStore(file) - assert.throws(() => other.load(), /schemaVersion=99/) - } finally { - rmSync(dir, { recursive: true, force: true }) - } -}) - -test('ids factory is shared with event ids for deterministic tests', () => { - const ids = createIdFactory({ random: () => 2, length: 6 }) - assert.match(ids.task(), /^task_2{6}$/) - // 常量随机源会让 ID 冲突,因此 store 自带事件去重后缀 - const constant = new WorkbenchStore({ file: null, clock: () => 0, random: () => 7 }) - const projectId = constant.createProject({ hostWorkspaceId: 'ws-a' }) - const first = constant.appendEvent({ type: 'x', projectId }) - const second = constant.appendEvent({ type: 'x', projectId }) - assert.match(first.eventId, /^evt_7{12}/) - assert.notEqual(first.eventId, second.eventId) - assert.deepEqual(constant.listEvents(projectId).map((row) => row.seq), [1, 2, 3]) -}) - -test('schema version and entity mapping are exported constants', () => { - assert.equal(SCHEMA_VERSION, 1) - assert.equal(entityOf('tasks'), 'task') - assert.equal(entityOf('contextPackets'), 'contextPacket') - assert.equal(entityOf('nope'), null) - const error = new StoreError('BOOM', '炸了') - assert.ok(error instanceof Error) - assert.equal(error.name, 'StoreError') - assert.equal(error.code, 'BOOM') - assert.equal(error.details, undefined) - assert.deepEqual(new StoreError('X', 'y', { a: 1 }).details, { a: 1 }) - // 缺省路径:%DSH_HOME%\sansheng-liubu\workbench.json,未设置时落 ~/.dsh - const sep = String.fromCharCode(92) - const winPath = defaultStorePath({ DSH_HOME: 'C:' + sep + 'dsh-home' }).split(sep).join('/') - assert.equal(winPath, 'C:/dsh-home/sansheng-liubu/workbench.json') - const homePath = defaultStorePath({}).split(sep).join('/') - assert.match(homePath, /\.dsh\/sansheng-liubu\/workbench\.json$/) -}) diff --git a/workbench/test/tasks.test.mjs b/workbench/test/tasks.test.mjs deleted file mode 100644 index 46bd4c7..0000000 --- a/workbench/test/tasks.test.mjs +++ /dev/null @@ -1,368 +0,0 @@ -// 任务生命周期测试:重点验证「完成判定三分支」与乱序/重复事件不回退状态。 -// 这些是 v0.1 最容易出错的地方,全部用纯函数直接断言,不依赖 store 或宿主。 - -import test from 'node:test' -import assert from 'node:assert/strict' - -import { - TaskError, - TASK_TRANSITIONS, - isStaleSeq, - isRegressingEvent, - createTask, - startTask, - beginAttempt, - validateReport, - checkCompletion, - evaluateCompletion, - decide, - requestInput, - supplyInput, - completeTask, - failTask, - cancelTask, - applyDecision, - isOpenTask, -} from '../core/tasks.mjs' -import { WorkbenchStore } from '../core/store.mjs' - -const clock = () => 1700000000000 - -function draftTask(overrides = {}) { - return createTask( - { - projectId: 'proj_a', - title: '整理季度报表', - objective: '把三份表合并成一份差异表', - ownerRoleId: 'hubu', - sourceRoleId: 'zhongshu', - ...overrides, - }, - { newTaskId: () => 'task_1', now: clock }, - ) -} - -function runningTask() { - const task = startTask(draftTask(), { now: clock }) - return beginAttempt(task, { id: 'att_1', projectId: 'proj_a', taskId: 'task_1' }, { now: clock }) -} - -const goodReport = { - attemptId: 'att_1', - taskId: 'task_1', - summary: '差异 12 处,已附差异表', - checks: [{ name: '数量核对', ok: true }], - artifactRefs: ['art_1'], -} - -test('createTask 只建草稿,缺字段或未知席直接拒绝', () => { - const task = draftTask() - assert.equal(task.status, 'draft') - assert.equal(task.ownerRoleId, 'hubu') - assert.equal(task.sourceRoleId, 'zhongshu') - assert.equal(task.activeAttemptId, null) - assert.equal(task.revision, 1) - assert.deepEqual(task.attempts, []) - assert.throws(() => createTask({ title: 'x', objective: 'y', ownerRoleId: 'hubu' }), TaskError) - assert.throws(() => draftTask({ ownerRoleId: 'hufu' }), /未知主责部门/) - assert.throws(() => draftTask({ sourceRoleId: 'nobody' }), /未知来源部门/) - assert.throws(() => draftTask({ objective: ' ' }), /objective/) -}) - -test('TASK_TRANSITIONS 与方案一致且不可变', () => { - assert.ok(Object.isFrozen(TASK_TRANSITIONS)) - const pairs = TASK_TRANSITIONS.map(([from, to]) => `${from}->${to}`) - for (const expected of ['draft->queued', 'running->completed', 'running->needs_attention', 'needs_attention->completed', 'waiting_input->running']) { - assert.ok(pairs.includes(expected), `缺少迁移 ${expected}`) - } - assert.ok(!pairs.includes('completed->running'), '终态不能被复活') - assert.ok(Object.isFrozen(TASK_TRANSITIONS[0])) -}) - -test('startTask 只从草稿或待补充入队', () => { - const queued = startTask(draftTask(), { now: clock }) - assert.equal(queued.status, 'queued') - assert.equal(queued.revision, 2) - assert.throws(() => startTask(queued), /只有草稿或待补充/) - const waiting = requestInput(runningTask(), '缺少上月口径', { now: clock }).task - assert.equal(waiting.status, 'waiting_input') - assert.equal(startTask(waiting, { now: clock }).status, 'queued') -}) - -test('beginAttempt 绑定新尝试并保留历史', () => { - const task = runningTask() - assert.equal(task.status, 'running') - assert.equal(task.activeAttemptId, 'att_1') - assert.deepEqual(task.attempts, ['att_1']) - // 旧尝试仍活跃时不允许并发换绑:先对账再重试 - assert.throws( - () => beginAttempt(task, { id: 'att_2', projectId: 'proj_a', taskId: 'task_1' }), - (error) => error.code === 'ACTIVE_ATTEMPT', - ) - const settled = { ...task, activeAttemptId: null, status: 'needs_attention' } - const retried = beginAttempt(settled, { id: 'att_2', projectId: 'proj_a', taskId: 'task_1' }, { now: clock }) - assert.equal(retried.activeAttemptId, 'att_2') - assert.deepEqual(retried.attempts, ['att_1', 'att_2'], '旧尝试不能被覆盖') - assert.throws(() => beginAttempt({ ...task, status: 'completed' }, { id: 'att_3', projectId: 'proj_a', taskId: 'task_1' }), /不能开始新的尝试/) - assert.throws( - () => beginAttempt({ ...task, status: 'queued' }, { id: 'att_2', projectId: 'proj_b', taskId: 'task_1' }), - /不属于同一项目/, - ) - assert.throws( - () => beginAttempt({ ...task, status: 'queued' }, { id: 'att_2', projectId: 'proj_a', taskId: 'task_9' }), - /别的任务/, - ) - assert.throws(() => beginAttempt({ ...task, status: 'queued' }, null), /尝试记录不合法/) -}) - -test('beginAttempt 不再被已取消的旧尝试挡住重试', () => { - const running = runningTask() - // 取消后 activeAttemptId 仍指向旧尝试(保留审计),旧 Attempt 已转 cancelled 终态 → 允许重试 - const cancelledLookup = (id) => ({ id, state: 'cancelled' }) - const next = { id: 'att_2', projectId: 'proj_a', taskId: 'task_1' } - const retried = beginAttempt(running, next, { now: clock, attemptLookup: cancelledLookup }) - assert.equal(retried.status, 'running') - assert.equal(retried.activeAttemptId, 'att_2') - assert.deepEqual(retried.attempts, ['att_1', 'att_2'], '旧尝试保留在历史里') - // running 但当前尝试已 unknown/failed/succeeded 终态时同样放行 - for (const state of ['failed', 'succeeded']) { - assert.equal(beginAttempt(running, next, { now: clock, attemptLookup: (id) => ({ id, state }) }).activeAttemptId, 'att_2') - } - // needs_attention 下旧尝试已取消:不被 ACTIVE_ATTEMPT 挡住 - const needsAttention = { ...running, status: 'needs_attention' } - const retriedAfterCancel = beginAttempt(needsAttention, next, { now: clock, attemptLookup: cancelledLookup }) - assert.equal(retriedAfterCancel.status, 'running') - assert.equal(retriedAfterCancel.needsAttentionReason, null) - // 旧尝试 still running / unknown / cancel_requested:仍在活动,必须挡住 - const queuedAttempt = (id) => ({ id, state: 'queued' }) - const unknownAttempt = (id) => ({ id, state: 'unknown' }) - for (const lookup of [queuedAttempt, unknownAttempt]) { - assert.throws( - () => beginAttempt(running, next, { now: clock, attemptLookup: lookup }), - (error) => error.code === 'ACTIVE_ATTEMPT', - ) - assert.throws( - () => beginAttempt(needsAttention, next, { now: clock, attemptLookup: lookup }), - (error) => error.code === 'ACTIVE_ATTEMPT', - ) - } - // 不注入 attemptLookup 时无法证明旧尝试已对账 → 保持旧行为(非空即挡) - assert.throws( - () => beginAttempt(running, next, { now: clock }), - (error) => error.code === 'ACTIVE_ATTEMPT', - ) - // needs_attention 且 activeAttemptId 为空 → 本来就不受影响 - assert.equal(beginAttempt({ ...running, activeAttemptId: null, status: 'needs_attention' }, next, { now: clock }).activeAttemptId, 'att_2') -}) - -test('validateReport 只认结构化字段', () => { - assert.deepEqual(validateReport(goodReport), []) - assert.deepEqual(validateReport({ attemptId: 'a', taskId: 't', summary: 's' }), []) - assert.deepEqual(validateReport(null), ['报告必须是对象']) - const errors = validateReport({ summary: ' ', artifactRefs: ['res_1'], checks: 'ok' }) - assert.ok(errors.some((row) => row.includes('attemptId'))) - assert.ok(errors.some((row) => row.includes('taskId'))) - assert.ok(errors.some((row) => row.includes('摘要为空'))) - assert.ok(errors.some((row) => row.includes('成果引用形状非法'))) - assert.ok(errors.some((row) => row.includes('checks 必须是数组'))) - assert.ok(validateReport({ attemptId: 'a', taskId: 't', summary: 's', artifactRefs: 'art_1' }).some((row) => row.includes('artifactRefs'))) -}) - -test('checkCompletion 三条条件各占一票', () => { - const all = checkCompletion({ report: goodReport, runTerminal: 'succeeded', artifactRefs: ['art_1'], artifactLookup: () => ({ id: 'art_1' }) }) - assert.deepEqual(all, { reportOk: true, runOk: true, refsValid: true, blockers: [], ok: true }) - - const noReport = checkCompletion({ report: null, runTerminal: 'succeeded' }) - assert.equal(noReport.reportOk, false) - assert.equal(noReport.ok, false) - assert.ok(noReport.blockers.includes('未收到结构化报告')) - - const noTerminal = checkCompletion({ report: goodReport, runTerminal: null }) - assert.equal(noTerminal.runOk, false) - assert.ok(noTerminal.blockers.includes('宿主运行尚未结束')) - - const failedRun = checkCompletion({ report: goodReport, runTerminal: 'failed' }) - assert.equal(failedRun.runOk, false) - assert.ok(failedRun.blockers.some((row) => row.includes('failed'))) - - const blocked = checkCompletion({ report: { ...goodReport, blockedReason: '缺权限' }, runTerminal: 'succeeded' }) - assert.equal(blocked.reportOk, false) - - const danglingRef = checkCompletion({ report: goodReport, runTerminal: 'succeeded', artifactRefs: ['art_1'], artifactLookup: () => undefined }) - assert.equal(danglingRef.refsValid, false) - assert.ok(danglingRef.blockers.some((row) => row.includes('成果引用无效'))) - - const missingArtifact = checkCompletion({ report: goodReport, runTerminal: 'succeeded', artifactRefs: ['art_1'], artifactLookup: () => ({ id: 'art_1', verification: { status: 'missing' } }) }) - assert.equal(missingArtifact.refsValid, false) - - // 纯分析任务允许无附件:空引用不算失败 - assert.equal(checkCompletion({ report: goodReport, runTerminal: 'succeeded', artifactRefs: [] }).ok, true) -}) - -test('完成判定三分支:三者齐全 → completed', () => { - const decision = evaluateCompletion( - runningTask(), - { report: goodReport, runTerminal: 'succeeded', artifactRefs: ['art_1'], artifactLookup: () => ({ id: 'art_1' }) }, - { now: clock }, - ) - assert.equal(decision.applied, true) - assert.equal(decision.task.status, 'completed') - assert.ok(decision.task.reportReceivedAt) - assert.equal(decision.task.needsAttentionReason, null) -}) - -test('完成判定三分支:只有报告 → 等待,不置 completed', () => { - // 报告先到:保存候选结果,等宿主终态 - const reported = decide(runningTask(), { kind: 'report', report: goodReport }, { now: clock }) - assert.equal(reported.applied, true) - assert.equal(reported.task.status, 'running', '报告先到不得直接置完成') - assert.ok(reported.task.reportReceivedAt !== null) - - // 只有报告、终态尚未到达 —— 保持 running - const pending = evaluateCompletion(runningTask(), { report: goodReport, runTerminal: null }) - assert.equal(pending.applied, false) - assert.equal(pending.task.status, 'running') - assert.ok(pending.reason.includes('宿主运行尚未结束')) - - // 报告到达后终态成功 → 顺理成章完成 - const finished = decide(reported.task, { kind: 'run_terminal', runTerminal: 'succeeded' }, { now: clock }) - assert.equal(finished.applied, true) - assert.equal(finished.task.status, 'completed') -}) - -test('完成判定三分支:只有终态 → needs_attention', () => { - // 宿主运行先结束但无报告 - const onlyTerminal = evaluateCompletion(runningTask(), { report: null, runTerminal: 'succeeded' }, { now: clock }) - assert.equal(onlyTerminal.applied, true) - assert.equal(onlyTerminal.task.status, 'needs_attention') - assert.match(onlyTerminal.task.needsAttentionReason, /没有有效的结构化报告/) - - // 运行失败同样进入 needs_attention,而不是 completed - const failed = decide(runningTask(), { kind: 'run_terminal', runTerminal: 'failed' }, { now: clock }) - assert.equal(failed.task.status, 'needs_attention') - assert.match(failed.task.needsAttentionReason, /failed/) - - // 终态成功但报告不完整:也不能置完成,最多进入 needs_attention 等补报 - const partial = evaluateCompletion(runningTask(), { report: { attemptId: 'att_1' }, runTerminal: 'succeeded' }) - assert.notEqual(partial.task.status, 'completed') - assert.equal(partial.task.status, 'needs_attention') -}) - -test('运行终态为 cancelled 时任务直接取消', () => { - const decision = decide(runningTask(), { kind: 'run_terminal', runTerminal: 'cancelled' }, { now: clock }) - assert.equal(decision.task.status, 'cancelled') - assert.ok(decision.task.endedAt) -}) - -test('乱序事件:旧 seq 不回退,迟到 running 不覆盖终态', () => { - assert.equal(isStaleSeq(null, 5), false) - assert.equal(isStaleSeq(5, 5), true, '同 seq 视为重复') - assert.equal(isStaleSeq(5, 4), true) - assert.equal(isStaleSeq(5, 6), false) - assert.equal(isStaleSeq(5, Number.NaN), true) - - const withSeq = { ...runningTask(), lastSeq: 10 } - const stale = decide(withSeq, { kind: 'input_required', reason: '旧事件', seq: 9 }, { now: clock }) - assert.equal(stale.applied, false) - assert.equal(stale.stale, true) - assert.equal(stale.task.status, 'running') - - const done = evaluateCompletion( - { ...withSeq, lastSeq: 11 }, - { report: goodReport, runTerminal: 'succeeded', seq: 12 }, - { now: clock }, - ) - assert.equal(done.task.status, 'completed') - assert.equal(done.task.lastSeq, 12) - - const late = decide(done.task, { kind: 'input_required', reason: '迟到的求助', seq: 13 }, { now: clock }) - assert.equal(late.applied, false) - assert.equal(late.task.status, 'completed', '终态不能被迟到事件覆盖') - // 终态之后即使 seq 更大也只记 no-op:调用方据此知道「没有状态变化」 - assert.match(late.reason, /不接受|已终态/) - - assert.equal(isRegressingEvent('completed', 'running'), true) - assert.equal(isRegressingEvent('completed', 'completed'), false) - assert.equal(isRegressingEvent('running', 'running'), false) -}) - -test('waiting_input 往返与非法事件', () => { - const asked = requestInput(runningTask(), '缺口径', { now: clock }) - assert.equal(asked.task.status, 'waiting_input') - assert.equal(asked.task.waitingReason, '缺口径') - const back = supplyInput(asked.task, { now: clock }) - assert.equal(back.task.status, 'running') - assert.equal(back.task.waitingReason, null) - assert.equal(supplyInput(back.task).applied, false, '不在待补充时忽略') - assert.equal(requestInput(draftTask(), 'x').applied, false) - assert.throws(() => decide(runningTask(), { kind: 'nope' }), /未知事件类型/) - assert.throws(() => decide(runningTask(), null), /事件必须是对象/) - assert.throws(() => decide({}, { kind: 'report' }), /任务记录不合法/) - assert.throws( - () => decide(runningTask(), { kind: 'report', report: { summary: '' } }), - (error) => error.code === 'INVALID_REPORT', - ) - assert.throws( - () => decide({ ...runningTask(), status: 'failed' }, { kind: 'retry' }), - (error) => error.code === 'RETRY_REQUIRES_NEW_TASK', - ) - assert.equal(decide(runningTask(), { kind: 'retry' }).applied, false) -}) - -test('failTask 必须带原因,终态后忽略', () => { - const failed = failTask(runningTask(), '模型超时', { now: clock }) - assert.equal(failed.task.status, 'failed') - assert.equal(failed.task.failureReason, '模型超时') - assert.ok(failed.task.endedAt) - assert.throws(() => failTask(runningTask(), ' '), /reason/) - assert.equal(failTask(failed.task, 'again').applied, false) -}) - -test('cancelTask 记录取消原因且只写一次结束时间', () => { - const cancelled = cancelTask(runningTask(), '用户点了取消', { now: clock }) - assert.equal(cancelled.task.status, 'cancelled') - assert.equal(cancelled.task.cancelReason, '用户点了取消') - const again = cancelTask(cancelled.task, '重复取消') - assert.equal(again.applied, false) - assert.equal(again.task.endedAt, cancelled.task.endedAt) - assert.equal(cancelTask(draftTask()).task.cancelReason, '用户取消') -}) - -test('completeTask 是 completion 事件的便捷包装', () => { - const decision = completeTask( - runningTask(), - { report: goodReport, runTerminal: 'succeeded', artifactRefs: ['art_1'], artifactLookup: () => ({ id: 'art_1' }), seq: 3 }, - ) - assert.equal(decision.task.status, 'completed') - assert.equal(decision.task.lastSeq, 3) -}) - -test('applyDecision 只在 applied 时落库', () => { - const store = new WorkbenchStore({ file: null, clock, random: () => 3 }) - const projectId = store.createProject({ hostWorkspaceId: 'ws-a' }) - const created = createTask( - { projectId, title: 't', objective: 'o', ownerRoleId: 'hubu' }, - { newTaskId: () => 'task_1', now: clock }, - ) - store.insertTask(created) - const queued = startTask(store.getTask('task_1'), { now: clock }) - const stale = applyDecision(store, 'task_1', { applied: false, stale: true, task: created }) - assert.equal(stale.applied, false) - assert.equal(store.getTask('task_1').revision, 1, '陈旧事件不得产生版本抖动') - - const started = applyDecision(store, 'task_1', { applied: true, stale: false, task: queued }) - assert.equal(started.task.status, 'queued') - assert.equal(store.getTask('task_1').status, 'queued') - // null 会被默认参数换成 undefined,所以显式传 undefined 才能走到 store 校验 - assert.throws(() => applyDecision(undefined, 'task_1', {}), /需要 store/) - // 未启用的事件不得落库:返回原判定,store 保持 revision 不变 - assert.equal(applyDecision(store, 'task_1', { applied: false, task: queued }).task.status, 'queued') - assert.throws(() => applyDecision(store, 'task_1', null), /判定结果不合法/) -}) - -test('isOpenTask 区分终态与活动态', () => { - assert.equal(isOpenTask(draftTask()), true) - assert.equal(isOpenTask(cancelTask(draftTask()).task), false) - assert.equal(isOpenTask(null), false) - assert.equal(isOpenTask({ status: 'bogus' }), false) -})